text:
Q: How do I point my browser to a specific NIC on my machine I am on a local area network that has no external access to the internet.  However I have been tasked to find a way to allow certain machines to access the web (HTTP, HTTPS, etc) via a wireless card on their laptop.  So my question is, is there a way to tell the browser which NIC it should be using.  Such as setting up IE for the local LAN, and say FireFox for the WAN?  The browser setup doesn't really matter all that much just that one browser is LAN only and one browser is WAN only.

A: It's rather question of routing. Default route through WiFi, while route with your local LAN mask through Ethernet.
Assuming, that WiFi card has IP 12.34.56.78 and Eth card 192.168.1.123
you'd have routing table something like:
Network Address   Netmask          Gateway Address  Interface       Metric
0.0.0.0           0.0.0.0          12.34.56.1       12.34.56.78     1
192.168.1.0       255.255.255.0    192.168.1.1      192.168.1.123   1

See MS KB article on basic routing.

A: What kind of environment are we talking about? The problem here is introducing an internet connected host practically bridged into your isolated local network. I doubt finding a way to access the internet included uncontrolled access from those machines across both networks at the same time?
If the wifi-connected clients gets compromised or even just slightly misconfigured you'd open up the entire local network for grabs depending on its configuration (do you use domain isolation and require ipsec and isolate all clients from eachother?).
It sounds better to just set up a firewall (and/or a proxy as suggested) on the local network that allow whatever http traffic you need for the specific clients only. That way you're still in control.
But if not, then I'd simply disconnect the client from the local network and only use the internet-facing wifi when needed - with no local network access available. That'd feel a tiny bit more secure if it was me anyway. The local client firewall could be configured to lock things down when not connected to the domain/local network. It's still scary though ^^

A: You don't tell the browser, this is done at OS level.
Just make sure there is a gateway specified for the wireless card in the TCP/IP settings and not for the Ethernet card.
That way it'll route LAN traffic over the Ethernet and anything it doesn't know about over the wireless.

A: This is really a routing question ... Just make sure the default route is set for the wireless gateway

A: Nathan is right about it being OS level.  Can you not instead put a proxy server in place?  That's one of the big main purposes for them.

A: You can setup a proxy in a browser, that will allow them outside access. You can configure that in Firefox or IE individually.
Depending on the IP address you should be able to route that through the Ethernet or Wireless adapter.


text:
Q: How to use \nameref with xstring package to check string length I need to measure a number of characters in string, that I returned from label through \nameref command.
Here is my MWE:
\documentclass{article}

\usepackage{hyperref}
\usepackage{xstring}

\begin{document}

\protected\def\testStr{\nameref{testLabel}}
String content = \testStr
\par

\newlength\testStrWidth
\settowidth{\testStrWidth}{\testStr}
String width = \the\testStrWidth
\par

\StrLen{\testStr}[\testStrNumOfChars]
Number of characters in string = \testStrNumOfChars

\clearpage

\makeatletter
\edef\@currentlabelname{This is a somewhat long string}
\label{testLabel}
\makeatother

Here we have some text to make another page.

\end{document}

Here is the result:

MWE doesn't give any errors.
I'm using XeTeX, but it doesn't work in pdfLaTeX too. I've tried \edef, \def, \let instead of \protected\def, but nothing seems to work.
Of course, if I set tested string explicitly inside \StrLen command, everything will work as it should.
Any help would be much appreciated.

A: You need an expandable version of \nameref:
\documentclass{article}

\usepackage{xstring}
\usepackage{hyperref}

\makeatletter
\newcommand{\getnamereftext}[1]{%
  \@ifundefined{r@#1}{}{%
    \unexpanded\expandafter\expandafter\expandafter{%
      \expandafter\expandafter\expandafter\@thirdoffive\csname r@#1\endcsname
    }%
  }%
}

\begin{document}

\StrLen{\getnamereftext{testLabel}}[\testStrNumOfChars]
Number of characters in string = \testStrNumOfChars

\makeatletter
\edef\@currentlabelname{This is a somewhat long string}
\label{testLabel}
\makeatother

\end{document}

This will return 0 when the label is not yet defined.

A: The \nameref command needs to be fully expanded into its textual form. To that end, you need to remove the hyperlinking that surrounds it, as that is what's causing the problems.
The following is marginally different from egreg's answer and uses e-TeX for conditioning on the existence of the reference - \r@<label>. All we're interested in is extracting the name/title. Nothing more...

\documentclass{article}

