text:
Q: Sum sub groups with dplyr I'm trying to sum sub groups with dplyr using mutate, but this means I need to know each row group to create a conditional. The idea is not to change the current grouping, as the code below shows:
mutate(mtcars, cond_disp = ifelse(vs==1,sum(disp[vs==1]),sum(disp[vs==0])))

Is there a dynamic method to achieve this?

A: You can do it with group_by(vs) and summarise. But as wished here is the version with mutate.
library(tidyverse)

mtcars %>%
  group_by(vs) %>%
  #summarise(cond_disp = sum(disp))
  mutate(cond_disp = sum(disp))
#> # A tibble: 32 x 12
#> # Groups:   vs [2]
#>      mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb cond_disp
#>    <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>     <dbl>
#>  1  21       6  160    110  3.9   2.62  16.5     0     1     4     4     5529.
#>  2  21       6  160    110  3.9   2.88  17.0     0     1     4     4     5529.
#>  3  22.8     4  108     93  3.85  2.32  18.6     1     1     4     1     1854.
#>  4  21.4     6  258    110  3.08  3.22  19.4     1     0     3     1     1854.
#>  5  18.7     8  360    175  3.15  3.44  17.0     0     0     3     2     5529.
#>  6  18.1     6  225    105  2.76  3.46  20.2     1     0     3     1     1854.
#>  7  14.3     8  360    245  3.21  3.57  15.8     0     0     3     4     5529.
#>  8  24.4     4  147.    62  3.69  3.19  20       1     0     4     2     1854.
#>  9  22.8     4  141.    95  3.92  3.15  22.9     1     0     4     2     1854.
#> 10  19.2     6  168.   123  3.92  3.44  18.3     1     0     4     4     1854.
#> # … with 22 more rows

A: dplyr::mutate() will take multiple rows as inputs to functions on the right hand side of the equation(s) that are arguments to mutate(). As noted in the comments, one can use group_by() to break the inputs on the right hand side functions into subgroups. This eliminates the need for conditional logic in mutate() as specified in the original question.
We'll illustrate by calculating cond_disp from the original post, and include n to count the number of rows included in the summary data.
mtcars %>% group_by(vs) %>%
     mutate(cond_disp = sum(disp),
            n = n()) -> result
result[,c("vs","n","cond_disp","disp")]

# A tibble: 32 x 4
# Groups:   vs [2]
      vs     n cond_disp  disp
   <dbl> <int>     <dbl> <dbl>
 1     0    18     5529.  160
 2     0    18     5529.  160
 3     1    14     1854.  108
 4     1    14     1854.  258
 5     0    18     5529.  360
 6     1    14     1854.  225
 7     0    18     5529.  360
 8     1    14     1854.  147.
 9     1    14     1854.  141.
10     1    14     1854.  168.
# … with 22 more rows

The mutate() approach is useful when one needs to calculate percentage values row by row where the denominator of the percentage is a sum of a column within a combination of by groups. To illustrate, we'll calculate percentage of total displacement for V versus straight engines, print the results, and print the sum of pct_disp to illustrate that it equals 100 for V engines.
mtcars %>% group_by(vs) %>%
     mutate(pct_disp = 100* disp / sum(disp),
            n = n()) -> result
result[result$vs==0,c("vs","n","disp","pct_disp")]
sum(result$pct_disp[result$vs==0])

# A tibble: 18 x 4
# Groups:   vs [1]
      vs     n  disp pct_disp
   <dbl> <int> <dbl>    <dbl>
 1     0    18  160      2.89
 2     0    18  160      2.89
 3     0    18  360      6.51
 4     0    18  360      6.51
 5     0    18  276.     4.99
 6     0    18  276.     4.99
 7     0    18  276.     4.99
 8     0    18  472      8.54
 9     0    18  460      8.32
10     0    18  440      7.96
11     0    18  318      5.75
12     0    18  304      5.50
13     0    18  350      6.33
14     0    18  400      7.23
15     0    18  120.     2.18
16     0    18  351      6.35
17     0    18  145      2.62
18     0    18  301      5.44
> sum(result$pct_disp[result$vs==0])
[1] 100

When to use summarise()
dplyr::summarise() is useful if one wants to summarise the data without adding additional column(s) to the input data frame in the pipeline. The result of summarise() is one row for each combination of variables in the group_by() specification in the pipeline, and the column(s) for the summarized data.
mtcars %>% group_by(vs) %>%
     summarise(cond_disp = sum(disp),
            n = n())
# A tibble: 2 x 3
     vs cond_disp     n
  <dbl>     <dbl> <int>
1     0     5529.    18
2     1     1854.    14

row by row calculations
If one needs to use R functions to calculate values across columns within a row, one can use the rowwise() function to prevent mutate() from using multiple rows in the functions on the right hand side of equations within mutate().
To illustrate, we'll sum the values of vs, am. Notice that the result of n = n() in the output is 1 for each row printed.
mtcars %>% rowwise(.) %>%
     mutate(cond_binary = sum(vs,am),
            n = n()) -> result
result[,c("vs","am","n","cond_binary")]

# A tibble: 32 x 4
# Rowwise:
      vs    am     n cond_binary
   <dbl> <dbl> <int>       <dbl>
 1     0     1     1           1
 2     0     1     1           1
 3     1     1     1           2
 4     1     0     1           1
 5     0     0     1           0
 6     1     0     1           1
 7     0     0     1           0
 8     1     0     1           1
 9     1     0     1           1
10     1     0     1           1
# … with 22 more rows


text:
Q: Two value random variables which are independent I am a bit confused about some notions from probabilities, and I'm asking for clarifications. The problem is the following:

Let $X$ and $Y$ be two random variables, each taking values either $a$
  or $b$. Assume that $\mathbb{E}(XY)=\mathbb{E}(X)\mathbb{E}(Y)$. Prove
  that $X$ and $Y$ are independent.

So, if say $a$ and $b$ are the values that they can take, to show that they are independent, we have to check that $\mathbb P(X=x,Y=y)= \mathbb P(X=x) \mathbb P(Y=y)$ for all $x,y \in \left\{a,b\right\}$, right?
How does that follow from the equality on expectations?

A: Hint: This is intended as both a hint and a general approach to thinking about problem solving in situations like this.
Step 1: Prove the result for a simple subcase. Here the most obvious choice (why?) is to take $a = 0$ and $b = 1$. What do you need to check?
Step 2: Think about how your approach in Step 1 might generalize. In many cases (Hint: This one!) it is possible to go from the specific case to the general one with very little extra work. Can you take a random variable $X$ on $\{a,b\}$ and convert it in a simple way to another random variable $\tilde X$ on $\{0,1\}$? How does this allow you to conclude the general result?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Aggregation inconsistently prints different value I have the following code snippet that should retrieve the total count of the account using spring-data-mongodb
TypedAggregation<Account> agg = Aggregation.newAggregation(Account.class,
        group("user.id"),
        group().count().as("total"));

AggregationResults<AccountTotal> result = mongos.aggregate(agg, AccountTotal.class);
AccountTotal account = result.getMappedResults().get(0);
account.getTotal(); // should print 90 but prints 1

Here is the equivalent mongo script returning from the agg field that I use in the mongo shell prints 90
{ "$group" : { "_id" : "$user.id"}} ,
{ "$group" : { "_id" :  null  , "total" : { "$sum" : 1}}}

> db.accounts.aggregate(
[
{ "$group" : { "_id" : "$user.id"}} ,
{ "$group" : { "_id" :  null  , "total" : { "$sum" : 1}}}
])

What am I missing actually that I get 1 in the Java platform.
EDIT:
After changing the previous one with the following one I get the expected count:
Aggregation agg = Aggregation.newAggregation(
                   group("user.id"),
                   group().count().as("total"));
AggregationResults<AccountTotal> result =
mongos.aggregate(agg, this.getCollectionName(), AccountTotal.class);

Btw, thanks @chridam.

A: The reason you are getting 1 is because of the current aggregation pipeline which returns all 90 documents grouped by user.id in an array and each may have a total of 1 (I guess). This line result.getMappedResults().get(0) will get the first element in the aggregation results and that element has a total of 1. The total you are trying to get is the total of all the grouped documents i.e. the length of the aggregation result cursor array.
I believe you want to group all the documents by the $user.id field, get the count on each grouped result and then do another $group operation to get the sum of all the group counts:
> db.accounts.aggregate(
[
    { "$group" : { "_id" : "$user.id", "count" : { "$sum" : 1 } } },
    { "$group" : { "_id" : null, "total" : { "$sum" : "$count" } } }
])

which will give you the desired results. The Spring aggregation equivalent
TypedAggregation<Account> agg = Aggregation.newAggregation(Account.class,
      group("user.id").count().as("count"),
      group().sum("count").as("total"));

AggregationResults<AccountTotal> result = mongos.aggregate(agg, AccountTotal.class);
List<AccountTotal> accountCount = result.getMappedResults();
(accountCount.get(0).total == 90); // should be true


text:
Q: Read CSV to a class Dataflow Java from GCS I'm a newby on Java Dataflow and I want to read a CSV file from GCS and have in output a PCollection.
How can I do it efficiently?
Thanks a lot for your help.

A: Ideally you would have to convert that CSV file to something else. If you can share more details on what you are trying to do with that PCollection, we could provide more insight.
Here is a very generic example that might help. Suppose that you have a CSV gs://sample-bucket-name/teams.csv:
id,name,score
1,Team A,35
2,Team B,40

You could create a pipeline and a component to convert those lines to a POJO in which Beam knows the schema, for example:
  @DefaultSchema(JavaFieldSchema.class)
  public class Team implements Serializable {
    int id;
    String name;
    int score;

    @Override
    public boolean equals(Object o) {
      if (this == o) {
        return true;
      }

      return o != null
          && o instanceof Team
          && id == ((Team) o).id;
    }
  }

