答:
You should consider using np.random.randint() This function takes a range as an input.
For example,

```<code>>>> np.random.randint(2)
</code>```

This will give you an output of either 0 or 1

Title: How do you produce a random 0 or 1 with random.rand

Body:
I'm trying to produce a 0 or 1 with numpy's random.rand.

np.random.rand() produces a random float between 0 and 1 but not just a 0 or a 1.

Thank you.

Body:
You should consider using np.random.randint() This function takes a range as an input.
For example,

>>> np.random.randint(2)

This will give you an output of either 0 or 1


来源: stackexchange

问:
How to access google chrome extension from any page's javascript
I am trying to figure out how can I call into my extension from a normal web page.
All documentation that I find seems to be either for communication between extensions, or between content scripts and extensions.

Any pointers are much appreciated!

答:
I think you should make a content script, that injects an object into your page that calls your extension.

Create a content script that injects YourExt.js into every page, which should contain:

```<code>var YourExt = {
doThis: function () {
    chrome.extension.sendRequest('doThis');
},
doThat: function () {
    chrome.extension.sendRequest({
        action: 'doThat',
        params: ['foo','bar']
    });
}
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I think you should make a content script, that injects an object into your page that calls your extension.

Create a content script that injects YourExt.js into every page, which should contain:

var YourExt = {
doThis: function () {
    chrome.extension.sendRequest('doThis');
},
doThat: function () {
    chrome.extension.sendRequest({
        action: 'doThat',
        params: ['foo','bar']
    });
}
}


问:
How to set the default JDBC URL value in H2 console using spring boot
I have enable the H2 console in spring boot. However, when I open the console connection page the default url is the one staved in the H2 console history.  How can i configure the project to populate the URL to be the same as spring.datasource.url on project start? Currently I set the url in the console manually but I would like to have it setup automatically by the project itself.

yaml:

```<code>spring:
  h2:
    console:
      enabled: true
      path: /admin/h2

  datasource:
    url: jdbc:h2:mem:foobar
</code>```

update:
I know that the last connection settings are saved to ~/.h2.server.properties but what I need is to set the properties from the starting application potentially, potentially switching between several of them

答:
There is no hook provided to fill in settings.

The good news is that we can change that with a bit of code.

Current state

The Login screen is created in WebApp.index()

String[] settingNames = server.getSettingNames();
String setting = attributes.getProperty("setting");
if (setting == null && settingNames.length > 0) {
    setting = settingNames[0];
}
String combobox = getComboBox(settingNames, setting);
session.put("settingsList", combobox);
ConnectionInfo info = server.getSetting(setting);
if (info == null) {
    info = new ConnectionInfo();
}
session.put("setting", PageParser.escapeHtmlData(setting));
session.put("name", PageParser.escapeHtmlData(setting));
session.put("driver", PageParser.escapeHtmlData(info.driver));
session.put("url", PageParser.escapeHtmlData(info.url));
session.put("user", PageParser.escapeHtmlData(info.user));
return "index.jsp";
```

<p>We want to tap into <code>server.getSettingNames()</code>, and precisely into <code>server.getSettings()</code> used underneath.</p>

<pre class="lang-java prettyprint-override"><code>synchronized ArrayList<ConnectionInfo> getSettings() {
    ArrayList<ConnectionInfo> settings = new ArrayList<>();
    if (connInfoMap.size() == 0) {
        Properties prop = loadProperties();
        if (prop.size() == 0) {
            for (String gen : GENERIC) {
                ConnectionInfo info = new ConnectionInfo(gen);
                settings.add(info);
                updateSetting(info);
            }
        } else {
            for (int i = 0;; i++) {
                String data = prop.getProperty(Integer.toString(i));
                if (data == null) {
                    break;
                }
                ConnectionInfo info = new ConnectionInfo(data);
                settings.add(info);
                updateSetting(info);
            }
        }
    } else {
        settings.addAll(connInfoMap.values());
    }
    Collections.sort(settings);
    return settings;
}
</code>```

The plan

disable ServletRegistrationBean<WebServlet> created by H2ConsoleAutoConfiguration

replace it with our config class with a subclass of WebServlet

our CustomH2WebServlet will override init and register CustomH2WebServer (subclass of WebServer)

in CustomH2WebServer we override getSettings() and we are done

The Code

@EnableConfigurationProperties({H2ConsoleProperties.class, DataSourceProperties.class})
@Configuration
public class H2Config {

    private final H2ConsoleProperties h2ConsoleProperties;

    private final DataSourceProperties dataSourceProperties;

    public H2Config(H2ConsoleProperties h2ConsoleProperties, DataSourceProperties dataSourceProperties) {
        this.h2ConsoleProperties = h2ConsoleProperties;
        this.dataSourceProperties = dataSourceProperties;
    }

    @Bean
    public ServletRegistrationBean<WebServlet> h2Console() {
        String path = this.h2ConsoleProperties.getPath();
        String urlMapping = path + (path.endsWith("/") ? "*" : "/*");
        ServletRegistrationBean<WebServlet> registration = new ServletRegistrationBean<>(
                new CustomH2WebServlet(this.dataSourceProperties.getUrl()), urlMapping);
        H2ConsoleProperties.Settings settings = this.h2ConsoleProperties.getSettings();
        if (settings.isTrace()) {
            registration.addInitParameter("trace", "");
        }
        if (settings.isWebAllowOthers()) {
            registration.addInitParameter("webAllowOthers", "");
        }
        return registration;
    }
}

```

<pre class="lang-java prettyprint-override"><code>package org.h2.server.web;

import javax.servlet.ServletConfig;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Enumeration;

public class CustomH2WebServlet extends WebServlet {

    private final String dbUrl;

    public CustomH2WebServlet(String dbUrl) {
        this.dbUrl = dbUrl;
    }

    @Override
    public void init() {
        ServletConfig config = getServletConfig();
        Enumeration<?> en = config.getInitParameterNames();
        ArrayList<String> list = new ArrayList<>();
        while (en.hasMoreElements()) {
            String name = en.nextElement().toString();
            String value = config.getInitParameter(name);
            if (!name.startsWith("-")) {
                name = "-" + name;
            }
            list.add(name);
            if (value.length() > 0) {
                list.add(value);
            }
        }
        String[] args = list.toArray(new String[0]);
        WebServer server = new CustomH2WebServer(dbUrl);
        server.setAllowChunked(false);
        server.init(args);
        setServerWithReflection(this, server);
    }

    private static void setServerWithReflection(final WebServlet classInstance, final WebServer newValue) {
        try {
            final Field field = WebServlet.class.getDeclaredField("server");
            field.setAccessible(true);
            field.set(classInstance, newValue);
        }
        catch (SecurityException|NoSuchFieldException|IllegalArgumentException|IllegalAccessException ex) {
            throw new RuntimeException(ex);
        }
    }
}
</code>```

package org.h2.server.web;

import java.util.ArrayList;
import java.util.Collections;

class CustomH2WebServer extends WebServer {

    private final String connectionInfo;

    CustomH2WebServer(String dbUrl) {

        this.connectionInfo = "Test H2 (Embedded)|org.h2.Driver|" +dbUrl+"|sa";
    }

    synchronized ArrayList<ConnectionInfo> getSettings() {
        ArrayList<ConnectionInfo> settings = new ArrayList<>();
        ConnectionInfo info = new ConnectionInfo(connectionInfo);
        settings.add(info);
        updateSetting(info);
        Collections.sort(settings);
        return settings;
    }
}
```

```spring.h2.console.enabled=false
spring.datasource.url=jdbc:h2:mem:foobar

```

Everything went smoolthly, except of one private field that needed to be set via reflection.

The code provided works with H2 1.4.199

ContentLicense: CC BY-SA 4.0

Body:
I have enable the H2 console in spring boot. However, when I open the console connection page the default url is the one staved in the H2 console history.  How can i configure the project to populate the URL to be the same as spring.datasource.url on project start? Currently I set the url in the console manually but I would like to have it setup automatically by the project itself.

yaml:

spring:
  h2:
    console:
      enabled: true
      path: /admin/h2

  datasource:
    url: jdbc:h2:mem:foobar

update:
I know that the last connection settings are saved to ~/.h2.server.properties but what I need is to set the properties from the starting application potentially, potentially switching between several of them

Body:
There is no hook provided to fill in settings.

The good news is that we can change that with a bit of code.

Current state

The Login screen is created in WebApp.index()

String[] settingNames = server.getSettingNames();
String setting = attributes.getProperty("setting");
if (setting == null && settingNames.length > 0) {
    setting = settingNames[0];
}
String combobox = getComboBox(settingNames, setting);
session.put("settingsList", combobox);
ConnectionInfo info = server.getSetting(setting);
if (info == null) {
    info = new ConnectionInfo();
}
session.put("setting", PageParser.escapeHtmlData(setting));
session.put("name", PageParser.escapeHtmlData(setting));
session.put("driver", PageParser.escapeHtmlData(info.driver));
session.put("url", PageParser.escapeHtmlData(info.url));
session.put("user", PageParser.escapeHtmlData(info.user));
return "index.jsp";

We want to tap into server.getSettingNames(), and precisely into server.getSettings() used underneath.

synchronized ArrayList<ConnectionInfo> getSettings() {
    ArrayList<ConnectionInfo> settings = new ArrayList<>();
    if (connInfoMap.size() == 0) {
        Properties prop = loadProperties();
        if (prop.size() == 0) {
            for (String gen : GENERIC) {
                ConnectionInfo info = new ConnectionInfo(gen);
                settings.add(info);
                updateSetting(info);
            }
        } else {
            for (int i = 0;; i++) {
                String data = prop.getProperty(Integer.toString(i));
                if (data == null) {
                    break;
                }
                ConnectionInfo info = new ConnectionInfo(data);
                settings.add(info);
                updateSetting(info);
            }
        }
    } else {
        settings.addAll(connInfoMap.values());
    }
    Collections.sort(settings);
    return settings;
}

The plan

disable ServletRegistrationBean<WebServlet> created by H2ConsoleAutoConfiguration

replace it with our config class with a subclass of WebServlet

our CustomH2WebServlet will override init and register CustomH2WebServer (subclass of WebServer)

in CustomH2WebServer we override getSettings() and we are done

The Code

@EnableConfigurationProperties({H2ConsoleProperties.class, DataSourceProperties.class})
@Configuration
public class H2Config {

    private final H2ConsoleProperties h2ConsoleProperties;

    private final DataSourceProperties dataSourceProperties;

    public H2Config(H2ConsoleProperties h2ConsoleProperties, DataSourceProperties dataSourceProperties) {
        this.h2ConsoleProperties = h2ConsoleProperties;
        this.dataSourceProperties = dataSourceProperties;
    }

    @Bean
    public ServletRegistrationBean<WebServlet> h2Console() {
        String path = this.h2ConsoleProperties.getPath();
        String urlMapping = path + (path.endsWith("/") ? "*" : "/*");
        ServletRegistrationBean<WebServlet> registration = new ServletRegistrationBean<>(
                new CustomH2WebServlet(this.dataSourceProperties.getUrl()), urlMapping);
        H2ConsoleProperties.Settings settings = this.h2ConsoleProperties.getSettings();
        if (settings.isTrace()) {
            registration.addInitParameter("trace", "");
        }
        if (settings.isWebAllowOthers()) {
            registration.addInitParameter("webAllowOthers", "");
        }
        return registration;
    }
}