\usepackage{hyperref,xstring}
\newcommand{\thirdoffive}[5]{#3}% Similar to \@thirdoffive
% \assignnameref{<ref>}{<macro>}
\newcommand{\assignnameref}[2]{%
  \gdef#2{}% Assign macro to be blank
  \ifcsname r@#1\endcsname % If the reference exists...
    \xdef#2{\expandafter\expandafter\expandafter\thirdoffive\csname r@#1\endcsname}% ...grab the third argument - the name/title
  \fi
}
\begin{document}

\assignnameref{testLabel}{\testStr}%
String content = \testStr
\par

\newlength\testStrWidth
\settowidth{\testStrWidth}{\testStr}%
String width = \the\testStrWidth
\par

\StrLen{\testStr}[\testStrNumOfChars]%
Number of characters in string = \testStrNumOfChars

\clearpage

\makeatletter
\edef\@currentlabelname{This is a somewhat long string}
\label{testLabel}
\makeatother

Here we have some text to make another page.

\end{document}

Yes, \labels exist in the .aux file as macros in the form \r@<label> (via \newlabel). See Understanding how references and labels work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Move any word that starts with x, y, or z to the front of the arraylist - wrong output I need gone through arraylist and remove to the front all words that starts from x y or z.
But my testing output shows that this method have some logical bug.
Code:
/**
   * Moves any word that startw with x, y, or z to the front of the arraylist, but
   * otherwise preserves the order
   */
  public void xyzToFront()
  {
      int insertAt = 0;
      but otherwise preserves the order
      for (int i = 0; i < list.size(); i++) {
          String temp = list.get(i);
          if (temp.startsWith("x") || temp.startsWith("y") || temp.startsWith("z")) {
              list.remove(i);
              list.add(0, temp);
          }
      }
  }

testing output:
Actual: [yak, zebra, xantus, ape, dog, cat] - what is after executing
Expected: [xantus, zebra, yak, ape, dog, cat] - what we should have

How to solve this trouble?

A: Based on your method, which inserts every next word starting with x, y or z before previous, and actual and expected output, I think you want to insert the words to the front of the list in order in which they were removed. If that's the case, you could just use a counter variable and insert the next word after previously removed. For example:
public void xyzToFront()
  {
      int insertAt = 0;
      but otherwise preserves the order
      for (int i = 0; i < list.size(); i++) {
          if (temp.startsWith("x") || temp.startsWith("y") || temp.startsWith("z")) {
              String temp = list.get(i);
              list.remove(i);
              list.add(insertAt++, temp);
          }
      }
 }


text:
Q: What is  the method to compute $\binom{n}{r}$ in a recursive manner? How do you solve this?

Find out which recurrence relation involving $\dbinom{n}{r}$ is valid, and thus prove that we can compute $\dbinom{n}{r}$ in a recursive manner.

I appreciate any help. Thank You

A: From the familiar $\binom{n}{r}=\frac{n!}{r!(n-r)!}$, you can readily derive the formula
$$\binom{n}{r}=\frac{n}{r}\binom{n-1}{r-1}.$$
This can be computationally and theoretically useful, particularly when we are interested in the expression
$$\binom{n}{r}p^r(1-p)^{n-r}$$
that comes up when we are working with the Binomial Distribution.

A: There are many recurrence relations for $\dbinom{n}{r}$. One of the most commonly used one is the following. $$\binom{n+1}{r} = \binom{n}{r} + \binom{n}{r-1}.$$ There are many ways to prove this and one simple way is to look at $\displaystyle (1+x)^{n+1}$. We know that $$(1+x)^{n+1} = (1+x)^{n} (1+x).$$ Now compare the coefficient of $x^r$ on both sides.

 The left hand the coefficient of $x^r$ is $$\dbinom{n+1}{r}.$$ On the right hand side, the $x^r$ term is obtained by multiplying the $x^r$ term of $(1+x)^n$ with the $1$ from $(1+x)$ and also by multiplying the $x^{r-1}$ term of $(1+x)^n$ with the $x$ from $(1+x)$. Hence, the coefficient of $x^r$ is given by the sum of these two terms from the right hand side i.e. $$\dbinom{n}{r} + \dbinom{n}{r-1}$$
  As Rob and J.M have pointed out, these recurrences define the celebrated Pascal's triangle. A pictorial representation is shown above. Each row represents the value of $n$ starting from $0$. On a row, as we proceed from left to right, the different values of $r$ from $0$ to $n$ are hit. The arrows indicate how the $r^{th}$ value on the $(n+1)^{th}$  row is obtained as the sum of the $(r-1)^{th}$ and $r^{th}$ value on the $n^{th}$ row.

A: To prove:
$$\dbinom{n}{k}=\dbinom{n-1}{k-1}+\dbinom{n-1}{k}$$
We have:
$$\dbinom{n-1}{k-1}=\frac{(n-1)!}{(k-1)!(n-k)!}=\frac{(n-1)!}{(k-1)!(n-k-1)!}\frac{1}{n-k}$$
$$\dbinom{n-1}{k}=\frac{(n-1)!}{(k)!(n-k-1)!}=\frac{(n-1)!}{(k-1)!(n-k-1)!}\frac{1}{k}$$
Adding the two together:
$$\dbinom{n-1}{k-1}+\dbinom{n-1}{k}=\frac{(n-1)!}{(k-1)!(n-k-1)!}(\frac{1}{n-k}+\frac{1}{k})$$
$$=\frac{(n-1)!}{(k-1)!(n-k-1)!}\frac{n}{k(n-k)}$$
$$=\frac{n!}{k!(n-k)!}$$
$$=\dbinom{n}{k}$$


text:
Q: Slicing a mesh of unknown dimensions I'm trying to do a grid search over a model I've trained. So, producing a mesh, then predicting that mesh with the model to find a maximum.
I'm producing the mesh with:
def generate_random_grid(n_scanning_parameters,n_points_each_dimension):
  points=np.linspace(1,0,num=n_points_each_dimension,endpoint=False)
  x_points=[points for dimension in range(n_scanning_parameters)]
  mesh=np.array(np.meshgrid(*x_points))
  return mesh

As you can see, I don't know the dimensions in advance. So later when I want to index the mesh to predict different points, I don't know how to index.
E.g, if I have 4 dimensions and 10 points along each dimension, the mesh has the shape (4,10,10,10,10). And I need to access points like e.g. [:,0,0,0,0] or [:,1,2,3,4]. Which would give me a 1-D vector with 4 elements.
Now I can produce the 4 last indices using
for index in np.ndindex(*mesh.shape[1:]):
, but then indexing my mesh like mesh[:,index] doesn't result in a 1-D vector with 4 elements as I expect it to.
How can I index the mesh?

A: Since you're working with tuples, and numpy supports tuple indexing, let's start with that.
Effectively, you want to do your slicing like a[:, 0, 0, 0, 0]. But your index is a tuple, and you're attempting something like a[:, (0,0,0,0)] - this gives you four hyperplanes along the second dimension instead. Your indexing should be more like a[(:,0,0,0,0)] - but this gives a syntax error.
So the solution would be to use the slice built-in.
a[(slice(None),0,0,0,0)]

This would give you your one dimensional vector.
In terms of your code, you can simply add the tuples to make this work.
for index in np.ndindex(*mesh.shape[1:]):
    vector = mesh[(slice(None), ) + index]

An alternative approach would be to simply use a transposed array and reversed indices. The first dimension is at the end, removing the need for :.
for index in np.ndindex(*mesh.shape[1:]):
    vector = mesh.T[index[::-1]]


text:
Q: Empty rows when retrieving data from database to dataGridView in c# Why do I get blank rows when I retrieve rows from MySQL database to dataGridView? I end up getting the amount of rows but its empty (it has no text).
this is my code so far:
        private void button2_Click(object sender, EventArgs e)
    {
        string constring = "Data Source = localhost; port = 3306; username = root; password = 0159";
        MySqlConnection conDataBase = new MySqlConnection(constring);
        MySqlCommand cmdDataBase = new MySqlCommand("Select * FROM TopShineDB.Table1 ;", conDataBase);
        using (MySqlConnection conn = new MySqlConnection(constring))
        {
            try
            {
                MySqlDataAdapter sda = new MySqlDataAdapter();
                sda.SelectCommand = cmdDataBase;
                DataTable dt = new DataTable();
                sda.Fill(dt);

                BindingSource bs = new BindingSource();
                bs.DataSource = dt;
                dataGridView1.DataSource = bs;
                sda.Update(dt);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

A:
I tried below code sample to get data from database and bind to datagridview.

var ConnectionString = "your ConnectionString";
MySqlConnection connect = new MySqlConnection(ConnectionString);
MySqlCommand cmd = new MySqlCommand("your query");
connect.Open();
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
DataTable dt = new DataTable();
dt = DtSet.Tables[0];
dataGridView1.DataSource = DtSet.Tables[0];
connect.Close();

A: Try This:
private void BindGrid()
{
    string conString = @"Data Source=localhost;port=3306;Initial Catalog=TopShineDB;User Id=root;password=0159";
    using (MySqlConnection con = new MySqlConnection(conString))
    {
        using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM Table1", con))
        {
            cmd.CommandType = CommandType.Text;
            using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd))
            {
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    dataGridView1.DataSource = dt;
                }
            }
        }
    }
}

A: *Just Clear your Columns you define in DataGridView *
      private void button2_Click(object sender, EventArgs e)
{
    string constring = "Data Source = localhost; port = 3306; username = root; password = 0159";
    MySqlConnection conDataBase = new MySqlConnection(constring);
    MySqlCommand cmdDataBase = new MySqlCommand("Select * FROM TopShineDB.Table1 ;", conDataBase);
    using (MySqlConnection conn = new MySqlConnection(constring))
    {
        try
        {
            MySqlDataAdapter sda = new MySqlDataAdapter();
            sda.SelectCommand = cmdDataBase;
            DataTable dt = new DataTable();
            sda.Fill(dt);

                 dataGridView1.Columns.Clear();
            dataGridView1.DataSource = bs;

        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

c#


text:
Q: .htaccess redirect http and https subdomain to other domain I have subdomain: subdomain.example.com
I would like to redirect http and https to another domain
 http://subdomain.example.com --> https://subdomain.exampleNew.com
 https://subdomain.example.com --> https://subdomain.exampleNew.com

Does anyone know how to do this?
Currently I have only:
 RewriteCond %{HTTP_HOST} ^subdomain.example.com$ [NC]
 RewriteRule ^(.*)$ https://subdomain.exampleNew.com/$1 [R=301,L]

A: If you want to retain the http/https status, the status needs to be captured first and then passed to the rule as %1. Use the following instead:
RewriteCond %{HTTPS}s ^on(s)|off
RewriteCond %{HTTP_HOST} ^subdomain.example.com$ [NC]
RewriteRule ^(.*)$ http%1://subdomain.exampleNew.com/$1 [R=301,L]


text:
Q: Not able to convert UTC time I'm getting this UTC time in string format from the server.."2019-12-18T10:58:40Z"

Now I want to convert it into local time. For that I referred this link. But it's not working..
What I wanted to achieve was to convert UTC time to local time and set a timer based on that time.
This is what I've tried..
var utcTime = "\(json["expirationDate"]!)"

self.dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let date = self.dateFormatter.date(from: utcTime)
let utcDate = date?.toGlobalTime()
let localDate = utcDate?.toLocalTime()

But I'm getting nil values for the dates..

A: You don't have milliseconds in your UTC date string example. Your date format should be
self.dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"

A: you have to change this format from
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" to "yyyy-MM-dd'T'HH:mm:ss'Z'"**you have to
let utcTime = "2019-12-18T10:58:40Z"
let dateFormatter = DateFormatter.init()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")!
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
let date = dateFormatter.date(from: utcTime)
print(date)


text:
Q: Display pages and posts in archive I have many categories, but for clearity I will do an example with only two:

*

*News that contains many posts

*Products that contains many pages (I've added this feature in functions.php)

I want that archive.php displays:

*

*the posts when the user choose the category News

*the pages when the user choose the category Products

At the moment Wordpress by deafult shows only posts and not pages.
I know that this is possible by adding a simple function in functions.php but I can't find it.
EDIT: For another project with custom post type "Books" I used this code
function query_post_type($query) {
    $post_types = get_post_types();

    if ( is_category() || is_tag()) {

        $post_type = get_query_var('books');

        if ( $post_type ) {
            $post_type = $post_type;
        } else {
            $post_type = $post_types;
        }

        $query->set( 'post_type', $post_type );

        return $query;
    }
}
add_filter('pre_get_posts', 'query_post_type');

Is there something like that for my case?

A: You can query for solely pages in the WP Query.
PHP:
$args = array(
  'post_type' => 'page'
);

$query = new WP_Query( $args );

This will return all pages in your database, and zero posts. Vice versa, you could have 'post_type' => 'post' to query all posts, but that's the default behaviour of the WP Query.
For more documentation on this, check out the WP Query reference in the Wordpress Codex.


text:
Q: How do I interpret these results from a paired t-test? t.test(price1,price2,mu=0,alt="two.sided",paired=T,conf.level=0.95)

    Paired t-test

data:  price1 and price2
t = 1.4268, df = 29, p-value = 0.1643
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -6.861169 38.518502

If initially I hypothesized that:
$H0: \mu_1 = \mu_2$
and
$Ha: \mu_1 > \mu_2$
And those were the results from my paired t-test in R, I'm not sure how to make sense of them. Because the resulting p-value is 0.1643 at significance level of $\alpha$ = 0.05, this means we accept H0 correct? I don't know how to explain the 95% confidence interval from these results either, what does the -6.861169 mean? If someone could just put all of this into words that would be easy to understand, that'd be great going forward, thanks!

A: *

*No, we don't "accept $H_o$", instead we fail to reject the null hypothesis. So we are not "rejecting the null", implying that we don't have enough evidence to assume that the difference in means is different from zero.

*The confidence interval includes the value zero, and gives us the ranges of values within which the mean difference in the population would lie with a confidence level of $95\%$. In your results, this is a very broad range, but the inclusion of the value zero prevents you from excluding the null.

A: The alternative hypothesis that you proposed is one-sided but you have used a two-sided t-test. Had you set alt="greater" in the t-test to get the one-sided result you would have had p-value = 0.082.
Do not dichotomise the result into significant and not significant on the basis of comparison of your observed p-value and the unthinkingly arbitrary threshold of 0.05. To do so is to use the "bright-line" thinking that is warned against in the recent American Statistical Association's official statement on p-values. http://amstat.tandfonline.com/doi/abs/10.1080/00031305.2016.1154108#.VyUnhmR95cw
Instead of dichotomising, look at the result and weigh it in light of what you know and what you want the data to tell you. Your data appear to contain relatively weak evidence against your null hypothesis.
There are many references in the ASA statement that will help you with the distinction between the dichotomous result of a hypothesis test and an evidence-respecting interpretation of a significance test, but I like my own: http://www.ncbi.nlm.nih.gov/pubmed/22394284


text:
Q: Python project relative modules import I am sure the question might seem pretty stupid, but searching around didn't yield me much result, so a redirection towards a response would be quite welcome.
So, I have a Python project with nested modules:
src
 |-package_1
  |-__init__.py
  |-module_1_1
  |-module_1_2
 |-package_2
  |-__init__.py
  |module_2_1
  |module_2_2
 |-main_module
 |-__init__.py

From the main_module I import the contents of package_2 and from modules inside package_2 I import contents of package_1 modules with the similar statements:
(main_module)
from package_2.module_2_1 import foo

(module_2_1)
from package_1.module_1_1 import bar

It all works well as a long as I run
Python main_module

but as soon as I try to run, for instance to use a function of the module_2_1 on it's own
Python module_2_1,

if fails with a message that it could not resolve the following import:
from package_1.module_1_1 import bar

From my understanding, Python is not aware of where it should go look for package_1, because it is not aware of where the project root is.
As a remedy, I am currently pre-pending the following line to all the inner modules to properly resolve the import:
if __name__ == "__main__":
    import os
    os.chdir("..")

But it just don't feel right.
What would be the correct way of solving this problem?

A: You need to invoke it properly in the first place. Change to src/ and run:
python -m package_2.module_2_1


text:
Q: Where did I go wrong in this putnam question? I won't be writing each step explicitly because it takes me forever to write this up in math format.
$$
\int_2^4 \frac{\sqrt{\ln{(9-x)}}}{{\sqrt{\ln{(9-x)}}}+{\sqrt{\ln{(x+3)}}}}\,dx $$
My solving of it went as follows:
$$
\int_2^4 \frac{\sqrt{\ln{(9-x)}}}{{\sqrt{\ln{(9-x)}}}+{\sqrt{\ln{(x+3)}}}}  \frac{\sqrt{\ln{(9-x)}}}{\sqrt{\ln{(9-x)}}}\,dx=
$$
$$
=\int_2^4 \frac{{\ln{(9-x)}}}{{{\ln{(9-x)}}}+{\sqrt{\ln{(9-x)}\ln{(x+3)}}}}\,dx
$$
It has at this point been an hour and I won't waste more time to make the equations look pretty.
$$
=\int_2^4\frac{\ln(9-x)}{(\ln(9-x) + \ln(9-x)^{\ln(x+3)/2}}\,dx
$$
Factor out ln(9-x) and cancel and you get
$$
\int_2^4\frac{1}{1+\ln(9-x)^{(\ln(x+3)-2)/2}}\,dx
$$
After a bit more simplifying (bringing down the exponent and multiplying, then moving the 2 out of the integral, then simplifying the remaining $\ln$'s) you get
$$
2\int_2^4\frac{1}{2+\ln\frac{x+3}{9-x}}\,dx
$$
And this is an easy integral because it is directly derived from arctan. I get the antiderivative is
$$
\frac{1}{\sqrt2}\arctan\left(\frac{1}{\sqrt2}\sqrt{\ln\frac{x+3}{9-x}}\right).
$$
But when I try to use that for the definite integral, I get a negative under the square root, so it must be wrong. Can someone explain where I must've gone wrong? I hope I gave enough information so that you know what I did.


text:
Q: Incorrect R lm() slope with plot/interpretation I need a little help understanding the output of my regression model.
As a result of lm() I get that my slope is -1.2. However, when plotting the graph, it doesn't looke like the slope is actually -1.2 but much less. I also dont understand why my intercept looks that way.
What am I missing?
library(zoo)
library(ggplot2)

a <- as.yearmon(c("2022-01", "2022-02", "2022-03", "2022-04", "2022-05"))
b <- c(2,0,2,1,1)

df <- data.frame(a,b)
df

ggplot(df, aes(x = a, y = b)) +
  geom_point() +
  stat_smooth(method = lm)

lm(b ~ a, df)

A: The plot is fine. unclass(a) shows that the predictor is in years,
unclass(a)
[1] 2022.000 2022.083 2022.167 2022.250 2022.333

The slope is 1.2 per year, and you have a third of a year, so get a change of 0.4.
The intercept is where the predicted value when x = 0. Two thousand and twenty two years to the left of your plot. This is why it is so high

A: Another way to look at this is to change the units of your time variable so that the regression results match the visual intuition given by the plot. The way to do this is to convert the time variable into "months since first data point":
df$months_since_start <- 12 * (df$a - df$a[1])

df
#>          a b months_since_start
#> 1 Jan 2022 2                  0
#> 2 Feb 2022 0                  1
#> 3 Mar 2022 2                  2
#> 4 Apr 2022 1                  3
#> 5 May 2022 1                  4

Now your lm results are much more in keeping with the plot (an intercept of 1.4 and slope of -0.1 per month)
lm(b ~ months_since_start, df)
#>
#> Call:
#> lm(formula = b ~ months_since_start, data = df)
#>
#> Coefficients:
#>        (Intercept)  months_since_start
#>                1.4                -0.1

I think this is probably a more natural way to present the results, since although it is equivalent numerically, saying that "the value started at 1.4 at the start of the year and has drifted down by 0.1 per month on average" is likely to be more factually accurate than "the value started at 2043 in 1 BCE and has drifted down 1.2 per year since then."
Created on 2022-06-21 by the reprex package (v2.0.1)

A: Often taking out the constant when working on yearly data gives a more intuitive value.  Try:
ggplot(df, aes(x = a, y = b)) +
  geom_point() +
  stat_smooth(aes(colour = "With constant"), method = lm, formula = y ~ x, se = 0) +
  stat_smooth(aes(colour = "Without constant"), method = lm, formula = y ~ x - 1, se = 0)


text:
Q: Teste unitário RxJS + NgRx subscription no Angular com Karma Estou com dificuldade de executar teste unitário para a seguinte função:
subscribeToUsuario(): void {
    this.subscription.add(
      this.store$.pipe(select(selectors.selectUsuario)).subscribe(state => {
        if (!state || !state.usuario) return;
        this.usuario = state.usuario;
      })
    );
  }

No istanbul sempre bate como function/statement not covered, qual seria a forma ideal de testar essa função?

A: você poderia fazer dessa maneira:
1- dentro da suíte de testes, você iria criar uma propriedade para o store que contem um spy para o pipe:
const storeMock = jasmine.createSpyObj(['pipe']);

2- criar um mock que possua a mesma estrutura de retorno do seu seletor.
3- No providers dentro do seu configureTestingModule você iria associar seu spy com o modulo da biblioteca dessa maneira:
beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [],
      declarations: [],
      schemas: [NO_ERRORS_SCHEMA],
      providers: [
        { provide: Store, useValue: storeMock },
      ]
    }).compileComponents();
  }));

4- Dentro do seu caso de teste você iria adcionar o spy dessa maneira:
storeMock.pipe.and.returnValue(of(selectUsuarioMock));


text:
Q: The DataGrid select all button loading slow I have a DataGrid with ItemsSource and columns with bound values.
For some reason the "select all button" is loading last, so firstly the column headers are aligned to the left and after the whole content is loaded the "select all button" appears. How can I fix that blink?
http://i.stack.imgur.com/EhesT.png
Here is my code

                <DataGrid.RowHeaderTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGridRow}},
                            Path=Item.RowHeader}"
                                   HorizontalAlignment="Stretch"
                                   MinWidth="55"/>
                    </DataTemplate>
                </DataGrid.RowHeaderTemplate>

                <DataGrid.Columns>
                    <!--m-->
                    <DataGridTextColumn Binding="{Binding Path=m, IsAsync=True, StringFormat='{}{0:0.##}'}" Header="m"/>

                    <!--α-->
                    <DataGridTextColumn Binding="{Binding Path=a, IsAsync=True}" Header="α" />

                    <!--h-->
                    <DataGridTextColumn Binding="{Binding Path=h, IsAsync=True, StringFormat='{}{0:0.#}'}" Header="h" />

                    <!--D1-->
                    <DataGridTextColumn Binding="{Binding Path=D1, IsAsync=True, StringFormat='{}{0:F0}'}">
                        <DataGridTextColumn.Header>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock>
                                    D
                                    <InlineUIContainer BaselineAlignment="Subscript">
                                        <TextBlock Text="1"/>
                                    </InlineUIContainer>
                                </TextBlock>
                            </StackPanel>
                        </DataGridTextColumn.Header>
                    </DataGridTextColumn>

                    <!--D2-->
                    <DataGridTextColumn Binding="{Binding Path=D2, IsAsync=True, StringFormat='{}{0:F0}'}">
                        <DataGridTextColumn.Header>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock>
                                    D
                                    <InlineUIContainer BaselineAlignment="Subscript">
                                        <TextBlock Text="2"/>
                                    </InlineUIContainer>
                                </TextBlock>
                            </StackPanel>
                        </DataGridTextColumn.Header>
                    </DataGridTextColumn>

                </DataGrid.Columns>

            </DataGrid>