A ParDo function could look like this (although you can use any tools you'd like to read and parse CSV, instead of using String.split):
public class TeamCSVtoBeanFunction extends DoFn<String, Team> {
    @ProcessElement
    public void processElement(@Element String line, OutputReceiver<Team> outputReceiver) {

      // ignore header or empty lines
      if (line.equals("id,name,score") || line.isEmpty()) {
        return;
      }
      String[] split = line.split(",");

      Team team = new Team();
      team.id = Integer.parseInt(split[0]);
      team.name = split[1];
      team.score = Integer.parseInt(split[2]);
      outputReceiver.output(team);
    }
  }

Finally, the pipeline, which uses TextIO to read the text file into a PCollection of Team. Ideally, you would want to use other IOs to fulfill your needs, and write your results somewhere.
    PCollection<Team> teams = pipeline
        .apply("ReadCSV", TextIO.read().from("gs://sample-bucket-name/teams.csv"))
        .apply("ConvertToBean", ParDo.of(new TeamCSVtoBeanFunction()));


text:
Q: How do I set a window icon to a Buffer image in Electron? I have an image that is stored in a buffer. I'm trying to set it as the window icon, but I can't find a way to do so. There is no path to the image, so I can't just use win.setIcon('path/to/image').
I tried to do the following, to no success.
win.setIcon(buffer); // giving the buffer by itself
win.setIcon(buffer.toString('base64')); // giving the buffer as base64
win.setIcon(`data:image/png;base64,${buffer.toString('base64')}`); // giving as base64 url

let imageObject = new Image();
imageObject.src = `data:image/png;base64,${buffer.toString('base64')}`;
win.setIcon(imageObject); // giving image object

A: According to Electron's documentation, BrowserWindow.setIcon () takes either a string or a NativeImage, a data type provided by Electron. You can convert your buffer to a NativeImage by using the following code:
const { nativeImage } = require ("electron");

win.setIcon (nativeImage.createFromBuffer (buffer));

If that does not help, you can also pass your buffer as a Base 64 string in a data URL (like you have tried before) to the function createFromDataURL. For more information, see the documentation on NativeImage. It is also worth noting that you can pass advanced options to the createFromBuffer function to give Electron more hints about how to display your icon.


text:
Q: What is deferred assignment in Kotlin? In Kotlin Documentation, there is mentioned about deferred assignment
val a: Int = 1  // immediate assignment
val b = 2   // `Int` type is inferred
val c: Int  // Type required when no initializer is provided
c = 3       // **deferred assignment**

What is the meaning of deferred assignment?

A: As stated in the Documentation the val c: Int is declared before c is initialized in the following line.
This means you can initialize a non nullable val inside a function some lines after you declared it.
For example like this:
class Hichhiker {
    fun foo() {
        val firstName: String
        val lastName: String
        val age: Int
        firstName = "Arthur"
        lastName = "Dent"
        age = 40
    }
}

Instead of this:
class Hichhiker {
    fun foo() {
        val firstName = "Arthur"
        val lastName = "Dent"
        val age = 40
    }
}

So the compiler recognizes the initalization of the non nullable val even if the assignment was deferred by some lines of code.
For something similar on the class level and more often used see lateinit and delegates like lazy()

A: This means simply that the variable is initialized not in its declaration but at a later point.

A: It simply means that the variable has been initialized and the assignment of a value to it takes place lines of code below the initialization.Meaning the assignment has been postponed for later.


text:
Q: Prove $ \left(\sum \limits_{k=1}^n (2k-1)\frac{k+1}{k}\right) \left( \sum \limits_{k=1}^n (2k-1)\frac{k}{k+1}\right) \le \frac{9}{8}n^4$
Prove that for all $n \in \mathbb{N}$ the inequality $$ \left(\sum \limits_{k=1}^n (2k-1)\frac{k+1}{k}\right) \left( \sum \limits_{k=1}^n (2k-1)\frac{k}{k+1}\right) \le \frac{9}{8}n^4$$ holds.

My work. I proved this inequality, but my proof is ugly (it is necessary to check by brute force whether the inequality holds for $n=1,2,3,...,15$). I hope that there is nice proof of this inequality. Michael Rozenberg wrote a very nice solution to a similar problem ( Prove the inequality $\sum \limits_{k=1}^n \frac{k+1}{k} \cdot \sum \limits_{k=1}^n \frac{k}{k+1} \le \frac{9}{8}n^2$ ). I think this inequality has a similar proof, but I can't prove in a similar way. I will write as I proved the inequality. Let $S_n= \sum \limits_{k=1}^n \frac{1}{k} $. Then $$ \sum \limits_{k=1}^n (2k-1)\frac{k+1}{k}=n^2+2n-S_n $$ and $$\sum \limits_{k=1}^n (2k-1)\frac{k}{k+1}=n^2-2n-3+\frac{3}{n+1}+3S_n$$ We need to prove that $$3S_n^2-S_n \left( 2n^2+8n+3-\frac{3}{n+1}\right)+\frac{n^4}{8}+7n^2+3n-3+\frac{3}{n+1} \ge 0$$ To prove this inequality, I found discriminant of the quadratic polynomial and used the fact that $S_n \le n$. It was possible to prove that the inequality holds for all $n \ge 16$.

A: Here is a way, which is motivated by the excellent approach of @MichaelRozenberg's. Let us write $\displaystyle a_k = \frac { k}{k+1}, b_k = 2k-1$. We then have
\begin{align*}
S =& \sum_{i\le n} a_i b_i\sum_{j\le n}\frac{b_j}{a_j} \\
=& \sum_{i,j\le n} \frac{a_i}{a_j}b_ib_j \\
=& \frac 1 2 \sum_{i,j\le n} \left(\frac {a_i}{a_j} + \frac{a_j}{a_i}\right) b_ib_j.
\end{align*} We then observe
\begin{align*}
\frac {a_i}{a_j} + \frac{a_j}{a_i} \le& \begin{cases} 2\quad \text {if}\quad i=j=1\\
\frac{5}{2}\quad\text{if}\quad i=1, j> 1\ \text{ or }\ i>1, j=1\\
\frac{13}{6}\quad \text{if} \quad i > 1, j> 1
\end{cases}
\end{align*} thus
\begin{align*}
S \le &\frac 1 2 \left[2 + 2\cdot\frac {5}{2}(n^2-1) + \frac {13}{6}(n^2-1)^2\right]\\
<& \frac 9 8 n^4
\end{align*} for all $n\ge 1$ except for $n=2$. We can check $n=2$ case manually...

A: We can use also the Cassel's inequality:

Let $a$, $b$ and $w$ be sequences of $n$ positive numbers such that $1<m\leq\frac{a_k}{b_k}\leq M$ for any $k.$ Prove that:
  $$\sum_{k=1}^nw_ka_k^2\sum_{k=1}^nw_kb_k^2\leq\frac{(M+m)^2}{4Mm}\left(\sum_{k=1}^nw_ka_kb_k\right)^2.$$

This inequality was here:
G.S. WATSON, Serial Correlation in Regression Analysis, Ph.D. Thesis, Dept. of Experimental
Statistics, North Carolina State College, Raleigh; Univ. of North Carolina, Mimograph Ser., No.
49, 1951, appendix 1.
In our case $w_k=2k-1$, $a_k=\sqrt{\frac{k+1}{k}}$, $b_k=\sqrt{\frac{k}{k+1}},$ $M=2$ and $m=1$, which gives:
$$\sum_{k=1}^n(2k-1)\frac{k+1}{k}\sum_{k=1}^n(2k-1)\frac{k}{k+1}\leq\frac{(2+1)^2}{4\cdot2\cdot1}\left(\sum_{k=1}^n(2k-1)\right)^2=\frac{9n^4}{8}.$$


text:
Q: Can we lower bound the volume of the image of a ball under a diffeomorphism? Apologies if this question is overly simple, I'm new to differential geometry.
Suppose I have two Riemannian manifolds $M_1$ and $M_2$, along with a
diffeomorphism $f:M_1\to M_2$ between them. Let $d$ denote the geodesic distance on $M_1$. Let $B_r=\{x'\in M_1: d(x, x') \le
r\}$ be a ball of radius $r$ centered around a point $x\in M_1$, and let
$B_r'=\{x'\in M_2: d(f^{-1}(x'), x) \le r\}$, so that $B'$ is the image of $B$
under $f$. What (if anything) can I say about the volume of $B'$ as $r\to 0$? In
particular, is it the case that there are constants $r_0>0,C>0$ such that
$\text{Vol}(B_r') \ge C \text{Vol}(B_r)\forall r \le r_0$?

A: Yes, for small $r$ the volume ratio is determined by the determinant of the differential, as in the Euclidean case.
Fix orthonormal bases $e_i$ for $T_xM_1$ and $v_i$ for $T_{f(x)}M_2$ and let $A$ be the matrix of $Df$ in these frames; i.e. $A_{ij} = g_2(v_i, Df(e_j))$.
Since $Df$ is a diffeomorphism, $A$ is invertible, and thus $|\det A| > 0$.
Then the precise result you're looking for is
$$\lim_{r\to 0}\frac{V(f(B_r))}{V(B_r)} = |\det A|.$$
In particular, for any $\epsilon > 0$ we can find an $r_0 >0$ such that $$(|\det A| - \epsilon)V(B_r) \le V(f(B_r)) \le (|\det A|+\epsilon) V(B_r)$$
whenever $r < r_0$.
We often write $|\det Df|$ instead of setting up $A$ and taking $|\det A|$, with the understanding that the determinant of a map between $n$-dimensional inner product spaces is taken in orthonormal bases for those inner products.


text:
Q: Populate data in a gridview using multiple selection in listview? I am trying to populate data in a gridview using multiple selection from a listview?
This is my code for the gridview
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        SelectCommand="SELECT employee.Empno, employee.Dptno, employee.Grade, employee.Employee FROM employee INNER JOIN grade ON employee.Grade = grade.Grade INNER JOIN empskill ON employee.Empno = empskill.Empno WHERE (empskill.Skillno = @Skillno)">
        <SelectParameters>
            <asp:ControlParameter ControlID="ListBox1" Name="Skillno"
                PropertyName="SelectedValue" />
        </SelectParameters>
    </asp:SqlDataSource>

but the problem i'm having is that the data is not from all the selected rows in the listview.
The listview is a list of skills and the data populated in the gridview is the employees who posses these skills selected in the listbox.  So if you select 2 skills, it should display the employees who has BOTH the selected skills not combined them.  Hope that makes my question clear.


text:
Q: Disabling HTTP methods and using Force HTTP with mod_rewrite in Apache In my virtual host file on Apache, I want to disable HTTP methods and use force https as well. How will the mod_rewrite rules and conditions work? I have following in virtual host file.
RewriteEngine On
RewriteCond %{REQUEST_METHOD} ^(OPTIONS|TRACE)
RewriteRule .* - [F]
RewriteCond %{HTTPS} !=on
RewriteRule ^/(.*) https://%{SERVER_NAME}/$1 [L,R]

A: For the requirements you noted, the Rewrites you listed seem correct. The first Cond/Rule pair returns a 403 Forbidden for any requests that use the OPTIONS or TRACE methods. The second Cond/Rule pair redirects any http request over to https and preserves the original hostname and URI.

A: Adding the mod-rewrite rule for disabling HTTP options methods in "ssl.conf" file solved the issue.


text:
Q: SVG as Xamarin.Forms Button image I have a Xamarin.Forms Shared project and I'm working on UI (XAML). I want to use SVG image as a button image in my app. The problem is that I don't know how to do that.
I will be grateful if someone  will show me how to do that step by step.

A: You can convert SVG to XAML using Inkscape.

*

*Open the SVG

*Save As...   Microsoft XAML

*Use the XAML in your button style

A: First convert svg file to android vector using the this link. Then add an android vector file (xml) like below:

And finally use this file as button Image
<Button Image="vector.xml">


text:
Q: Proof check: a riemannian 2-manifold is orientable if its unit tagent bundle is principal For a two-dimensional smooth manifold $M$ with a Riemannian metric, we can consider the unit tangent bundle $S\to M$, which is a circle bundle over $M$. I am trying to show that if $S\to M$ is a "principal" circle bundle, then $M$ must be orientable. Here is my try: Suppose $S\to M$ is a principal circle bundle. Then there is a right action of $S^1$ on $S$. Then we can define orientation on each tangent space of $M$ by declaring $\{v, v\cdot i\}$ to be a positive basis for any nonzero tangent vector $v$. This implies that $M$ is orientable.
Does my argument work?  I should show that the orientation on tangent spaces are well-defined (does not depend on the choice of $v$), but I got stuck showing this. Any hints?


text:
Q: NPM package not installing for tpp project I am trying to follow this tutorial to get a twitch plays node server up. I installed node.js. I go to the node.js command prompt, CD to the folder containing all the information that I downloaded from the tutorial, type npm install as said in the tutorial and I get this error:
npm ERR! code ENOENT
npm ERR! syscall spawn git
npm ERR! path git
npm ERR! errno ENOENT
npm ERR! enoent Error while executing:
npm ERR! enoent undefined ls-remote -h -t ssh://git@github.com/martynsmith/node-irc.git
npm ERR! enoent
npm ERR! enoent
npm ERR! enoent spawn git ENOENT
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:

error log: here (Download)

A: Install gitbash from here - https://gitforwindows.org/
and run npm install in it - see if that works for you.
do cd "~documents/mde/front mission"
and perform npm install


text:
Q: Slim\Exception\HttpNotFoundException I'm creating a new Slim project and getting the following error:
Slim Application Error:
The application could not run because of the following error:
Error Details
Type: Slim\Exception\HttpNotFoundException
Code: 404
Message: Not found.
File: C:\xampp\htdocs\MyApi\vendor\slim\slim\Slim\Middleware\RoutingMiddleware.php
Line: 91

Trace
#0 C:\xampp\htdocs\MyApi\vendor\slim\slim\Slim\Middleware\RoutingMiddleware.php(57): Slim\Middleware\RoutingMiddleware->performRouting(Object(Slim\Psr7\Request))
#1 C:\xampp\htdocs\MyApi\vendor\slim\slim\Slim\MiddlewareDispatcher.php(124): Slim\Middleware\RoutingMiddleware->process(Object(Slim\Psr7\Request), Object(Slim\Routing\RouteRunner))
#2 C:\xampp\htdocs\MyApi\vendor\slim\slim\Slim\Middleware\ErrorMiddleware.php(89): class@anonymous->handle(Object(Slim\Psr7\Request))
#3 C:\xampp\htdocs\MyApi\vendor\slim\slim\Slim\MiddlewareDispatcher.php(124): Slim\Middleware\ErrorMiddleware->process(Object(Slim\Psr7\Request), Object(class@anonymous))
#4 C:\xampp\htdocs\MyApi\vendor\slim\slim\Slim\MiddlewareDispatcher.php(65): class@anonymous->handle(Object(Slim\Psr7\Request))
#5 C:\xampp\htdocs\MyApi\vendor\slim\slim\Slim\App.php(174): Slim\MiddlewareDispatcher->handle(Object(Slim\Psr7\Request))
#6 C:\xampp\htdocs\MyApi\vendor\slim\slim\Slim\App.php(158): Slim\App->handle(Object(Slim\Psr7\Request))
#7 C:\xampp\htdocs\MyApi\public\index.php(18): Slim\App->run()
#8 {main}

Here is my index.php
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require '../vendor/autoload.php';

$app = AppFactory::create();
$app->addRoutingMiddleware();
$errorMiddleware = $app->addErrorMiddleware(true, true, true);

$app->get('/hello/{name}', function (Request $request, Response $response, array $args) {
    $name = $args['name'];
    $response->getBody()->write("Hello, $name");
    return $response;
});

$app->run();

This might be a basic problem.But I am new.Need help please.

A: This worked for me (based on Mandien's answer).
I've just added index.php in setBasePath(...), no .htaccess needed.
$app->setBasePath("/myapp/public/index.php");

// Define app routes
$app->get('/hello/{name}', function (Request $request, Response $response, $args) {
    $name = $args['name'];
    $response->getBody()->write("Hello, $name");
    return $response;
});

http://localhost/myapp/public/index.php/hello/world
shows Hello, world
Linux, Apache, Slim 4

A: To solve the problem with Slim 4 here is what I did :
1/ Just after
$app = AppFactory::create();

I added :
$app->setBasePath("/myapp/api"); // /myapp/api is the api folder (http://domain/myapp/api)

2/ In my .htaccess :
RewriteEngine on
RewriteCond %{ENV:REDIRECT_STATUS} !200
RewriteRule ^api/(.*)$ api/index.php/$1

3/ Finaly to handle the 'HttpNotFoundException' Slim Exception I added a try/catch (I don't know why Slim doesn't handle it internaly => maybe to give us more possibility?)
try {
    $app->run();
} catch (Exception $e) {
  // We display a error message
  die( json_encode(array("status" => "failed", "message" => "This action is not allowed")));
}

Hope it can help
** Edited => To force Slim to handle Exceptions, after : **
$app = AppFactory::create();

add :
$app->addErrorMiddleware(true, true, true);

Ref : http://www.slimframework.com/docs/v4/middleware/body-parsing.html

A: I was getting the same error, let me describe what I was exactly doing and then how did it work!
I was running local server using the command on terminal php -S localhost:8002
The command returned Document root is /Users/Codeus/Desktop/ and error occured when I navigated to localhost:8002
Then again I ran localhost from the directory where index.php or whatever your is that you wanna run and it worked fine for me. For example, for me, it was two levels up then command php -S localhost:8002 returned Document root is /Users/Codeus/Desktop/myslim/src/public and this is exactly where my index.php file was. Hope this works for you as well.

A: If you are using slim and a newbie then try this code and it will work
Simply change your code a little.
Right now, you all have this code:
$app->get('/hello/{name}', function (Request $request, Response $response, array $args) { ... }

Change it to full naming convention:
$app->get('/[my-appname]/public/hello/{name}', function (Request $request, Response $response, array $args) { .. }

Full code
 <?php
 use Psr\Http\Message\ResponseInterface as Response;
 use Psr\Http\Message\ServerRequestInterface as Request;
 use Slim\Factory\AppFactory;

 require __DIR__ . '/../vendor/autoload.php';

 $app = AppFactory::create();

//here i used the url change to your project name on [my-appname]
 $app->get('/[my-appname]/public/hello/{name}', function (Request $request,
 Response $response, array $args) {
    $name = $args['name'];
    $response->getBody()->write("Hello, $name");
    return $response;
 });

$app->run();

A: After nearly 3 hours of intense browsing, I have come up with the solution which would be to downgrade the version of Slim framework from the project's root directory.
I was using v4.3.0 which due to some strange reasons didn't want to behave the way it is meant to and the resolution for which was beyond my understanding.
The steps would be as follows:

*

*Go to the project root directory and type cmd in the file path for
the command prompt window.

*Type in composer require slim/slim:3.*

*Once done, you would then need to replace the pre-existing code on
public/index.php from your code editor with the below:

<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
//use Slim\Factory\AppFactory;

require '../vendor/autoload.php';

$app = new \Slim\App;

$app->get('/hello/{name}', function (Request $request, Response $response, array $args) {
    $name = $args['name'];
    $response->getBody()->write("Hello, $name");
    return $response;
});

$app->run();

The above snippet is basically the intro page code but from Slim v3.12.3


text:
Q: Cannot read property 'initialize' of undefined - SailsJs I'm trying to create a sailsjs webapi with authentication.
My api works fine until I add packages for authentication without changing anything else.
My api give a 500 Internal Server Error after I run this command:
sudo npm install sails-permissions sails-auth@2.1.1 lodash sails-mongo --save

I have the following error:
error: Sending 500 ("Server Error") response:
TypeError: Cannot read property 'initialize' of undefined
at module.exports (/home/rick/Documents/apexBackend/node_modules/sails-auth/dist/api/policies/passport.js:35:11)
at routeTargetFnWrapper (/usr/lib/node_modules/sails/lib/router/bind.js:179:5)
at callbacks (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:164:37)
at param (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:138:11)
at pass (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:145:5)
at nextRoute (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:100:7)
at callbacks (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:167:11)
at /usr/lib/node_modules/sails/lib/router/bind.js:187:7
at module.exports (/home/rick/Documents/apexBackend/node_modules/sails-auth/dist/api/policies/basicAuth.js:13:12)
at routeTargetFnWrapper (/usr/lib/node_modules/sails/lib/router/bind.js:179:5)
at callbacks (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:164:37)
at param (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:138:11)
at pass (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:145:5)
at nextRoute (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:100:7)
at callbacks (/usr/lib/node_modules/sails/node_modules/express/lib/router/index.js:167:11)
at /usr/lib/node_modules/sails/lib/router/bind.js:187:7 [TypeError: Cannot read property 'initialize' of undefined]

These are my dependencies:
"ejs": "~0.8.4",
"grunt": "0.4.2",
"grunt-contrib-clean": "~0.5.0",
"grunt-contrib-coffee": "~0.10.1",
"grunt-contrib-concat": "~0.3.0",
"grunt-contrib-copy": "~0.5.0",
"grunt-contrib-cssmin": "~0.9.0",
"grunt-contrib-jst": "~0.6.0",
"grunt-contrib-less": "0.11.1",
"grunt-contrib-uglify": "~0.4.0",
"grunt-contrib-watch": "~0.5.3",
"grunt-sails-linker": "~0.9.5",
"grunt-sync": "~0.0.4",
"include-all": "~0.1.3",
"lodash": "^3.10.1",
"rc": "~0.5.0",
"sails": "~0.11.3",
"sails-auth": "^2.1.1",
"sails-disk": "~0.10.0",
"sails-mongo": "^0.11.5",
"sails-permissions": "^2.1.11"

A: Fixed it using this command:
 sudo npm install git://github.com/balderdashy/sails.git#master -g

Latest version of sails works again.


text:
Q: behavior of git branch in powerlevel10k I am using oh-my-zsh and powerlevel10k on Mac and I observed a weird behavior when using git branch. Instead of like other commands, like git status which will list the result in current terminal.

However, git branch is like into an editor mode and I have to press q to exit the mode to get back to terminal.

Anyone knows how to fix it, i.e., let the git branch command to show results in current terminal instead of entering into an editor mode?

A: It seems that since version 2.16, git defaults to use the pagination for the branch command.
You can disable pagination for branch command only using
git config --global pager.branch false

It seems to be working for your specific shell

A: git is using the pager (usually less command) for its output.
you can configure it via core.pager for all the git commands or use per command config pager.<cmd>; there is also GIT_PAGER env variable
the easiest way to skip the paging for one time is to use --no-pager option for command; and to disable the paging completely git documentation suggests:

To disable pagination for all commands, set core.pager or GIT_PAGER to cat.

git config --global core.pager cat
you may experiment with setting the pager to less -F -X; this will make less command to page the content only if it does not fit the screen -F, and not to clean the terminal buffer -X
git config --global core.pager 'less -F -X'
or simply disable the pager for the branch command
git config --global pager.branch false


text:
Q: Stored Procedure error handling using java How do you handle error condition  while writing stored procedure or accessing stored procedure from java?

A: stored procedure should return error code if some operation fails but if stored procedure itself fail than catching SQLException is only choice.

A: try {
    CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");
    stmt.setInt(1,1011);
    stmt.setString(2,"Amit");
    stmt.execute();
} catch(SQLException e) {
    e.printStack();
}

A: this piece of code is taken from oracle [docs][1] to answer.

public void
    createProcedureShowSuppliers()
    throws SQLException {
    String createProcedure = null;

    String queryDrop =
        "DROP PROCEDURE IF EXISTS SHOW_SUPPLIERS";

    createProcedure =
        "create procedure SHOW_SUPPLIERS() " +
        "begin " +
            "select SUPPLIERS.SUP_NAME, " +
            "COFFEES.COF_NAME " +
            "from SUPPLIERS, COFFEES " +
            "where SUPPLIERS.SUP_ID = " +
            "COFFEES.SUP_ID " +
            "order by SUP_NAME; " +
        "end";
    Statement stmt = null;
    Statement stmtDrop = null;

    try {
        System.out.println("Calling DROP PROCEDURE");
        stmtDrop = con.createStatement();
        stmtDrop.execute(queryDrop);
    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } finally {
        if (stmtDrop != null)
        {
            stmtDrop.close();
        }
    }

    try {
        stmt = con.createStatement();
        stmt.executeUpdate(createProcedure);
    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } finally {
        if (stmt != null) { stmt.close(); }
    }
}

  [1]: https://docs.oracle.com/javase/tutorial/jdbc/basics/storedprocedures.html

A: When you call a stored procedure, it will execute in database server so if there any exception occurs that can be handled in EXCEPTION block in the stored procedure. If that stored procedure itself fails, it throws a SQL exception which can be handled by try/catch block and wrap it to your project specific exception.
Example
try {
    CallableStatement stmt = con.prepareCall("{call geNamebyId(?)}");
    stmt.setInt(1);
    stmt.execute();
} catch(SQLException e) {
    e.printStack();
}


text:
Q: Unable to Add UI elements on top of AGSMapView I have an app that I'm trying to migrate from Google Maps to ArcGIS maps because I need to use the maps offline.
I'm using the ArcGIS iOS 100.6 SDK and am trying to place a UIbutton on top of AGSMapView. In the View Controller "MapView" and the UIButton are under "View". The UIbutton is not a subview of MapView. I also have three other elements that should overlay the map that I hide and unhide using "isHidden = true/false" and these cannot be displayed either. The app is written in Swift 4.2 and I'm using Xcode 10.3.
Here is the view in the view controller:

View
   Safe Area
   Btn Satellite Toggle (outlet name: "btnSatelliteToggle")
   View Mark Location
   View Verify Location
   View Pic Detail
   MapView
   Constraints

This is the code where I show the map and try to add the button on top:

let viewMap = AGSMapView(frame: .zero)
viewMap.map = AGSMap(basemapType: .navigationVector,
                                         latitude:   currentLocation.latitude, longitude: currentLocation.longitude,
                                         levelOfDetail: zoomLevel)
viewMap.graphicsOverlays.add(overlay)
viewMap.touchDelegate = self
view = viewMap
view.bringSubviewToFront(btnSatelliteToggle)

The map is displayed along with the graphics overlay, but I am unable to show any UI elements on top of the map.  This works fine with Google maps, but not with ArcGIS maps.
How do I get these UI elements to be displayed on top of the AGSMapView generated map?
Thanks in advance for your help.

A: It appears your MapView is at the top of the view hierarchy and thus obscuring its sibling views.
Try rearranging the view hierarchy to place the MapView at the bottom:
View
   Safe Area
   MapView
   Btn Satellite Toggle (outlet name: "btnSatelliteToggle")
   View Mark Location
   View Verify Location
   View Pic Detail
   Constraints

A: I actually just solved this.  Here is the updated code that works:
viewMap.map = AGSMap(basemapType: .navigationVector,
                                         latitude: currentLocation.latitude, longitude: currentLocation.longitude,
                                         levelOfDetail: zoomLevel)
viewMap.graphicsOverlays.add(overlay)
viewMap.touchDelegate = self

I removed:
Setting AGSMapView(frame: .zero)
as this prevented the map from being displayed in MapView.
Also, by not setting a view (thus using the default view controller "view") all siblings are available for display and can be controlled via "isHidden."


text:
Q: error in the usestate or in the uuid library? I'm doing a project to manage patient appointments and everything was fine until I installed the 'uuid' library, the library didn't give me a problem, but from then on it gave me this error, apparently it is with the useState but not I find it, I thank you in advance!
error image...
enter image description here

import React, { Fragment, useState } from 'react';
import { v4 as uuidv4 } from 'uuid';

const Form = () => {

    //creando el State para las citas
    const [ cita, actualizarCita ] = useState({
        mascota: '',
        propietario: '',
        fecha: '',
        hora: '',
        sintomas: ''
    });

    const [ error, actualizarError ] = useState(false)

    // funcion que se ejecutara cada vez que el usuario escribe en el input para validar lo que hace
    const actualizarState = e => {
        actualizarCita({
            ...cita,
            [e.target.name]: e.target.value
        })
    }

    // Extraer los valores de cita
    const { mascota, propietario, fecha, hora, sintomas } = cita;

    // Cuando el usuario envia el formulario
    const submitCita = e => {
        e.preventDefault();

        // Validacion

        if(mascota.trim() === '' || propietario.trim() === '' || fecha.trim() === '' || hora.trim() === '' || sintomas.trim() === ''){
            actualizarError(true);
            return;
        }
    }

    // Eliminando el mensaje previo
    actualizarError(false);

    // Asignando un ID

    cita.id = uuidv4();

    return (
        <Fragment>

 Crear Cita

        { error ?
Todos los campos son obligatorios
 : null }

        <form
            onSubmit={submitCita}
        >
            Nombre Mascota
            <input
                type="text"
                name="mascota"
                className="u-full-width"
                placeholder="Nombre Mascota"
                onChange={actualizarState}
                value={mascota}
            />

            Nombre Dueño
            <input
                type="text"
                name="propietario"
                className="u-full-width"
                placeholder="Nombre dueño de la mascota"
                onChange={actualizarState}
                value={propietario}
            />

            Fecha
            <input
                type="date"
                name="fecha"
                className="u-full-width"
                onChange={actualizarState}
                value={fecha}
            />

            Hora
            <input
                type="time"
                name="hora"
                className="u-full-width"
                placeholder="Nombre dueño de la mascota"
                onChange={actualizarState}
                value={hora}
            />

            Sintomas
            <textarea
                className="u-full-width"
                name="sintomas"
                onChange={actualizarState}
                value={sintomas}
            ></textarea>

            <button
                type="submit"
                className="u-full-width button-primary"
            >Agregar Cita</button>

        </form>
        </Fragment>
    )
}

export default Form;

A: It's hard to be sure what the problem might be without a proper sandbox (codesandbox for example).
But the error seems to indicate that you've gotten stuck in an infinite loop, which usually means the component is cause its own state dependencies to change, which causes a redraw (which again causes a change, etc.)
I'd start by moving
    // Eliminando el mensaje previo
    actualizarError(false);

into
    const actualizarState = e => {
        actualizarCita({
            ...cita,
            [e.target.name]: e.target.value
        })
    }

A: you can't update state out side function,
actualizarError(false);

you should remove this, otherwise infinite re-render


text:
Q: What is the meaning of the ? operator?
Possible Duplicate:
C# using the question mark after a type, for example: int? myVariable; what is this used for?

I saw the ? operator used in many places and tried to Google and StackOverflow it but both search engine exclude it from the query and does not return any good answers.
What is the meaning of this operator? I usually see it after the type declaration like:
int? x;
DateTime? t;

What is the difference between the two following declaration of an int for example:
int? x;
// AND
int x;

A: This operator is not an operator, but merely the syntactic sugar for a Nullable type:
int? x;

is the same as
Nullable<int> x;

A: You can read this : Nullable type -- Why we need Nullable types in programming language ?
int? x;//this defines nullable int x
x=null; //this is possible
// AND
int x; // this defines int variable
x=null;//this is not possible

A: It is not operator, but int? is shortcut for the Nullable<int>. Nullable<> is container that allows to set some value-type variable null value as well.

A: It called nullable types.

Nullable types are instances of the System.Nullable struct. A nullable
  type can represent the normal range of values for its underlying value
  type, plus an additional null value.

int? x;

is equivalent to
Nullable<int> x;

A: ? operator indicates the type is nullable.
For example;
int? x = null; //works properly since x is nullable

and
int x = null; //NOT possible since x is NOT nullable

Note that the way you access the value of the variable changes;
int? x = null;
int y = 0;
if (x.HasValue)
{
    y = x.Value; // OK
}

And
y = x; //not possible since there is no direct conversion between types.

A: Diffrence b/w int? and int is int? can store null but int can't.
int? is called nullable operators and its used basically when working with database entities.
more info -http://msdn.microsoft.com/en-us/library/1t3y8s4s(v=vs.80).aspx
hope this helps !!

A: That operator makes all objects that is non nullable to nullable.
So it means if you will declare a variable int? x, it could be assigned like this:
int? x = null. If without the ? sign, you cannot assign it with a null value.


text:
Q: Javascript: Parsing HTML table with Cheerio I am trying to develop a web scraper using Cheerio to parse an HTML table and output the results in a CSV file, unfortunately the code won't return anything. My code is the following:
var request = require("request");
var cheerio = require("cheerio");
var fs = require("fs");

var url = "https://stat.epa.gov.tw/";

request(url, function(err, response, html){
if(!err) {
    var $ = cheerio.load(html);
    var allitems = $('table.tableAQI').children().children();
    var items = []
    allitems.each(function(index){
        var result = $('table.tableAQI').children().children().eq(index).find("td").text();
        if(result !="") {
            items.push(result);
        }
    });
    fs.writeFile("output2.csv", JSON.stringify(items, null, 4), function(err){
        if(err) {
            console.log(err);
        } else {
            console.log("Data has been written");
        }
    });

    console.log(items);
}
});

The website provides 2 tables I tried the same code to parse the other table ('table.aqicolor') and it worked just fine so I am not really sure what is wrong.
I appreciate your support.


text:
Q: Gmail detecting mails as spam [Postfix] I am running an ispconfig web/mail server and the problem is that my mail ends up in spam at google. I have everything set up rDNS, DKIM, SPF, dmarc, so i dont think that the record part would be an issue. However my mail header contains at one place localhost that its a very bad practice how i heard cause google doesn't like it.
Delivered-To: privateacc@gmail.com
Received: by 2002:aed:2be7:0:0:0:0:0 with SMTP id e94-v6csp879456qtd;
        Tue, 26 Jun 2018 01:16:08 -0700 (PDT)
X-Google-Smtp-Source: AAOMgpdMXb1sd9e8+CGZm5UWsGVGV2G5So66uCWqVsQCptMdhHxphnQj2iyCHqJgHJhujlVRGeaa
X-Received: by 2002:a5d:4306:: with SMTP id h6-v6mr558073wrq.58.1530000968344;
        Tue, 26 Jun 2018 01:16:08 -0700 (PDT)
ARC-Seal: i=1; a=rsa-sha256; t=1530000968; cv=none;
        d=google.com; s=arc-20160816;
        b=MhBt1s06ETIYsikSsJkpxi0hyr4cCgI/+/4zE+vMSzV4Su4SHqkjtE968b45v9aUHR
         4F0OZZRwzm3BjPHBDjrg5FY55D49rQB+GUYwiNR6wmWRVx9Cjlfd9K3TpHMQlpWEx955
         5FAJ4dlhNGmYAdzZ8XWiRacbfQrR7YWeQHAqqCx6TbOMQ4N9SUS4oWY9OyBZ6Vcdyp0K
         M/1uSFUldLSjauIzMCu6binU6BN5q/6TNIC03FxyWhRE0xowszA4LgJD4UqQD64fKEoA
         txZ1QjXC+OASiWfL1R2lQS/zCBwMUq3qjMtrBGDdVTmsQdG0bqt2rLUv4pjajDJiXIM7
         U8fA==
ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816;
        h=content-language:mime-version:user-agent:date:message-id:subject
         :from:to:dkim-signature:arc-authentication-results;
        bh=f87H22OjvOAW9flgprGZogNpubh4T1X8JmegL8h3LxM=;
        b=dcZMOGTjiaxxHwav6FRyqLnRkmtqakBEEGGO0W7uy3Uq9UGdGJ4/BRpjGLg4Y4qbvl
         df79X6i51neY/G6X7eVBoKpiTkF+fIAYbRNJNembCbmDJfR0m4J/Ba6lsH6DJRNzaOSV
         EjJrXA22d0rdtiqLWAUXfwzBLXzZ7Hsu49/B0DMCulk4+WMbCI+Jqw5/lCnS7DV5FA/q
         9d9oMRPLWAvwc4/xPXsJWzgoYMyhQXYeGYFRDT+qM8P0eOf+tRDC3pkTT0JQL7f3uOLz
         SzjDH4ln3JjoN4WCwtC9aS332rpAmQuF/Q0qbztb3a4QRGQho1LYpzRkp0C5q6fowmY7
         C+yw==
ARC-Authentication-Results: i=1; mx.google.com;
       dkim=pass header.i=@example.com header.s=default header.b=MLJoQ6mi;
       spf=pass (google.com: domain of company@example.com designates YY.YY.YYY.YYY as permitted sender) smtp.mailfrom=company@example.com;
       dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=example.com
Return-Path: <company@example.com>
Received: from mail.example.com (mail.example.com. [YY.YY.YYY.YYY])
        by mx.google.com with ESMTPS id h18-v6si1173503wrr.20.2018.06.26.01.16.08
        for <privateacc@gmail.com>
        (version=TLS1_2 cipher=ECDHE-RSA-CHACHA20-POLY1305 bits=256/256);
        Tue, 26 Jun 2018 01:16:08 -0700 (PDT)
Received-SPF: pass (google.com: domain of company@example.com designates YY.YY.YYY.YYY as permitted sender) client-ip=YY.YY.YYY.YYY;
Authentication-Results: mx.google.com;
       dkim=pass header.i=@example.com header.s=default header.b=MLJoQ6mi;
       spf=pass (google.com: domain of company@example.com designates YY.YY.YYY.YYY as permitted sender) smtp.mailfrom=company@example.com;
       dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=example.com
Received: from localhost (localhost [127.0.0.1]) by mail.example.com (Postfix) with ESMTP id BC89B56406 for <privateacc@gmail.com>; Tue, 26 Jun 2018 10:16:07 +0200 (CEST)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=example.com; h= content-language:content-type:content-type:mime-version :user-agent:date:date:message-id:subject:subject:from:from; s= default; t=1530000966; x=1531815367; bh=y3K031cw5dXuKH6FKdvt0KZN 8YuBBixONrHJK24NlAM=; b=MLJoQ6mipg+fjabDpidFG5ysG7zhKhKO7+uJm55S 4IFiYv5s3zPgj0VfH/RW0D3Z9+AjbxnZ5Ed7KrFmq3wjBGQCbhnBhvT/yAAIGaTq sgLe5xdiSyUzKOfSD7Zu/vbBt9KCvIjeufgiRhp3THEZeOgoA8aA4Ftw7wbvYpBc RT4=
X-Virus-Scanned: Debian amavisd-new at mail.example.com
Received: from mail.example.com ([127.0.0.1]) by localhost (mail.example.com [127.0.0.1]) (amavisd-new, port 10026) with ESMTP id rxAAFvmoEOV3 for <privateacc@gmail.com>; Tue, 26 Jun 2018 10:16:06 +0200 (CEST)
Received: from [192.168.1.149] (unknown [XX.XXX.XXX.XXX]) (Authenticated sender: company@example.com) by mail.example.com (Postfix) with ESMTPSA id B46F75635F for <privateacc@gmail.com>; Tue, 26 Jun 2018 10:16:06 +0200 (CEST)
To: privateacc@gmail.com
From: Diogo Jesus <company@example.com>
Subject: test
Message-ID: <cc6d790a-8c7c-7751-6864-fe36962d9c1d@example.com>
Date: Tue, 26 Jun 2018 10:16:04 +0200
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Thunderbird/52.8.0
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="------------E56F9C1A6EEA50EAF52DC248"
Content-Language: fr
X-Antivirus: Avast (VPS 180625-4, 25/06/2018), Outbound message
X-Antivirus-Status: Clean

--------------E56F9C1A6EEA50EAF52DC248
Content-Type: text/plain; charset=utf-8; format=flowed
Content-Transfer-Encoding: 7bit

--------------E56F9C1A6EEA50EAF52DC248--

My question is, why am I still sending mail to spam on gmail?


text:
Q: JPA Embeddable bidirectional What's the correct way to create bidirectional 1to1 mapping using Embeddable annotation? This one throws error
"EmpId has no persistent id property: Emp.id"
@Entity
public class Per implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "per_id")
    private Long id;

    @OneToOne
    @JoinColumn(name = "per_id", referencedColumnName = "emp_id")
    private Emp emp;

}

@Embeddable
public class EmpId implements Serializable {
    private static final long serialVersionUID = 1L;

    @OneToOne(mappedBy = "emp")
    private Per per;

}

@Entity
public class Emp implements Serializable {
    @EmbeddedId
    private EmpId id;
}

I'd like to operate entities like
per.getEmp();
emp.getId().getPer();


text:
Q: Different line-height on iphone using font-face To vertically center my text in a box I use the same line-height as the height of the box. It works perfect on the iphone for system fonts.
But when I use @font-face I have to ad at least 3px to the line-height for the iphone or otherwise the text isn't vertically centered anymore (it's up or 3px).
Does anybody know why?

A: Have you tried adding to the CSS:
myel {
  -webkit-text-size-adjust: none;
}

A: SOLVED:
The Problem is that I was still on OS 3.1.3 on my 3G cause I made terrible experience on the perfomance using 4.2.
Whatever, updating to the latest OS 4.2 solves the line-height problem on fonts used with font-face in Mobile Safari.


text:
Q: How to decompose the component that is influenced by X from time-series Y? There is a time series Y, which is the remaining part of the initial time series after removing the trend and seasonal periodic components. And there is also a time series X, which represents the change of water level.
(The data file is here.)
I've read some papers, and they talk about time series decomposing trend, season component, and few talks about how the decompose the remaining part. Time series Y is influenced by X, so I think time series Y should contain the influence of X and some noise.
I've analyzed the Y is not white noise:

I have visualized X and Y respectively, and compared them after standardization.
In addition, I plotted a scatter figure of Y vs X and its standardized version.
But I did not find an obvious relationship.

Does anyone know how to decompose the influence of X on Y from time series Y?
Thanks!


text:
Q: File comparison / highlighting differences in asp.net We need to add a feature in our application which will allow user to compare two versions of files with differences highlighted. This feature has to similar to SVN. Is there any utility/API that we can use to achieve this functionality?

A: Our tool ECMerge is used by several websites that way to produce diff reports (typically by running the command line and applying your own XSLT or scripting the output directly as ECMerge uses Javascript 3rd edition as its scripting language and differences lists are available to scripting).
There is also an ActiveX which can be called directly from C#.


text:
Q: Listener of the NetInfo works just one time on react-native When the component is mount the NetInfo.isConnected.addEventListener works, but when I enter in another page and back to the first component, being that, I reset de stack of pages, the NetInfo.isConnected.addEventListener don't works
The Code


text:
Q: Image displayed partially if in drawable-xxhdpi I'm displaying an image through an ImageSwitcher with this factory:
    view_background.setFactory {
        val imageView = ImageView(this@MainActivity)
        imageView.scaleType = ImageView.ScaleType.CENTER_CROP
        imageView
    }

And I'm displaying correctly this 2341x1246 PNG 2.55 MB image on a Nexus 5 emulator:

However, if I use it on Nexus 6, it crashes:
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.llovagn.t4r, PID: 4693
    java.lang.RuntimeException: Canvas: trying to draw too large(142936136bytes) bitmap.

By putting it in drawable-xxhdpi as suggested in this answer, it now look like this on both devices:

Which I something that I don't really want (the first way is the correct one). Why and how can I solve this?

A:
2341x1246 PNG 2.55 MB
Canvas: trying to draw too large(142936136bytes) bitmap

This doesn't look like a good approach. Reduce the size of the image and put the image in the drawable directory.
It happens because you put the picture inside "drawable-xxhdpi". Take a look at the sizes in here.
However, after doing what I suggested, use FIT_XY to fit the image:
imageView.scaleType = ImageView.ScaleType.FIT_XY

You won't need 2.5 MB image in your application. That's pretty too much with that size.

A: To avoid this error try to use as small resolution of image as possible, also the image view should also be small, you could also get OOM on bigger and high res devices.
Best way would be to use a png image on a background view where background can be solid color or gradient. By this way you can use smaller images that might not need to fill the whole screen size.


text:
Q: Propose Merge 'post' And 'http-post' Tags On Stack Overflow On Stack Overflow, the post and http-post tags are used synonymously.  The 'post' tag wiki also describes that it's to be used to categorize HTTP POST questions.
Would someone with sufficient permission (more than 2500 reputation and a total answer score of 5 or more on the tag) suggest one of the tags as a synonym of the other, please?

A: I'd prefer to kill post as too generic a tag; although for web-focused developers, it will probably implicitly mean HTTP POST, it can also correctly refer to message-passing mechanisms.


text:
Q: rails + jquery comfirming delete then calling delete method I'm working with Rails and jquery. I have a link..
<%= link_to 'Delete Meeting', "/meetings/#{@meeting.id}", {:class => "delete_meeting"}, :method => :delete %>

The above link is in my meetings show page. The behavior i'm looking for is that when a user clicks on the delete link, I want it to delete the meeting and then redirect to the meetings/index page where the remaining meetings are listed. I also want to display a "Your meeting has been deleted notice" on the index page.
When the user clicks on the above link, I ask for confirmation after which I want to simply call the delete method in the meetings controller. I don't want to use AJAX though, since after deletion I want to be routed to the meetings_path. For all this I have the following jquery..
$(".delete_meeting").click(function(e){
  e.preventDefault();
  jConfirm('Are you sure you want to delete this meeting?', 'Confirm Delete', function(r) {
    if(r){
        // what does here? I want to call the link's href here
    }
    return false;
  });
})

..If the confirm returns true then I want to send the request to the controller's delete action. How can i achieve this? I don't think i should be using a window.location.href for this. Do I?

A: delete your jquery function, and add "redirect_to meetings_path" in destroy action


text:
Q: Sum of Product of Numbers taken two at a time So the question is
Find the Sum of Product taken two at a time of of numbers  $1,2,2^2,2^3...2^{n-2},2^{n-1}$
My approach was to create a double summation like this $y=\sum_{i=0}^{n-1}\sum_{j=0}^{n-1}2^i\cdot2^j$ but the answer comes out to be wrong.
What's wrong with my approach?
Edit:
My answer comes out to be $(2^{n-1}-1)^2$ however my book mentions the answer as $\frac{1}{3}2^{2n}-2^n-\frac{1}{3}$


text:
Q: How to correctly reference an object property in objective-c I'm doing some cleanup after my Xcode 4 migration and noticed a few warnings that I can't get corrected. In the example below I'm trying to build an dynamic url to get an image.
NSString* imgUrl = [NSString stringWithFormat:@"http://images.localhost.com/Image/%@", [selectedHat img]];

(selectedHat is an object with a @synth property "img" that is of type NSString)
The warning in Xcode is around how I get the img property from selectedHat
"method img not found (return type defaults to 'id')"
Obviously I'm not after a method (unless objective-c considers the getter on my property to be a method). This approach works fine, but I'm out to cleanup the warnings and understand how I should ask for the img property here going forward
Thank you in advance
Edit
The Hat interface looks something like the below
#import <Foundation/Foundation.h>

@interface Hat : NSObject {
  NSString* img;
}

@property (nonatomic, retain) NSString* img;

@end

A: You need to do two things. Not sure what your hat class is called, so lets call it Hat for this example:

*

*Make sure that the img property is declared in the Hat.h

*Make sure that you do #import "Hat.h" in any file calling this property.


text:
Q: how to copy latest file after finding the files with specified format Script
while read file
do
  find $FILE_PATH -type f -name "$file" -exec cp -f {} $FILE_LOC \;
  if [[ -e $FILE_LOC/"$file" ]];
  then
    echo file $file exist
  else
   echo $file not present
  fi
done <$INPUT_LIST

Content of $INPUT_LIST
DLY_202204*.dat
MNTH_202204*.dat

Problem I am facing, in $FILE_PATH I have:
DLY_20220415.dat
DLY_20220420.dat
MNTH_20220402.dat
MNTH_20220403.dat

Script is copying all 4 files but throwing:
DLY_202204*.dat not present
MNTH_202204*.dat not present

But I need o/p:
DLY_202204*.dat exist
MNTH_202204*.dat exist

Also, want to copy the latest files i.e. DLY_20220420.dat and MNTH_20220403.dat


text:
Q: Can't create image from tar.gz file in bucket I'm trying to create a custom image using Console or gcloud, i.e. (Note: URLs are masked with [naURL] to get around URL posting limitation.):

$ gcloud compute images create debian-9-1-v20170810-1 --source-uri=https:[naURL]//storage.googleapis.com/[my bucket]/compressed-image.tar.gz

The command runs for about half an hour (i.e. 1800s) and then gives the following error:

ERROR: (gcloud.compute.images.create) Could not fetch resource:
   - Did not create the following resources within 1800s: https:[naURL]//www.googleapis.com/compute/v1/projects/spherical-proxy-175708/global/images/debian-9-1-v20170810-1. These operations may still be underway remotely and may still succeed; use gcloud list and describe commands or https:[naURL]//console.developers.google.com/ to check resource state

The corresponding REST record accessible via Console>Compute Engine>Operations for the item reads:
{
  "kind": "compute#operation",
  "id": "5371669110648613089",
  "name": "operation-1502320142020-5565a2a676da1-06d76920-4c86568d",
  "operationType": "insert",
  "targetLink": "https:[naURL]//www.googleapis.com/compute/v1/projects/spherical-proxy-175708/global/images/debian-9-1-v20170810-1",
  "targetId": "3098231522309056737",
  "status": "DONE",
  "user": "andree.leidenfrost@gmail.com",
  "progress": 100,
  "insertTime": "2017-08-09T16:09:02.501-07:00",
  "startTime": "2017-08-09T16:09:03.136-07:00",
  "endTime": "2017-08-09T16:59:29.128-07:00",
  "error": {
             "errors": [
               {
                 "code": "INTERNAL_ERROR",
                 "message": "Code: '8625676013601614622'"
               }
             ]
           },
  "httpErrorStatusCode": 503,
  "httpErrorMessage": "SERVICE UNAVAILABLE",
  "selfLink": "https:[naURL]//www.googleapis.com/compute/v1/projects/spherical-proxy-175708/global/operations/operation-1502320142020-5565a2a676da1-06d76920-4c86568d"
}

Because the HTTP error is 503 "SERVICE UNAVAILABLE" I've tried a few times over the last couple of days but the problem persists.
I'm trying to follow the instructions in document Importing Boot Disk Images to Compute Engine.
Any help or hints how to debug further would be greatly appreciated!


text:
Q: Update error in my Products table after creating AFTER UPDATE trigger I had inserted a simple Procedure (_ControlProduct) and it is working fine in SQL
I am calling it from the AFTER UPDATE trigger in Products Table but then I am having this error

ERROR 1109: 1109: Unknown table 'Products' in field list

SQL Statement:
UPDATE `lakcom_NewDB`.`Products`
   SET `SuppCat_id` = '2'
 WHERE (`Product_id` = '43')

my trigger is:
CREATE TRIGGER `lakcom_NewDB`.`Products_AFTER_UPDATE`
    AFTER UPDATE ON `Products`
    FOR EACH ROW
        BEGIN
            call _controlproduct(Products.Product_id);
        END

my _ControlProduct is:
CREATE  PROCEDURE `_ControlProduct`(Product int)
BEGIN
update Basket
    set Basket.ToControl = 1
where Basket.Product_id=Product
and Basket.id<>0;
END

A: This is equivalent to your code attempt
CREATE TRIGGER `lakcom_NewDB`.`Products_AFTER_UPDATE`
    AFTER UPDATE ON `Products`
    FOR EACH ROW
        BEGIN
            update Basket
              set Basket.ToControl = 1
              where Basket.Product_id=new.product_id
              and Basket.id<>0;
        END

Sample data and expected outcome would be helpful(to you)


text:
Q: How to identify errors from casting a column? I have a table that is all NVARCHAR. I am trying to cast a column into a date; however, there appears to be some value in the column that will not cast as date and is throwing an error halfway through.
I am trying to find the rows that are problematic. However, I don't know how to equal a result to an error..
SELECT id,
CASE WHEN CAST(date_of_birth AS DATE) = error
     THEN 1
     ELSE 0
FROM TABLE1

Table1
id    date_of_birth
1     05/05/1934
2     feathers
3     06/06/1843

Expected results
id    date_of_birth
1     0
2     1
3     0

Any advice on how to isolate the problematic rows?

A: Use TRY_CAST():
SELECT id,
       (CASE WHEN TRY_CAST(date_of_birth AS DATE) IS NULL AND date_of_birth IS NOT NULL
             THEN 1
             ELSE 0
        END) as is_bad_date_of_birth
FROM TABLE1;

A: To identify error rows, use the ISDATE function:
SELECT * FROM TABLE WHERE ISDATE(date_of_birth)=0


text:
Q: Find best match with Mongo ODM I would like to find the best match with a mongo odm query on Symfony. I have a function that search for objects with an array of terms.
Here an exemple :
I want to search all the users that are nammed 'Paul', 'Peter' and 'Smith'.
So my array $search = array('Paul', 'Peter', 'Smith');
I have 3 users who match this request :

*

*Peter Anderson

*Paul Smith

*Paul Peter Smith

So I would like that this request order the users like this :

*

*Paul Peter Smith

*Paul Smith

*Peter Anderson

Here my current method :
    public function search($search) {
    $query = $this->createQueryBuilder('AcmeDataBundle:users');
    $users = $query
        ->field('name')->in($search)
        ->getQuery()->execute();

    return $users;
}

Do you have any clue on how I can do that ?
Thanks

A: Lets forget about php and see how we can achieve that with MongoDB itself (using js) first.
when you want to have "text search" functionality, you have to create a TEXT INDEX on the field you want to search on. source
that can be achieved by:
db.yourCollectionName.createIndex({ fieldName: "text" })
After this, whenever you do text-searching, you will have some meta data related to your query, which contains some scores that MongoDB generates based on the relevancy of results against keywords.
So, because you want to have most accurate result first, we should only sort by that scores.
In your case, it will be:
db.User.createIndex( { name: "text" } )

db.User.find(
    {$text:{$search:"Paul Smith Peter"}},
    { score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } );

Okay. This will give you what you want. but let convert it to Doctrine query style.
For the index:
/**
 * @ODM\Document
 * @ODM\Indexes({
 *   @ODM\Index(keys={"name"="text"})
 * })
 */
class User{
    /** @ODM\String */
    private $name;

    //...
}

Then run this command to ensure scheme and the index are created:
php app/console doctrine:mongodb:schema:create
and final part:
$search = ['Paul', 'Peter', 'Smith'];

$names = implode(' ', $search);

$queryBuilder = $documentManager->createQueryBuilder('User');

$expr = $queryBuilder->expr()->operator('$text', array('$search' => $names));

$result = $queryBuilder
            ->equals($expr->getQuery())
            ->sortMeta('score', 'textScore')
            ->getQuery();

foreach ($result as $user) {
    var_dump($user);
}


text:
Q: A positive definite matrix A can be express as a polynomial of $ A^2 $ I have recently come across this question in my studies of matrix theory stating :

If A is a real symmetric positive definite matrix, we are asked to show it can be expressed as a polynomial of $ A^2 $

I thought about using the Cayley-Hamilton theorem via the characteristic polynomial, by I cannot guarantee only even powers of A in this matrix equation, so I am stuck and require help here. I thank all helpers.

A: This has little to do with Cayley-Hamilton theorem. You only need to find a polynomial $p$ such that $p(\lambda_i^2)=\lambda_i$ over a set of distinct positive numbers $\lambda_1,\lambda_2,\ldots,\lambda_k$.

A: Suppose $\lambda_i\geq 0$ are the distinct eigenvalues of $A$
and let $e_i(x)=\prod_{j\neq i}(x-\lambda_j^2)/\prod_{j\neq i}(\lambda_i^2-\lambda_j^2)$. Then $e_i(A^2)$ is a projection onto the eigenspace associated with $\lambda_i^2$ (of $A^2$), whence with $\lambda_i$ (of $A$). Then
$$ A=\sum_i \lambda_i e_i(A^2)$$
If I am not mistaking one only need $A$ diagonalizable and the $\lambda_i^2$'s being distinct.


text:
Q: Conceptual explanation of Optical Tweezers I have been trying to get my head around Optical Tweezers and why they work.
I understand it as that light rays holds the particle in place since if the particle moves, it changes the profile of the light an hence its momentum. Because of the conservation of momentum a resorting force would be exerted on the particle. That is, it is the geometry of the rays that lies behind the restoring force.
However, according to the Wikipedia article it can also be explained as the light acting as a non-homogeneous electric field. Particles that become dipoles under varying electric fields are held into place by the electric force.
I am not sure how to consolidate these two different explanations.
To what extent does it matter if the particle under study is dielectric?

Dielectric objects are attracted to the center of the beam, slightly
  above the beam waist, as described in the text. The force applied on
  the object depends linearly on its displacement from the trap center
  just as with a simple spring system. Note that in contrast to what is
  shown in the figure, the force is equal to $$-k_{trap} x$$ (Wikipedia).


text:
Q: New GDR3 "close button" doesn't terminate the app? So I was debugging my app on my phone with Visual Studio attached. I've decided to close the app using the new close button introduced in GDR3. At this point the app has disappeared from the screen and quick switch, but Visual Studio was still attached.
Does that mean that the new close button doesn't actually close the app? What does it do then? Tombstoning it?

A: The application is killed. Visual Studio stays attached to help you debug background tasks, if any, and alternative ways of starting your app (through a pinned tile for instance). The same thing happens when you exit the app "normally" by pressing the back button multiple times.


text:
Q: How do I programmatically bring a label on top of a blurred effect view How do I programmatically bring a label to the front of a blurred effect view which was added programmatically?
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->
        UITableViewCell {

        println("celler \(indexPath.row)")

        var cell:MainViewTableViewCell = self.mainTableView.dequeueReusableCellWithIdentifier("mainTableViewCell", forIndexPath:indexPath) as MainViewTableViewCell

        cell.mainTableViewCellTitle?.text = feedRow.title <<<<<<<< this on top of blurred

        var url =  String(format: "http://localhost:5000/%@")
        let data = NSData(contentsOfURL:NSURL(string: url)!)

        var image = UIImage(data:data!)

        cell.mainTableViewCellBackgroundImage.image = image

        var effect = UIBlurEffect(style: .Light)

        var effectView = UIVisualEffectView(effect: effect)

        var height_of_header = (cell.bounds.height*0.2)
        var y_position = (cell.bounds.height-height_of_header)
        effectView.frame = CGRect(x: 0,y: y_position ,width: cell.bounds.width,height:height_of_header)
        cell.addSubview(effectView)

        cell.mainTableViewCellBackgroundImage.layer.masksToBounds = true
}

The label was created using a storyboard. I'm not sure if I am able to mix and match like this for swift.
cell.mainTableViewCellTitle?.text <<<< This is the label which I want to bring in front.
Thanks in advance!


text:
Q: Handle auction time between users in different timezone I have implemented my own script for auctions. But my problem is how to handle time.
Right now all auctions are based on UTC time, so whatever user's timezone is when he/she comes to site auction will start and end at the same time(UTC). I used date_default_timezone_set('UTC') to set default timezone throughout whole site.
But I guess that might be little bit confusing for users. Did anyone have similar problem and what could be the best solution for it.

A: I created a family website (family around the world).
All dates were stored with timestamp (which is UTC-timezone independent).
When a member created an account, he/she had to enter the country he/she was living it (as the PHP timezone guess is not reliable).
From that, I stored the name of the timezone of his /her country (https://php.net/manual/en/timezones.php).
When the member logs in, I PHP-set the timezone to his/her country to display dates with his/her timezone.


text:
Q: OpenTK - How to rotate a 2D object I'm trying to rotate 2D objects in my OpenTK project.
What's happening is that the objects after the rotated object are rotating and I don't want them to do that.
How do I reset the rotation after I've already rotated one object?
      protected override void OnRenderFrame(FrameEventArgs e)
       {
           GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
           GL.MatrixMode(MatrixMode.Projection);
           GL.LoadIdentity();
           GL.Ortho(0, game.Width, game.Height, 0, -1, 4);

           GL.MatrixMode(MatrixMode.Modelview);
           GL.LoadIdentity();

          drawObject();
          GL.Rotate(180, Vector3d.UnitZ);
          drawObject(); // Object I want to rotate
          GL.Rotate(-180, Vector3d.UnitZ);
          drawObject(); // I don't want this object to be rotated, but it does. How do I fix this?
}

Thanks!

A: In the fixed function pipeline, Rotate operations are not appended. Instead the second one is replacing the first one (as long as there is no PushMatrix operation inbetween). So what you are currently drawing is the first object rotated around 180 degree and the second object around -180 degree.
Back to your question: If you replace the second call to Rotate with LoadIdentity, the current modelmatrix is resetted to an identity matrix, removing all transformations.
drawObject();
GL.Rotate(180, Vector3d.UnitZ);
drawObject();
GL.LoadIdentity();
drawObject();

Note: All transformations are resetted here, if you want to keep translation and scaling you can try GL.Rotate(0, Vector3d.UnitZ);


text:
Q: Tabelas POO em Lua! Gostaria de saber porque não está retornando uma tabela no código que eu fiz:
TP = {}
function TP:new(pos, newpos, effect)
    return setmetatable({pos = pos, newpos = newpos, effect = effect}, { __index = self })
end
function TP:setNewPos(position)
    self.newpos = position
end
function TP:setEffect(efeito)
    self.effect = efeito
end

var = TP:new({x = 160, y = 54, z = 7}, {x = 180, y = 60, z = 7}, 10)
print("is "..var.newpos) -- era para retornar uma tabela.

A: Os valores não são retornados porque você está tentando concatenar um objeto table com uma string usando o operador .., para imprimir os valores da tabela, faça:
var = TP:new({x = 160, y = 54, z = 7}, {x = 180, y = 60, z = 7}, 10)

print ("is")
for chave, valor in pairs(var.newpos) do
  print (chave, valor)
end

Ver demonstração
Alternativamente você pode criar uma função e retornar a tabela:
function TP:getNewPos()
    return self.newpos
end

Para utilizá-la, faça assim:
var = TP:new({x = 160, y = 54, z = 7}, {x = 180, y = 60, z = 7}, 10)
newpos = var:getNewPos()

print ("is")
for chave, valor in pairs(newpos) do
    print (chave, valor)
end

Ver demonstração

A: O problema ai é que tu ta tentando concatenar uma string com uma tabela, e que define o metamétodo que vai ser chamado é o primeiro operador. Felizmente pro caso de strings, tem como fazer uma implementação nesses metamétodos que vai funcionar para o que tu pretendia ai.
-- captura a metatable de string
local mt = getmetatable("")

-- faz override no metametodo __concat
mt.__concat = function(a, b)
  if type(a) == "string" and type(b) == "table" then
    local at = {}
    for k, v in pairs(b) do
      table.insert(at, k .. " = " .. v)
    end

    return a .. " {" .. table.concat(at, ", ") .. "}"
  end

  return a .. b
end

-- com o metametodo sobreposto
-- agora quando chamar o operador .. que é o operador de concatenação
-- a sua função costomizada será chamada no lugar da padrão
print("is:" .. {x=2, y = 2, z = 3})


text:
Q: cuda streams: callback not getting called after stream execution I am having trouble with the cuda streams callback function. The problem is that it does not execute after the kernel is run. I am encapsulating the cuda streams in a C++ class as follows:
class Stream
{
public:
    Stream();
    void run(float *input, int points);
    ~Stream();
    static void CUDART_CB callback(cudaStream_t stream,
                                   cudaError_t status,
                                   void * user_data);

private:
    void callback_function();

    cudaStream_t s;

};

Now, I have the callback function setup as suggested before as follows:
void CUDART_CB StreamWorkflow::callback(cudaStream_t stream,
                                    cudaError_t status,
                                    void * user_data)
{
    Stream* thiz = (Stream *)(user_data);
    thiz->callback_function();
}

And the constructor sets up the stream and attaches the callback
Stream::Stream()
{
    checkCudaErrors(cudaStreamCreate(&s));
    checkCudaErrors(cudaStreamAddCallback(s, Stream::callback, this, 0));
}

Now the run method calls the cuda kernel on this stream and I know this executes fine. It is implemented like:
void Stream::run(float *f, int p)
{
    dim3 block(16, 16);
    dim3 grid((int)ceil(double(p) / 256.0));
    my_kernel(f, p, grid, block, s);
    checkCudaErrors(cudaDeviceSynchronize());
    getLastCudaError("kernel launch failed");
}

My problem is that the callback only gets called when the constructor gets executed. So, as soon as the object is created the callback_function() gets executed through the registered callback(). The kernel gets executed multiple times by the host and it never executes the callback function when it is finished. I can see the kernel is executed successfully but the callback never comes.
Do I have to register the callback everytime the kernel is run (so register this callback before executing the run function) or am I doing something really wrong here?

A: I think you're probably confused about how callbacks work.    In general, when you issue a CUDA operation to a CUDA stream, that CUDA operation is executed when all preceding CUDA activity issued to that stream has been completed (and before any subsequent activity issued to that stream is begun).
callbacks are no different.  If you want a call back to execute after a kernel has executed, then you must issue that callback to that stream after you issue the kernel.  The definition of the add callback function is not:

"any time a kernel completes in this stream, run this callback"

The definition of the add callback function is:

"when the CUDA stream has completed all CUDA activity up to this point, then execute the callback"

or, quoting directly from the documentation:

The function to call once preceding stream operations are complete

Therefore this constructor makes no sense to me:
Stream::Stream()
{
    checkCudaErrors(cudaStreamCreate(&s));
    checkCudaErrors(cudaStreamAddCallback(s, Stream::callback, this, 0));
}

This constructor says:
"create a CUDA stream"
"when all previously issued activity to this stream is complete, run this callback"
But of course, you haven't issued any activity to that stream, so the callback runs immediately, (and only once,) right after stream creation.

"so register this callback before executing the run function"

No, if this is what you want:

The problem is that it does not execute after the kernel is run

then move your add callback function to after your kernel launch, and I think you're more likely to see the activity you want.


text:
Q: What is the difference between the different scroll options? I have tried a few ways of adding scrolling to tables, but just one of them works correctly. What is the different between them?
First:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView();", Element);

Second:
WebElement element1 = driver.findElement(By.id("scrolled_element"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element1);

Third:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,1000)");

Fourth:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");

A: Element.scrollIntoView()
Element.scrollIntoView() method scrolls the element on which it's called into the Viewport of the browser window.

*

*Syntax:

*

*element.scrollIntoView()

*element.scrollIntoView(alignToTop) // Boolean parameter

*element.scrollIntoView(scrollIntoViewOptions) // Object parameter

*Your usecases:

*

*executeScript("arguments[0].scrollIntoView();", Element): This line of code will scroll the element into the visible area of the browser window.

*executeScript("arguments[0].scrollIntoView(true);", element1): This line of code will scroll the element to be aligned to the top of the Viewport of the scrollable ancestor. This option corresponds to scrollIntoViewOptions: {block: "start", inline: "nearest"}. Basically, this is the default value.

*executeScript("arguments[0].scrollIntoView(false)", element1);: This line of code will scroll the element to be aligned to the bottom of the Viewport of the scrollable ancestor. This option corresponds to scrollIntoViewOptions: {block: "end", inline: "nearest"}.

Window.scrollBy()
window.scrollBy() method scrolls the document in the current window by the given amount.

*

*Syntax:

*

*window.scrollBy(x-coord, y-coord)

*window.scrollBy(options)

*Parameters:

*

*x-coord is the horizontal pixel value that you want to scroll by.

*y-coord is the vertical pixel value that you want to scroll by.

*options is a ScrollToOptions dictionary.

*Your usecase:

*

*executeScript("window.scrollBy(0,1000)"): This line of code will scroll the document in the window down by 0 horizontal pixels and 1000 vertical pixels that you want to scroll by.

Window.scrollTo()
Window.scrollTo() method scrolls to a particular set of coordinates in the document.

*

*Syntax:

*

*window.scrollTo(x-coord, y-coord)

*window.scrollTo(options)

*Parameters:

*

*x-coord is the pixel along the horizontal axis of the document that you want displayed in the upper left.

*y-coord is the pixel along the vertical axis of the document that you want displayed in the upper left.

*options is a ScrollToOptions dictionary.

*Your usecase:

*

*executeScript("window.scrollTo(0, document.body.scrollHeight)"): This line of code will scroll the document in the window down to the bottom of the page.

A: I'll put the relevant documentation below each example so that you can refer to it yourself, and give some of my very humble opinions:

.scrollIntoView() vs .scrollIntoView(true)
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
There shouldn't be a difference since the documentation states that by default, .scrollIntoView() actually has a default value of true.

.scrollBy()
https://www.w3schools.com/jsref/met_win_scrollby.asp
Scrolls the document by the indicated pixels. Meaning if your top left viewport is at (10,10), doing a .scrollby(5,6) means the viewport will, after shifting, be at a pixel coordinate of (15,16).

.scrollTo()
https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo
Does what it suggests -- i.e. scrolls to the coordinates you have provided. This is different to scroll by (i.e. above example). This means that .scrollTo(1,1) will scroll the document so that your top-left viewport is now at a pixel coordinate of (1,1), regardless of what it was before.

To your separate question of what are the total scroll options -- well, there's also window.scroll(), but based on the below SO article there shouldn't be any difference to scrollTo():
JavaScript window.scroll vs. window.scrollTo?


text:
Q: Animation code doesnt animate? I have a view with which I have a button calling the following method. The view hides/shows but without any animation
- (void) displayEvent:(id)sender {

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:2.5];
    modal.hidden = !modal.hidden;
    [UIView commitAnimations];
}

Any ideas?

A: There's no states in between hidden and non-hidden. How to animate?
To have the fade-in effect you should modify the alpha property.
- (void) displayEvent:(id)sender {
    BOOL wasHidden = modal.hidden;
    modal.hidden = ! wasHidden;
    modal.alpha = ! wasHidden; // wasHidden ? 0 : 1;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:2.5];
    modal.alpha = wasHidden; // wasHidden ? 1 : 0;
    [UIView commitAnimations];
}


text:
Q: Store large amount of data to Database using Spring Batch
*

*I'm having large amount of data to verify. Then setting in an object and
finally save in database one by one. So it's consuming much time. I'm
planning to use Spring Batch to store that large amount of data
after processing in a single shot. By this I can eliminate the time
taking to talk with db each time.

*Can I store the whole data in a list and store with Spring batch
or there is any other way?
Please help me with any example.

*Coading Language - Java - struts

*Database - MySql Server

A:
Store large amount of data
Can I store the whole data in a list

If your "large amount" of data fits in memory then you can do that. But I'm not sure this is the way to go if your data is big enough and would not fit in memory.
The idea of chunk oriented processing in Spring Batch is to not load the whole data set in memory but to load it in chunks. This model is robust and can handle any amount of input data with a low memory footprint (only the chunk size items are loaded in memory).


text:
Q: Writing nested associations From an Organization table two other tables are hanging with belongs_to and has_many associations, they both have that organization_id key.

So for eager loading I wrote this:
@organization = Organization.includes(:population_summaries, :key_performance_inds).find(params[:id])

This should work.
But now I have a third table to include in there. key_performance_interval  which has that kpi_id field that is used as foreign key to point to key_performance_int table. I can't get that part to write and add to my eager loading section.  How should I add that one?

A: To included nested associations, you write it as a hash:
@organization = Organization.includes([:population_summaries, key_performance_inds:  :key_performance_interval]).find(params[:id])

You can read about it on this rails guide under section 12.1.2


text:
Q: Rails comments and username won't show up in post views / undefined method `user' for nil:NilClass So I have a post.rb model where I can display who wrote the post in the show post view, and that works wonderfully.
However, I've been trying to add comments, which belong to a post, and also belong to a user.
I can't seem to get all the comments or the names of the users who posted the coments to show up in the post show.html.erb.
I guess my question is, how do I integrate controller and model information in between controller and model views? I know if it exists in the model and controller and view of the same type, it is accessible, but cross-linking or sharing controller model information is hard for me.
I want to be able to display the user that made the comment, along with the body of the comment in the show view of the post, and not the comment.
comment.rb
class Comment < ApplicationRecord
  belongs_to :post
  belongs_to :user
  validates :body, :presence => true
end

post.rb
class Post < ApplicationRecord
  belongs_to :user, optional: true
  validates :user, presence: true;

  validates :title, presence: true,
                    length: { minimum: 5}

  extend FriendlyId
  friendly_id :title, use: :slugged
  validates :title, :slug, presence: true

  # comments
  has_many :comments

end

user.rb
class User < ApplicationRecord
  has_many :posts, dependent: :destroy
  has_many :comments, dependent: :destroy
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  validates :first_name, presence: true
  validates :last_name, presence: true
  validates :school_name, presence: true, inclusion: { in: %w(Harvard Yale),
    message: "%{value} is not a valid choice" }

  validates :graduation_year, presence: true, inclusion: { in: %w(2017 2018 2019 2020 2021 2022 2023),
    message: "%{value} is not a valid choice currently" }

    def superadmin?
      self.role.name == "Superadmin"
    end

end

comments_controller.rb
class CommentsController < ApplicationController
before_action :authenticate_user!
# GET /posts/:post_id/comments
# GET /posts/:post_id/comments.xml

def index
#1st you retrieve the post thanks to params[:post_id]
post = Post.friendly.find(params[:post_id])
#2nd you get all the comments of this post
@comments = post.comments

respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @comments }
end
 end

 # GET /posts/:post_id/comments/:id
 # GET /comments/:id.xml
 def show
 #1st you retrieve the post thanks to params[:post_id]
 post = Post.friendly.find(params[:post_id])
 #2nd you retrieve the comment thanks to params[:id]
 @comment = post.comments.find(params[:id])

respond_to do |format|
  format.html # show.html.erb
  format.xml  { render :xml => @comment }
end
end

# GET /posts/:post_id/comments/new
# GET /posts/:post_id/comments/new.xml
def new
#1st you retrieve the post thanks to params[:post_id]
post = Post.friendly.find(params[:post_id])
#2nd you build a new one
@comment = post.comments.new(params[:comment])
@comment.user = current_user

end

# GET /posts/:post_id/comments/:id/edit
def edit
#1st you retrieve the post thanks to params[:post_id]
post = Post.friendly.find(params[:post_id])
#2nd you retrieve the comment thanks to params[:id]
@comment = post.comments.find(comment_params[:id])
end

# POST /posts/:post_id/comments
# POST /posts/:post_id/comments.xml
def create
#1st you retrieve the post thanks to params[:post_id]
post = Post.friendly.find(params[:post_id])
#2nd you create the comment with arguments in params[:comment]
@comment = post.comments.create(comment_params)
@comment.user = current_user

respond_to do |format|
  if @comment.save
    #1st argument of redirect_to is an array, in order to build the correct route to the nested resource comment
    format.html { redirect_to([@comment.post, @comment], :notice => 'Comment was successfully created.') }
    #the key :location is associated to an array in order to build the correct route to the nested resource comment
    format.xml  { render :xml => @comment, :status => :created, :location => [@comment.post, @comment] }
  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @comment.errors, :status => :unprocessable_entity }
  end
end
end

A: In the show method of your post_controller, you'll need to do something like:
def show
  @post = Post.find_by(id: params[:id]) # or however you find your post
  ....
end

Then, in your views/posts/_show.html.erb (if you're using erb), you'll do something like:
<% @post.comments.each do |comment| %>
  ... show some comment stuff
  <%= comment.user.name %>
<% end %>


text:
Q: How to determine the clients .NET framework version in a web application? I need to determine the clients .NET framework version in my web application. I'm running in partial trust so I can not read the filesystem or registry (Is there an easy way to check .net framework verison using C#?).

*

*System.Environment.Version returns the runtime version, so I can not use that.

*I cannot use javascript
The only way I can think of at the moment is to try to load a .NET 3.5 dll and catch an exception, but this does not sound very nice.
Any suggestions?
Update:
Request.Browser.ClrVersion and Request.Browser.GetClrVersions() will return the .NET framework version(s) installed on the client.

A: You can use the Request.Browser.ClrVersion property to get the client's highest .NET version and Request.Browser.GetClrVersions() method to get all the installed .NET versions.
These methods simply parse the Request.ServerVariables("HTTP_USER_AGENT") server variable.
But please note that a browser (or user or hacker) may put anything he wishes in the string, so you won't have 100% accuracy.

A: I think you should do something like the following msdn article suggests. It uses java script to do the detection of .NET Framework.

A: One way could be to get the referenced assemblies list from current assembly. And then look for mscorlib.dll (or any other .net assembly that you are sure is loaded) and get the version of that assembly. This way you would know the version of framework installed.
try this code:
Version version = null;
AssemblyName[] names = Assembly.GetExecutingAssembly().GetReferencedAssemblies();
foreach (AssemblyName name in names)
{
      if (name.Name == "mscorlib")
      {
            version = name.Version;
      }
}

This all depends on the availability of the assembly that you choose to get the version from.
Or have a look at this CodeProject article. In this article he/she gives reference to another article by Junfeng Zhang which uses unmanaged code to determine CLR version.

A: I use the following class, called directly from the Main() method entry point, and then have the choice to inform user through MessageBox or Console.WriteLine. This code is based on the fact that:

*

*The class System.Linq.Enumerable appeared with .NET v3.5

*This class is declared in the assembly System.Core.dll that also appeared with .NET v3.5

*The exception FileNotFoundException is thrown when an assembly is no found.

static class DotNetFx35Checker {
   [MethodImpl(MethodImplOptions.NoInlining)]
   internal static bool IsDotNetFx35Available(out string failureReason, out string productName) {
      productName = "MyProductName";
      try {
         TestLinqAvailable();
         failureReason = null;
         return true;
      } catch (System.IO.FileNotFoundException) {
         var productVersion = Assembly.GetExecutingAssembly().GetName().Version;
         var productNameAndVersion = productName + " v" + productVersion.Major + "." + productVersion.Minor;
         failureReason = "To run " + productNameAndVersion + ", please download and install .NET Fx v3.5 or upper version.";
         return false;
      }
   }
   [MethodImpl(MethodImplOptions.NoInlining)]
   private static void TestLinqAvailable() {
      var i = System.Linq.Enumerable.Count(new int[] { 1 });
   }
}

A: You can use the browser's network tab. Load any page off the application and then in the network tab, choose any request made to server. Then in the Headers => Response Headers section of the request, you can see the X-AspNet-Version:


text:
Q: SQL Server: how to acquire exclusive lock to prevent race condition? I have the following T-SQL code:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRANSACTION T1_Test

    /*This is a dummy table used for "locking"
    and it doesn't contain any meaningful data.*/
    UPDATE lockTable
        SET ID = 1
        WHERE ID = 1

    DECLARE @Count TINYINT

    SELECT @Count = COUNT(*)
    FROM debugSP

    WAITFOR DELAY '00:00:5';

    INSERT INTO debugSP
        (DateCreated, ClientId, Result)
    SELECT
        GETDATE(), @@SPID, @Count

COMMIT TRANSACTION T1_Test

I am using "locking" hack marked with comment to acquire the exclusive lock.
NOTE: using TABLOCKX or UPDLOCK hints will not work because I have broken ATOMIC-ity by splitting statements and adding WAITFOR command in the middle for testing purposes.
I don't want something like that:
INSERT INTO debugSP (DateCreated, ClientId, Result)
SELECT GETDATE(), @@SPID, COUNT(*)
FROM debugSP

This is the correct result after running two simultaneous sessions (with lock table)
Id DateCreated           ClientId Result
-- ----------------------- -------- ------
 1 2011-03-17 15:52:12.287       66      0
 2 2011-03-17 15:52:24.534       68      1

and that is the incorrect result of running the code with lock commented out
Id DateCreated           ClientId Result
-- ----------------------- -------- ------
 1 2011-03-17 15:52:43.128       66      0
 2 2011-03-17 15:52:46.341       68      0

Is there a better way of acquiring transaction-wide exclusive lock without such hacks?

A: I'm not exactly sure what you are trying to do from the posted code. I presume you are just trying to serialize access to that piece of code? If so sp_getapplock should do what you need instead of creating a new dummy table that you just use to take locks on.
Details here

A: You can use the locking hint WITH(XLOCK, ROWLOCK) within the scope of a transaction with Repeatable Read isolation. At Serializable isolation the exclusive lock is obtained by default on a read operation, so if you needed a particular transaction to play nice in parallel, you could specify an increased serialization level for that one transaction when creating it (which you are doing; this isn't a hack, just the way things are done depending on the situation).


text:
Q: How do i solve this "Run-Time Error '-2147023706 (800704a6)"? i have a big problem with this code:
Sub EstrazDati_A_ieri()

Dim doc As HTMLDocument
Dim output As Object

Set IE = New InternetExplorer
IE.Visible = False
IE.navigate Range("D2")

Do
    DoEvents
    Loop Until IE.readyState = READYSTATE_COMPLETE

Set doc = IE.document
Set output = doc.getElementsByTagName("a")

For Each link In output
    If link.innerHTML = "Main" Then
        Range("D3").Value2 = link
    End If

Next
IE.Quit

End Sub

The code is correct and it works, but sometimes after a continuous use of itself a Windows box appear with a Run-Time Error on this line:
Set IE = New InternetExplorer

I have already tested several solutions found on the internet but i couldn't fix it.
p.s. I'm an Italian boy sorry for the bad English :)

A: I found this solution on the internet and it works by the moment, do you think is it right?
Sub EstrazDati_A_ieri()
On Error Resume Next

Dim doc As HTMLDocument
Dim output As Object

Set IE = New InternetExplorer
IE.Visible = False
IE.navigate Range("D2")

Do
    DoEvents
    Loop Until IE.readyState = READYSTATE_COMPLETE

Set doc = IE.document
Set output = doc.getElementsByTagName("a")

For Each link In output
    If link.innerHTML = "Main" Then
        Range("D3").Value2 = link
    End If

Next
IE.Quit
Set IE = Nothing
End Sub

EDIT : Now i've tried in this way
Sub EstrazDati_A_ieri()
Dim IE As Object
Dim doc As HTMLDocument
Dim output As Object

Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = False
IE.navigate Range("D2")

Do
    DoEvents
    Loop Until IE.readyState = READYSTATE_COMPLETE

Set doc = IE.document
Set output = doc.getElementsByTagName("a")

For Each link In output
    If link.innerHTML = "Main" Then
        Range("D3").Value2 = link
    End If

Next
IE.Quit
Set IE = Nothing
End Sub

But after the eighth run of these macro's ERROR :(

A: Sub EstrazDati_A_ieri()
Dim IE As Object
Dim doc As HTMLDocument
Dim output As Object

Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.navigate Range("D2")

Do
    DoEvents
    Loop Until IE.readyState = READYSTATE_COMPLETE

Set doc = IE.document
Set output = doc.getElementsByTagName("a")

For Each link In output
    If link.innerHTML = "Main" Then
        Range("D3").Value2 = link
    End If

Next

End Sub

Ok Guys! in this way no error. The problem is just that i would not open up a new web page every time but i would used the same, because i have to run this macro repeatedly for 12 times.
How can i modify this line of code?
Set IE = CreateObject("InternetExplorer.Application")