package org.h2.server.web;

import javax.servlet.ServletConfig;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Enumeration;

public class CustomH2WebServlet extends WebServlet {

    private final String dbUrl;

    public CustomH2WebServlet(String dbUrl) {
        this.dbUrl = dbUrl;
    }

    @Override
    public void init() {
        ServletConfig config = getServletConfig();
        Enumeration<?> en = config.getInitParameterNames();
        ArrayList<String> list = new ArrayList<>();
        while (en.hasMoreElements()) {
            String name = en.nextElement().toString();
            String value = config.getInitParameter(name);
            if (!name.startsWith("-")) {
                name = "-" + name;
            }
            list.add(name);
            if (value.length() > 0) {
                list.add(value);
            }
        }
        String[] args = list.toArray(new String[0]);
        WebServer server = new CustomH2WebServer(dbUrl);
        server.setAllowChunked(false);
        server.init(args);
        setServerWithReflection(this, server);
    }

    private static void setServerWithReflection(final WebServlet classInstance, final WebServer newValue) {
        try {
            final Field field = WebServlet.class.getDeclaredField("server");
            field.setAccessible(true);
            field.set(classInstance, newValue);
        }
        catch (SecurityException|NoSuchFieldException|IllegalArgumentException|IllegalAccessException ex) {
            throw new RuntimeException(ex);
        }
    }
}

package org.h2.server.web;

import java.util.ArrayList;
import java.util.Collections;

class CustomH2WebServer extends WebServer {

    private final String connectionInfo;

    CustomH2WebServer(String dbUrl) {

        this.connectionInfo = "Test H2 (Embedded)|org.h2.Driver|" +dbUrl+"|sa";
    }

    synchronized ArrayList<ConnectionInfo> getSettings() {
        ArrayList<ConnectionInfo> settings = new ArrayList<>();
        ConnectionInfo info = new ConnectionInfo(connectionInfo);
        settings.add(info);
        updateSetting(info);
        Collections.sort(settings);
        return settings;
    }
}

spring.h2.console.enabled=false
spring.datasource.url=jdbc:h2:mem:foobar

Everything went smoolthly, except of one private field that needed to be set via reflection.

The code provided works with H2 1.4.199


问:
executing python scripts from a server
I have some python scripts on a server machine and i want to run those programs from a different machine on the same network. is there any way to run those programs remotely using a path somewhat like "http(or ftp):/10.10.5.18/path/script.py"

i am at an internship and i have made some basic python programs working with csv files, txt files, apis, gmplot, databases, mysql, pymysql, sqlite etc.. We have installed IDLE on the server machine and also have put all the pythhon scripts on it. now, to prevent the company's employees from coming to me again and again to get their work done, i want to give them links to the programs so that they can do their tasks themselves. is that possible in a simple way?

答:
You can ssh into the system and run your scripts. (Linux)</p>

```<code>  #!/bin/bash

  ssh <my_user>@<my_host> "bash -s" << EOF
  # here you just type all your commmands, as you can see, i.e.
      python /tmp/test.py;
      python /tmp/test1.py;
      python /tmp/test2.py;
  EOF
</code>```

Title: executing python scripts from a server

Body:
You can ssh into the system and run your scripts. (Linux)

  #!/bin/bash

  ssh <my_user>@<my_host> "bash -s" << EOF
  # here you just type all your commmands, as you can see, i.e.
      python /tmp/test.py;
      python /tmp/test1.py;
      python /tmp/test2.py;
  EOF


问:
how to sum amount for each user?
I have data like this:

```<code> USER_ID   NUM   num_id
1   47641   800    1
2   47641   100    2
3   47641   250    3
4   70919   200    1
5   70919   200    2
6   70919   200    3
7   70919   200    4
</code>```

...

I have no idea what to try, result that i want is this:

```<code> USER_ID   NUM   num_id
1   47641   800    1
2   47641   100    2
3   47641   100    3
4   70919   200    1
5   70919   200    2
6   70919   200    3
7   70919   200    4
...
</code>```

so if for each user, sum of num < 1000 than all num must be same, but if sum of num for each user > 1000 for example for 47641 user we have 800 100 and 250 so we have to sum 800 and 100 and from 250 we need only 100 because 800+100+100=1000 so for num_id=3 we need only 100

I have not written some code...

I only want some ways what to try.
hope you will get idea of problem

答:
```<code>create table t1(
tuser number,
tnum number,
numid number
);
</code>```

Inserted records :

```<code>TUSER   TNUM    NUMID
47641   800     1
47641   100     2
47641   300     3
70919   200     1
70919   200     2
70919   200     3
70919   400     4
23451   800     1
23451   100     2
23451   600     3
</code>```

Solution query:

```<code>select Tuser,
case
when sum(Tnum) over(partition by Tuser order by numid)<=1000 then Tnum
when sum(Tnum) over(partition by Tuser order by numid)>1000 then 1000-((sum(Tnum) over(partition by Tuser order by numid))-tnum)
end Tnum,numid
from t1;
</code>```

Output:

```<code>TUSER   TNUM    NUMID
23451   800     1
23451   100     2
23451   100     3
47641   800     1
47641   100     2
47641   100     3
70919   200     1
70919   200     2
70919   200     3
70919   400     4
</code>```

Title: how to sum amount for each user?

Body:
I have data like this:

 USER_ID   NUM   num_id
1   47641   800    1
2   47641   100    2
3   47641   250    3
4   70919   200    1
5   70919   200    2
6   70919   200    3
7   70919   200    4

...

I have no idea what to try, result that i want is this:

 USER_ID   NUM   num_id
1   47641   800    1
2   47641   100    2
3   47641   100    3
4   70919   200    1
5   70919   200    2
6   70919   200    3
7   70919   200    4
...

so if for each user, sum of num < 1000 than all num must be same, but if sum of num for each user > 1000 for example for 47641 user we have 800 100 and 250 so we have to sum 800 and 100 and from 250 we need only 100 because 800+100+100=1000 so for num_id=3 we need only 100

I have not written some code...

I only want some ways what to try.
hope you will get idea of problem

Body:
create table t1(
tuser number,
tnum number,
numid number
);

Inserted records :

TUSER   TNUM    NUMID
47641   800     1
47641   100     2
47641   300     3
70919   200     1
70919   200     2
70919   200     3
70919   400     4
23451   800     1
23451   100     2
23451   600     3

Solution query:

select Tuser,
case
when sum(Tnum) over(partition by Tuser order by numid)<=1000 then Tnum
when sum(Tnum) over(partition by Tuser order by numid)>1000 then 1000-((sum(Tnum) over(partition by Tuser order by numid))-tnum)
end Tnum,numid
from t1;

Output:

TUSER   TNUM    NUMID
23451   800     1
23451   100     2
23451   100     3
47641   800     1
47641   100     2
47641   100     3
70919   200     1
70919   200     2
70919   200     3
70919   400     4


问:
Two square bracket overloading
I am writing a matrix class in c++ and trying to overload some operator like = and >> and << etc.

I was unable to overload operator [][] for matrix class.
if i have an object of class matrix like M1  then i can use this way for giving value to each element:

```<code>M1[1][2]=5;
</code>```

OR

```<code>int X;

X=M1[4][5];
</code>```

答:
You could overload operator[]. So if you would like to use matrix that way, you should make matrix as array of vectors.

```<code>class Matrix
{
...
  Vector & operator[]( int index );
...
};
</code>```

and

```<code>class Vector
{
...
  double & operator[]( int index );
...
};
</code>```

Finally:

```<code>Matrix m;
...
double value = m[i][j];
...
</code>```

Title: Two square bracket overloading

Body:
I am writing a matrix class in c++ and trying to overload some operator like = and >> and << etc.

I was unable to overload operator [][] for matrix class.
if i have an object of class matrix like M1  then i can use this way for giving value to each element:

M1[1][2]=5;

OR

int X;

X=M1[4][5];

Body:
You could overload operator[]. So if you would like to use matrix that way, you should make matrix as array of vectors.

class Matrix
{
...
  Vector & operator[]( int index );
...
};

and

class Vector
{
...
  double & operator[]( int index );
...
};

Finally:

Matrix m;
...
double value = m[i][j];
...


问:
How to install Intellij IDEA on Ubuntu?
I'm new to Ubuntu and Linux in general. I want to code in Java on my computer, but I'm having problems installing IntelliJ IDEA on Ubuntu. I have downloaded and extracted the file and for some reason renamed the folder to idea. I tried moving the folder to /usr/share/applications or something but I didn't have permission. I used sudo -i in terminal to gain permission but didn't manage to get out of root folder. Can anyone help me with a step by step way to move the folder, create a shortcut in the search bar or whatever it's called and install it properly?

答:
try simple way to install intellij idea

Install IntelliJ on Ubuntu using Ubuntu Make

You need to install Ubuntu Make first. If you are using Ubuntu 16.04, 18.04 or a higher version, you can install Ubuntu Make using the command below:

sudo apt install ubuntu-make

Once you have Ubuntu Make installed, you can use the command below to install IntelliJ IDEA Community edition:

umake ide idea

To install the IntelliJ IDEA Ultimate edition, use the command below:

umake ide idea-ultimate

To remove IntelliJ IDEA installed via Ubuntu Make, use the command below for your respective versions:

umake -r ide idea

umake -r ide idea-ultimate

you may visit for more option.

https://itsfoss.com/install-intellij-ubuntu-linux/

Title: How to install Intellij IDEA on Ubuntu?


问:
Changes via SetEnvironmentVariable do not take effect in library that uses getenv
I have a simple c# application that is binding to a library compile with mingnu compiler toolset. I can easily call the functions in the library without issue.

However the library calls getenv to set itself up this environment variable needs to be set for the library to work correctly so I am using Environment.SetEnvironmentVariable however the library cannot retrieve the value I have set.

答: You just set environment variable after create a native C++ object, then the C++ can get the value of environment variable using getenv function or ACE_OS::getenv().</p>


问:
Time difference between row and its previous/next row for the same customer in pandas dataframe
I have a dataframe:

```<code>In [1]: import pandas as pd;import numpy as np

In [2]: df = pd.DataFrame(
   ...: [
   ...:     ['A', '2019-05-10 23:59:59', 'NOT_WORKING'],
   ...:     ['A', '2019-05-11 00:05:00', 'WORKING'],
   ...:     ['B', '2019-05-13 07:55:00', 'NOT_WORKING'],
   ...:     ['B', '2019-05-15 07:57:00', 'WORKING'],
   ...:     ['B', '2019-05-16 08:03:00', 'NOT_WORKING'],
   ...: ], columns=['cust', 'event_date', 'status'])
   ...: df.event_date = pd.to_datetime(df.event_date)

In [3]: df.loc[1, 'test'] = 'Y'
   ...: df.loc[3, 'test'] = 'Y'

In [4]: df
Out[4]:
  cust          event_date       status test
0    A 2019-05-10 23:59:59  NOT_WORKING  NaN
1    A 2019-05-11 00:05:00      WORKING    Y
2    B 2019-05-13 07:55:00  NOT_WORKING  NaN
3    B 2019-05-15 07:57:00      WORKING    Y
4    B 2019-05-16 08:03:00  NOT_WORKING  NaN
</code>```