text:
Q: "Application tried to present modally an active controller" when user pulls down Notification Center I have a view that gets presented when the user flips the phone to Landscape. It's presented by a UIViewController that's on top of a Navigation Control stack by using PresentViewController().
It works fine until the user pulls-down the Notification Center by dragging down from the top of the phone's screen, then the app instantly crashes with a MonoTouchException and the message:
"Objective-C exception thrown.  Name: NSInvalidArgumentException Reason: Application tried to present modally an active controller"
This crash does not occur when pulling down the Notification Center in any other view, but all of the other views are on the Navigation Controller's stack and not presented modally.

A: Figured it out with a bit more debugging:
I was subscribing to UIDeviceOrientationDidChangeNotification to find out when the phone was rotated and calling a "DeviceRotated()" method.
It turns out that when you pull down the Notification Center, this notification gets fired again even if the phone hasn't physically changed rotation. My code wasn't expecting this, so it tried to present the same Landscape View again while it was already being displayed, and the exception was thrown.
I added && (this.PresentedViewController == null || this.PresentedViewController == this) to the if-then that tests for the right circumstances to present the landscape view and the crash went away.


text:
Q: Not all CSS properties applied to  tag in blazor, Background color creates different color than value I tried to color my hr tag in Blazor but it did not work. The part that I am very surprised with is that the hr color is reflected differently. For example, the black color was always gray and the red color orange. I have tried all the approaches. By the way, the high property worked well but the color never did. Any ideas?
insline:

CSS isolation
hr{
   height:20px; '
   background-color: black;
}

A: Bootstrap sets the opacity. background-color: black; is working...
Try:

As a style:
hr {
    background-color: orange;
    height: 20px;
    opacity: 100%;
}

If your not using isolation you may need !important on height.


text:
Q: Return a list of e-mails, comma separated, based on information in another column I am currently trying to design an efficient system for my public library for contacting participants for courses. Currently, we have a giant list of hundreds of people that we have to manually comb through to find out what courses they're interested in, their information, etc.
I am trying to use the e-mails we have on record for these hundreds of people (a column of its own), and spit them out in a comma-separated list in another cell, based on whether or not they have an "x" in another column, which represents their interest.
Ex.
Email - - - - - - - (Class 1) | (Class 2)
johndoe@mail.com         x    |

If I wanted to print out an email list to another cell for Class 1, how would you propose it be done? The desired result is something like:
"email1@mail.com", "email2@mail.com"... etc, so it can be copied and pasted easily by the others who work here.