I need to find out time difference between test rows and their prvious/next rows for the same customer.

I have done it like this:

```<code>In [5]: df.loc[:, 'prev_time'] = df.event_date.shift(1)
   ...: df.loc[:, 'prev_cust'] = df.cust.shift(1)
   ...: df.loc[:, 'next_time'] = df.event_date.shift(-1)
   ...: df.loc[:, 'next_cust'] = df.cust.shift(-1)
   ...: df
Out[5]:
  cust          event_date  ...           next_time next_cust
0    A 2019-05-10 23:59:59  ... 2019-05-11 00:05:00         A
1    A 2019-05-11 00:05:00  ... 2019-05-13 07:55:00         B
2    B 2019-05-13 07:55:00  ... 2019-05-15 07:57:00         B
3    B 2019-05-15 07:57:00  ... 2019-05-16 08:03:00         B
4    B 2019-05-16 08:03:00  ...                 NaT       NaN

[5 rows x 8 columns]

In [9]: df = df.loc[df.test=='Y', :].assign(time_to_prev=lambda row: row.
   ...: event_date - row.prev_time ).assign(time_to_next=lambda row: row.
   ...: next_time - row.event_date)
   ...: df.loc[df.cust != df.prev_cust, 'time_to_prev'] = np.nan
   ...: df.loc[df.cust != df.next_cust, 'time_to_next'] = np.nan
   ...: df = df.drop(columns=['prev_time', 'prev_cust', 'next_time', 'nex
   ...: t_cust'])
   ...: df
Out[9]:
  cust          event_date   status test    time_to_prev    time_to_next
1    A 2019-05-11 00:05:00  WORKING    Y 0 days 00:05:01             NaT
3    B 2019-05-15 07:57:00  WORKING    Y 2 days 00:02:00 1 days 00:06:00
</code>```

It works, but I am looking for the more elegant solution that will incorporate groupby, diff...
How to do that?

答:
Use DataFrameGroupBy.diff for time_to_prev column, then DataFrameGroupBy.shift for time_to_next and last filter only Y rows by boolean indexing:

```<code>#if not sorted customers with datetimes column
#df = df.sort_values(['cust', 'event_date'])
df['time_to_prev'] = df.groupby('cust')['event_date'].diff()
df['time_to_next'] = df.groupby('cust')['time_to_prev'].shift(-1)

df = df[df.test=='Y'].copy()
print (df)
  cust          event_date   status test    time_to_prev    time_to_next
1    A 2019-05-11 00:05:00  WORKING    Y 0 days 00:05:01             NaT
3    B 2019-05-15 07:57:00  WORKING    Y 2 days 00:02:00 1 days 00:06:00
</code>```

Body:
I have a dataframe:

In [1]: import pandas as pd;import numpy as np

In [2]: df = pd.DataFrame(
   ...: [
   ...:     ['A', '2019-05-10 23:59:59', 'NOT_WORKING'],
   ...:     ['A', '2019-05-11 00:05:00', 'WORKING'],
   ...:     ['B', '2019-05-13 07:55:00', 'NOT_WORKING'],
   ...:     ['B', '2019-05-15 07:57:00', 'WORKING'],
   ...:     ['B', '2019-05-16 08:03:00', 'NOT_WORKING'],
   ...: ], columns=['cust', 'event_date', 'status'])
   ...: df.event_date = pd.to_datetime(df.event_date)

In [3]: df.loc[1, 'test'] = 'Y'
   ...: df.loc[3, 'test'] = 'Y'

In [4]: df
Out[4]:
  cust          event_date       status test
0    A 2019-05-10 23:59:59  NOT_WORKING  NaN
1    A 2019-05-11 00:05:00      WORKING    Y
2    B 2019-05-13 07:55:00  NOT_WORKING  NaN
3    B 2019-05-15 07:57:00      WORKING    Y
4    B 2019-05-16 08:03:00  NOT_WORKING  NaN

I need to find out time difference between test rows and their prvious/next rows for the same customer.

I have done it like this:

In [5]: df.loc[:, 'prev_time'] = df.event_date.shift(1)
   ...: df.loc[:, 'prev_cust'] = df.cust.shift(1)
   ...: df.loc[:, 'next_time'] = df.event_date.shift(-1)
   ...: df.loc[:, 'next_cust'] = df.cust.shift(-1)
   ...: df
Out[5]:
  cust          event_date  ...           next_time next_cust
0    A 2019-05-10 23:59:59  ... 2019-05-11 00:05:00         A
1    A 2019-05-11 00:05:00  ... 2019-05-13 07:55:00         B
2    B 2019-05-13 07:55:00  ... 2019-05-15 07:57:00         B
3    B 2019-05-15 07:57:00  ... 2019-05-16 08:03:00         B
4    B 2019-05-16 08:03:00  ...                 NaT       NaN

[5 rows x 8 columns]