A: Don't make your life harder than it needs to be. Use the column filters in the table heading to show only the emails with an X for that course. Then copy and paste the visible results.
You can paste straight into an email client "To" field, without converting to a comma separated list.
Or, use Word Mail Merge, with this file as the data source, merge to email. Edit the data source settings and filter on the desired column. Then merge to email. No appending, copying or pasting at all.


text:
Q: Trigger to convert empty string to 'null' before it posts in SQL Server decimal column I've got a front table that essentially matches our SSMS database table t_myTable. Some columns I'm having problems with are those with numeric data types in the db. They are set to allow null, but from the front end when the user deletes the numeric value and tries to send a blank value, it's not posting to the database. I suspect because this value is sent back as an empty string "" which does not translate to the null allowable data type.
Is there a trigger I can create to convert these empty strings into null on insert and update to the database? Or, perhaps a trigger would already happen too late in the process and I need to handle this on the front end or API portion instead?
We'll call my table t_myTable and the column myNumericColumn.
I could also be wrong and perhaps this 'empty string' issue is not the source of my problem. But I suspect that it is.

A: As @DaleBurrell noted, the proper place to handle data validation is in the application layer. You can wrap each of the potentially problematic values in a NULLIF function, which will convert the value to a NULL if an empty string is passed to it.
The syntax would be along these lines:
SELECT
  ...
  ,NULLIF(ColumnName, '') AS ColumnName

A: select nullif(Column1, '') from tablename

A: SQL Server doesn't allow to convert an empty string to the numeric data type. Hence the trigger is useless in this case, even INSTEAD OF one: SQL Server will check the conversion before inserting.
SELECT CAST('' AS numeric(18,2)) -- Error converting data type varchar to numeric
CREATE TABLE tab1 (col1 numeric(18,2) NULL);
INSERT INTO tab1 (col1) VALUES(''); -- Error converting data type varchar to numeric

As you didn't mention this error, the client should pass something other than ''. The problem can be found with SQL Profiler: you need to run it and see what exact SQL statement is executing to insert data into the table.


text:
Q: Oracle query - How to check if a user is the only one assigned to a project I am trying to determine if a user is assigned to any project with a specific role (ProjMemberTypeID) and if so, if s/he is the only one.
There is "projMember" table with Project ID, User ID and Project Member Type ID. I need to know if there are any project IDs where this user is the only one with member type id of 1.
Is it also possible to get some project info (like name, ...) joining the requested query with "Project" table, based on Project ID?
I tried this but it only gives me how many users are assigned to projects and if I filter by user ID I get how many projects user is assigned to but don't know how to check if s/he is the only one.
select count(userid), projectid
from projmember
where projmembertypeid = 1 -- and userid=73
group by projectid
order by projectid;

A: You can use a having clause:
select projectid
from projmember
where projmembertypeid = 1
group by projectid
having min(userid) = 73 and max(userid) = min(userid)
order by projectid;

The query filters on the relevant member type, then aggregates by project; all that is left to do is ensure that the given user was found, and no other.


text:
Q: c++: passing Eigen-defined matrices to functions, and using them - best practice I have a function which requires me to pass a fairly large matrix (which I created using Eigen) - and ranges from dimensions 200x200 -> 1000x1000. The function is more complex than this, but the bare bones of it are:
#include <Eigen/Dense>

int main()
{
    MatrixXi mIndices = MatrixXi::Zero(1000,1000);
    MatrixXi* pMatrix = &mIndices;
    MatrixXi mTest;

    for(int i = 0; i < 10000; i++)
     {
           mTest = pMatrix[0];
           // Then do stuff to the copy

     }
}

Is the reason that it takes much longer to run with a larger size of matrix because it takes longer to find the available space in RAM for the array when I set it equal to mTest? When I switch to a sparse array, this seems to be quite a lot quicker.
If I need to pass around large matrices, and I want to minimise the incremental effect of matrix size on runtime, then what is best practice here? At the moment, the same program is running slower in c++ than it is in Matlab, and obviously I would like to speed it up!
Best,
Ben

A: In the code you show, you are copying a 1,000,000 element 10,000 times. The assignment in the loop creates a copy.
Generally if you're passing an Eigen matrix to another function, it can be beneficial to accept the argument by reference.
It's not really clear from your code what you're trying to achieve however.


text:
Q: : aggregate() missing 1 required positional argument: 'func_or_funcs' I try to aggregate per ptid based on the diag_date, and calculate max, min and visit counts based on the diag_date:
output = df.groupby("ptid")["diag_date"].agg(Max_Pt_date="max", Min_Pt_date="min", Num_Visits="count")
output["TreatDuration"] = (output["Max_Pt_date"]-output["Min_Pt_date"]).dt.days

However, when I do the above (following all rules for agg) does not seem to work as I get the following error:
<class 'TypeError'>: aggregate() missing 1 required positional argument: 'func_or_funcs'

Any ideas, are greatly appreciated!

A: To answer my questions, after getting valuable inputs from responders above, I modified the code environment in Dataiku (which had a new Python and Pandas version) and it worked fine.


text:
Q: SMTP Error Issue - PHPMailer I have a daily newsletter I send out to a list of people each day. I use PHP and the PHPMailer object to send the emails.
This has been working fine up until today when I didn't get an email (test) and I checked the logs to find that intermittently I was getting SMTP errors back from
mail->Send();

Method of the class on SOME of the people - not all of them.
All of the emails were exactly the same size (length in characters) apart from their name and email address.
The error details from
$mail->ErrorInfo;

Included these two errors
SMTP Error: Data not accepted.<p>SMTP server error: 2.1.5 Ok
SMTP Error: Data not accepted.<p&gtSMTP server error: </p>
Why there are broken P tags in the error message I have no idea - also why the first error has OK in it??
However other people in the loop had emails go out fine.
Also when I put the script into test mode so ONLY these failures were emailed out (so one call of the script = one email to one person), I found no problem and the people got their emaail.
Now I asked tech support what the error meant and got back "Google it" and I can't find the error 2.1.5 OK anywhere. I don't really get why it says OK after an error either.
As a test for tomorrow I put a test in for a failed Send and then a Sleep for 5 seconds with a retry.
I don't know if this will help but I thought that maybe my SMTP server which is on the same server as my script (Rackspace VPS Linux) was having temporary issues connecting so a sleep might be handy in this situation.
This is the first time I have had this issue, I haven't rebooted APACHE or my server (or mailserver) and before this script I had another one send out 403 emails without any problem.
It would be nice to know what the error is and why it happened though.
Rob

A: That error is defined exactly where you would expect it to be - in the RFC that defines SMTP error codes. 2.1.5 means "Destination address valid". That it starts with a 2 means it's not an error as such, but a response code - warnings and errors start with 4 and 5. Why you got it, I don't know, but it certainly seems it was not expected in that context. Mail servers often have problems - they run out of disk space, get swamped by spam filtering, and this is why mail servers have queues. Sending directly using PHPMailer's SMTP class is not appropriate for high-volume sending - using SMTP is fine, but point it at a proper (nearby) MTA that can handle deliveries properly.
As for the garbled ErrorInfo content, I suspect you are using an old version of PHPMailer - the debug output has been cleaned up fairly recently. Another thing that changed lately is the handling of errors during single sends to multiple recipients (e.g. BCCs) - it's now much more likely to get to the end of a long recipient list without giving up than it was before.


text:
Q: Objective C Setter overriding in Swift I need to override the setter of UIViews highlighted property in my custom UIButton subclass ;
Objective C
@property(nonatomic,getter=isHighlighted) BOOL highlighted;

overridden like this
- (void) setHighlighted:(BOOL)highlighted {
    [super setHighlighted:highlighted];

    if (highlighted) {
        self.backgroundColor = UIColorFromRGB(0x387038);
    }
    else {
        self.backgroundColor = UIColorFromRGB(0x5bb75b);
    }

   [super setHighlighted:highlighted];

}

Swift
var highlighted: Bool

I tried:
var highlighted: Bool {

   get{ return false }

   set {

        if highlighted {

       self.backgroundColor = UIColor.whiteColor()
       //Error "Use unresolved identifier     'self'"

         I can't set the background color from value type in here
        , can't call self.backgroundColor in this value type ,
         can't call super too because this is a value type , doesn't work
        }

        }

   }

How and where should implement this method in Swift to get the same result . any idea?

A: There are a couple things wrong here, but this solution should help you...
In your case, since you do not really want computed values for the variable highlighted, but rather all you want is to know when highlighted changed, you should use willSet or didSet
for your case, didSet.
it looks like this
var highlighted:Bool = false {
    didSet {
        // You can use 'oldValue' to see what it used to be,
        // and 'highlighted' will be what it was set to.
        if highlighted
        {
            self.backgroundColor = UIColor.whiteColor()
        } else
        {
            self.backgroundColor = UIColor.blackColor()
        }
}
}

Keep in mind that the initial value is set to false BUT initializing the variable does not call the didSet block (i don't think), so default initialize this view with backgroundColor black... or whatever.
the Swift ibook has some good tips about set, get, didSet and willSet, around page 250 ish.
Let me know if your error remains, (and if so you should maybe post when you set this variable & the class headers and stuff, may not be enough information.  Also, are you using xcode6-beta4?)

A: In Swift the solution above worked for me, but I had to omit the Bool = true:
import UIKit

class CustomUIButtonForUIToolbar: UIButton {

    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
        super.drawRect(rect)

        self.layer.borderColor = UIColor.blueColor().CGColor
        self.layer.borderWidth = 1.0
        self.layer.cornerRadius = 5.0
        self.clipsToBounds = true
        self.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)

        self.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Highlighted)
    }

    override var highlighted: Bool {
        didSet {

            if (highlighted) {
                self.backgroundColor = UIColor.blueColor()
            }
            else {
                self.backgroundColor = UIColor.clearColor()
            }

        }
    }

}

A: You are using computed properties instead use stored property.As there is no UIColorFromRGB provided in swift so i have written mine
class ViewSubClass:UIView{

var highlighted: Bool = true {

   didSet {

      if (highlighted) {
    self.backgroundColor = UIColorFromRGB(0x387038);
      }
      else {
         self.backgroundColor = UIColorFromRGB(0x5bb75b);
      }
   }

}

init(frame: CGRect) {

    super.init(frame: frame)
}

func UIColorFromRGB(rgbValue: UInt) -> UIColor {
    return UIColor(
        red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
        green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
        blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
        alpha: CGFloat(1.0)
    )
 }
}