In [9]: df = df.loc[df.test=='Y', :].assign(time_to_prev=lambda row: row.
   ...: event_date - row.prev_time ).assign(time_to_next=lambda row: row.
   ...: next_time - row.event_date)
   ...: df.loc[df.cust != df.prev_cust, 'time_to_prev'] = np.nan
   ...: df.loc[df.cust != df.next_cust, 'time_to_next'] = np.nan
   ...: df = df.drop(columns=['prev_time', 'prev_cust', 'next_time', 'nex
   ...: t_cust'])
   ...: df
Out[9]:
  cust          event_date   status test    time_to_prev    time_to_next
1    A 2019-05-11 00:05:00  WORKING    Y 0 days 00:05:01             NaT
3    B 2019-05-15 07:57:00  WORKING    Y 2 days 00:02:00 1 days 00:06:00

It works, but I am looking for the more elegant solution that will incorporate groupby, diff...
How to do that?

Body:
Use DataFrameGroupBy.diff for time_to_prev column, then DataFrameGroupBy.shift for time_to_next and last filter only Y rows by boolean indexing:

#if not sorted customers with datetimes column
#df = df.sort_values(['cust', 'event_date'])
df['time_to_prev'] = df.groupby('cust')['event_date'].diff()
df['time_to_next'] = df.groupby('cust')['time_to_prev'].shift(-1)

df = df[df.test=='Y'].copy()
print (df)
  cust          event_date   status test    time_to_prev    time_to_next
1    A 2019-05-11 00:05:00  WORKING    Y 0 days 00:05:01             NaT
3    B 2019-05-15 07:57:00  WORKING    Y 2 days 00:02:00 1 days 00:06:00


问:
jspdf doesn't return the entire html page to pdf
enter image description hereI am trying to convert html page to PDF using JSPDF.The page is rendered in my screen with 65% resolution by default and upon converting this to PDF, it renders the PDF with a black strip on the right side of the generated PDF.
Resolving screen size to 100%, the black strip increases in thickness.

JSPDF method is applied to the entire div<> containing the page content.
Tried to fix the width of the content and page to adjust the content within the screen.

```<code>var pdf = new jsPDF('p', 'pt','a4');
    pdf.page = 1;
    var totalPages=1;

    pdf.text("Report", 220, 22);// set your margins

    var str = "Page " + pdf.page  + " of " +  totalPages;
    pdf.setFontSize(9);// optional
    pdf.text(str, 250, pdf.internal.pageSize.height - 10);
    pdf.text("Confidential", 490, pdf.internal.pageSize.height - 10);
    pdf.internal.scaleFactor = 2.10;
    pdf.addHTML($('#reportTabContent')[0], 30, 30, {
        'height': 1750,
        'width': 1058,
        background: '#fff',
        pageSplit:'true'
      },function () {
          pdf.save('Reports.pdf');
      });
</code>```

I expect the HTML page as it is in PDF form.
But the jspdf is creating pdf of the html page with a black patch in the right side of the generated pdf. Please help.enter image description here

答: Sometimes, the issue comes from the css code applied to that div, not the configuration with jsPdf. Can you also share you css code of that div?</p>

Body:
enter image description hereI am trying to convert html page to PDF using JSPDF.The page is rendered in my screen with 65% resolution by default and upon converting this to PDF, it renders the PDF with a black strip on the right side of the generated PDF.
Resolving screen size to 100%, the black strip increases in thickness.

JSPDF method is applied to the entire div<> containing the page content.
Tried to fix the width of the content and page to adjust the content within the screen.

var pdf = new jsPDF('p', 'pt','a4');
    pdf.page = 1;
    var totalPages=1;

    pdf.text("Report", 220, 22);// set your margins

    var str = "Page " + pdf.page  + " of " +  totalPages;
    pdf.setFontSize(9);// optional
    pdf.text(str, 250, pdf.internal.pageSize.height - 10);
    pdf.text("Confidential", 490, pdf.internal.pageSize.height - 10);
    pdf.internal.scaleFactor = 2.10;
    pdf.addHTML($('#reportTabContent')[0], 30, 30, {
        'height': 1750,
        'width': 1058,
        background: '#fff',
        pageSplit:'true'
      },function () {
          pdf.save('Reports.pdf');
      });

I expect the HTML page as it is in PDF form.
But the jspdf is creating pdf of the html page with a black patch in the right side of the generated pdf. Please help.enter image description here


问:
React: Suspended component doesn't run the useEffect hook
currently trying out react hooks & react suspense. I'm trying to make a hook useApolloQuery which would fetch some data and throw a promise to wait till the data loads.

I'm putting the logic to fetch the data in a useEffect, but it seems like the effect never gets run if you instantly throw a promise in the component (and thus suspend it).

Here's my code: (Or codesandbox link: https://codesandbox.io/s/x73pwj164q )

function createPromiseResolver() {
  let resolve;
  const promise = new Promise(newResolver => {
    resolve = newResolver;
  });

  return { resolve, promise };
}

function useApolloQuery() {
  const [data, setData] = useState();
  const promsieResolver = createPromiseResolver();

  console.log("this runs");
  useEffect(() => {
    console.log("this doesn't run");

    const timeoutId = setTimeout(() => {
      setData("Some fake data");
      promsieResolver.resolve();
    }, 500);

    return () => clearTimeout(timeoutId);
  });

  if (!data) throw promsieResolver.promise;

  return data;
}

function App() {
  const data = useApolloQuery();

  return (

Hello CodeSandbox

{data}

  );
}
```

So in that code only the first console.log runs, since the useEffect hook never runs

Is suspense supposed to work like this? Any way to make it work?

答:
The useEffect doesn't run because you are throwing a promise before the actual function returns, so the promise is never resolved.

The problem is in the line

if (!data) throw promsieResolver.promise;

Initial data is undefined and thus !data = true. It throws a promise and thus the function is never returned but short-circuited. Removing this line actually runs the useEffect hook

Solution 2:
Or you could set an initial state for data other than undefined as below
const [data, setData] = useState('initial data');

Body:
currently trying out react hooks & react suspense. I'm trying to make a hook useApolloQuery which would fetch some data and throw a promise to wait till the data loads.

I'm putting the logic to fetch the data in a useEffect, but it seems like the effect never gets run if you instantly throw a promise in the component (and thus suspend it).

Here's my code: (Or codesandbox link: https://codesandbox.io/s/x73pwj164q )

function createPromiseResolver() {
  let resolve;
  const promise = new Promise(newResolver => {
    resolve = newResolver;
  });

  return { resolve, promise };
}

function useApolloQuery() {
  const [data, setData] = useState();
  const promsieResolver = createPromiseResolver();

  console.log("this runs");
  useEffect(() => {
    console.log("this doesn't run");

    const timeoutId = setTimeout(() => {
      setData("Some fake data");
      promsieResolver.resolve();
    }, 500);

    return () => clearTimeout(timeoutId);
  });

  if (!data) throw promsieResolver.promise;

  return data;
}

function App() {
  const data = useApolloQuery();

  return (

Hello CodeSandbox

{data}

  );
}

So in that code only the first console.log runs, since the useEffect hook never runs

Is suspense supposed to work like this? Any way to make it work?


问:
How do I get the firebase current user id (uid) in python?
I need to get the current user id.

In Javascript I use this to obtain the id

```<code>uid = firebase.auth().currentUser.uid // uid= ABO0Xc2E6KSDodEhenICkXF371x1
</code>```

how do I get the uid in python
?

答:
```<code>user = auth.sign_in_with_email_and_password(email,password)
print(user['localId'])
</code>```

this will display the current firebase UID on output screen

Body:
I need to get the current user id.

In Javascript I use this to obtain the id

uid = firebase.auth().currentUser.uid // uid= ABO0Xc2E6KSDodEhenICkXF371x1

how do I get the uid in python
?

Body:
user = auth.sign_in_with_email_and_password(email,password)
print(user['localId'])

this will display the current firebase UID on output screen


问:
Should a mvc model in php just be a PDO wrapper?
I have been trying to learn about MVC pattern (without frameworks), however no matter material I read on the Internet, it just seems to be contradicting itself all the time.

My project right now consists of a form that can be submitted in order to add an element to the database. Another page just lists all the elements that are on the database.

So as I understand, my model should connect to the database (or just take the connection as a parameter, something else that was not very clear to me) and have functions like "saveItem" (which takes the $_POST variable as an input and parses it) and "listItems" (which just returns all entries to the page).

However, where does the controller come in? Now I parse my data in the model. But, if that should be rather done in the controller, what does the model actually do? I came across this page. Here, the model only has methods like "select" whose input is just a sql query. But this seems essentially just a PDO wrapper. (Contradicting information in this page about PDO already being a kind-of wrapper and there isn't really any need to do it.)

I guess it kind of makes sense, if the model was written as just a wrapper, it wouldn't actually have anything to do with the specifics of my website. (My understanding now is that each part of mvc is highly specific for each project.)

But then, it seems that either the model or the controller is just unnecessary. Either model parses the data leaving nothing for the controller to do or vice-versa.

I would be deeply grateful for any clarification.

答:
I came across this page. Here, the model only has methods like "select" whose input is just a sql query. But this seems essentially just a PDO wrapper.

You're correct. In fact, this example is very poorly structured, and does not conform to any sensible conception of MVC design. I would recommend that you disregard it entirely and look for a better example.

The DB class (allegedly a "model") in this example is a database helper class. While this is a useful thing to have, it is not a MVC model in any sense, and this one is not particularly well written, either.

The Users class (allegedly a "controller") is not a controller. It is actually more akin to a model, as it attempts (awkwardly) to represent a business object as a class.

(As an aside, extending a database helper class is a design "smell" which should be avoided -- it means that every object instantiated will create its own separate connection to the database.)

The list.php file (allegedly a "view") is not much of a view, either. While it provides some presentation functionality, it also takes on the role of a controller by operating on the model. In most MVC applications, views are implemented as pure template files -- often not even executable code -- which are passed data by a controller.

Now that we've properly torn apart this terrible tutorial:

A common architecture in MVC applications is the active record pattern, in which each table in your database (other than purely relational tables) is represented by a class, each row from those tables which has been loaded by your application is represented by an instance of that class, and each of those instances has methods which can be used to manipulate the contents of that row.

Implementing such an architecture usually requires some form of database mapper or ORM framework.


问:
Issue in oracle query execution
```<code>    Below is the module in sybase.

   sub execute_query{
    $connect = "isql  -S $SERVER-U $USER -P $PASS -D $DBNAME";
    $pid = open2(\*Rder, \*Wrter, "$connect");
    Writer->autoflush();
    print Write qq!
    set transaction isolation level 0
    go
    Select * from remtrench
    go
    !;
    Wrter->close();
    while(<Rder>)
     {
      Parse data
      }
</code>```

The above code made changes to support oracle below.
I was able to connect to oracle.But selecting database query and other query ther than connection doesnt work.Please guide me

```<code>    sub execute_query{
    $connect = "sqlplus  $USER/PASS@SERVER
    $pid = open2(\*Rder, \*Wrter, "$connect");
    Writer->autoflush();
    alter session set current_schema = $DBNAME;
    Select * from remtrench;
    Writer->close();
     ....
     }
</code>```

The above change of mine does not work for alter session the other query (select).Googled on how to execute multiple queries.But still this doesnt help me.
Thanks.

答:
the ALTER SESSION will be valid within that session, but not if you open more sessions for each sql command.

You may simply prefix the database objects in your queries to get around this requirement such as by referencing tables like this:

```<code>SELECT * FROM USER.TABLE
</code>```

Title: Issue in oracle query execution

Body:
    Below is the module in sybase.

   sub execute_query{
    $connect = "isql  -S $SERVER-U $USER -P $PASS -D $DBNAME";
    $pid = open2(\*Rder, \*Wrter, "$connect");
    Writer->autoflush();
    print Write qq!
    set transaction isolation level 0
    go
    Select * from remtrench
    go
    !;
    Wrter->close();
    while(<Rder>)
     {
      Parse data
      }

The above code made changes to support oracle below.
I was able to connect to oracle.But selecting database query and other query ther than connection doesnt work.Please guide me

    sub execute_query{
    $connect = "sqlplus  $USER/PASS@SERVER
    $pid = open2(\*Rder, \*Wrter, "$connect");
    Writer->autoflush();
    alter session set current_schema = $DBNAME;
    Select * from remtrench;
    Writer->close();
     ....
     }

The above change of mine does not work for alter session the other query (select).Googled on how to execute multiple queries.But still this doesnt help me.
Thanks.

Body:
the ALTER SESSION will be valid within that session, but not if you open more sessions for each sql command.

You may simply prefix the database objects in your queries to get around this requirement such as by referencing tables like this:

SELECT * FROM USER.TABLE


问:
Copy/paste cell data from selected cells in row
My job requires that I copy/paste data from multiple cells in a row from one Excel worksheet to specific cells in another Excel worksheet.

I created a macro, but it is only selecting the specific cells I selected when recording the macro - these cells will always change depending on which row I'm needing the data from, so the recorded macro is useless. Also, the location of where this info will be pasted on the other worksheet will always be different (the macro copies the same exact data selected when recording and pastes it in the same exact location selected to paste when recording). I'm a noob at VBA, so I'm unsure on how to accomplish this.

I basically want to specify a specific row to start copying data from, and always select the same cells on that specific row as well as paste the data to specific cells on whatever row I have selected on the destination worksheet. Can someone help? This is for my job - any help would be appreciated. Ideally I'd like the macro to tab over to the specific cells needed and copy that info, from whatever row the macros starts on - and then paste that data to the cells selected via tabbing over on whatever row is selected in the other worksheet at the time of the macro being ran, if that makes sense.

答:
You can do something like this (untested):</p>

```<code>Sub CopyOver()

    Dim rwSrc As Long, rwDest As Long
    Dim shtSrc As Worksheet, shtDest As Worksheet
    Dim p, arr

    'assume macro is run with the source workbook active
    Set shtSrc = ActiveSheet
    rwSrc = Selection(1).Row  '(1) = first selected cell only

    'switch to the "other" workbook and get the selection
    Workbooks("Joey's May FY19 Audit.xlsx").Activate
    Set shtDest = ActiveSheet
    rwDest = Selection(1).Row

    'Example [source:destination] pairs ColA>>ColB, B>>C, F>>H, etc
    For Each p In Array("A:B", "B:C", "F:H")
        arr = Split(p, ":")
        shtSrc.Cells(rwSrc, arr(0)).Copy shtDest.Cells(rwDest, arr(1))
    Next p

End Sub
</code>```

Body:
You can do something like this (untested):

Sub CopyOver()

    Dim rwSrc As Long, rwDest As Long
    Dim shtSrc As Worksheet, shtDest As Worksheet
    Dim p, arr

    'assume macro is run with the source workbook active
    Set shtSrc = ActiveSheet
    rwSrc = Selection(1).Row  '(1) = first selected cell only

    'switch to the "other" workbook and get the selection
    Workbooks("Joey's May FY19 Audit.xlsx").Activate
    Set shtDest = ActiveSheet
    rwDest = Selection(1).Row

    'Example [source:destination] pairs ColA>>ColB, B>>C, F>>H, etc
    For Each p In Array("A:B", "B:C", "F:H")
        arr = Split(p, ":")
        shtSrc.Cells(rwSrc, arr(0)).Copy shtDest.Cells(rwDest, arr(1))
    Next p

End Sub


问:
Laravel - How to Transform Raw Query to Eloquent in Laravel
How do I transform my raw query to Laravel Eloquent

I want to transform

```<code>        $games = DB::table('game_point')
                     ->select('game_point.game_name','game_point.description','game_point.point_assigned', DB::raw("DATE(game_point.created_at) as created_at"))
                       ->paginate(15);
</code>```

to

```<code>$games= new GamePoint();
</code>```

答:
try below:</p>

```<code>$games = GamePoint::paginate(15);
</code>```

Body:
How do I transform my raw query to Laravel Eloquent

I want to transform

        $games = DB::table('game_point')
                     ->select('game_point.game_name','game_point.description','game_point.point_assigned', DB::raw("DATE(game_point.created_at) as created_at"))
                       ->paginate(15);

to

$games= new GamePoint();

Body:
try below:

$games = GamePoint::paginate(15);


问:
Selenium WebDriver - How to set Page Load Timeout using C#
I am using Selenium 2.20 WebDriver to create and manage a firefox browser with C#. To visit a page, i use the following code, setting the driver timeouts before visiting the URL:

```<code>driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5)); // Set implicit wait timeouts to 5 secs
driver.Manage().Timeouts().SetScriptTimeout(new TimeSpan(0, 0, 0, 5));  // Set script timeouts to 5 secs
driver.Navigate().GoToUrl(myUrl);   // Goto page url
</code>```

The problem is that sometimes pages take forever to load, and it appears that the default timeout for a page to load using the selenium WebDriver is 30 seconds, which is too long. And i don't believe the timeouts i am setting apply to the loading of a page using the GoToUrl() method.

So I am trying to figure out how to set a timeout for a page to load, however, i cannot find any property or method that actually works. The default 30 second timeout also seems to apply to when i click an element.

Is there a way to set the page load timeout to a specific value so that when i call the GoToUrl() method it will only wait my specified time before continuing?

答:
For anyone who wants the opposite effect: setting timeout longer than 60s.

You need both use:

```<code>new FirefoxDriver(FirefoxDriverService.CreateDefaultService(), new FirefoxOptions(), TimeSpan.FromSeconds(120))
</code>```

and

```<code>driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(120);
</code>```

The new FirefoxDriver(binary, profile, timeSpan) has been obsolete.

Body:
I am using Selenium 2.20 WebDriver to create and manage a firefox browser with C#. To visit a page, i use the following code, setting the driver timeouts before visiting the URL:

driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5)); // Set implicit wait timeouts to 5 secs
driver.Manage().Timeouts().SetScriptTimeout(new TimeSpan(0, 0, 0, 5));  // Set script timeouts to 5 secs
driver.Navigate().GoToUrl(myUrl);   // Goto page url

The problem is that sometimes pages take forever to load, and it appears that the default timeout for a page to load using the selenium WebDriver is 30 seconds, which is too long. And i don't believe the timeouts i am setting apply to the loading of a page using the GoToUrl() method.

So I am trying to figure out how to set a timeout for a page to load, however, i cannot find any property or method that actually works. The default 30 second timeout also seems to apply to when i click an element.

Is there a way to set the page load timeout to a specific value so that when i call the GoToUrl() method it will only wait my specified time before continuing?

Body:
For anyone who wants the opposite effect: setting timeout longer than 60s.

You need both use:

new FirefoxDriver(FirefoxDriverService.CreateDefaultService(), new FirefoxOptions(), TimeSpan.FromSeconds(120))

and

driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(120);

The new FirefoxDriver(binary, profile, timeSpan) has been obsolete.


问:
SELECT JOIN Table Operations
In my query below, I joined tables b, c, d to a by the base_id column.
However, I need to do some operations in my SELECT statement.
Since b, c, and d are not joined to each other,

is my (a.qty - (b.qty - (c.qty + d.qty))) formula computing only those tables that have the same base_id column?

```<code>SELECT (a.qty - (b.qty - (c.qty + d.qty))) AS qc_in
  FROM receiving a
  LEFT JOIN (
     SELECT SUM(qty) AS qty, base_id
        FROM quality_control bb
       WHERE location_to = 6
         AND is_canceled = 0
       GROUP BY base_id
      ) b
         ON b.base_id = a.base_id
  LEFT JOIN (
      SELECT SUM(qty) AS qty, base_id
        FROM quality_control ba
       WHERE location_from = 6
         AND is_canceled = 0
       GROUP BY base_id
      ) c
         ON c.base_id = a.base_id
  LEFT JOIN (
     SELECT SUM(qty) AS qty, base_id
       FROM issuance
      WHERE location_from = 6
        AND is_canceled = 0
      GROUP BY base_id
      ) d
         ON d.base_id = a.base_id
 WHERE a.is_canceled = 0
</code>```

答: Surely. In the nested statements you join all the tables on base_id. That means, as the result of those joins you will get a huge table containing columns from all of the joined tables with a common column you join on (base_id in your case).

Title: SELECT JOIN Table Operations

Body:
In my query below, I joined tables b, c, d to a by the base_id column.
However, I need to do some operations in my SELECT statement.
Since b, c, and d are not joined to each other,

is my (a.qty - (b.qty - (c.qty + d.qty))) formula computing only those tables that have the same base_id column?

SELECT (a.qty - (b.qty - (c.qty + d.qty))) AS qc_in
  FROM receiving a
  LEFT JOIN (
     SELECT SUM(qty) AS qty, base_id
        FROM quality_control bb
       WHERE location_to = 6
         AND is_canceled = 0
       GROUP BY base_id
      ) b
         ON b.base_id = a.base_id
  LEFT JOIN (
      SELECT SUM(qty) AS qty, base_id
        FROM quality_control ba
       WHERE location_from = 6
         AND is_canceled = 0
       GROUP BY base_id
      ) c
         ON c.base_id = a.base_id
  LEFT JOIN (
     SELECT SUM(qty) AS qty, base_id
       FROM issuance
      WHERE location_from = 6
        AND is_canceled = 0
      GROUP BY base_id
      ) d
         ON d.base_id = a.base_id
 WHERE a.is_canceled = 0


问:
What's the difference between hacks and messy/bad code
When is code a hack?

People seem to define a hack as ugly coding to solve a problem but how is that different from writing messy code.

Also is the only difference between a problem coded badly and a problem hacked the mindset of the programmer?

When I say hack I mean in the programming/development sense not the illegal sense.

答:
A hack is an ugly solution which may be implemented in well documented, perfectly formatted code with exquisitely named variables and all that. As they say, you can put lipstick on a pig, but it's still a pig.

On the other hand, you can also have a messy, hard to read implementation of a beautiful algorithm. Poorly chosen names, bad formatting, and poor documentation make code harder to understand, but the underlying idea may still be sound. This sort of thing isn't lipstick on a pig, it's a diamond in the rough.


问:
How to use multiple tables using specific condition
I have two table TableA and TableB for these tables data will be populated based on certain process (means TableA will be like temp table if value finialised then data will be moved to TableB)

based on that X condition
I will select the value from TableA else from TableB

```<code>If X=10 condition
select col1,col2,col3,col4 from TableA
else
select col1,col2,col3,col4 from TableB
</code>```

Both tables TableA and TableB will have same table structure,So here i dont want use the same code statement again in else by changing the table name alone.Is any other way that can be used without repeating the select statement again by changing the table.

答:
You can simply roll your condition into a UNION statement.

If @condition = 1 we only select from tableA, else we only select from tableB.

```<code>DECLARE @condition bit

SET @condition = 0

SELECT * FROM  [dbo].[TableA] WHERE @condition = 1
UNION
SELECT * FROM  [dbo].[TableB] WHERE @condition != 1
</code>```

Body:
I have two table TableA and TableB for these tables data will be populated based on certain process (means TableA will be like temp table if value finialised then data will be moved to TableB)

based on that X condition
I will select the value from TableA else from TableB

If X=10 condition
select col1,col2,col3,col4 from TableA
else
select col1,col2,col3,col4 from TableB

Both tables TableA and TableB will have same table structure,So here i dont want use the same code statement again in else by changing the table name alone.Is any other way that can be used without repeating the select statement again by changing the table.

Body:
You can simply roll your condition into a UNION statement.

If @condition = 1 we only select from tableA, else we only select from tableB.

DECLARE @condition bit

SET @condition = 0

SELECT * FROM  [dbo].[TableA] WHERE @condition = 1
UNION
SELECT * FROM  [dbo].[TableB] WHERE @condition != 1


问:
Google Annotation Chart load from CSV
I am trying to create a Google Annotation chart by loading some data from a CSV file using the example found here:

https://developers.google.com/chart/interactive/docs/gallery/annotationchart

I've tried to modify the code (using my limited JS knowledge) to load from a CSV file but I'm getting no graph.

My code so far:

```<code><html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type='text/javascript'>
google.charts.load('current', {'packages':['annotationchart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart()
{
$.get('test.csv', function(csvString)
{
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
arrayData = arrayData.map(function (row)
{
return
[new Date(row[0]),row[1]];
});

var data = google.visualization.arrayToDataTable(arrayData);
var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));

var options = {
displayAnnotations: true
};

chart.draw(data, options);
}
}
</script>
</head>

<body>
<div id='chart_div' style='width: 900px; height: 500px;'></div>
</body>
</html>
</code>```

CSV File

```<code>Date,Value1
2014-01-01,1233
2014- 01-02,1334
2014-01-03,1488
2014-01-04,1888
2014-01-05,2011
2014-01-06,1900
2014-01-07,1768
2014-01-08,2345
</code>```

答:
You need to follow 3 step for this task

Fire ajax request and take csv data

Convert csv data into array

Pass csv array in google graph

Please take refrence from following example:

```<code><html>
<head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type='text/javascript'>

        //Step 1: Get string from csv
        $(document).ready(function () {
            $.ajax({
                type: "GET",
                url: "test.csv",
                dataType: "text",
                success: function (data) {
                    //Step 2: Convert "," seprated string into array
                    let arrData = csvToArray(data);
                    //Step 3: call chart with array data
                    callChart(arrData);
                }
            });
        });

        //convert csv string into array function
        function csvToArray(allText) {
            var allTextLines = allText.split(/\r\n|\n/);
            var headers = allTextLines[0].split(',');
            var lines = [];

            for (var i = 1;i < allTextLines.length;i++) {
                var data = allTextLines[i].split(',');
                if (data.length == headers.length) {

                    var tarr = [];
                    for (var j = 0;j < headers.length;j++) {
                        tarr.push(headers[j] + ":" + data[j]);
                    }
                    lines.push(tarr);
                }
            }
            return lines;
        }

        function callChart(arrData) {
            google.charts.load('current', { 'packages': ['annotationchart'] });
            google.charts.setOnLoadCallback(function () { drawChart(arrData); });
        }

        function drawChart(arrData) {
            var data = new google.visualization.DataTable();
            //Step 4: add csv your column
            data.addColumn('date', 'Date');
            data.addColumn('number', 'Kepler-22b mission');
            //Step 5: pass your csv data as array
            data.addRows(arrData);
            var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
            var options = {
                displayAnnotations: true
            };
            chart.draw(data, options);
        }
    </script>
</head>
<body>
    <div id='chart_div' style='width: 900px; height: 500px;'></div>
</body>
</html>
</code>```

Title: Google Annotation Chart load from CSV

Body:
I am trying to create a Google Annotation chart by loading some data from a CSV file using the example found here:

https://developers.google.com/chart/interactive/docs/gallery/annotationchart

I've tried to modify the code (using my limited JS knowledge) to load from a CSV file but I'm getting no graph.

My code so far:

CSV File

Date,Value1
2014-01-01,1233
2014- 01-02,1334
2014-01-03,1488
2014-01-04,1888
2014-01-05,2011
2014-01-06,1900
2014-01-07,1768
2014-01-08,2345

Body:
You need to follow 3 step for this task

Fire ajax request and take csv data

Convert csv data into array

Pass csv array in google graph

Please take refrence from following example:

<html>
<head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type='text/javascript'>

        //Step 1: Get string from csv
        $(document).ready(function () {
            $.ajax({
                type: "GET",
                url: "test.csv",
                dataType: "text",
                success: function (data) {
                    //Step 2: Convert "," seprated string into array
                    let arrData = csvToArray(data);
                    //Step 3: call chart with array data
                    callChart(arrData);
                }
            });
        });

        //convert csv string into array function
        function csvToArray(allText) {
            var allTextLines = allText.split(/\r\n|\n/);
            var headers = allTextLines[0].split(',');
            var lines = [];

            for (var i = 1;i < allTextLines.length;i++) {
                var data = allTextLines[i].split(',');
                if (data.length == headers.length) {

                    var tarr = [];
                    for (var j = 0;j < headers.length;j++) {
                        tarr.push(headers[j] + ":" + data[j]);
                    }
                    lines.push(tarr);
                }
            }
            return lines;
        }

        function callChart(arrData) {
            google.charts.load('current', { 'packages': ['annotationchart'] });
            google.charts.setOnLoadCallback(function () { drawChart(arrData); });
        }

        function drawChart(arrData) {
            var data = new google.visualization.DataTable();
            //Step 4: add csv your column
            data.addColumn('date', 'Date');
            data.addColumn('number', 'Kepler-22b mission');
            //Step 5: pass your csv data as array
            data.addRows(arrData);
            var chart = new google.visualization.AnnotationChart(document.getElementById('chart_div'));
            var options = {
                displayAnnotations: true
            };
            chart.draw(data, options);
        }
    </script>
</head>
<body>
    <div id='chart_div' style='width: 900px; height: 500px;'></div>
</body>
</html>


问:
How to get the value of multidimensional array based on the ID
I have a multidimensional array, i display all of the values in a table using foreach loop. in that table i have an view profile (a href=). what i want to do is to get the array and pass it to another page and display the value of the array based on the id</p>

```<code><?php include_once('fake_db.php'); ?>

<--index.php-->

<div class="widget-body">
<table class="table table-condensed table-striped table-bordered table-hover no-margin">
    <thead>
    <tr>
        <th>Name</th><th>Position</th><th>Action</th>
    </tr>
    </thead>
    <?php foreach($employees as $key => $value){ ?>
        <tr>
            <td><?= $value['name']?></td>
            <td><?= $value['position']; ?></td>
            <td><a href="profile.php?id=<?= $key; ?>">View Profile</a></td>
        </tr>
    <?php } ?>
</table>
</div>

<-- profile.php -->
<h3>Employee Profile : Employee Name</h3>
<a href="index.php">Back to Employee List</a>
<table class="table table-condensed table-striped table-bordered table-hover no-margin">
    <thead>
    <tr>
        <td>Name </td>
        <td>Employee Position</td>
    </tr>
    </thead>
    <tr>

            <td></td>
            <td></td>
    </tr>
</table>

<--fake_db.php-->
<?php

$employees = array
             (
               1 => array("name" => 'Jason Alipala', "employee_id" => 'G1001-05', 'position' => 1),
               2 => array("name" => 'Bryann Revina', "employee_id" => 'G1009-03', 'position' => 2),
               3 => array("name" => 'Jeniel Mangahis', "employee_id" => 'G1009-04', 'position' => 2),
               4 => array("name" => 'Arjay Bussala', "employee_id" => 'G1009-05', 'position' => 3),
               5 => array("name" => 'Ronnel Ines', "employee_id" => 'G1002-06', 'position' => 3)
             );

$emp_positions = array_count_values(array_column($employees, 'position'));

$positions = array(1 => 'TL', 2 => 'Programmer', 3 => 'Converter');

?>

</code>```

答:
You can take @Khiev' s answer. But if you don't want to include the data file twice then you can follow this procedure- </p>

```<code>    <?php include_once('fake_db.php'); ?>

    <--index.php-->

    <div class="widget-body">
    <table class="table table-condensed table-striped table-bordered table-hover no-margin">
        <thead>
        <tr>
            <th>Name</th><th>Position</th><th>Action</th>
        </tr>
        </thead>
        <?php foreach($employees as $key => $value){ ?>
            <tr>
                <td><?= $value['name']?></td>
                <td><?= $value['position']; ?></td>
                <td><a href="profile.php?id=<?= rawurlencode(json_encode($value)); ?>">View Profile</a></td>
            </tr>
        <?php } ?>
    </table>
    </div>

  And in the `profile.php` file grab the `id` variable via `$_GET` variable.

<?php
    $id = $_GET['id'];
    $employee = json_decode(rawurldecode($id), true);
?>
    <h3>Employee Profile : Employee Name</h3>
    <a href="index.php">Back to Employee List</a>
    <table class="table table-condensed table-striped table-bordered table-hover no-margin">
        <thead>
            <tr>
                <td>Name </td>
               <td>Employee Position</td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><?php echo $employee['name'] ?></td>
                <td><?php echo $employee['position'] ?></td>
            </tr>
        </tbody>
    </table>
</code>```

Body:
I have a multidimensional array, i display all of the values in a table using foreach loop. in that table i have an view profile (a href=). what i want to do is to get the array and pass it to another page and display the value of the array based on the id

<?php include_once('fake_db.php'); ?>

<--index.php-->

        Name	Position	Action

    <?php foreach($employees as $key => $value){ ?>

            <?= $value['name']?>
            <?= $value['position']; ?>
            <a href="profile.php?id=<?= $key; ?>">View Profile

    <?php } ?>

<-- profile.php -->

Employee Profile : Employee Name

Back to Employee List

        Name
        Employee Position

<--fake_db.php-->
<?php

$employees = array
             (
               1 => array("name" => 'Jason Alipala', "employee_id" => 'G1001-05', 'position' => 1),
               2 => array("name" => 'Bryann Revina', "employee_id" => 'G1009-03', 'position' => 2),
               3 => array("name" => 'Jeniel Mangahis', "employee_id" => 'G1009-04', 'position' => 2),
               4 => array("name" => 'Arjay Bussala', "employee_id" => 'G1009-05', 'position' => 3),
               5 => array("name" => 'Ronnel Ines', "employee_id" => 'G1002-06', 'position' => 3)
             );

$emp_positions = array_count_values(array_column($employees, 'position'));

$positions = array(1 => 'TL', 2 => 'Programmer', 3 => 'Converter');

?>

Body:
You can take @Khiev' s answer. But if you don't want to include the data file twice then you can follow this procedure-

    <?php include_once('fake_db.php'); ?>

    <--index.php-->

    <div class="widget-body">
    <table class="table table-condensed table-striped table-bordered table-hover no-margin">
        <thead>
        <tr>
            <th>Name</th><th>Position</th><th>Action</th>
        </tr>
        </thead>
        <?php foreach($employees as $key => $value){ ?>
            <tr>
                <td><?= $value['name']?></td>
                <td><?= $value['position']; ?></td>
                <td><a href="profile.php?id=<?= rawurlencode(json_encode($value)); ?>">View Profile</a></td>
            </tr>
        <?php } ?>
    </table>
    </div>

  And in the `profile.php` file grab the `id` variable via `$_GET` variable.

<?php
    $id = $_GET['id'];
    $employee = json_decode(rawurldecode($id), true);
?>
    <h3>Employee Profile : Employee Name</h3>
    <a href="index.php">Back to Employee List</a>
    <table class="table table-condensed table-striped table-bordered table-hover no-margin">
        <thead>
            <tr>
                <td>Name </td>
               <td>Employee Position</td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><?php echo $employee['name'] ?></td>
                <td><?php echo $employee['position'] ?></td>
            </tr>
        </tbody>
    </table>


问:
Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release
react-native run-android command terminates by leaving a message in android simulator. The message is as follows:

Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release.

What am I doing wrong?

答:
I just want to add a non-obvious possibility not covered here. I am using @react-native-community/netinfo for detecting network changes, primarily network state. To test network-off state, the WIFI switch (on the emulator) needs to be switched off. This also effectively cuts off the bridge between the emulator and the debug environment. I had not re-enabled WIFI after my tests since i was away from the computer and promptly forgot about it when i got back.

There is a possibility that this could be the case for somebody else as well and worth checking before taking any other drastic steps.


问:
Python Pickle object in Django model
I would like to know what would be the simplest way to store pickle objects in PostgreSQL DB using Django ORM.</p>

答:
You can use BinaryField to store pickled object.

From comments of the question, you can also use JSONField to store dict from class instance. You can do it like this:

```<code>from django.contrib.postgres.fields import JSONField

class YourModel(models.Model):
    data = <b>JSONField()</b></code>```

Lets say you have a class like this(which you want to store):

```<code>class YourClass(object):
    a = None
    b = None
    c = None

    def __str__(self):
        return 'Your Class: {}, {}, {}'.format(self.a, self.b, self.c)
</code>```

Now you can generate dictionary like this:

```<code>some_instance = YourClass(a=1, b=2, c=3)
cls_dict = some_instance.__dict__
print(cls_dict)
# {'a': 1, 'b': 2, 'c': 3}

y = YourModel(data=cls_dict)
y.save()
</code>```

Now you can try restoring Class instance from dictionary like this:

```<code>y = YourModel.objects.first()
some_instance = YourClass()
some_instance.__dict__.update(y.data)

print(some_instance)

# 'Your Class: 1, 2, 3'
</code>```

Title: Python Pickle object in Django model

Body:
You can use BinaryField to store pickled object.

From comments of the question, you can also use JSONField to store dict from class instance. You can do it like this:

from django.contrib.postgres.fields import JSONField

class YourModel(models.Model):
    data = JSONField()

Lets say you have a class like this(which you want to store):

class YourClass(object):
    a = None
    b = None
    c = None

    def __str__(self):
        return 'Your Class: {}, {}, {}'.format(self.a, self.b, self.c)

Now you can generate dictionary like this:

some_instance = YourClass(a=1, b=2, c=3)
cls_dict = some_instance.__dict__
print(cls_dict)
# {'a': 1, 'b': 2, 'c': 3}

y = YourModel(data=cls_dict)
y.save()

Now you can try restoring Class instance from dictionary like this:

y = YourModel.objects.first()
some_instance = YourClass()
some_instance.__dict__.update(y.data)

print(some_instance)

# 'Your Class: 1, 2, 3'


问:
What could cause a persistent error while uninstalling local packages?
I am trying to use a boilerplate code but before doing so I have to replace/remove some local packages. For some reasons almost every package I am trying to remove is causing errors.

Particularly I am trying to remove babel-cli and install using @babel/cli (same with other dependencies such as presets etc.). I stuck at uninstall stage and spent couple of days trying to fix this problem. I added relevant paths to env.variables section but it doesn't seem to help.

$ npm uninstall babel-cli

node-sass@4.5.3 install C:\Users\feat\Desktop\expensify\node_modules\node-sass
  node scripts/install.js

Downloading binary from https://github.com/sass/node-sass/releases/download/v4.5.3/win32-x64-64_binding.node
Cannot download "https://github.com/sass/node-sass/releases/download/v4.5.3/win32-x64-64_binding.node":

HTTP error 404 Not Found

Hint: If github.com is not accessible in your location
      try setting a proxy via HTTP_PROXY, e.g.

```<code>  export HTTP_PROXY=http://example.com:1234
</code>```

or configure npm proxy via

```<code>  npm config set proxy http://example.com:8080
</code>```

node-sass@4.5.3 postinstall C:\Users\feat\Desktop\expensify\node_modules\node-sass
  node scripts/build.js

Building: C:\Program Files\nodejs\node.exe C:\Users\feat\Desktop\expensify\node_modules\node-gyp\bin\node-gyp.js rebuild --verbose --libsass_ext=
--libsass_cflags= --libsass_ldflags= --libsass_library=

```<code>gyp verb cli [ 'C:\\Program Files\\nodejs\\node.exe',
gyp verb cli   'C:\\Users\\feat\\Desktop\\expensify\\node_modules\\node-gyp\\bin\\node-gyp.js',
gyp verb cli   'rebuild',
gyp verb cli   '--verbose',
gyp verb cli   '--libsass_ext=',
gyp verb cli   '--libsass_cflags=',
gyp verb cli   '--libsass_ldflags=',
gyp verb cli   '--libsass_library=' ]
gyp info using node-gyp@3.8.0
gyp info using node@10.15.3 | win32 | x64
gyp verb command rebuild []
gyp verb command clean []
gyp verb clean removing "build" directory
gyp verb command configure []
gyp verb check python checking for Python executable "python2" in the PATH
gyp verb `which` failed Error: not found: python2
gyp verb `which` failed     at getNotFoundError (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:13:12)
gyp verb `which` failed     at F (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:68:19)
gyp verb `which` failed     at E (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:80:29)
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\which\which.js:89:16
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\isexe\index.js:42:5
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\isexe\windows.js:36:5
gyp verb `which` failed     at FSReqWrap.oncomplete (fs.js:153:21)
gyp verb `which` failed  python2 { Error: not found: python2
gyp verb `which` failed     at getNotFoundError (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:13:12)
gyp verb `which` failed     at F (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:68:19)
gyp verb `which` failed     at E (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:80:29)
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\which\which.js:89:16
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\isexe\index.js:42:5
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\isexe\windows.js:36:5
gyp verb `which` failed     at FSReqWrap.oncomplete (fs.js:153:21)
gyp verb `which` failed   stack:
gyp verb `which` failed    'Error: not found: python2\n    at getNotFoundError (C:\\Users\\feat\\Desktop\\expensify\\node_modules\\which\\which.js:13:12)\n    at F (C:\\Users\\feat\\Desktop\\expensify\\node_modules\\which\\which.js:68:19)\n    at E (C:\\Users\\feat\\Desktop\\expensify\\node_modules\\which\\which.js:80:29)\n    at C:\\Users\\feat\\Desktop\\expensify\\node_modules\\which\\which.js:89:16\n    at C:\\Users\\feat\\Desktop\\expensify\\node_modules\\isexe\\index.js:42:5\n    at C:\\Users\\feat\\Desktop\\expensify\\node_modules\\isexe\\windows.js:36:5\n    at FSReqWrap.oncomplete (fs.js:153:21)',
gyp verb `which` failed   code: 'ENOENT' }
gyp verb check python checking for Python executable "python" in the PATH
gyp verb `which` failed Error: not found: python
gyp verb `which` failed     at getNotFoundError (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:13:12)
gyp verb `which` failed     at F (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:68:19)
gyp verb `which` failed     at E (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:80:29)
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\which\which.js:89:16
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\isexe\index.js:42:5
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\isexe\windows.js:36:5
gyp verb `which` failed     at FSReqWrap.oncomplete (fs.js:153:21)
gyp verb `which` failed  python { Error: not found: python
gyp verb `which` failed     at getNotFoundError (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:13:12)
gyp verb `which` failed     at F (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:68:19)
gyp verb `which` failed     at E (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:80:29)
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\which\which.js:89:16
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\isexe\index.js:42:5
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\isexe\windows.js:36:5
gyp verb `which` failed     at FSReqWrap.oncomplete (fs.js:153:21)
gyp verb `which` failed   stack:
gyp verb `which` failed    'Error: not found: python\n    at getNotFoundError (C:\\Users\\feat\\Desktop\\expensify\\node_modules\\which\\which.js:13:12)\n    at F (C:\\Users\\feat\\Desktop\\expensify\\node_modules\\which\\which.js:68:19)\n    at E (C:\\Users\\feat\\Desktop\\expensify\\node_modules\\which\\which.js:80:29)\n    at C:\\Users\\feat\\Desktop\\expensify\\node_modules\\which\\which.js:89:16\n    at C:\\Users\\feat\\Desktop\\expensify\\node_modules\\isexe\\index.js:42:5\n    at C:\\Users\\feat\\Desktop\\expensify\\node_modules\\isexe\\windows.js:36:5\n    at FSReqWrap.oncomplete (fs.js:153:21)',
gyp verb `which` failed   code: 'ENOENT' }
gyp verb could not find "python". checking python launcher
gyp verb could not find "python". guessing location
gyp verb ensuring that file exists: C:\Python27\python.exe
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env variable.
gyp ERR! stack     at PythonFinder.failNoPython (C:\Users\feat\Desktop\expensify\node_modules\node-gyp\lib\configure.js:484:19)
gyp ERR! stack     at PythonFinder.<anonymous> (C:\Users\feat\Desktop\expensify\node_modules\node-gyp\lib\configure.js:509:16)
gyp ERR! stack     at C:\Users\feat\Desktop\expensify\node_modules\graceful-fs\polyfills.js:282:31
gyp ERR! stack     at FSReqWrap.oncomplete (fs.js:153:21)
gyp ERR! System Windows_NT 10.0.17763
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\feat\\Desktop\\expensify\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd C:\Users\feat\Desktop\expensify\node_modules\node-sass
gyp ERR! node -v v10.15.3
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
Build failed with error code: 1
npm WARN ajv-keywords@2.1.1 requires a peer of ajv@^5.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN expensify@1.0.0 No description
npm WARN expensify@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-sass@4.5.3 postinstall: `node scripts/build.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-sass@4.5.3 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\feat\AppData\Roaming\npm-cache\_logs\2019-05-30T04_42_51_796Z-debug.log

Prior to this case all my attempts were resulting in an expected message that such package has been uninstalled. Now it gives out this message.
</code>```

答: this issue is resolved. probably the best solution is to wipe down the package.json, package0lock.json and node modules and install everything from scratch. most important part is to install separately node-sass with --save flag. --save is must in this case unlike with many other cases</p>

Body:
I am trying to use a boilerplate code but before doing so I have to replace/remove some local packages. For some reasons almost every package I am trying to remove is causing errors.

Particularly I am trying to remove babel-cli and install using @babel/cli (same with other dependencies such as presets etc.). I stuck at uninstall stage and spent couple of days trying to fix this problem. I added relevant paths to env.variables section but it doesn't seem to help.

$ npm uninstall babel-cli

node-sass@4.5.3 install C:\Users\feat\Desktop\expensify\node_modules\node-sass
  node scripts/install.js

Downloading binary from https://github.com/sass/node-sass/releases/download/v4.5.3/win32-x64-64_binding.node
Cannot download "https://github.com/sass/node-sass/releases/download/v4.5.3/win32-x64-64_binding.node":

HTTP error 404 Not Found

Hint: If github.com is not accessible in your location
      try setting a proxy via HTTP_PROXY, e.g.

  export HTTP_PROXY=http://example.com:1234

or configure npm proxy via

  npm config set proxy http://example.com:8080

node-sass@4.5.3 postinstall C:\Users\feat\Desktop\expensify\node_modules\node-sass
  node scripts/build.js

Building: C:\Program Files\nodejs\node.exe C:\Users\feat\Desktop\expensify\node_modules\node-gyp\bin\node-gyp.js rebuild --verbose --libsass_ext=
--libsass_cflags= --libsass_ldflags= --libsass_library=

gyp verb cli [ 'C:\\Program Files\\nodejs\\node.exe',
gyp verb cli   'C:\\Users\\feat\\Desktop\\expensify\\node_modules\\node-gyp\\bin\\node-gyp.js',
gyp verb cli   'rebuild',
gyp verb cli   '--verbose',
gyp verb cli   '--libsass_ext=',
gyp verb cli   '--libsass_cflags=',
gyp verb cli   '--libsass_ldflags=',
gyp verb cli   '--libsass_library=' ]
gyp info using node-gyp@3.8.0
gyp info using node@10.15.3 | win32 | x64
gyp verb command rebuild []
gyp verb command clean []
gyp verb clean removing "build" directory
gyp verb command configure []
gyp verb check python checking for Python executable "python2" in the PATH
gyp verb `which` failed Error: not found: python2
gyp verb `which` failed     at getNotFoundError (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:13:12)
gyp verb `which` failed     at F (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:68:19)
gyp verb `which` failed     at E (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:80:29)
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\which\which.js:89:16
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\isexe\index.js:42:5
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\isexe\windows.js:36:5
gyp verb `which` failed     at FSReqWrap.oncomplete (fs.js:153:21)
gyp verb `which` failed  python2 { Error: not found: python2
gyp verb `which` failed     at getNotFoundError (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:13:12)
gyp verb `which` failed     at F (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:68:19)
gyp verb `which` failed     at E (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:80:29)
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\which\which.js:89:16
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\isexe\index.js:42:5
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\isexe\windows.js:36:5
gyp verb `which` failed     at FSReqWrap.oncomplete (fs.js:153:21)
gyp verb `which` failed   stack:
gyp verb `which` failed    'Error: not found: python2\n    at getNotFoundError (C:\\Users\\feat\\Desktop\\expensify\\node_modules\\which\\which.js:13:12)\n    at F (C:\\Users\\feat\\Desktop\\expensify\\node_modules\\which\\which.js:68:19)\n    at E (C:\\Users\\feat\\Desktop\\expensify\\node_modules\\which\\which.js:80:29)\n    at C:\\Users\\feat\\Desktop\\expensify\\node_modules\\which\\which.js:89:16\n    at C:\\Users\\feat\\Desktop\\expensify\\node_modules\\isexe\\index.js:42:5\n    at C:\\Users\\feat\\Desktop\\expensify\\node_modules\\isexe\\windows.js:36:5\n    at FSReqWrap.oncomplete (fs.js:153:21)',
gyp verb `which` failed   code: 'ENOENT' }
gyp verb check python checking for Python executable "python" in the PATH
gyp verb `which` failed Error: not found: python
gyp verb `which` failed     at getNotFoundError (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:13:12)
gyp verb `which` failed     at F (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:68:19)
gyp verb `which` failed     at E (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:80:29)
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\which\which.js:89:16
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\isexe\index.js:42:5
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\isexe\windows.js:36:5
gyp verb `which` failed     at FSReqWrap.oncomplete (fs.js:153:21)
gyp verb `which` failed  python { Error: not found: python
gyp verb `which` failed     at getNotFoundError (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:13:12)
gyp verb `which` failed     at F (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:68:19)
gyp verb `which` failed     at E (C:\Users\feat\Desktop\expensify\node_modules\which\which.js:80:29)
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\which\which.js:89:16
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\isexe\index.js:42:5
gyp verb `which` failed     at C:\Users\feat\Desktop\expensify\node_modules\isexe\windows.js:36:5
gyp verb `which` failed     at FSReqWrap.oncomplete (fs.js:153:21)
gyp verb `which` failed   stack:
gyp verb `which` failed    'Error: not found: python\n    at getNotFoundError (C:\\Users\\feat\\Desktop\\expensify\\node_modules\\which\\which.js:13:12)\n    at F (C:\\Users\\feat\\Desktop\\expensify\\node_modules\\which\\which.js:68:19)\n    at E (C:\\Users\\feat\\Desktop\\expensify\\node_modules\\which\\which.js:80:29)\n    at C:\\Users\\feat\\Desktop\\expensify\\node_modules\\which\\which.js:89:16\n    at C:\\Users\\feat\\Desktop\\expensify\\node_modules\\isexe\\index.js:42:5\n    at C:\\Users\\feat\\Desktop\\expensify\\node_modules\\isexe\\windows.js:36:5\n    at FSReqWrap.oncomplete (fs.js:153:21)',
gyp verb `which` failed   code: 'ENOENT' }
gyp verb could not find "python". checking python launcher
gyp verb could not find "python". guessing location
gyp verb ensuring that file exists: C:\Python27\python.exe
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env variable.
gyp ERR! stack     at PythonFinder.failNoPython (C:\Users\feat\Desktop\expensify\node_modules\node-gyp\lib\configure.js:484:19)
gyp ERR! stack     at PythonFinder.<anonymous> (C:\Users\feat\Desktop\expensify\node_modules\node-gyp\lib\configure.js:509:16)
gyp ERR! stack     at C:\Users\feat\Desktop\expensify\node_modules\graceful-fs\polyfills.js:282:31
gyp ERR! stack     at FSReqWrap.oncomplete (fs.js:153:21)
gyp ERR! System Windows_NT 10.0.17763
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\feat\\Desktop\\expensify\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd C:\Users\feat\Desktop\expensify\node_modules\node-sass
gyp ERR! node -v v10.15.3
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
Build failed with error code: 1
npm WARN ajv-keywords@2.1.1 requires a peer of ajv@^5.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN expensify@1.0.0 No description
npm WARN expensify@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-sass@4.5.3 postinstall: `node scripts/build.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-sass@4.5.3 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\feat\AppData\Roaming\npm-cache\_logs\2019-05-30T04_42_51_796Z-debug.log

Prior to this case all my attempts were resulting in an expected message that such package has been uninstalled. Now it gives out this message.


问:
Inconsistent behaviour with IntersectionObserver API
I have the requirement to display multiple animated counters on a web page where the animation is triggered when the element is intersecting based on the IntersectionObserver API return.

What I have observed is that despite the API returning true for all the counters most of the time only the first animation is executed and for the rest of the animations I need to scroll the page up/down for the rest of the counters to animate.

This inconsistent behaviour holds true even if I just need to replace the inner text with the value from data-attribute (did this to validate that animation script is not the culprit).

Below is the code and the screenshot of the 3 counters on a single web page, off the three only the first one works even if all the three counters are within the first fold of the screen.

HTML:

```<code><div class="counter-value" data-count="10000">0</div>
<div class="counter-value" data-count="183.4">0</div>
<div class="counter-value" data-count="270">0</div>
</code>```

JS:

```<code>var config = {
    root: null,
    rootMargin: '0px',
    threshold: 0.5
};

function callback(entry, observer){
    console.log(entry);
    if (entry[0].isIntersecting) {

        var $this = $(entry[0].target),
            countTo = $this.attr('data-count');

        $this.prop({
            countNum: $this.text()
        }).animate({
            countNum: countTo
        },
        {
            duration: 1000,
            easing: 'swing',
            step: function () {
                $this.text(Math.floor(this.countNum));
            },
            complete: function () {
                var localNum = this.countNum.toLocaleString()
                $this.text(localNum);
                console.log(localNum);
            }
        });
        observer.unobserve(entry[0].target);
    };
};

var observer = new IntersectionObserver(callback,config);
var counters = document.querySelectorAll('.counter-value'); //make this an array if more than one item
counters.forEach(counter => {
    observer.observe(counter);
});
</code>```

Any pointers on this if you have ever faces such an issue before?

答:
The Intersection Observer API accepts a callback that sets the first argument to all the entries attached to the observer. You have to loop through all of them and check whether they intersect.

```<code>function callback(entries, observer){
  entries.forEach(entry => {
    if (entry.isIntersecting) {

        var $this = $(entry.target),
            countTo = $this.attr('data-count');

        $this.prop({
            countNum: $this.text()
        }).animate({
            countNum: countTo
        },
        {
            duration: 1000,
            easing: 'swing',
            step: function () {
                $this.text(Math.floor(this.countNum));
            },
            complete: function () {
                var localNum = this.countNum.toLocaleString()
                $this.text(localNum);
                console.log(localNum);
            }
        });
        observer.unobserve(entry.target);
    }
  }
};
</code>```

Body:
I have the requirement to display multiple animated counters on a web page where the animation is triggered when the element is intersecting based on the IntersectionObserver API return.

What I have observed is that despite the API returning true for all the counters most of the time only the first animation is executed and for the rest of the animations I need to scroll the page up/down for the rest of the counters to animate.

This inconsistent behaviour holds true even if I just need to replace the inner text with the value from data-attribute (did this to validate that animation script is not the culprit).

Below is the code and the screenshot of the 3 counters on a single web page, off the three only the first one works even if all the three counters are within the first fold of the screen.

HTML:

0

0

0

JS:

var config = {
    root: null,
    rootMargin: '0px',
    threshold: 0.5
};

function callback(entry, observer){
    console.log(entry);
    if (entry[0].isIntersecting) {

        var $this = $(entry[0].target),
            countTo = $this.attr('data-count');

        $this.prop({
            countNum: $this.text()
        }).animate({
            countNum: countTo
        },
        {
            duration: 1000,
            easing: 'swing',
            step: function () {
                $this.text(Math.floor(this.countNum));
            },
            complete: function () {
                var localNum = this.countNum.toLocaleString()
                $this.text(localNum);
                console.log(localNum);
            }
        });
        observer.unobserve(entry[0].target);
    };
};

var observer = new IntersectionObserver(callback,config);
var counters = document.querySelectorAll('.counter-value'); //make this an array if more than one item
counters.forEach(counter => {
    observer.observe(counter);
});

Any pointers on this if you have ever faces such an issue before?

Body:
The Intersection Observer API accepts a callback that sets the first argument to all the entries attached to the observer. You have to loop through all of them and check whether they intersect.

function callback(entries, observer){
  entries.forEach(entry => {
    if (entry.isIntersecting) {

        var $this = $(entry.target),
            countTo = $this.attr('data-count');

        $this.prop({
            countNum: $this.text()
        }).animate({
            countNum: countTo
        },
        {
            duration: 1000,
            easing: 'swing',
            step: function () {
                $this.text(Math.floor(this.countNum));
            },
            complete: function () {
                var localNum = this.countNum.toLocaleString()
                $this.text(localNum);
                console.log(localNum);
            }
        });
        observer.unobserve(entry.target);
    }
  }
};


答:
Another option would be to use coord_cartesian based on the range of the source data:

```<code>ggplot()+
  geom_col(data = x, aes(x = date, y = inf),
           fill= "cadetblue3", size = 0.1) +
  coord_cartesian(xlim = range(x$date))
</code>```

Title: ggplot omits day with missing data

Body:
I am trying to plot data which has missing values for the first and last day. ggplot simply 'eats' that day:

ggplot()+
     geom_col(data = x, aes(x = date, y = inf),fill= "cadetblue3", size = 0.1)

How do I make R plot the whole range of date(and time)?
I have tried a small trick to assign 0 at the beginning, but that is a dirty solution.

 x$spor[1] <-0
 x$spor[nrow(x)] <-0

Any better suggestions?

Data:

x  <- structure(list(date = structure(c(1465689600, 1465693200, 1465696800,
1465700400, 1465704000, 1465707600, 1465711200, 1465714800, 1465718400,
1465722000, 1465725600, 1465729200, 1465732800, 1465736400, 1465740000,
1465743600, 1465747200, 1465750800, 1465754400, 1465758000, 1465761600,
1465765200, 1465768800, 1465772400, 1465776000, 1465779600, 1465783200,
1465786800, 1465790400, 1465794000, 1465797600, 1465801200, 1465804800,
1465808400, 1465812000, 1465815600, 1465819200, 1465822800, 1465826400,
1465830000, 1465833600, 1465837200, 1465840800, 1465844400, 1465848000,
1465851600, 1465855200, 1465858800, 1465862400, 1465866000, 1465869600,
1465873200, 1465876800, 1465880400, 1465884000, 1465887600, 1465891200,
1465894800, 1465898400, 1465902000, 1465905600, 1465909200, 1465912800,
1465916400, 1465920000, 1465923600, 1465927200, 1465930800, 1465934400,
1465938000, 1465941600, 1465945200, 1465948800, 1465952400, 1465956000,
1465959600, 1465963200, 1465966800, 1465970400, 1465974000, 1465977600,
1465981200, 1465984800, 1465988400, 1465992000, 1465995600, 1465999200,
1466002800, 1466006400, 1466010000, 1466013600, 1466017200, 1466020800,
1466024400, 1466028000, 1466031600, 1466035200, 1466038800, 1466042400,
1466046000, 1466049600, 1466053200, 1466056800, 1466060400, 1466064000,
1466067600, 1466071200, 1466074800, 1466078400, 1466082000, 1466085600,
1466089200, 1466092800, 1466096400, 1466100000, 1466103600, 1466107200,
1466110800, 1466114400, 1466118000, 1466121600, 1466125200, 1466128800,
1466132400, 1466136000, 1466139600, 1466143200, 1466146800, 1466150400,
1466154000, 1466157600, 1466161200, 1466164800, 1466168400, 1466172000,
1466175600, 1466179200, 1466182800, 1466186400, 1466190000, 1466193600,
1466197200, 1466200800, 1466204400), class = c("POSIXct", "POSIXt"
), tzone = "UTC"), inf = c(NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 18.4313, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, 25.3237, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 22.9965,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 11.7823, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)), class = "data.frame", row.names = 2997018:2997161)

Body:
Another option would be to use coord_cartesian based on the range of the source data:

ggplot()+
  geom_col(data = x, aes(x = date, y = inf),
           fill= "cadetblue3", size = 0.1) +
  coord_cartesian(xlim = range(x$date))


答:
The way I would achieve this is with a variable and a union query. The variable allows you to give a true false condition for your where clause so everything is returned from the table you want and nothing from the table you don't want. The structure of the tables allows you to use the query in a union statement so you can see all of the code in one place.</p>

```<code>Declare @x int = 10
Select col1, col2, col3, col4 from TableA where @x=10
Union
Select col1, col2, col3, col4 from TableB where @x<>10;
</code>```

Title: How to use multiple tables using specific condition

Body:
The way I would achieve this is with a variable and a union query. The variable allows you to give a true false condition for your where clause so everything is returned from the table you want and nothing from the table you don't want. The structure of the tables allows you to use the query in a union statement so you can see all of the code in one place.

Declare @x int = 10
Select col1, col2, col3, col4 from TableA where @x=10
Union
Select col1, col2, col3, col4 from TableB where @x<>10;