text:
Q: Google Earth Engine: Extract second largest value from annual observations? In Google Earth Engine, is it possible to extract the annual second largest and second smallest value and construct an imagecollection?
Apparently, there is no build-in reducer for this purpose.
Here is my code for getting the min, please guide me on how to get the second max and min.
Thank you!
Here is the code:
var startDate = ee.Date('2001-01-01'); // set start time for analysis
var endDate = ee.Date('2021-12-31'); // set end time for analysis

// calculate the number of year to process
var nyears = ee.Number(endDate.difference(startDate,'year'));

//init a time band
var createTimeBand= function(image) {
  return image.addBands(image.metadata('system:time_start')
  .divide(1e18))
 // .divide(1000*60*60*24*365))
}

var sst = ee.ImageCollection('MODIS/006/MOD11A1').select('LST_Day_1km')
            .filterDate(startDate, endDate)
            .map(createTimeBand)

var byyearMin = ee.ImageCollection(
  // map over each month
  ee.List.sequence(0,nyears).map(function (n) {
    // calculate the offset from startDate
    var ini = startDate.advance(n,'year');
    // advance just one month
    var end = ini.advance(1,'year');
    // filter and reduce
    return sst.filterDate(ini,end)
                .select(0).min()
              //  .sort('LST_Day_1km').reverse().first()
                .multiply(0.02)
                .subtract(273.15)
                .set('system:time_start', ini.millis());//convert time to number
}));

A: var startDate = ee.Date('2001-01-01'); // set start time for analysis
var endDate = ee.Date('2021-12-31'); // set end time for analysis

// calculate the number of year to process
var nyears = ee.Number(endDate.difference(startDate,'year'));

//init a time band
var createTimeBand= function(image) {
  return image.addBands(image.metadata('system:time_start')
  .divide(1e18))
 // .divide(1000*60*60*24*365))
}

var sst = ee.ImageCollection('MODIS/006/MOD11A1').select('LST_Day_1km')
            .filterDate(startDate, endDate)
            //.map(createTimeBand)

var byyearMin = ee.ImageCollection(
  // map over each month
  ee.List.sequence(0,nyears).map(function (n) {
    // calculate the offset from startDate
    var ini = startDate.advance(n,'year');
    // advance just one month
    var end = ini.advance(1,'year');

    var sortedDays = sst.filterDate(ini,end)
    .sort('LST_Day_1km')
    .toList(sst.size())

    var secondLargest = ee.List(sortedDays.get(1))
    var secondSmallest = ee.List(sortedDays.get(-1))

    var collection = ee.Image(secondLargest)
    .addBands(secondSmallest).rename(['secondLargest', 'secondSmallest'])
    .multiply(0.02)
      .subtract(273.15)
      return collection
      .set('system:time_start', ini.millis()) //convert time to number
      .set('Date', ee.Date(ini))
}));

print(byyearMin)


text:
Q: How to set a time value for a WKInterfaceTimer using a Slider I am creating a test app to get used to WatchKit, and was wondering if it possible to use a slider to set a countdown time. I have this so far:
import WatchKit
import Foundation

class InterfaceController: WKInterfaceController {

@IBOutlet weak var footText: WKInterfaceLabel!
@IBOutlet weak var timerOutput: WKInterfaceTimer!

@IBAction func button() {
}
@IBAction func timeSlider(value: Float) {
var myValue = String(format: "Value is %f", value)
    func setAttributedText(attributedText: NSAttributedString?) {}

}
var testtest = "This is a test"

override func awakeWithContext(context: AnyObject?) {
    super.awakeWithContext(context)

    // Configure interface objects here.
}

override func willActivate() {
    // This method is called when watch view controller is about to be visible to user
    super.willActivate()
}

override func didDeactivate() {
    // This method is called when watch view controller is no longer visible
    super.didDeactivate()
}

}

Is it possible to change the value of the timer?

A: If you want to change the value of your timer, you can set it like this :

*

*First of all, you use your slider to change the value of the countTime

*After that you can set the timer, depending on your countTime:
timer.setDate(NSDate(timeIntervalSinceNow: countTime))
        timer.start()
Hope this helps!


text:
Q: Confident interval different t.test and manual calculation I am getting a different result when I apply t.test than when I do calculations manually, for a contrast of hypotheses, alternative hypothesis being mean1 < mean2. The observed value, degrees of freedom and p-value is the same, but not the interval and I can't figure what I'm doing wrong.
       a <- c(18,2,563,45,35,6,7,8)
       b <- c(7,5,4,6,8,5,4,2)

# function, left side, unequal variance
STAT_3 <- function ( x, y, NC ) {

          mean1 <- mean(x)
          mean2 <- mean(y)
          var1 <- var(x)
          var2 <- var(y)
          n1 <- length(x)
          n2 <- length(y)
          tobs <- (mean1 - mean2) / sqrt (var1/n1 + var2/n2)
          v <- (var1/n1 + var2/n2)^2 / ( ((var1/n1)^2 / (n1-1)) + ((var2/n2)^2 / (n2-1)) )
          tcrit <- qt( p = (1-NC/100)/2, df = v )
          pvalue <- pt( tobs, lower.tail=TRUE, df = v )
          return ( c(round(tobs,2), round(tcrit,2), pvalue, v) )

        }

        t.test(a,b,alternative='less',var.equal=FALSE)
        STAT_3(a,b,95)

Results I get are:
t.test:

    Welch Two Sample t-test

data:  a and b
t = 1.1745, df = 7.0013, p-value = 0.8607
alternative hypothesis: true difference in means is less than 0
95 percent confidence interval:
     -Inf 210.0197
sample estimates:
mean of x mean of y
   85.500     5.125

manual:
 t = 1.1700000 tcrit = -2.3600000  p-value = 0.8607113  df = 7.0013281

Would anyone know why?

A: You have a balanced design with eight observations in each group. However, the two sample standard
deviations are massively different: $S_a=193.5, S_b
= 1.89.$
a <- c(18,2,563,45,35,6,7,8)
b <- c(7,5,4,6,8,5,4,2)
summary(a); sd(a)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   2.00    6.75   13.00   85.50   37.50  563.00
[1] 193.5436
summary(b); sd(b)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  2.000   4.000   5.000   5.125   6.250   8.000
[1] 1.885092

Because of the equal sample sizes, the pooled and Welch t statistics will be equal, but of course
it's the Welch 2-sample t test you need to do.
t.test(a,b, alt="less")

        Welch Two Sample t-test

data:  a and b
t = 1.1745, df = 7.0013, p-value = 0.8607
alternative hypothesis:
 true difference in means is less than 0
95 percent confidence interval:
     -Inf 210.0197
sample estimates:
mean of x mean of y
   85.500     5.125

I get the same result in R that you do.
The purpose of your uncommented and unmotivated
function STAT-3. I would try to de-bug that--if it is giving different results.


text:
Q: Easiest way to select distinct with least number of null I want to create a view over a table that has 500k rows and 10 columns. In that table there are duplicate id but with different amount of information, because some of the columns are NULL. My objective is to keep one column in case of duplicates, but want to keep the one with less number of NULL values.
Let me explain it with a quick example. I am working with a query similar to this.

CREATE TABLE test (ID INT, b char(1), c char (1), d char(1))

INSERT INTO test(ID,b,c,d) VALUES
(1,NULL,NULL,NULL),
(1,'B', NULL,NULL),
(1,'B','C',NULL),
(1,'B','C','D'),
(2,'E','F',NULL),
(2,'E',NULL,NULL),
(3,NULL,NULL,NULL),
(3,'G',NULL,NULL)

SELECT DISTINCT ID,b,c,d FROM test

DROP TABLE test

The result is

ID  b     c     d
--------------------
1   NULL  NULL  NULL
1   B     NULL  NULL
1   B     C     NULL
1   B     C     D
2   E     F     NULL
2   E     NULL  NULL
3   NULL  NULL  NULL
3   G     NULL  NULL

However, the output I want to see is

ID  b     c     d
--------------------
1   B     C     D
2   E     F     NULL
3   G     NULL  NULL

So, based on the id and if there are duplicates, I want to have the row with the least number of nulls. How is it possible?
Thank you very much

A: If you want the row with the least number of NULLs, then you would basically count them:
select t.*
from test t
order by ( (case when b is null then 1 else 0 end) +
           (case when c is null then 1 else 0 end) +
           (case when d is null then 1 else 0 end)
         ) desc
fetch first 1 row only;

However, if you want one row per id with a non-NULL value in each column (if available) then @maSTAShuFu's answer is appropriate.
EDIT:
If you want one row per client, then simply use row_number():
select t.*
from (select t.*,
             row_number() over (partition by client_id
                                order by ( (case when b is null then 1 else 0 end) +
                                           (case when c is null then 1 else 0 end) +
                                           (case when d is null then 1 else 0 end)
                                         ) desc
                                ) as seqnum
      from t
     ) t
where seqnum = 1;

A: using MAX.
SELECT
  MAX(ID) ID,
  MAX(B) B,
  MAX(C) C,
  MAX(D) D
FROM test


text:
Q: how to get height of event while setting the content in eventContent for fullcalendar v5 how we can get height of event while setting the content in eventContent for fullcalendar v5.
i have checked the code and it is generated automatically, but i want to get the height at  eventContent to hide/show info depending on height.

A: Make a hook on
"eventDidMount" :
link
an search in arg.el for the item.
arg.el.find(".fc-title")  // jQuery, geht aber auch ohne

get the height
.height()  // jQuery, geht aber auch ohne

Summary:
eventDidMount:function(argE) {
    h = arg.el.find(".fc-title").height();
    if(typeof(h) != "undefined") {
       if (h > 20) {
       // ... your code
       }
    }
    return (argE.event._def.title;); // dont forget the reason for this hook
},  // <= das Komma für die Liste nicht vergessen


text:
Q: Tomcat 8 Basic auth i am trying to implement BASIC auth in Apache Tomcat, but encounter a strange problem.
when i access the http://localhost:8080. The box is show allow to enter username and password, the problem is it seens can not auth success, the box show again and again.
below is my setting:
/WEB-INF/web.xml
 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">

  <display-name>test</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <security-constraint>
    <web-resource-collection>
        <web-resource-name></web-resource-name>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>manager</role-name>
    </auth-constraint>
   </security-constraint>

   <login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>my realm</realm-name>
   </login-config>

</web-app>

apache-tomcat-8.0.14/conf/tomcat-users.xml
<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<tomcat-users>
<!--
  NOTE:  By default, no user is included in the "manager-gui" role required
  to operate the "/manager/html" web application.  If you wish to use this app,
  you must define such a user - the username and password are arbitrary.
-->
<!--
  NOTE:  The sample user and role entries below are wrapped in a comment
  and thus are ignored when reading this file. Do not forget to remove
  <!.. ..> that surrounds them.
-->
<!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>
-->
  <role rolename="manager" />

<!--
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
-->
  <user username="manager" password="manager" roles="manager"/>

</tomcat-users>

this is my project structure
WebContent/index.jsp
just a welcome file.
what did i do wrong? or what did i miss? i have searched much for this but still can not find a solution.
i am new to stackoverflow, hope my question is clear, and some body can help!

A: If you are using Eclipse integrated Tomcat, then configure tomcat-users.xml file that you can see in left navigation panel of your project. Servers --> Tomcat --> tomcat-users.xml
Remove my realm from your web.xml if you have not configured a realm called 'my realm' or set my-realm value as 'default'.


text:
Q: Error on Apply lambda function to multiple columns pandas I'm looking to include multiple columns in a lambda function on the following df:
target_df.columns
Index(['Surname', 'Name', 'Sex', 'BirthDate', 'BirthPlace', 'FiscalCode'], dtype='object')

but is seems do not recognize a column name:
target_df['FiscalCode'] = target_df.apply(lambda x: codicefiscale.encode(x['Surname'], x['Name'], x['Sex'], x['BirthDate'], x['BirthPlace']))
target_df

---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2897             try:
-> 2898                 return self._engine.get_loc(casted_key)
   2899             except KeyError as err:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()

KeyError: 'Surname'
...
   2902         if tolerance is not None:

KeyError: 'Surname'

A: I solved it this way:
target_df['FiscalCode'] = target_df.apply(lambda x: codicefiscale.encode(x["Surname"], x["Name"], x["Sex"], x["BirthDate"], x["BirthPlace"]), axis=1)


text:
Q: Return any items that cost less than $300 in Ruby Hash I want to return any items that are cheap, which should return any items that cost less than $300.
This is the main class;
class ShoesInventory
  def initialize(items)
    @items = items
  end

  def cheap
    # this is my solution, but it just print out an array of boolean
    @items.map { |item| item[:price] < 30 }

    # to be implemented
  end
end

This is an instance of the class ;
ShoesInventory.new([
  {price: 101.00, name: "Nike Air Force 1 Low"}},
  {price: 232.00, name: "Jordan 4 Retro"},
  {price: 230.99, name: "adidas Yeezy Boost 350 V2"},
  {price: 728.00, name: "Nike Dunk Low"}
]).cheap

I want the result to be like this;
# => [
#      {price: 101.00, name: "Nike Air Force 1 Low"}},
#      {price: 232.00, name: "Jordan 4 Retro"},
#      {price: 230.99, name: "adidas Yeezy Boost 350 V2"},
#    ]

Can you guide me ?

A: What you're looking for is Enumerable#select.
class ShoesInventory
  def initialize(items)
    @items = items
  end

  def cheap
    @items.select { |item| item[:price] < 30 }
  end
end

If you want to be able to chain methods, you might also want to return a new inventory instance:
def cheap
  self.class.new(@items.select { |item| item[:price] < 30 })
end


text:
Q: How can I get Mac Voiceover to read numbers as numbers instead of individual digits? When I render a number in a span tag, Mac Voiceover is reading individual digits instead of numbers. For example, 10 is read as "one zero" instead of "ten".
How can I make it read "ten" instead of "one zero"?
I have searched for answers, but it seems most people have the opposite problem. CSS properties like speak and speak-as seem to have no effect.
If you'd like to see an example, try loading up the following pen and having Mac Voiceover read it (to use Mac Voiceover, use Command + f5).
https://codepen.io/davescode/full/GeGLYv
Or literally just: 10

A: Ensure that your VoiceOver settings are set to read numbers as words:

Whenever I access the codepen from your question using these settings in Safari, the number is read as the word "ten", instead of the digits, "one zero".


text:
Q: How do create a "manager class" with events for android? Thank you, for reading this ;)
I have a class "scanner" with events that trigger when a barcode gets scanned and three activities. I want to let the user switch from activity to activity, but when an event is triggered in "scanner" i want the "scanner" class to start/resume a new activity (one of the three).
So, basically i want to create a "manager class" which events will always trigger, even if another activity is on the foreground.
How do i do this? I am coming from Xamarin Android so my Java knowledge isn't that great...

A: *

*Java equivalent for event is an Observer design Pattern. If you look at the button Click handler you'll see listener interface. Listener is an Observer of the event.

*If you want to handle navigation from any activity you need to have single navigation manager shared by activities. You can create singleton in Application inherited class.  See how this is achieved. And subscribe to scanner events using observer pattern. Then since you need to get access to navigation manager create base activity class and implement there Navigation Manager member and navigation methods. Inherit from this base activity your's 3 activities.


text:
Q: How to measure model complexity in the context of classification decision trees? Let us have some response variable y which can only get 0 or 1, and some predictor space in $X \in R^n$ (for illustration let's say $n=2$ and that we have $X1, X2$ two explanatory variables, each one between -1 to 1).
I can intuitively say that if the rule of the tree is only y = 1 if X1 > 0 (and 0 otherwise), then the model is not very complex. However, if I say that in order for y to be equal to 1 I need that X1 > 0 & X2 > 0, than this model "feels" to be more "complex". Also, if y = 1 only when observations in $X \in R^2$ are within the radius of 1/2 (i.e. a circle that within it y = 1 and outside of it y = 0), then it is clear I will need infinite number of linear splits in order to create a model that knows when y is 0 and when it is 1. It would also seem to me to be a more "complex" model than the one where y = 1 only when observations in $X \in R^2$ are within the radius of 1/10000 (since then most of the observations would just be 0).
Which type of measure(s) could help here?

A: I believe this has been discussed in the literature. In regression context, the measures of model complexity utilize the linear regression relation of the rank of the projection matrix being equal to the number of (non-collinear) regressors. So Ye (1998) generalized this by perturbing the data $\tilde y_i^{(k)} \leftarrow y_i + \delta_i^{(k)}$, running your favorite machine learning model (these were called data mining back then) on these perturbed data, getting predictions $\hat y_i^{(k)}$, and measuring how much the predictions changed in response to perturbations. Repeating this many times, you collect a big data set with such predictions as outcomes, and the magnitude of perturbations as regressors, $\hat y_i^{(k)} \sim \mbox{const} + h_i \delta_i^{(k)}$. Then the sum of regression coefficients $h_i$ gives you the degrees of freedom.
The HTF ESL book repeats this argument in Section 7.6, although without attribution to Ye. They further discuss MDL and VC dimension, which are probably relevant to your case, too.

A: First, it is important to note that you are not talking about the complexity of the model, but the complexity of the relation between X and Y, which has nothing to do with modelling. When we try to figure out such relations, we use models, which typically involve some kind of assumptions, etc. in order to track down that relationship. but there is an inherent difference between the complexity of the underlying relationship and the complexity of a model.
Given that, there is always a tradeoff between model complexity (in some intuitive sense) and model accuracy. when there is underlying complex relationship we try to model, the simpler the model is, the less accurate are its prediction likely to be. So the underlying relationship complexity is in some sense the "sum" of actual model complexity and its lack of fit.
I think that the AIC measure is an attempt to capture such complexity (that takes into account both inaccuracy and the model's "degrees of freedom" so to speak. I use it often to compare models that fall under common "strategies" even if they do not contain the same variables (e.g. two logistic regressions with the same response, but with different set of predictors), but tend to find it less useful/reliable comparing models of different nature.
Second, the example you bring about the circle, emphasize the importance of feature representation and two different sources of "complexity". after all, with a simple polar transformation, the circle with fixed radius become analogous to your first example. so what is worse? another explanatory variable or a transformation on an existing one? and is sin(x) is more complex that x^2 as transformations?
This is to emphasize how "measure of complexity" is totally dependent on the context. you must have some kind of a "loss function" that will quantify/penalize you for any "step" you do in order to get from X to Y. and this function is unlikely to have universal features. it is context specific.
I know this is not the kind of answer that you expected (sorry), But I do think there is no hope for the expectation you expressed in your question.
HTH


text:
Q: Which parts of DirectShow's Filter Graph Manager are thread safe? The MSDN doesn't say. IGraphBuilder has a function Abort. That implies that at the very least it's safe to call Abort and any one other IGraphBuilder function at the same time. With this question, I want to obtain proof that Filter Graph Manager is thread safer than that.

A: DirectShow is thread safe and is typically working on multiple threads even in simple scenarios. For example, a source filter typically owns its own worker thread and streams from there.


text:
Q: How do I find the smallest, largest value and total and the average in a 2D list that the user provides in python? How do I find the smallest, largest value and total and the average in a 2D list that the user provides in python?

A: You can flatten it first.
a = [[1, 2], [3, 4]]
flattened = [num for sublist in a for num in sublist]
min_val = min(flattened)
max_val = max(flattened)
sum_val = sum(flattened)
avg_val = sum(flattened) / len(flattened)

So in your case it'll be:
def list_stats(a):
    flattened = [num for sublist in a for num in sublist]
    min_val = min(flattened)
    max_val = max(flattened)
    sum_val = sum(flattened)
    avg_val = sum_val / len(flattened)
    return min_val, max_val, sum_val, avg_val

#Testing
a = [[1.2,3.5],[5.5,4.2]]
small, large, total, average = list_stats(a)

A:
This what I have so far:

    a = [[]]
    total = 0
    counter = 0
    small = a[0][0]
    for i in a:
        if i > small:
            return True
            total += i
            counter += 1
    average = total / counter
    return small, large, total, average

#Testing
a = [[1.2,3.5],[5.5,4.2]]
small, large, total, average = list_stats(a)

I'm getting the following two errors: small, large, total, average =
  list_stats(a) small = a[0][0] IndexError: list index out of range

The function list_stats is not defined.
a = [[]] is a list that contains an empty list. a[0][0] is an element that does not exist.

A: try this:
def list_stats(a):
    total = 0
    counter = 0
    small = 99999
    large = -999
    for x in a:
        for y in x:
            if y < small:
                small = y
            if y > large:
                large = y
            counter += 1
            total += y
    average = total / counter
    return small, large, total, average

I like Eric's answer better


text:
Q: Limiting input range of integer in QTableWidget column I am writing a table using QTableWidget. How can I limit the range of input (to 0 r 1 for example) in one particular column of the table?
Is delegating the only option?


text:
Q: Detecting Duplicate Entries, Listview? I have a listview in which a user can browse for assemblies, the problem is that the user can add the same entry from the dialogbox. This is useless and does not account for anything, so how can i get rid of this?
My question is, how does one compare with the item in the listview so that it does rule this out. Yes! There has already been a question about this but neither of the answers helped.
I just need guidance, as I can't find many good examples on the net.
Thanks

A: You can use LINQ:
string newName = searcha.GetName().Name;
if (!assemblyView.Items.Cast<ListViewItem>().Any(lvi => lvi.Text == newName))

A: I would basically keep what you already have but instead of throwing an error I would just not add it and move the existing item to the top (or bottom) of the ListBox.  It's not really an error; it's more like they can't find what they were looking for so they added a new one.


text:
Q: codegen and scalar struct argument Codegen commands like this:
codegen -config:dll ep1 -args single(0) ep2 -args {0,0}

are easy for functions like this:
function y = ep1(u) %#codegen
y = u;

function y = ep2(u, v) %#codegen
y = u + v;

I am just wondering how to define scalar struct arguments. Let us assume that the above argument u should look like this (i.e. consist of 2 fields - one char and one double):
u.FirstName = 'Loren';
u.Height = 150

PS:
Just found something like this:
s = struct('a',42,'b',4711);
codegen topfun.m -args { s }

would this be a solution? I believe, this is a definition by example.

A: This seems to work for me:
codegen -report -config:dll ep1 ...
                            ep2

The actual 'function signature' (and thus scalar struct) can be defined in the function like this:
function [bla] = ep1(parameters)
%#codegen

assert(isstruct(parameters));
assert(isa(parameters.x1,'char'));
assert(size(parameters.x1, 1) >= 1);
assert(size(parameters.x1, 1) <= 1024);
assert(isa(parameters.x2,'double'));
...

Problem I have is that I seem to have to define all the parameters in the parent functions even-though I do not use the parameter in the parent function.
Looking at the stuff above. Let us say ep1 is the parent function of ep2 and ep1 does not use parameters.x2, I still have to assert it in ep1.Hope this makes sense.

A: The definitions of the structs can be captured using the coder.typeof function.
First initialise the structs using a script, capture the struct definitions using coder.typeof and then pass the definitions using -args as shown below:
u = Initialise(u);
p = InitialiseParameters();

tx = coder.typeof(u);
tp = coder.typeof(p);

codegen topfun.m -args {tx, tp} -config:dll


text:
Q: PHP Singleton pattern, fatal error when calling getter I am pretty new to PHP and try to learn it the OOP way as I have an understanding of it. My problem is I have no idea why I am getting the null error below when I try to get the mysqli connection.

Fatal error: Uncaught Error: Call to a member function getConn() on
  null

    <?php

class ConnectDB
{
    private $conn;

    private function __construct()
    {
        $this->conn = new mysqli('localhost', 'root', 'root', 'gs');
        $this->checkConnection();
    }

    public function getConn()
    {
        return $this->conn;
    }

    /**
     * @return ConnectDB
     */
    public static function getInstance()
    {
        static $instance = null;
        if($instance == null)
        {
            $instance == new ConnectDB();
        }
        return $instance;
    }

    public function checkConnection()
    {
        if($this->conn->connect_errno)
        {
            echo "Can't connect to Database: " .mysqli_connect_error();
            exit();
        }
        else
        {
            echo "Connected!";
        }

    }

}

$conn = ConnectDB::getInstance()->getConn();

A: In your getInstance method, where you create the class instance you wrote $instance == new ConnectDB();. Use a single = for assignments.
I don't think that your getInstance method is a singleton at all. You are initializing the variable $instance in every call to null, so you should get a new instance every time.
Try it like this:
class ConnectDB
{
    private $conn;
    private static $instance = null;
    ...
    public static function getInstance()
    {
        if(self::$instance == null)
        {
            self::$instance == new ConnectDB();
        }
        return self::$instance;
    }
    ...

A: See if you can make this work:
<?php

class ConnectDB {
    private $_connection;
    private static $_instance; //The single instance
    private $_host = "localhost";
    private $_username = "root";
    private $_password = "root";
    private $_database = "gs";

    //
    public static function getInstance() {
        if(!self::$_instance) { // If no instance then make one
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    // Constructor
    private function __construct() {
        $this->_connection = new mysqli($this->_host, $this->_username, $this->_password, $this->_database);

        // Error handling
        if(mysqli_connect_error()) {
            trigger_error(
                "Failed to conencto to MySQL: " . mysql_connect_error(),E_USER_ERROR
            );
        } else{
            echo "Connected!";
        }
    }

    private function __clone() { }

    public function getConn() {
        return $this->_connection;
    }

    $db = ConnectDB::getInstance();
    $mysqli = $db->getConn();

}
?>


text:
Q: Disable/Enable USB port Android Xamarin I need to disable/enable a USB port from an Android device, the project is Xamarin Android.
I've just test the USBManager class, from USB Host API, but I need to detach the USB device programmaticaly, and not only disconnect it.
Are there some libraries or work around to manage this kind of problems?
Thanks.


text:
Q: vpnc connects but does not set up nameservers in /etc/resolv.conf I am not a big Ubuntu guru, running 12.04 LTS version. I need to connect via vpnc from university to the work network. Logging in works fine, however I cannot reach any machine behind the VPN. Also, my internet still works w/o me setting up the work proxy. Any help is highly appreciated!
This is my /etc/resolv.conf before connecting:
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
nameserver 127.0.0.1
search [university-domain]

And this is the same file after connection has been set up:
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
nameserver 127.0.0.1
search [university-domain] [work-domain]

From looking at other resov.conf contents on my colleagues' machines, the nameserver is not updated to the one within the work network. This is how my colleagues' resolv.conf looks:
# Generated by NetworkManager
domain [work-domain]
search [work-domain]
nameserver 147.243.4.86
nameserver 147.243.4.70
nameserver 147.243.1.52
# NOTE: the libc resolver may not support more than 3 nameservers.
# The nameservers listed below may not be recognized.
nameserver 147.243.1.53
nameserver 147.243.128.216
nameserver 147.243.128.217

My colleague runs an older Ubuntu version (11.04 I guess).
Please let me know!

A: Your /etc/resolv.conf looks correct both before and after you connect, assuming that you have a local forwarding nameserver running which listens at 127.0.0.1. In Ubuntu 12.04 Desktop such a nameserver is running by default. To see the nameserver process, run
ps -elf|grep dnsmasq

The reason your colleague's /etc/resolv.conf looks different is that your colleague is not running a local forwarding nameserver. Also, your colleague does not have the resolvconf package installed and so your colleague's NetworkManager process is writing directly to /etc/resolv.conf instead of using resolvconf for that purpose.
On your machine, addresses for work LAN nameservers should not appear in /etc/resolv.conf. That should continue to show only "nameserver 127.0.0.1" (or "nameserver 127.0.1.1" in Ubuntu 12.10.) The work LAN nameserver addresses should be sent by NetworkManager to the local forwarding resolver to use as forwarding addresses. To see what addresses have been sent, do
nmcli -f IP4 dev list | grep DNS

In Ubuntu 12.04 the addresses can also be seen in /run/nm-dns-dnsmasq.conf but in Ubuntu 12.10 the addresses are sent from NM to dnsmasq over D-Bus and so can't be inspected that way.
In the original question it is not even clear that the problem is DNS-specific. Does the questioner have any network connectivity at all with the work LAN?  Can the questioner ping IP addresses on the work LAN?


text:
Q: Transaction log partition still full after full backup? I'm just curious and confused, how come after full backup of my Exchange Server 2007 SP1 with CCR using HP Data Protector (A06.11) one of my Storage Group transaction log partition still not cleared ?
While the other partitions can be as low as 0.1 GB after the full backup, but only this one particular stays about 11 GB

A: Firstly, are you using an Exchange aware backup application and is it set up correctly? Check you're specifically doing an Exchange aware backup job (as opposed to some shadow copy of the .edb and log files) and that all license keys and/or agents required are correctly installed and configured.
Secondly, assuming the application is doing an Exchange aware backup - are the backups actually completing successfully? Your backup application should be able to provide you with information as to whether the backup completed, failed or skipped some things - that would be a good log to interrogate. The Exchange server itself will also log events relating to ESE backups - they might be worth checking out in this case.
Lastly, it may sound like a dumb thing to say, but are the log files you see definitely associated with a database that you have just backed up? Is there any possibility these log files belong to another database that is either not being backed up, has backups failing, or the database itself has simply been deleted and the logs left in place.


text:
Q: Xcode UI tests - Lost connection to test manager service Sometimes while running my UI tests, I get the following error Lost connection to test manager services. No logs or anything. Happens randomly. I would provide more information but I just don't have it because of the nature of the error.
Using Xcode 7 beta 5.

A: The error appear for every async operations made in tests. It can be:

*

*Operation on non existing object

*dispatch_after

*Network operations with wrongly assign block handler

A: I was getting the same error when running UI tests written in Swift. It turned out that the memory usage was increasing constantly when running a longer test (no memory release). When memory had been exhausted, the device "Lost connection to test manager services."
The solution? Using 'autoreleasepool' in its Swift version, in proper places.


text:
Q: "Keep one's fingers crossed" VS Wish I am wondering how the following sentences differ in meaning:

I wish you success.
I keep my fingers crossed for you.

I cannot come up with any nuance myself.

A: Wishing someone success is a simple expression of goodwill.
Keeping your fingers crossed is a superstitious gesture which is supposed to bring good luck. Doing it for someone else (or claiming to) implies 'hoping for the best', perhaps fearing that what they plan to do is something risky.


text:
Q: Lodash complicated key value replace I am using lodash/_, and I'd like to generate the following output from the input JSON.
Any input on how to achieve this, would be great.
Input:
{
    "hex": "#EFDECD",
    "name": "Almond",
    "rgb": "(239, 222, 205)"
},
{
    "hex": "#CD9575",
    "name": "Antique Brass",
    "rgb": "(205, 149, 117)"
},

Desired Output:
{
  Almond: '#EFDECD',
  Antique Brass: '#CD9575',
  ...
};

Thanks for your time

A: You can use plain Javascript to achieve that (Array.prototype.reduce):

const collection = [{
    hex: '#EFDECD',
    name: 'Almond',
    rgb: '(239, 222, 205)',
  },
  {
    hex: '#CD9575',
    name: 'Antique Brass',
    rgb: '(205, 149, 117)',
  },
]

const sorted = collection.reduce((result, el) => {
  result[el.name] = el.hex
  return result
}, {})
console.log(sorted)

A: Use can use Array.prototype.reduce method for this:
let data = [{
  "hex": "#EFDECD",
  "name": "Almond",
  "rgb": "(239, 222, 205)"
},
{
  "hex": "#CD9575",
  "name": "Antique Brass",
  "rgb": "(205, 149, 117)"
}];

let newData = data.reduce((result, elem) => {
    result[elem.name] = elem.hex
    return result;
}, {});

A: Just incase you really do want to lodash, the reduce function is indeed available there too:

const collection = [{
    hex: '#EFDECD',
    name: 'Almond',
    rgb: '(239, 222, 205)',
  },
  {
    hex: '#CD9575',
    name: 'Antique Brass',
    rgb: '(205, 149, 117)',
  },
]

const sorted = _.reduce(collection, (result, el) => {
    result[el.name] = el.hex
    return result
}, {})

console.log(sorted)
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>


text:
Q: cut command --complement flag equivalent in AWK I am new to writing shell scripts
I am trying to write an AWK command which does exactly the below
cut --complement -c $IGNORE_RANGE file.txt > tmp

$IGNORE_RANGE can be of any value say, 1-5 or 5-10 etc
i cannot use cut since i am in AIX and AIX does not support --complement, is there any way to achieve this using AWK command
Example:
file.txt
abcdef
123456

Output
cut --complement -c 1-2 file.txt > tmp

cdef
3456

cut --complement -c 4-5 file.txt > tmp
abcf
1236

cut --complement -c 1-5 file.txt > tmp
f
6

A: Could you please try following, written and tested with shown samples. We have range variable of awk which should be in start_of_position-end_of_position and we could pass it as per need.
awk -v range="4-5" '
BEGIN{
  split(range,array,"-")
}
{
  print substr($0,1,array[1]-1) substr($0,array[2]+1)
}
' Input_file

OR to make it more clear in understanding wise try following:
awk -v range="4-5" '
BEGIN{
  split(range,array,"-")
  start=array[1]
  end=array[2]
}
{
  print substr($0,1,start-1) substr($0,end+1)
}
'  Input_file

Explanation: Adding detailed explanation for above.
awk -v range="4-5" '                                ##Starting awk program from here creating range variable which has range value of positions which we do not want to print in lines.
BEGIN{                                              ##Starting BEGIN section of this program from here.
  split(range,array,"-")                            ##Splitting range variable into array with delimiter of - here.
  start=array[1]                                    ##Assigning 1st element of array to start variable here.
  end=array[2]                                      ##Assigning 2nd element of array to end variable here.
}
{
  print substr($0,1,start-1) substr($0,end+1)       ##Printing sub-string of current line from 1 to till value of start-1 and then printing from end+1 which basically means will skip that range of characters which OP does not want to print.
}
'  Input_file                                       ##Mentioning Input_file name here.

A: You can do this in awk:
awk -v st=1 -v en=2 '{print substr($0, 1, st-1) substr($0, en+1)}' file

cdef
3456

Or:
awk -v st=4 -v en=5 '{print substr($0, 1, st-1) substr($0, en+1)}' file

abcf
1236


text:
Q: c++ Legacy code using method const , still need to create function that takes const method members i have legacy c++ code that is const method :
Id LegacyCode::GetIdByName(const char* sName,
                          const char* pName) const
{

  long lID;
  char szProcessName[MAXPATH];
  for (int iP = 0;
       iP < iNum;
       iP++) {

      if (strnicmp(sName, "Test.exe", MAX_LENGTH) == 0)
      {
          if (strnicmp(szProcessName, pName, MAX_LENGTH) == 0)
          {
              // If the proces name was found, return its ID.

                return (lID);
          }
      }
      else if (strnicmp(sName, "Test2.exe", MAX_LENGTH) == 0)
      {
          if (strnicmp(szProcessName, pName, MAX_LENGTH) == 0)
          {
              // If the proces name was found, return its ID.

                return (lID);
          }
      }
      else
      {

        if (strnicmp(sName, szProcessName, MAX_LENGTH) == 0)
         return (lID);
      }
  }

  return (0);
}

and i like to replace it with shorter code like this using the helper function
Id LegacyCode::GetIdByName(const char* sName,
                          const char* pName) const
{

  long lID;
  char szProcessName[MAXPATH];
  for (int iP = 0;
       iP < iNum;
       iP++) {

      if (isProcessName(sName,pName,szProcessName))
      {
                return (lID);

      }
      else
      {

        if (strnicmp(sName, szProcessName, MAX_LENGTH) == 0)
         return (lID);
      }
  }

  return (0);
}

bool LegacyCode::isProcessName(char* _sName,char* _pName,char* _szProcessName)
{
       if (strnicmp(_sName, "Test.exe", MAX_LENGTH) == 0)
      {
          if (strnicmp(_szProcessName, pName, MAX_LENGTH) == 0)
          {
              // If the proces name was found, return its ID.

                return (lID);
          }
      }
      else if (strnicmp(sName, "Test2.exe", MAX_LENGTH) == 0)
      {
          if (strnicmp(_szProcessName, pName, MAX_LENGTH) == 0)
          {
              // If the proces name was found, return its ID.

                return (lID);
          }
      }
      return false;
}

but Unfortunately im getting the const error:
error C2662: 'LegacyCode::isProcessName' : cannot convert 'this' pointer from 'const LegacyCode' to 'LegacyCode &'

is there any way to overcome this without adding mutable to the function membres ?

A: Make LegacyCode::isProcessName const:
bool LegacyCode::isProcessName(char* _sName,char* _pName,char* _szProcessName) const;


text:
Q: PHP - cronjob failing to execute on Ubuntu 18.04 I have a PHP file that I want to run as a cron job.
On the server the file is located at /var/www/html/directory/file.php and has no errors as it can be run in the browser by going to www.exampledomain.com/directory/file.php.
In the file /etc/crontab I have the following line:
* * * * * root /usr/bin/php /var/www/html/directory/file.php >/dev/null 2>&1
On my server typing sudo service cron status I see:
● cron.service - Regular background program processing daemon
   Loaded: loaded (/lib/systemd/system/cron.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2021-07-29 10:23:11 UTC; 4 months 23 days ago
     Docs: man:cron(8)
 Main PID: 769 (cron)
    Tasks: 1 (limit: 1140)
   CGroup: /system.slice/cron.service
           └─769 /usr/sbin/cron -f

Dec 21 17:46:01 ip-172-31-34-251 CRON[20648]: (ubuntu) CMD (root /usr/bin/php /var/www/html/directory/file.php >/dev/null
Dec 21 17:46:01 ip-172-31-34-251 CRON[20649]: (root) CMD (root /usr/bin/php /var/www/html/directory/file.php >/dev/null 2
Dec 21 17:46:01 ip-172-31-34-251 CRON[20647]: pam_unix(cron:session): session closed for user ubuntu
Dec 21 17:46:01 ip-172-31-34-251 CRON[20646]: pam_unix(cron:session): session closed for user root
Dec 21 17:47:01 ip-172-31-34-251 CRON[20661]: pam_unix(cron:session): session opened for user ubuntu by (uid=0)
Dec 21 17:47:01 ip-172-31-34-251 CRON[20660]: pam_unix(cron:session): session opened for user root by (uid=0)
Dec 21 17:47:01 ip-172-31-34-251 CRON[20662]: (ubuntu) CMD (root /usr/bin/php /var/www/html/directory/file.php >/dev/null
Dec 21 17:47:01 ip-172-31-34-251 CRON[20663]: (root) CMD (root /usr/bin/php /var/www/html/directory/file.php >/dev/null 2
Dec 21 17:47:01 ip-172-31-34-251 CRON[20661]: pam_unix(cron:session): session closed for user ubuntu
Dec 21 17:47:01 ip-172-31-34-251 CRON[20660]: pam_unix(cron:session): session closed for user root

The cron job is supposed to update another file but that is not happening. What is going wrong or what can I do to troubleshoot this further. Previously I would have used cron as a service in a hosted domain but have only recently started using ubuntu so am unsure of linux commands.

A: Don't use /etc/crontab to run your cron jobs. Instead use the user account that you wish to run the job under. The environment for system crons will almost never match what you need to run the job you want to do. So in this case, su to the root user and then crontab -e or sudo crontab -e. Then make your entry as such...
* * * * * /usr/bin/php /var/www/html/directory/file.php >/dev/null 2>&1


text:
Q: Multinomial logit model in R with class factor predictors I am running multinomial logit model using mlogit in R. The model includes 3 alternatives as the dependent variable and 4 individual specific predictors. Sample size is 50. The three of them are of class:factor while the other predictor is in class numeric.
When I run model with ONLY 3 class factor predictors it works OK. But when I include numeric predictor along with the above three predictors it returns the following error in R.
mlogit_model<-mlogit(y ~ 1| x1+x2+x3+x4, data=dat_long, reflevel = "3")

Error in solve.default(H, g[!fixed]) :
system is computationally singular: reciprocal condition number =   8.31637e-17

What could be the reason for this error? I searched for this and found several related posts online, but in this case multi-collinearity eg would not be the cause because the problem with numeric and factor variables.
Any help would be much appreciated.