问:
How to save/download generate QR Code in react native using hooks?
I'm trying to build an app generator and scanner QR code in react native using hooks. I want a solution to save/download the QR code in the device after generating them. I need help plz, thanks

react-native-qrcode-generator
 Can anyone give me suggestions on how to save this generated QR Code? Any help much appreciated

答:
If you want to save the information in QR code as a QR code, you have to convert the QR code into a png image and then store it in your database as an image.

So, what I advise you to do is, when saving, just store the information as a string (or whatever necessary) in the database. When downloading, just retrieve the information from your database and immediately generate the QR Code. It's not consuming a longer time. After the QR Code is generated, then display it.

I think this is the most appropriate solution for you.

You may need react-native-qrcode-generator for generate the QR Code.

Here is a sample code...

You can input key and value (at the top inputs) and press 'Save' button. When the 'Save' button is pressed, you have to store your key-value pair (data) to your database.

Then, input the key (at the bottom input) of which you want to download and press 'Download' button. Then you have to retrieve the data (value) associated with the given key.

State value is set after the value is successfully retrieved from the database. That state is given as a prop to the QRCode component.

```<code>import React, { useState } from 'react';
import { StyleSheet, View, Text, TextInput, TouchableOpacity, AsyncStorage } from 'react-native';
import QRCode from 'react-native-qrcode-generator';

export default function App() {
  const [key, setKey] = useState(null);
  const [value, setValue] = useState(null);
  const [downloadKey, setDownloadKey] = useState(null);
  const [qrCodeValue, setQRCodeValue] = useState('');

  const save = async () => {
    //You have to implement the function that saves your information into your database.
    //Here I'm saving data to AsyncStorage. (For sample)

    await AsyncStorage.setItem(key, value);
  }

  const download = async () => {
    //You have to implement the function that retrieves your information from your database for given key.
    //Here I'm retrieving data from AsyncStorage. (For sample)

    const qrValue = await AsyncStorage.getItem(downloadKey);
    setQRCodeValue(qrValue);
  }

  return (
    <View style={styles.container}>

      <View style={styles.row}>
        <TextInput placeholder={'Key'} value={key} onChangeText={(key) => setKey(key)} style={styles.textInput}/>
        <TextInput placeholder={'Value'} value={value} onChangeText={(value) => setValue(value)} style={styles.textInput}/>
      </View>
      <TouchableOpacity style={{ flexDirection: 'row', marginBottom: 50 }} onPress={save}>
        <Text style={styles.button}>Save</Text>
      </TouchableOpacity>

      {qrCodeValue ? <QRCode value={qrCodeValue} size={200} /> : null}

      <Text style={{ margin: 10 }}>{qrCodeValue}</Text>

      <View style={[styles.row, { marginTop: 50 }]}>
        <TextInput placeholder={'Key'} value={downloadKey} onChangeText={(downloadKey) => setDownloadKey(downloadKey)} style={styles.textInput}/>
        <TouchableOpacity style={{ flex: 1, flexDirection: 'row' }} onPress={download}>
          <Text style={styles.button}>Download</Text>
        </TouchableOpacity>
      </View>

    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    paddingTop: 50,
    paddingBottom: 50
  },
  row: {
    flexDirection: 'row',
  },
  textInput: {
    flex: 1,
    borderColor: '#808080',
    borderWidth: 1,
    borderRadius: 5,
    margin: 5,
    paddingLeft: 5,
    paddingRight: 5,
  },
  button: {
    flex: 1,
    borderColor: '#0040FF',
    backgroundColor: '#0080FF',
    borderWidth: 1,
    borderRadius: 5,
    margin: 5,
    textAlign: 'center',
    textAlignVertical: 'center',
    height: 30
  },
});
</code>```

Here is a Demo...

Please go through this and feel free to ask me if you have any further problems. Good luck!

Body:
If you want to save the information in QR code as a QR code, you have to convert the QR code into a png image and then store it in your database as an image.

So, what I advise you to do is, when saving, just store the information as a string (or whatever necessary) in the database. When downloading, just retrieve the information from your database and immediately generate the QR Code. It's not consuming a longer time. After the QR Code is generated, then display it.

I think this is the most appropriate solution for you.

You may need react-native-qrcode-generator for generate the QR Code.

Here is a sample code...

You can input key and value (at the top inputs) and press 'Save' button. When the 'Save' button is pressed, you have to store your key-value pair (data) to your database.

Then, input the key (at the bottom input) of which you want to download and press 'Download' button. Then you have to retrieve the data (value) associated with the given key.

State value is set after the value is successfully retrieved from the database. That state is given as a prop to the QRCode component.

import React, { useState } from 'react';
import { StyleSheet, View, Text, TextInput, TouchableOpacity, AsyncStorage } from 'react-native';
import QRCode from 'react-native-qrcode-generator';

export default function App() {
  const [key, setKey] = useState(null);
  const [value, setValue] = useState(null);
  const [downloadKey, setDownloadKey] = useState(null);
  const [qrCodeValue, setQRCodeValue] = useState('');

  const save = async () => {
    //You have to implement the function that saves your information into your database.
    //Here I'm saving data to AsyncStorage. (For sample)

    await AsyncStorage.setItem(key, value);
  }

  const download = async () => {
    //You have to implement the function that retrieves your information from your database for given key.
    //Here I'm retrieving data from AsyncStorage. (For sample)

    const qrValue = await AsyncStorage.getItem(downloadKey);
    setQRCodeValue(qrValue);
  }

  return (
    <View style={styles.container}>

      <View style={styles.row}>
        <TextInput placeholder={'Key'} value={key} onChangeText={(key) => setKey(key)} style={styles.textInput}/>
        <TextInput placeholder={'Value'} value={value} onChangeText={(value) => setValue(value)} style={styles.textInput}/>
      </View>
      <TouchableOpacity style={{ flexDirection: 'row', marginBottom: 50 }} onPress={save}>
        <Text style={styles.button}>Save</Text>
      </TouchableOpacity>

      {qrCodeValue ? <QRCode value={qrCodeValue} size={200} /> : null}

      <Text style={{ margin: 10 }}>{qrCodeValue}</Text>

      <View style={[styles.row, { marginTop: 50 }]}>
        <TextInput placeholder={'Key'} value={downloadKey} onChangeText={(downloadKey) => setDownloadKey(downloadKey)} style={styles.textInput}/>
        <TouchableOpacity style={{ flex: 1, flexDirection: 'row' }} onPress={download}>
          <Text style={styles.button}>Download</Text>
        </TouchableOpacity>
      </View>

    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    paddingTop: 50,
    paddingBottom: 50
  },
  row: {
    flexDirection: 'row',
  },
  textInput: {
    flex: 1,
    borderColor: '#808080',
    borderWidth: 1,
    borderRadius: 5,
    margin: 5,
    paddingLeft: 5,
    paddingRight: 5,
  },
  button: {
    flex: 1,
    borderColor: '#0040FF',
    backgroundColor: '#0080FF',
    borderWidth: 1,
    borderRadius: 5,
    margin: 5,
    textAlign: 'center',
    textAlignVertical: 'center',
    height: 30
  },
});

Here is a Demo...

Please go through this and feel free to ask me if you have any further problems. Good luck!


来源: stackexchange

问:
How can I read an input string of unknown length?
If I don't know how long the word is, I cannot write char m[6];,

The length of the word is maybe ten or twenty long.
How can I use scanf to get input from the keyboard?

```<code>#include <stdio.h>
int main(void)
{
    char  m[6];
    printf("please input a string with length=5\n");
    scanf("%s",&m);
    printf("this is the string: %s\n", m);
    return 0;
}
</code>```

please input a string with length=5

input: hello

this is the string: hello

答:
There is a new function in C standard for getting a line without specifying its size. getline function allocates string with required size automatically so there is no need to guess about string's size. The following code demonstrate usage:

```<code>#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char *line = NULL;
    size_t len = 0;
    ssize_t read;

    while ((read = getline(&line, &len, stdin)) != -1) {
        printf("Retrieved line of length %zu :\n", read);
        printf("%s", line);
    }

    if (ferror(stdin)) {
        /* handle error */
    }

    free(line);
    return 0;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If I don't know how long the word is, I cannot write char m[6];,

The length of the word is maybe ten or twenty long.
How can I use scanf to get input from the keyboard?

#include <stdio.h>
int main(void)
{
    char  m[6];
    printf("please input a string with length=5\n");
    scanf("%s",&m);
    printf("this is the string: %s\n", m);
    return 0;
}

please input a string with length=5

input: hello

this is the string: hello

Body:
There is a new function in C standard for getting a line without specifying its size. getline function allocates string with required size automatically so there is no need to guess about string's size. The following code demonstrate usage:

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

int main(void)
{
    char *line = NULL;
    size_t len = 0;
    ssize_t read;

    while ((read = getline(&line, &len, stdin)) != -1) {
        printf("Retrieved line of length %zu :\n", read);
        printf("%s", line);
    }

    if (ferror(stdin)) {
        /* handle error */
    }

    free(line);
    return 0;
}


问:
Assigning variables returned by Sklearn train_test_split()
I was confused about using train_test_split() in sklearn. Here is a code snippet of something I've tried:

```<code>X = example_df.drop('features', axis=1)
y = example_df['price']

y_test, X_train, X_test, y_train= train_test_split(X, y, test_size=0.2)
</code>```

How does it split the rows of example_df? example_df has 100 rows, so I expected the datasets to be split with the following sizes.

y_test should have 80 rows

X_train should have 20 rows

X_test should have 80 rows

y_train should have 20 rows

But the sizes of my datasets were, respectively: 20, 20, 80, 20.

Why is this?

答:
So in this case, the correct order of variable assignment you should be using is
X_train, X_test, y_train, y_test. i.e. you need to rewrite your code to be

```<code>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
</code>```

Multiple assignment unpacking

Additionally, I suspect your confusion might also come from a misunderstanding of how multiple assignment unpacking in python works, and the return value of train_test_split(...).

Let us consider giving train_test_split(...) a single array to split, e.g. y = [0, 1, 2, 3, 4]. train_test_split(y) gives us an output that will look something like [[0, 1, 2], [3, 4]] (plus or minus some shuffling). We see that it takes our original list and returns a list of 2 lists.

We can pass train_test_split(...) an arbitrary number of lists to split. So let's see what happens if we gave train_test_split(...) 2 lists (list_1, list_2) as input. It would return a list of 4 lists. The first two inner lists would be the training set of list_1 followed by the testing set of list_1, and the last two inner lists would be the training set of list_2 followed by the testing set of list_2. The returned lists however, are do not correspond to any keywords such as "X_train" or "x_test", they're just good old regular lists.

One way to handle the output would be like this

```<code>datasets = train_test_split(list_1, list_2)
list_1_train = datasets[0]
list_1_test = datasets[1]
list_2_train = datasets[2]
list_2_test = datasets[3]
</code>```

However this is lengthy, repetitive, and prone to bugs. Thankfully, python gives us the syntax to unpack multiple variables and assign them in a single statement. The equivalent of assigning the four lists as shown in the above code snippet would be to do this:

```<code>[list_1_train, list_1_test, list_2_train, list_2_test] = train_test_split(list_1, list_2)
</code>```

or with more sugar:

```<code>list_1_train, list_1_test, list_2_train, list_2_test = train_test_split(list_1, list_2)
</code>```

Body:
I was confused about using train_test_split() in sklearn. Here is a code snippet of something I've tried:

X = example_df.drop('features', axis=1)
y = example_df['price']

y_test, X_train, X_test, y_train= train_test_split(X, y, test_size=0.2)

How does it split the rows of example_df? example_df has 100 rows, so I expected the datasets to be split with the following sizes.

y_test should have 80 rows

X_train should have 20 rows

X_test should have 80 rows

y_train should have 20 rows

But the sizes of my datasets were, respectively: 20, 20, 80, 20.

Why is this?

Body:
So in this case, the correct order of variable assignment you should be using is
X_train, X_test, y_train, y_test. i.e. you need to rewrite your code to be

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

Multiple assignment unpacking

Additionally, I suspect your confusion might also come from a misunderstanding of how multiple assignment unpacking in python works, and the return value of train_test_split(...).

Let us consider giving train_test_split(...) a single array to split, e.g. y = [0, 1, 2, 3, 4]. train_test_split(y) gives us an output that will look something like [[0, 1, 2], [3, 4]] (plus or minus some shuffling). We see that it takes our original list and returns a list of 2 lists.

We can pass train_test_split(...) an arbitrary number of lists to split. So let's see what happens if we gave train_test_split(...) 2 lists (list_1, list_2) as input. It would return a list of 4 lists. The first two inner lists would be the training set of list_1 followed by the testing set of list_1, and the last two inner lists would be the training set of list_2 followed by the testing set of list_2. The returned lists however, are do not correspond to any keywords such as "X_train" or "x_test", they're just good old regular lists.

One way to handle the output would be like this

datasets = train_test_split(list_1, list_2)
list_1_train = datasets[0]
list_1_test = datasets[1]
list_2_train = datasets[2]
list_2_test = datasets[3]

However this is lengthy, repetitive, and prone to bugs. Thankfully, python gives us the syntax to unpack multiple variables and assign them in a single statement. The equivalent of assigning the four lists as shown in the above code snippet would be to do this:

[list_1_train, list_1_test, list_2_train, list_2_test] = train_test_split(list_1, list_2)

or with more sugar:

list_1_train, list_1_test, list_2_train, list_2_test = train_test_split(list_1, list_2)


问:
MySQL licensing and GPL
As far as I know, when I build a desktop/server app using any GPL code like MySQL I will have to release the source code of my software under the GPL.

If I want to develop a web-app using MySQL, my code will link against the MySQL libraries. Must I release the sourcecode of my webapp in this situation to be in accordance with the GPL?

答:
Unless you derive from and/or distribute the GPL'd software, you should be safe.

Linking against the MySQL client library is neither a derivative work, nor distribution.

UPDATE: Come to think about it, how you link (dynamic or static) against the libraries will make a difference. Static linking is distribution, but if you link dynamically and your clients download the connectors themselves, that's not distribution and you should be safe.

Oh, and IANAL.

ContentLicense: CC BY-SA 2.5

Title: MySQL licensing and GPL

LastEditorDisplayName: Roger Pate

OwnerDisplayName: Can Berk Güder

LastEditorDisplayName: Can Berk Güder


问:
How do I put extra number at the end of username if duplicate
Hard to explain, and let me show an example.

If username foo already exists in MySQL I want php script will allow it but to be foo1

Then if foo1 exists too, script will generate the username will be foo2

If foo2 existed then become foo3

How to make like that?

Like Col. Shrapnel said Natural increment which seems more sensible. just like "New Folder(3)" stuff in Windows

答:
```<code>    while (exists($username)) {
        if (!is_numeric(substr($username, -1, 1))) {
            $username = "{$username}0";
        }
        $username++;
    }

    return $username;
</code>```

You get: test, test1, test2 and so on

Body:
    while (exists($username)) {
        if (!is_numeric(substr($username, -1, 1))) {
            $username = "{$username}0";
        }
        $username++;
    }

    return $username;

You get: test, test1, test2 and so on


问:
Read multiple CSVs & merge those CSVs into separate files based on year in filename python
Suppose I have the following data sets that I successfully read into my notebook:

```<code>data1-format1-1991-1992.csv
data2-format1-1993-1994.csv
data3-format1-1995-1996.csv

data4-format2-1991-1992.csv
data5-format2-1993-1994.csv
data6-format2-1995-1996.csv
</code>```

I can easily read these sets in, from their own directories like so:

```<code>files1 = [filename for filename in os.listdir(master_dir_1) if filename.startswith("data-")] # would do same for second set of files, in master_dir_2

for filename in files1:
    df = pd.read_csv(filename)
    print(df)
</code>```

This prints them out in one frame - but I need to read them in, and then pd.merge() each separate file based on the year in the file name. E.g., data1-format1-1991-1992.csv gets joined with data1-format2-1991-1992.csv, and so on.

The process would be to read in both sets from their own directories with the loop above, and then have another loop that combines and saves based on the matching years in the file names (I think). How do I split based on the years, and save each joined file separately, with the years in the saved csv name? I've got the process for reading in single data sets and joining/saving, but not for multiple read ins, joins, and saves.

This question gets me some of the way there, because of how .format() is utilized.

答:
```<code>years = [name.split('-')[-2:] for name in names]
years = ['-'.join(y) for y in years]
years = set(years) #unique years
print(years)

dataformat = [name.split('-')[:2] for name in names]
dataformat = ['-'.join(df) for df in dataformat]
print(dataformat)

year_data = dict()
for year in years:
    yragne=year.split('.')[0]
    year_data[yragne] = pd.DataFrame([])
    for df in dataformat:
        try:
            gg = pd.read_csv(rootdir+'/'+df+'-'+year,header = None)
            print(gg)
            year_data[yragne] = year_data[yragne].append(pd.read_csv(rootdir+'/'+df+'-'+year,header = None),True)
        except:
            pass
</code>```

Body:
Suppose I have the following data sets that I successfully read into my notebook:

data1-format1-1991-1992.csv
data2-format1-1993-1994.csv
data3-format1-1995-1996.csv

data4-format2-1991-1992.csv
data5-format2-1993-1994.csv
data6-format2-1995-1996.csv

I can easily read these sets in, from their own directories like so:

files1 = [filename for filename in os.listdir(master_dir_1) if filename.startswith("data-")] # would do same for second set of files, in master_dir_2

for filename in files1:
    df = pd.read_csv(filename)
    print(df)

This prints them out in one frame - but I need to read them in, and then pd.merge() each separate file based on the year in the file name. E.g., data1-format1-1991-1992.csv gets joined with data1-format2-1991-1992.csv, and so on.

The process would be to read in both sets from their own directories with the loop above, and then have another loop that combines and saves based on the matching years in the file names (I think). How do I split based on the years, and save each joined file separately, with the years in the saved csv name? I've got the process for reading in single data sets and joining/saving, but not for multiple read ins, joins, and saves.

This question gets me some of the way there, because of how .format() is utilized.


问:
copying c++ abstract classes
Ok heres some code.

```<code>#include <iostream>
#include <deque>
using namespace std;
class A
{
public:
    virtual void Execute()
    {
        cout << "Hello from class A" << endl;
    }
};
class B: public A
{
public:
    void Execute()
    {
        cout << "Hello from class B" << endl;
    }
};
void Main()
{
    deque<A *> aclasses = deque<A*>(0);
    deque<A *> aclasses2 = deque<A*>(0);
    A a1 = A();
    B b1 = B();
    aclasses.push_back(&a1);
    aclasses.push_back(&b1);
    aclasses[0]->Execute();
    aclasses[1]->Execute();

    //Now say I want to copy a class from aclasses to aclasses2
    //while perserving it's identity and making it a seperate entity, without
    //knowing the exact type it is.

    aclasses2.push_back(new A(*aclasses[0]));
    aclasses2.push_back(new A(*aclasses[1]));
    //Now my problem show itself
    for each(A * a in aclasses2)
        a->Execute();
    //Execute is called from the original class A both times.

}
</code>```

Now you might say, why don't you just put the pointers from the first deque into the second deque? While I could but I need the data to be independent. Basically I want to be able to clone items from the first deque while preserving there identity and giving them there own data.

Now the current modified version

```<code>#include <iostream>
#include <deque>
using namespace std;
class A
{
public:
    virtual void Execute()
    {
        cout << "Hello from class A" << endl;
    }
    virtual ~A() {}             // don't forget the virtual destructor
    virtual A* clone() const {
       return new A(*this);
    }
};
class B: public A
{
public:
    void Execute()
    {
        cout << "Hello from class B" << endl;
    }
    virtual B* clone() {     // return type is co-variant
       return new B( *this );
    }
};
void MainRUNNER()
{
    deque<A *> aclasses = deque<A*>(0);
    deque<A *> aclasses2 = deque<A*>(0);
    A a1 = A();
    B b1 = B();
    aclasses.push_back(&a1);
    aclasses.push_back(&b1);
    aclasses[0]->Execute();
    aclasses[1]->Execute();

    //Now say I want to copy a class from aclasses to aclasses2
    //while perserving it's identity and making it a seperate entity, without
    //knowing the exact type it is.

    aclasses2.push_back(aclasses[0]->clone());
    aclasses2.push_back(aclasses[1]->clone());
    //Now my problem show itself
    for each(A * a in aclasses2)
        a->Execute();
    //Execute is called from the original class A both times.
}
</code>```

答:
The common pattern for handling that is through a virtual clone() method in the base class that will create a new object of the appropriate type:

```<code>struct base {
    virtual ~base() {}             // don't forget the virtual destructor
    virtual base* clone() const {
       return new base(*this);
    }
};
struct derived : base {
    virtual derived* clone() const {     // return type is co-variant
       return new derived( *this );
    }
};
int main() {
   std::auto_ptr<base> b1( new derived );
   std::auto_ptr<base> b2( b1->clone() ); // will create a derived object
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: copying c++ abstract classes

Body:
Ok heres some code.

#include <iostream>
#include <deque>
using namespace std;
class A
{
public:
    virtual void Execute()
    {
        cout << "Hello from class A" << endl;
    }
};
class B: public A
{
public:
    void Execute()
    {
        cout << "Hello from class B" << endl;
    }
};
void Main()
{
    deque aclasses = deque(0);
    deque aclasses2 = deque(0);
    A a1 = A();
    B b1 = B();
    aclasses.push_back(&a1);
    aclasses.push_back(&b1);
    aclasses[0]->Execute();
    aclasses[1]->Execute();

    //Now say I want to copy a class from aclasses to aclasses2
    //while perserving it's identity and making it a seperate entity, without
    //knowing the exact type it is.

    aclasses2.push_back(new A(*aclasses[0]));
    aclasses2.push_back(new A(*aclasses[1]));
    //Now my problem show itself
    for each(A * a in aclasses2)
        a->Execute();
    //Execute is called from the original class A both times.

}

Now you might say, why don't you just put the pointers from the first deque into the second deque? While I could but I need the data to be independent. Basically I want to be able to clone items from the first deque while preserving there identity and giving them there own data.

Now the current modified version

#include <iostream>
#include <deque>
using namespace std;
class A
{
public:
    virtual void Execute()
    {
        cout << "Hello from class A" << endl;
    }
    virtual ~A() {}             // don't forget the virtual destructor
    virtual A* clone() const {
       return new A(*this);
    }
};
class B: public A
{
public:
    void Execute()
    {
        cout << "Hello from class B" << endl;
    }
    virtual B* clone() {     // return type is co-variant
       return new B( *this );
    }
};
void MainRUNNER()
{
    deque aclasses = deque(0);
    deque aclasses2 = deque(0);
    A a1 = A();
    B b1 = B();
    aclasses.push_back(&a1);
    aclasses.push_back(&b1);
    aclasses[0]->Execute();
    aclasses[1]->Execute();

    //Now say I want to copy a class from aclasses to aclasses2
    //while perserving it's identity and making it a seperate entity, without
    //knowing the exact type it is.

    aclasses2.push_back(aclasses[0]->clone());
    aclasses2.push_back(aclasses[1]->clone());
    //Now my problem show itself
    for each(A * a in aclasses2)
        a->Execute();
    //Execute is called from the original class A both times.
}

Body:
The common pattern for handling that is through a virtual clone() method in the base class that will create a new object of the appropriate type:

struct base {
    virtual ~base() {}             // don't forget the virtual destructor
    virtual base* clone() const {
       return new base(*this);
    }
};
struct derived : base {
    virtual derived* clone() const {     // return type is co-variant
       return new derived( *this );
    }
};
int main() {
   std::auto_ptr<base> b1( new derived );
   std::auto_ptr<base> b2( b1->clone() ); // will create a derived object
}


问:
Are Data marts sit within Data warehouses or completely separate DBs in Kimball Methodology?
According to Kimball methodology whether data marts sit within a DW as related star schemas combination OR are they (data marts) separate(different databases, not inside a DW) from the main Data warehouse and they extract/update data from the Data warehouse for a scheduled period?. Which is correct?

From my memory the Kimball methodology says DW is a combination of data marts.
Does this mean the data marts sit inside the main Data Warehouse?

The above 2 questions are related to the DW related data marts and NOT every department related isolated data marts which are get updated directly from source

答:
Under the Kimball methodology, the data warehouse is comprised of star schemas that are related to each other via conformed dimensions. So, if you consider a star schema to be the same thing as a data mart (I always have) then Kimball's data warehouse is just a collection of data marts.

FWIW, I'm not a huge fan of that architecture. I believe that your analytics databases must perform two functions: data integration (i.e. ETL that brings together data from multiple sources) and data distribution (i.e. reporting). While stars are great for reporting, I find them quite brittle for integration. Thus, I find that a normalized data warehouse feeding stars tends to be a more reliable, if perhaps more complex, architecture.

Also, FWIW, I've been working with a data vault data modeling approach for the integration layer and am having a lot of success with it. It's a bit complex to learn but really cool once you figure it all out.


问:
How to build a correct CA chain using cloudflare oigin certificates?

Use Case

this is my use case: I have a page available trough cloudflare (proxied), let's call it example.com.
I created a Origin Certificate with Cloudflare and linked it in my nginx config, works fine. Cloudflare works in "Full" SSL mode.
Now I want to be able to basically add 127.0.0.1   example.com to my /etc/hosts so the server itself can directly access the page (it is not really an option to use a different domain with software running on this server to circumvent this).

Now obviously when I curl -v https://example.com I get a ssl error.

What I did so far

So basically, did some research and learned about CA chains and so on.
I found the Cloudflare Origin root CA's (Cloudflare Documentation, Step 4) and included that in the cert chain in my nginx server (basically first the Cloudflare Origin cert they generated for me, then the Root CA). I also installed the Root CA to /usr/share/ca-certificates (and /usr/local/share/ca-certificates) and ran dpkg-reconfigure ca-certificates and it was properly added to the /etc/ssl/certs dir. So far so good?

Result: Does not work.

Further research

Stumbling upon this guide I looked the following up:

cert.pem is my Cloudflare issued certificate

ca.pem is the cloudflare root CA (the ecc file)

```<code>root@host:~/ssltest# openssl verify cert.pem
O = "CloudFlare, Inc.", OU = CloudFlare Origin CA, CN = CloudFlare Origin Certificate
error 20 at 0 depth lookup: unable to get local issuer certificate
error cert.pem: verification failed
root@host:~/ssltest# openssl x509 -noout -issuer -in cert.pem
issuer=C = US, O = "CloudFlare, Inc.", OU = CloudFlare Origin SSL Certificate Authority, L = San Francisco, ST = California
root@host:~/ssltest# openssl x509 -noout -issuer -in ca.pem
issuer=C = US, ST = California, L = San Francisco, O = "CloudFlare, Inc.", OU = CloudFlare Origin SSL ECC Certificate Authority
root@host:~/ssltest# openssl verify -CAfile ca.pem cert.pem
O = "CloudFlare, Inc.", OU = CloudFlare Origin CA, CN = CloudFlare Origin Certificate
error 20 at 0 depth lookup: unable to get local issuer certificate
error cert.pem: verification failed
</code>```

So basically the Issuer of cert.pem and Subject of ca.pem do not match up.
This means for me: Either there is an Intermediate Cert that I do not know how to get, or Cloudflare gave me a cert that is not from the root CA they gave me.

Also the difference between Issuer and Subject is super small:

CloudFlare Origin SSL Certificate Authority

CloudFlare Origin SSL ECC Certificate Authority

What can I do to fix it?
I'm probably just not seeing something here, can anyone help me out? Thank you!

答:
There are two CA certificates offered on the site you refer to:

The first one is the RSA certificate with the OU "CloudFlare Origin SSL Certificate Authority". The seconds one is the ECC certificate OU "CloudFlare Origin SSL ECC Certificate Authority".

Looks like you took ECC certificate while you should have taken the RSA certificate.

Body:
Use Case

this is my use case: I have a page available trough cloudflare (proxied), let's call it example.com.
I created a Origin Certificate with Cloudflare and linked it in my nginx config, works fine. Cloudflare works in "Full" SSL mode.
Now I want to be able to basically add 127.0.0.1   example.com to my /etc/hosts so the server itself can directly access the page (it is not really an option to use a different domain with software running on this server to circumvent this).

Now obviously when I curl -v https://example.com I get a ssl error.

What I did so far

So basically, did some research and learned about CA chains and so on.
I found the Cloudflare Origin root CA's (Cloudflare Documentation, Step 4) and included that in the cert chain in my nginx server (basically first the Cloudflare Origin cert they generated for me, then the Root CA). I also installed the Root CA to /usr/share/ca-certificates (and /usr/local/share/ca-certificates) and ran dpkg-reconfigure ca-certificates and it was properly added to the /etc/ssl/certs dir. So far so good?

Result: Does not work.

Further research

Stumbling upon this guide I looked the following up:

cert.pem is my Cloudflare issued certificate

ca.pem is the cloudflare root CA (the ecc file)

root@host:~/ssltest# openssl verify cert.pem
O = "CloudFlare, Inc.", OU = CloudFlare Origin CA, CN = CloudFlare Origin Certificate
error 20 at 0 depth lookup: unable to get local issuer certificate
error cert.pem: verification failed
root@host:~/ssltest# openssl x509 -noout -issuer -in cert.pem
issuer=C = US, O = "CloudFlare, Inc.", OU = CloudFlare Origin SSL Certificate Authority, L = San Francisco, ST = California
root@host:~/ssltest# openssl x509 -noout -issuer -in ca.pem
issuer=C = US, ST = California, L = San Francisco, O = "CloudFlare, Inc.", OU = CloudFlare Origin SSL ECC Certificate Authority
root@host:~/ssltest# openssl verify -CAfile ca.pem cert.pem
O = "CloudFlare, Inc.", OU = CloudFlare Origin CA, CN = CloudFlare Origin Certificate
error 20 at 0 depth lookup: unable to get local issuer certificate
error cert.pem: verification failed

So basically the Issuer of cert.pem and Subject of ca.pem do not match up.
This means for me: Either there is an Intermediate Cert that I do not know how to get, or Cloudflare gave me a cert that is not from the root CA they gave me.

Also the difference between Issuer and Subject is super small:

CloudFlare Origin SSL Certificate Authority

CloudFlare Origin SSL ECC Certificate Authority

What can I do to fix it?
I'm probably just not seeing something here, can anyone help me out? Thank you!


问:
Save cell name and use it later for range
This is a very basic Excel VBA macro question.

I want to save the current cell to a variable.

And later want to use that variable to select a range of that cell into 4 adjacent cells.

So far I have:

```<code>Dim StartCell As Object
Set StartCell = ActiveCell
Range("StartCell.Name:StartCell.Name.Offset(0,4)").Select
</code>```

Obviously it is not working.

Can anyone help me please?

答:
This should work.</p>

```<code>Dim StartCell As Range
Set StartCell = ActiveCell
StartCell.Resize(1,4).Select
</code>```

Body:
This is a very basic Excel VBA macro question.

I want to save the current cell to a variable.

And later want to use that variable to select a range of that cell into 4 adjacent cells.

So far I have:

Dim StartCell As Object
Set StartCell = ActiveCell
Range("StartCell.Name:StartCell.Name.Offset(0,4)").Select

Obviously it is not working.

Can anyone help me please?

Body:
This should work.

Dim StartCell As Range
Set StartCell = ActiveCell
StartCell.Resize(1,4).Select


问:
GWT interaction with external standalone application
I work on a standalone Java application that is a command-and-control system for an assortment of hardware.  The C&C software basically runs from a command line, and controls the system hardware which is spread out all over the place.  It does not require a GUI to meet the business requirements.  I have written a small swing GUI just so I can see what the overall status is of the system, but again, that is not essential.

Going forward, we would like to have a Administrative web GUI with system status and something that would give a user some level of control over the hardware.  We were thinking that GWT might be a viable solution.  Our GWT app would have to have some sort of IPC with the C&C software.  I don't know how viable that is, I don't know that we want the C&C software bundled as a web app that has to run under application server.

I just don't have much experience with this.  I was thinking that the GWT client would interact through RPC with the GWT server, and the GWT server would have some sort of RPC (RMI???) with the C&C.

答: Another option you have is to run a Java Applet that can interact with both GWT (using JSNI) and with the OS. A simple example would be to open a common file in the user's home folder and read/write to that file (with the C&C app doing the same as well).</p>


问:
How to align divs (selects) of different widths and lines vertically whilst also aligning them with other (text)- HTML and CSS
So, I know the question sounds super confusing but I have an image to demonstrate what I want to achieve.
The image:

The part that I am having trouble with is aligning the selection parts to "start" at the same place so that it's not messy. e.g. If you were to put a ruler on the screen they would all start at the same place. And the same problem for the text which looks messy as the words are different lengths.

I have tried using padding, css grids,   etc. but I haven't had luck - I don't feel that I need to add it because none of it really worked but I can if need be.

My HTML is as follows:

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-  scale=1.0">
<link rel="stylesheet" href="jquery-ui.min.css">
<link rel="stylesheet" href="main.css">
<title>Document</title>
</head>
<body>
    <h1>Solve the case!</h1>

    <div class="who-container">
        <h2 class="who">Who                </h2>
        <select class="who" id="who">
            <option>‘Small’ Paul Romano</option>
            <option>Steven Smith aka The Black Widow</option>
            <option>Ronnie ‘The Face’ Jones</option>
            <option>Joe Sharp</option>
        </select>
    </div>

    <div class="where-container">
        <h2 class="where">Where             </h2>
        <select class="where" id="where">
            <option>Mount Road</option>
            <option>Coronation Street</option>
            <option>Windsor Drive</option>
            <option>Back Street</option>
            <option>Queens Close</option>
            <option>Gladstone Road</option>
            <option>Kings Road</option>
            <option>Devon Road</option>
            <option>The Pines</option>
            <option>Saxon Way</option>
            <option>Alexandra Street</option>
            <option>The Grange</option>
            <option>Gloucester Road</option>
            <option>Larch Close</option>
            <option>Cedar Close</option>
            <option>Orchard Grove</option>
            <option>Robin Close</option>
            <option>Third Avenue</option>
            <option>Crescent Road</option>
            <option>Heath Lane</option>
            <option>Church Way</option>
            <option>South Drive</option>
            <option>Herbert Street</option>
            <option>Bedford Street</option>
            <option>Ash Grove</option>
            <option>St Peter's</option>
            <option>Road Thornton</option>
            <option>Road Avenue</option>
            <option>Road Parkway</option>
            <option>North Street</option>
            <option>Hazel Grove</option>
            <option>Shaftesbury Road</option>
            <option>Oak Tree</option>
            <option>Close Juniper</option>
            <option>Close Heron</option>
            <option>Close St</option>
            <option>Paul's Road</option>
            <option>Meadow Way</option>
            <option>Wordsworth Avenue</option>
            <option>Woodland Way</option>
            <option>Windsor Avenue</option>
            <option>Stanley Street</option>
            <option>The Moorings</option>
            <option>Wellington Street</option>
            <option>Edward Street</option>
            <option>Poplar Drive</option>
            <option>Trinity Close</option>
            <option>Railway Terrace</option>
            <option>Oak Close</option>
            <option>The Fairway</option>
            <option>Hall Street</option>
        </select>
    </div>

    <div class="when-container">
        <h2 class="when">When                 </h2>
        <select class="when" id="when">
            <option>00:00 - 00:30</option>
            <option>00:30 - 01:00</option>
            <option>01:00 - 01:30</option>
            <option>01:30 - 02:00</option>
            <option>02:00 - 02:30</option>
            <option>02:30 - 03:00</option>
            <option>03:00 - 03:30</option>
            <option>03:30 - 04:00</option>
            <option>04:00 - 04:30</option>
            <option>04:30 - 05:00</option>
            <option>05:00 - 05:30</option>
            <option>05:30 - 06:00</option>
            <option>06:00 - 06:30</option>
            <option>06:30 - 07:00</option>
            <option>07:00 - 07:30</option>
            <option>07:30 - 08:00</option>
            <option>08:00 - 08:30</option>
            <option>08:30 - 09:00</option>
            <option>09:00 - 09:30</option>
            <option>09:30 - 10:00</option>
            <option>10:00 - 10:30</option>
            <option>10:30 - 11:00</option>
            <option>11:00 - 11:30</option>
            <option>11:30 - 12:00</option>
            <option>12:00 - 12:30</option>
            <option>12:30 - 13:00</option>
            <option>13:00 - 13:30</option>
            <option>13:30 - 14:00</option>
            <option>14:00 - 14:30</option>
            <option>14:30 - 15:00</option>
            <option>15:00 - 15:30</option>
            <option>15:30 - 16:00</option>
            <option>16:00 - 16:30</option>
            <option>16:30 - 17:00</option>
            <option>17:00 - 17:30</option>
            <option>17:30 - 18:00</option>
            <option>18:00 - 18:30</option>
            <option>18:30 - 19:00</option>
            <option>19:00 - 19:30</option>
            <option>19:30 - 20:00</option>
            <option>20:00 - 20:30</option>
            <option>20:30 - 21:00</option>
            <option>21:00 - 21:30</option>
            <option>21:30 - 22:00</option>
            <option>22:00 - 22:30</option>
            <option>22:30 - 23:00</option>
            <option>23:00 - 23:30</option>
            <option>23:30 - 00:00</option>
        </select>
    </div>

    <div class="what-container">
        <h2 class="what">What                 </h2>
        <select class="what" id="what">
            <option>Candlestick</option>
            <option>Pipe</option>
            <option>Knife</option>
            <option>Gun</option>
            <option>Baseball Bat</option>
            <option>Spanner</option>
            <option>Hammer</option>
            <option>Rope</option>
            <option>Brick</option>
            <option>Golf Club</option>
        </select>
    </div>

    <div class="date-container">
        <h2 class="date">Date                 </h2>
        <input type="text" name="date" id="date">
    </div>

    <button onclick="submit()">Solve</button>

</body>
<script src="external/jquery/jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script>

<script src="jquery-ui.min.js"></script>
<script>
    $( "#date" ).datepicker();
    $.datepicker.setDefaults({
    dateFormat: 'dd/mm/yy'
    });
    $( "#date" ).datepicker("setDate", new Date(2020,01,01));
</script>
<script src="form-handler.js"></script>
</html>
</code>```

And my CSS (that DOESN'T WORK!!!):

```<code>.who-container, .where-container, .when-container, .what-container,     .date-container{
    text-align: left;
}

.who, .where, .when, .what, .date{
    text-align: right;
    display: inline-block;
    padding-right: 20%
}

h2{
    padding-left: 40%;
}
</code>```

答:
All you need to do is to write them in form of table so that , it will be aligned just like you want.

You don't have to use containers for different rows.

Pseudocode

```<code><table>

    <tr>
        <td><h2>Who<h2></td>
        <td><input type="text" name=""></td>
    </tr>

    <tr>
        <td><h2>Where<h2></td>
        <td><input type="text" name=""></td>
    </tr>

    <tr>
        <td><h2>Time<h2></td>
        <td><input type="text" name=""></td>
    </tr>

    <tr>
        <td><h2>Date<h2></td>
        <td><input type="text" name=""></td>
    </tr>

    <tr>
        <td><h2>How<h2></td>
        <td><input type="text" name=""></td>
    </tr>

    <input type="Submit" name=""> <!-- your button -->
</table>
</code>```

Body:
So, I know the question sounds super confusing but I have an image to demonstrate what I want to achieve.
The image:

The part that I am having trouble with is aligning the selection parts to "start" at the same place so that it's not messy. e.g. If you were to put a ruler on the screen they would all start at the same place. And the same problem for the text which looks messy as the words are different lengths.

I have tried using padding, css grids,   etc. but I haven't had luck - I don't feel that I need to add it because none of it really worked but I can if need be.

My HTML is as follows:

<!DOCTYPE html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-  scale=1.0">
<link rel="stylesheet" href="jquery-ui.min.css">
<link rel="stylesheet" href="main.css">
<title>Document</title>

Solve the case!

Who

        <select class="who" id="who">
            <option>‘Small’ Paul Romano</option>
            <option>Steven Smith aka The Black Widow</option>
            <option>Ronnie ‘The Face’ Jones</option>
            <option>Joe Sharp</option>
        </select>

Where

        <select class="where" id="where">
            <option>Mount Road</option>
            <option>Coronation Street</option>
            <option>Windsor Drive</option>
            <option>Back Street</option>
            <option>Queens Close</option>
            <option>Gladstone Road</option>
            <option>Kings Road</option>
            <option>Devon Road</option>
            <option>The Pines</option>
            <option>Saxon Way</option>
            <option>Alexandra Street</option>
            <option>The Grange</option>
            <option>Gloucester Road</option>
            <option>Larch Close</option>
            <option>Cedar Close</option>
            <option>Orchard Grove</option>
            <option>Robin Close</option>
            <option>Third Avenue</option>
            <option>Crescent Road</option>
            <option>Heath Lane</option>
            <option>Church Way</option>
            <option>South Drive</option>
            <option>Herbert Street</option>
            <option>Bedford Street</option>
            <option>Ash Grove</option>
            <option>St Peter's</option>
            <option>Road Thornton</option>
            <option>Road Avenue</option>
            <option>Road Parkway</option>
            <option>North Street</option>
            <option>Hazel Grove</option>
            <option>Shaftesbury Road</option>
            <option>Oak Tree</option>
            <option>Close Juniper</option>
            <option>Close Heron</option>
            <option>Close St</option>
            <option>Paul's Road</option>
            <option>Meadow Way</option>
            <option>Wordsworth Avenue</option>
            <option>Woodland Way</option>
            <option>Windsor Avenue</option>
            <option>Stanley Street</option>
            <option>The Moorings</option>
            <option>Wellington Street</option>
            <option>Edward Street</option>
            <option>Poplar Drive</option>
            <option>Trinity Close</option>
            <option>Railway Terrace</option>
            <option>Oak Close</option>
            <option>The Fairway</option>
            <option>Hall Street</option>
        </select>

When

        <select class="when" id="when">
            <option>00:00 - 00:30</option>
            <option>00:30 - 01:00</option>
            <option>01:00 - 01:30</option>
            <option>01:30 - 02:00</option>
            <option>02:00 - 02:30</option>
            <option>02:30 - 03:00</option>
            <option>03:00 - 03:30</option>
            <option>03:30 - 04:00</option>
            <option>04:00 - 04:30</option>
            <option>04:30 - 05:00</option>
            <option>05:00 - 05:30</option>
            <option>05:30 - 06:00</option>
            <option>06:00 - 06:30</option>
            <option>06:30 - 07:00</option>
            <option>07:00 - 07:30</option>
            <option>07:30 - 08:00</option>
            <option>08:00 - 08:30</option>
            <option>08:30 - 09:00</option>
            <option>09:00 - 09:30</option>
            <option>09:30 - 10:00</option>
            <option>10:00 - 10:30</option>
            <option>10:30 - 11:00</option>
            <option>11:00 - 11:30</option>
            <option>11:30 - 12:00</option>
            <option>12:00 - 12:30</option>
            <option>12:30 - 13:00</option>
            <option>13:00 - 13:30</option>
            <option>13:30 - 14:00</option>
            <option>14:00 - 14:30</option>
            <option>14:30 - 15:00</option>
            <option>15:00 - 15:30</option>
            <option>15:30 - 16:00</option>
            <option>16:00 - 16:30</option>
            <option>16:30 - 17:00</option>
            <option>17:00 - 17:30</option>
            <option>17:30 - 18:00</option>
            <option>18:00 - 18:30</option>
            <option>18:30 - 19:00</option>
            <option>19:00 - 19:30</option>
            <option>19:30 - 20:00</option>
            <option>20:00 - 20:30</option>
            <option>20:30 - 21:00</option>
            <option>21:00 - 21:30</option>
            <option>21:30 - 22:00</option>
            <option>22:00 - 22:30</option>
            <option>22:30 - 23:00</option>
            <option>23:00 - 23:30</option>
            <option>23:30 - 00:00</option>
        </select>

What

        <select class="what" id="what">
            <option>Candlestick</option>
            <option>Pipe</option>
            <option>Knife</option>
            <option>Gun</option>
            <option>Baseball Bat</option>
            <option>Spanner</option>
            <option>Hammer</option>
            <option>Rope</option>
            <option>Brick</option>
            <option>Golf Club</option>
        </select>

Date

        <input type="text" name="date" id="date">

    <button onclick="submit()">Solve</button>

And my CSS (that DOESN'T WORK!!!):

.who-container, .where-container, .when-container, .what-container,     .date-container{
    text-align: left;
}

.who, .where, .when, .what, .date{
    text-align: right;
    display: inline-block;
    padding-right: 20%
}

h2{
    padding-left: 40%;
}

Body:
All you need to do is to write them in form of table so that , it will be aligned just like you want.

You don't have to use containers for different rows.

Pseudocode

<table>

    <tr>
        <td><h2>Who<h2></td>
        <td><input type="text" name=""></td>
    </tr>

    <tr>
        <td><h2>Where<h2></td>
        <td><input type="text" name=""></td>
    </tr>

    <tr>
        <td><h2>Time<h2></td>
        <td><input type="text" name=""></td>
    </tr>

    <tr>
        <td><h2>Date<h2></td>
        <td><input type="text" name=""></td>
    </tr>

    <tr>
        <td><h2>How<h2></td>
        <td><input type="text" name=""></td>
    </tr>

    <input type="Submit" name=""> <!-- your button -->
</table>


问:
How to override the parents padding while adding a border bottom
I am building a dropdown such that there is a line below the first option like:

This is what my HTML looks like right now:

               <svg aria-label="magnifier" class="icon_n7qd0i" fill="#8796A6" width="14" height="14" data-component-id="Icon">
                  <use xlink:href="#sprite_magnifier"></use>
               </svg>

            <input class="input_h63q7t-o_O-bodyM_1n94ib9-o_O-iconInput_1oxe2z4" id="input-5" type="text" maxlength="127" min="" max="" placeholder="Find a Field" value="">

 Select All multiselect

               <input id="toggle-input-0" class="checkbox_1u9fru1" type="checkbox">

 No

               <input id="toggle-input-2" class="checkbox_1u9fru1" type="checkbox">

```

Now I tried adding a border-bottom: 1px solid black on the div with fields class eg:  i.e each of the optios.

But because the parent adds a padding it is not able to match full widt.
How can I override it

答:
Assuming the parent's paddings are like padding: 5px 10px;

Add margin-left: -10px; margin-right: -10px to the children would let border-bottom to take the full width.

parent {
  display: block;
  margin: 15px;
  padding: 5px 10px;
  border: 1px solid grey;
}

child {
  display: block;
  border-bottom: 1px solid blue;
}

.full-width child {
  margin-left: -10px;
  margin-right: -10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><parent>
  <child>Child - border bottom not taking full width</child>
</parent>
<parent class="full-width">
  <child>Child - border bottom takes full width</child>
</parent></code>```

Body:
I am building a dropdown such that there is a line below the first option like:

This is what my HTML looks like right now:

               <svg aria-label="magnifier" class="icon_n7qd0i" fill="#8796A6" width="14" height="14" data-component-id="Icon">
                  <use xlink:href="#sprite_magnifier"></use>
               </svg>

            <input class="input_h63q7t-o_O-bodyM_1n94ib9-o_O-iconInput_1oxe2z4" id="input-5" type="text" maxlength="127" min="" max="" placeholder="Find a Field" value="">

 Select All multiselect

               <input id="toggle-input-0" class="checkbox_1u9fru1" type="checkbox">

 No

               <input id="toggle-input-2" class="checkbox_1u9fru1" type="checkbox">

Now I tried adding a border-bottom: 1px solid black on the div with fields class eg:  i.e each of the optios.

But because the parent adds a padding it is not able to match full widt.
How can I override it

Body:
Assuming the parent's paddings are like padding: 5px 10px;

Add margin-left: -10px; margin-right: -10px to the children would let border-bottom to take the full width.

parent {
  display: block;
  margin: 15px;
  padding: 5px 10px;
  border: 1px solid grey;
}

child {
  display: block;
  border-bottom: 1px solid blue;
}

.full-width child {
  margin-left: -10px;
  margin-right: -10px;
}

<parent>
  <child>Child - border bottom not taking full width</child>
</parent>
<parent class="full-width">
  <child>Child - border bottom takes full width</child>
</parent>


问:
Finding window width in liquid
I am looking for a way to use an if statement including the viewport width directly in Liquid, not in CSS.

What I want to do is the following:
I have two different navigations for my website, one of them should be used for the mobile version and the other for the desktop version. In Liquid the navigation is loaded into the header like this:

```<code>        {% include 'navigation' %}
</code>```

So I hope I can do something like this:

```<code>    {%- if width > 1000 -%}
        {% include 'navigation' %}
    {%- else -%}
        {% include 'navigation-mobile' %}
    {%- endif -%}
</code>```

Thank you guys in advance!

答:
Liquid is a back-end framework, which means that it doesn't have access to the document and window objects or any of the front-end stuffs.

To say it simply Liquid loads before it actually knows what is the window width. (in developer words, it loads before the DOM is ready)

Or long story short, there is no way to access the window width from liquid, so you are fighting a lost battle here.

Consider using Javascript to add a class to a specific navigation in order to show it.

Title: Finding window width in liquid

Body:
I am looking for a way to use an if statement including the viewport width directly in Liquid, not in CSS.

What I want to do is the following:
I have two different navigations for my website, one of them should be used for the mobile version and the other for the desktop version. In Liquid the navigation is loaded into the header like this:

        {% include 'navigation' %}

So I hope I can do something like this:

    {%- if width > 1000 -%}
        {% include 'navigation' %}
    {%- else -%}
        {% include 'navigation-mobile' %}
    {%- endif -%}

Thank you guys in advance!


问:
Django @login_required not redirecting to login page
I am using class based views in Django. @login_required decorator is not redirecting to login page. It still shows the profile page.

```<code>class ProfileView(TemplateView):
template_name='profile.html'

@login_required(login_url='/accounts/login/')
def dispatch(self, *args, **kwargs):
        return super(ProfileView, self).dispatch(*args, **kwargs)
</code>```

Can anyone help me. I m new to Django and any help would be appreciated.

Thanks in advance

答:
When using class-based views, it's preferred to use the LoginRequiredMixin rather than the @login_required decorator. It performs essentially the same function.

    class ProfileView(LoginRequiredMixin, TemplateView):
        template_name='profile.html'
```

Body:
I am using class based views in Django. @login_required decorator is not redirecting to login page. It still shows the profile page.

class ProfileView(TemplateView):
template_name='profile.html'

@login_required(login_url='/accounts/login/')
def dispatch(self, *args, **kwargs):
        return super(ProfileView, self).dispatch(*args, **kwargs)

Can anyone help me. I m new to Django and any help would be appreciated.

Thanks in advance


问:
Patching nant 0.91 to use mono 4.0
The Nant doesn't support mono 4, but fortunately there's a patch for it.

I download the patch - http://sourceforge.net/tracker/download.php?group_id=31650&atid=402870&file_id=404197&aid=3206199

I also download the source.

I unzip the source and copy the patch inside the directory.

I run patch  < mono-4.0.diff, but I got this error.

can't find file to patch at input line 8
Perhaps you should have used the -p or --strip option?

The text leading up to this was:

|Index: src/NAnt.Core/Functions/AssemblyFunctions.cs
|===================================================================
|RCS file: /cvsroot/nant/nant/src/NAnt.Core/Functions/AssemblyFunctions.cs,v
|retrieving revision 1.12
|diff -u -r1.12 AssemblyFunctions.cs
|--- src/NAnt.Core/Functions/AssemblyFunctions.cs       10 Oct 2005 14:51:26 -0000      1.12

|+++ src/NAnt.Core/Functions/AssemblyFunctions.cs       13 Mar 2011 09:14:40 -0000

File to patch:

What might be wrong?

答: According to comments, this patch has been merged into the NAnt source tree, wouldn't you be better off to simply use the latest nightly? It's been built after the 'already merged' comment.</p>

Title: Patching nant 0.91 to use mono 4.0


问:
Android Apk Deployment to Github Releases With Travis
I configured my .travis.yml file to build and deploy my application to github releases. While the application builds successfully and seemingly everything goes smoothly (no error message in travis logs)

I only get a message as a result which indicates deploy is failed. I read somewhere that using travis for free works for public repositories only and mine is a private repository. Can it be the reason or am I missing something?
For completeness:

```<code>#app level gradle

    task printVersionName {
        doLast {
            println android.defaultConfig.versionName
        }
    }
</code>```

Here is the related part of .travis.yml

```<code>before_install:
  - openssl aes-256-cbc -K .. (I would assume this part is correct because when it wasn't I got an error from here)
    script:
      - "./gradlew assembleRelease"
    before_deploy:
      - export APP_VERSION=$(./gradlew :app:printVersionName)
    deploy:
      - provider: releases
        api_key: 000000000000 #Of course here is different
        file: app/build/outputs/apk/release/*
        file_glob: true
        skip_cleanup: true
        overwrite: true
        name: "$APP_VERSION"
        tag_name: "$APP_VERSION"
        on:
          branch: travis
</code>```

Here is the last part of travis log.

```<code>> Task :app:lintVitalRelease
> Task :app:assembleRelease
BUILD SUCCESSFUL in 4m 16s
38 actionable tasks: 38 executed
The command "./gradlew assembleRelease" exited with 0.
before_cache.1
0.01s$ rm -f $HOME/.gradle/caches/modules-2/modules-2.lock
before_cache.2
0.01s$ rm -fr $HOME/.gradle/caches/*/plugin-resolution/
cache.2
store build cache
before_deploy
10.76s$ export APP_VERSION=$(./gradlew :app:printVersionName)
dpl_0
1.80s$ rvm $(travis_internal_ruby) --fuzzy do ruby -S gem install dpl
Successfully installed dpl-1.10.15
Parsing documentation for dpl-1.10.15
Installing ri documentation for dpl-1.10.15
Done installing documentation for dpl after 0 seconds
1 gem installed
invalid option "--name=To honour the JVM settings for this build a new JVM will be forked. Please consider using the daemon: https://docs.gradle.org/4.10.1/userguide/gradle_daemon.html.\nDaemon will be stopped at the end of the build stopping after processing\n\n> Configure project :app\nWARNING: API 'variant.getAssemble()' is obsolete and has been replaced with 'variant.getAssembleProvider()'.\nIt will be removed at the end of 2019.\nFor more information, see https://d.android.com/r/tools/task-configuration-avoidance.\nTo determine what is calling variant.getAssemble(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.\nWARNING: API 'variantOutput.getProcessResources()' is obsolete and has been replaced with 'variantOutput.getProcessResourcesProvider()'.\nIt will be removed at the end of 2019.\nFor more information, see https://d.android.com/r/tools/task-configuration-avoidance.\nTo determine what is calling variantOutput.getProcessResources(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.\nWARNING: API 'variantOutput.getProcessManifest()' is obsolete and has been replaced with 'variantOutput.getProcessManifestProvider()'.\nIt will be removed at the end of 2019.\nFor more information, see https://d.android.com/r/tools/task-configuration-avoidance.\nTo determine what is calling variantOutput.getProcessManifest(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.\nWARNING: API 'variant.getMergeResources()' is obsolete and has been replaced with 'variant.getMergeResourcesProvider()'.\nIt will be removed at the end of 2019.\nFor more information, see https://d.android.com/r/tools/task-configuration-avoidance.\nTo determine what is calling variant.getMergeResources(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.\nWARNING: API 'variant.getMergeAssets()' is obsolete and has been replaced with 'variant.getMergeAssetsProvider()'.\nIt will be removed at the end of 2019.\nFor more information, see https://d.android.com/r/tools/task-configuration-avoidance.\nTo determine what is calling variant.getMergeAssets(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.\nWARNING: API 'variant.getPackageApplication()' is obsolete and has been replaced with 'variant.getPackageApplicationProvider()'.\nIt will be removed at the end of 2019.\nFor more information, see https://d.android.com/r/tools/task-configuration-avoidance.\nTo determine what is calling variant.getPackageApplication(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.\nWARNING: API 'variant.getExternalNativeBuildTasks()' is obsolete and has been replaced with 'variant.getExternalNativeBuildProviders()'.\nIt will be removed at the end of 2019.\nFor more information, see https://d.android.com/r/tools/task-configuration-avoidance.\nTo determine what is calling variant.getExternalNativeBuildTasks(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.\nWARNING: API 'variant.getPreBuild()' is obsolete and has been replaced with 'variant.getPreBuildProvider()'.\nIt will be removed at the end of 2019.\nFor more information, see https://d.android.com/r/tools/task-configuration-avoidance.\nTo determine what is calling variant.getPreBuild(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.\nregisterResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)\nregisterResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)\nregisterResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)\nregisterResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)\nregisterResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)\nregisterResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)\n\n> Task :app:printVersionName\n1.0013\n\nBUILD SUCCESSFUL in 10s\n1 actionable task: 1 executed"
failed to deploy
</code>```

What can be the cause of my error? I looked at the 6039 lines of output in travis but I am %99.99 sure that there is no clear message which indicates the reason for the failure of deployment.

Funny thing is if I change travis.yml's deploy to a simpler one, build succeeds but  deployment is still not done since build is not tagged

Simplified .travis.yml

```<code>deploy:
  - provider: releases
    api_key: 000000000
    file: app/build/outputs/apk/release/*
    file_glob: true
    skip_cleanup: true
    overwrite: true
    name: "$APP_VERSION"
    tag_name: "$APP_VERSION"
    on:
      branch: travis
</code>```

This information may help to examine the problem in a smaller area.

答:
It seems

```<code> name: "$APP_VERSION"
            tag_name: "$APP_VERSION
</code>```

isn't accepted in travis build anymore. I tagged the build with the following.

```<code> before_deploy:

      - git tag "Your custom tag"
</code>```

Body:
I configured my .travis.yml file to build and deploy my application to github releases. While the application builds successfully and seemingly everything goes smoothly (no error message in travis logs)

I only get a message as a result which indicates deploy is failed. I read somewhere that using travis for free works for public repositories only and mine is a private repository. Can it be the reason or am I missing something?
For completeness:

#app level gradle

    task printVersionName {
        doLast {
            println android.defaultConfig.versionName
        }
    }

Here is the related part of .travis.yml

before_install:
  - openssl aes-256-cbc -K .. (I would assume this part is correct because when it wasn't I got an error from here)
    script:
      - "./gradlew assembleRelease"
    before_deploy:
      - export APP_VERSION=$(./gradlew :app:printVersionName)
    deploy:
      - provider: releases
        api_key: 000000000000 #Of course here is different
        file: app/build/outputs/apk/release/*
        file_glob: true
        skip_cleanup: true
        overwrite: true
        name: "$APP_VERSION"
        tag_name: "$APP_VERSION"
        on:
          branch: travis

Here is the last part of travis log.

> Task :app:lintVitalRelease
> Task :app:assembleRelease
BUILD SUCCESSFUL in 4m 16s
38 actionable tasks: 38 executed
The command "./gradlew assembleRelease" exited with 0.
before_cache.1
0.01s$ rm -f $HOME/.gradle/caches/modules-2/modules-2.lock
before_cache.2
0.01s$ rm -fr $HOME/.gradle/caches/*/plugin-resolution/
cache.2
store build cache
before_deploy
10.76s$ export APP_VERSION=$(./gradlew :app:printVersionName)
dpl_0
1.80s$ rvm $(travis_internal_ruby) --fuzzy do ruby -S gem install dpl
Successfully installed dpl-1.10.15
Parsing documentation for dpl-1.10.15
Installing ri documentation for dpl-1.10.15
Done installing documentation for dpl after 0 seconds
1 gem installed
invalid option "--name=To honour the JVM settings for this build a new JVM will be forked. Please consider using the daemon: https://docs.gradle.org/4.10.1/userguide/gradle_daemon.html.\nDaemon will be stopped at the end of the build stopping after processing\n\n> Configure project :app\nWARNING: API 'variant.getAssemble()' is obsolete and has been replaced with 'variant.getAssembleProvider()'.\nIt will be removed at the end of 2019.\nFor more information, see https://d.android.com/r/tools/task-configuration-avoidance.\nTo determine what is calling variant.getAssemble(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.\nWARNING: API 'variantOutput.getProcessResources()' is obsolete and has been replaced with 'variantOutput.getProcessResourcesProvider()'.\nIt will be removed at the end of 2019.\nFor more information, see https://d.android.com/r/tools/task-configuration-avoidance.\nTo determine what is calling variantOutput.getProcessResources(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.\nWARNING: API 'variantOutput.getProcessManifest()' is obsolete and has been replaced with 'variantOutput.getProcessManifestProvider()'.\nIt will be removed at the end of 2019.\nFor more information, see https://d.android.com/r/tools/task-configuration-avoidance.\nTo determine what is calling variantOutput.getProcessManifest(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.\nWARNING: API 'variant.getMergeResources()' is obsolete and has been replaced with 'variant.getMergeResourcesProvider()'.\nIt will be removed at the end of 2019.\nFor more information, see https://d.android.com/r/tools/task-configuration-avoidance.\nTo determine what is calling variant.getMergeResources(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.\nWARNING: API 'variant.getMergeAssets()' is obsolete and has been replaced with 'variant.getMergeAssetsProvider()'.\nIt will be removed at the end of 2019.\nFor more information, see https://d.android.com/r/tools/task-configuration-avoidance.\nTo determine what is calling variant.getMergeAssets(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.\nWARNING: API 'variant.getPackageApplication()' is obsolete and has been replaced with 'variant.getPackageApplicationProvider()'.\nIt will be removed at the end of 2019.\nFor more information, see https://d.android.com/r/tools/task-configuration-avoidance.\nTo determine what is calling variant.getPackageApplication(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.\nWARNING: API 'variant.getExternalNativeBuildTasks()' is obsolete and has been replaced with 'variant.getExternalNativeBuildProviders()'.\nIt will be removed at the end of 2019.\nFor more information, see https://d.android.com/r/tools/task-configuration-avoidance.\nTo determine what is calling variant.getExternalNativeBuildTasks(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.\nWARNING: API 'variant.getPreBuild()' is obsolete and has been replaced with 'variant.getPreBuildProvider()'.\nIt will be removed at the end of 2019.\nFor more information, see https://d.android.com/r/tools/task-configuration-avoidance.\nTo determine what is calling variant.getPreBuild(), use -Pandroid.debug.obsoleteApi=true on the command line to display a stack trace.\nregisterResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)\nregisterResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)\nregisterResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)\nregisterResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)\nregisterResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)\nregisterResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)\n\n> Task :app:printVersionName\n1.0013\n\nBUILD SUCCESSFUL in 10s\n1 actionable task: 1 executed"
failed to deploy

What can be the cause of my error? I looked at the 6039 lines of output in travis but I am %99.99 sure that there is no clear message which indicates the reason for the failure of deployment.

Funny thing is if I change travis.yml's deploy to a simpler one, build succeeds but  deployment is still not done since build is not tagged

Simplified .travis.yml

deploy:
  - provider: releases
    api_key: 000000000
    file: app/build/outputs/apk/release/*
    file_glob: true
    skip_cleanup: true
    overwrite: true
    name: "$APP_VERSION"
    tag_name: "$APP_VERSION"
    on:
      branch: travis

This information may help to examine the problem in a smaller area.

Body:
It seems

 name: "$APP_VERSION"
            tag_name: "$APP_VERSION

isn't accepted in travis build anymore. I tagged the build with the following.

 before_deploy:

      - git tag "Your custom tag"


问:
Power BI - Merge field names as one
I have the following names on my table 'DependantTypes'
-Self
-Spouse
-Child
 I would like to create a bar graph that would display 'self' as a column, then combine "Spouse" and "Child" as one. This way, I'll be able to achieve the total amount for this two
The amount filed exists in the "TtlAmounts"</p>

答:
It sounds like you can create a calculated column that combines non-self types and then use that on your chart instead of DependantTypes.

```<code>SelfOrOther = IF ( [DependantTypes] = "Self", "Self", "Other" )
</code>```

You can, of course, change the name of the column or what you want to return in either case (e.g. "Spouse/Child" instead of "Other").

Title: Power BI - Merge field names as one

Body:
It sounds like you can create a calculated column that combines non-self types and then use that on your chart instead of DependantTypes.

SelfOrOther = IF ( [DependantTypes] = "Self", "Self", "Other" )

You can, of course, change the name of the column or what you want to return in either case (e.g. "Spouse/Child" instead of "Other").


问:
make chartJS labels clickable and get label details
I am new to angular and chartJS and using angular 5. I need to make chart labels clickable and should return its details like index and name. i have tried using getElementAtEvent() but it is returning only empty array onclick on anywhere on the chart. i have gone through many StackOverflow posts but i didn't find anything in angular. i have marked labels in red circle in the below pics. Thanks in advance.

  this.subPerf = new Chart(ctx2, {
      type: 'line',
      data: chartPerfData,
      options: {
        legend: legend,
        responsive: true,
        maintainAspectRatio: false,
        scales: scales,
        onClick: function (e) {
          var element = this.getElementAtEvent(e);
          console.log(element)
        }
      }
    })
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>            <div class=" chart">
                <div class="chartWrapper">
                    <div class="chartAreaWrapper">
                        <div class="chartAreaWrapper2 ">
                            <canvas #subPerf></canvas>
                        </div>
                    </div>
                    <canvas #subPerfAxis height="300" width="0"></canvas>
                </div>
            </div></code>```

答:
The problem with getElementAtEvent is that it returns a single chart element at the event position (a bar, a point etc.). The tick label is not considered to be a chart element, hence you won't get any data.

You can define your onClick function as follows instead.

```<code>onClick: event => {
  let point = Chart.helpers.getRelativePosition(event, subPerf.chart);
  let xIndex = subPerf.scales['x-axis-0'].getValueForPixel(point.x);
  let label = subPerf.data.labels[xIndex];
  console.log(label + ' at index ' + xIndex);
},
</code>```

Please have a look at this StackBlitz that uses Angular 6. I hope the same also works for Angular 5.

Body:
I am new to angular and chartJS and using angular 5. I need to make chart labels clickable and should return its details like index and name. i have tried using getElementAtEvent() but it is returning only empty array onclick on anywhere on the chart. i have gone through many StackOverflow posts but i didn't find anything in angular. i have marked labels in red circle in the below pics. Thanks in advance.

  this.subPerf = new Chart(ctx2, {
      type: 'line',
      data: chartPerfData,
      options: {
        legend: legend,
        responsive: true,
        maintainAspectRatio: false,
        scales: scales,
        onClick: function (e) {
          var element = this.getElementAtEvent(e);
          console.log(element)
        }
      }
    })
  }

                            <canvas #subPerf></canvas>

                    <canvas #subPerfAxis height="300" width="0"></canvas>

Body:
The problem with getElementAtEvent is that it returns a single chart element at the event position (a bar, a point etc.). The tick label is not considered to be a chart element, hence you won't get any data.

You can define your onClick function as follows instead.

onClick: event => {
  let point = Chart.helpers.getRelativePosition(event, subPerf.chart);
  let xIndex = subPerf.scales['x-axis-0'].getValueForPixel(point.x);
  let label = subPerf.data.labels[xIndex];
  console.log(label + ' at index ' + xIndex);
},

Please have a look at this StackBlitz that uses Angular 6. I hope the same also works for Angular 5.


问:
How to convert Python code to executable file
I want to convert Python code to executable file which can run on any machine without Python to be installed.
pygui.py is Python file name

```<code>pyinstaller.exe pygui.py
</code>```

I have try the above code but instead of executable file i got .pyc file

答:
PyInstaller should create a dist folder where your executable file is and all other files that need to be included in your distribution. Check out the docs here.

It could be that PyInstaller failed somehow. You'll have to read all of the lines in the output to get an idea of what went wrong.

Body:
I want to convert Python code to executable file which can run on any machine without Python to be installed.
pygui.py is Python file name

pyinstaller.exe pygui.py

I have try the above code but instead of executable file i got .pyc file


问:
Making a future prediction with trained Tensorflow model (LSTM-RNN)
I am having an issue with how to tell my RNN-LSTM model to generate future values. I think that I need to append values to "inputs" so that X_test extends beyond my test data set and into the future, but how should I go about that, or what should those values be? Go easy on me here, just getting into python/machine learning.

X_test.shape = (193, 60, 5) by the end of this code, by the way, containing "Open, High, Low, Close, Volume" values.

```<code>past_60_days = data_training.tail(60)

df = past_60_days.append(data_test, ignore_index = True)
df = df.drop(['Date', 'Adj Close'], axis = 1)

inputs = scaler.transform(df)

X_test = []
y_test = []

for i in range(60, inputs.shape[0]):
  X_test.append(inputs[i-60:i])
  y_test.append(inputs[i, 0])

X_test, y_test = np.array(X_test), np.array(y_test)

y_pred = regressior.predict(X_test)
</code>```

答:
Your problem is Time Series Analysis and yes, Forecasting the Future Predictions can be done using LSTM (RNN).

For example, you want to Forecast Next Days Value, considering past 60 days Data, important part of code would be

```<code>def multivariate_data(dataset, target, start_index, end_index, history_size,
                      target_size):
  data = []
  labels = []

  start_index = start_index + history_size
  if end_index is None:
    end_index = len(dataset) - target_size

  for i in range(start_index, end_index):
    indices = range(i-history_size, i)
    data.append(dataset[indices])

    labels.append(target[i:i+target_size])

  return np.array(data), np.array(labels)

past_history = 60
future_target = 1

x_train, y_train = multivariate_data(dataset, dataset[:, 0], 0,
                                                   training_data_len, past_history,
                                                   future_target)
x_val_single, y_val_single = multivariate_data(dataset, dataset[:, 0],
                                               training_data_len, None, past_history,
                                               future_target)
</code>```

Please refer this Comprehensive Tensorflow Tutorial which has the complete code for Multi-Variate Data (Multiple Columns like Open, Close, High, Low, etc..), which Predicts a Single Step and Multiple Steps.

If you face any error while implementing it, please reach out and I will be Happy to help you.

Hope this helps. Happy Learning!

Body:
I am having an issue with how to tell my RNN-LSTM model to generate future values. I think that I need to append values to "inputs" so that X_test extends beyond my test data set and into the future, but how should I go about that, or what should those values be? Go easy on me here, just getting into python/machine learning.

X_test.shape = (193, 60, 5) by the end of this code, by the way, containing "Open, High, Low, Close, Volume" values.

past_60_days = data_training.tail(60)

df = past_60_days.append(data_test, ignore_index = True)
df = df.drop(['Date', 'Adj Close'], axis = 1)

inputs = scaler.transform(df)

X_test = []
y_test = []

for i in range(60, inputs.shape[0]):
  X_test.append(inputs[i-60:i])
  y_test.append(inputs[i, 0])

X_test, y_test = np.array(X_test), np.array(y_test)

y_pred = regressior.predict(X_test)

Body:
Your problem is Time Series Analysis and yes, Forecasting the Future Predictions can be done using LSTM (RNN).

For example, you want to Forecast Next Days Value, considering past 60 days Data, important part of code would be

def multivariate_data(dataset, target, start_index, end_index, history_size,
                      target_size):
  data = []
  labels = []

  start_index = start_index + history_size
  if end_index is None:
    end_index = len(dataset) - target_size

  for i in range(start_index, end_index):
    indices = range(i-history_size, i)
    data.append(dataset[indices])

    labels.append(target[i:i+target_size])

  return np.array(data), np.array(labels)

past_history = 60
future_target = 1

x_train, y_train = multivariate_data(dataset, dataset[:, 0], 0,
                                                   training_data_len, past_history,
                                                   future_target)
x_val_single, y_val_single = multivariate_data(dataset, dataset[:, 0],
                                               training_data_len, None, past_history,
                                               future_target)

Please refer this Comprehensive Tensorflow Tutorial which has the complete code for Multi-Variate Data (Multiple Columns like Open, Close, High, Low, etc..), which Predicts a Single Step and Multiple Steps.

If you face any error while implementing it, please reach out and I will be Happy to help you.

Hope this helps. Happy Learning!


问:
Property 'value' does not exist on type 'EventTarget'
I am using TypeScript Version 2 for an Angular 2 component code.

I am getting error "Property 'value' does not exist on type 'EventTarget'" for below code, what could be the solution. Thanks!

e.target.value.match(/\S+/g) || []).length

import { Component, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'text-editor',
  template: `
    <textarea (keyup)="emitWordCount($event)"></textarea>
  `
})
export class TextEditorComponent {
  @Output() countUpdate = new EventEmitter<number>();

  emitWordCount(e: Event) {
    this.countUpdate.emit(
            (e.target.value.match(/\S+/g) || []).length);
  }
}
```

答:
Since I reached two questions searching for my problem in a slightly different way, I am replicating my answer in case you end up here.

In the called function, you can define your type with:

emitWordCount(event: { target: HTMLInputElement }) {
  this.countUpdate.emit(event.target.value);
}
```
<p>This assumes you are only interested in the <code>target</code> property, which is the most common case. If you need to access the other properties of <code>event</code>, a more comprehensive solution involves using the <code>&</code> type intersection operator:</p>
<pre class="lang-js prettyprint-override"><code>event: Event & { target: HTMLInputElement }
</code>```

You can also go more specific and instead of using HTMLInputElement you can use e.g. HTMLTextAreaElement for textareas.

Body:
Since I reached two questions searching for my problem in a slightly different way, I am replicating my answer in case you end up here.

In the called function, you can define your type with:

emitWordCount(event: { target: HTMLInputElement }) {
  this.countUpdate.emit(event.target.value);
}

This assumes you are only interested in the target property, which is the most common case. If you need to access the other properties of event, a more comprehensive solution involves using the & type intersection operator:

event: Event & { target: HTMLInputElement }

You can also go more specific and instead of using HTMLInputElement you can use e.g. HTMLTextAreaElement for textareas.


问:
Count all unique values in list + their Total quantity and Total price per Item cost
I would like to have the following:

List of unique values from another list

Total occurrences of that value in the other list

Total price of the items per Item cost

Play here: https://docs.google.com/spreadsheets/d/11EHm7N4iK8N9oLb8VXrycTwPVHLmoBay4Z6dugaOr7I/edit?usp=sharing

Thank you in advance!

答:
Edit

As requested:

"How about ordering the list in Item Cost from highest to lowest?"

```<code>=QUERY(A1:C9,"select A, sum(B), sum(B)*C where A is not null
               group by A, C order by sum(B)*C desc label sum(B) 'Total Quantity', sum(B)*C 'Item Cost'" )
</code>```

Original answer

Please use the following formula

```<code>=QUERY(A1:C9,"select A, sum(B), sum(B)*C where A is not null
               group by A, C label sum(B) 'Total Quantity', sum(B)*C 'Item Cost'" )</code>```

(adjust ranges to your needs)

Functions used:

QUERY

Body:
Edit

As requested:

"How about ordering the list in Item Cost from highest to lowest?"

=QUERY(A1:C9,"select A, sum(B), sum(B)*C where A is not null
               group by A, C order by sum(B)*C desc label sum(B) 'Total Quantity', sum(B)*C 'Item Cost'" )

Original answer

Please use the following formula

=QUERY(A1:C9,"select A, sum(B), sum(B)*C where A is not null
               group by A, C label sum(B) 'Total Quantity', sum(B)*C 'Item Cost'" )

(adjust ranges to your needs)

Functions used:

QUERY


问:
Check if the range time is 30 minutes before and after a new day
I have date and time stored separately in different column in a table. So I'm trying to check if the current time is 30 minutes early or late from the time in the database.

Let's say I have a list of date and time stored like this:

date         |       time

2020-05-29             00:10:00

2020-05-29             09:00:00

If my current date is 2020-05-28 and time is 23:50:00, the nearest date & time should be the 1st row 2020-05-29, 00:10:00 where the range should be from 2020-05-28, 23:35:00 - 2020-05-29, 00:35:00

I have the code done but it can only detect the range of time on the same date.

```<code>$currentTime = time();
$minTime     = date("H:i", strtotime('-30 minutes', $currentTime));
$maxTime     = date("H:i", strtotime('+30 minutes', $currentTime));

// My query to get the list of date and time on one specific date and populate to $datetimeArr
// $sql = 'SELECT id, date, time FROM table WHERE date = "'.date('Y-m-d').'"';

$datetimeArr = [
    [
        'date' => '2020-05-29',
        'time' => '00:10:00'
    ],
    [
        'date' => '2020-05-29',
        'time' => '09:00:00'
    ],
];

foreach ($datetimeArr as $k => $row) {
    if($row['time'] >= $minTime && $row['time'] <= $maxTime) {
        $nearestDate = $row;
        continue;
    }
}
</code>```

So the issue is, I'm unable to get the range correctly if it is 30 minutes before of after a new day.

答:
Why don't you do this with the mysql query that takes the data? It would be way simpler than doing it with php foreaches.

```<code>SELECT * FROM `TABLE` WHERE `time` > DATE_SUB(NOW(), INTERVAL 30 MINUTE) AND `time` < DATE_ADD(NOW(), INTERVAL 30 MINUTE)
</code>```

Update with a quirky solution for your case:

```<code>SELECT * from TableName where CONCAT(date, ' ', time) between DATE_SUB(NOW(), INTERVAL 30 MINUTE) and DATE_ADD(NOW(), INTERVAL 30 MINUTE)
</code>```

That would concatenate the date and time fields into a single datetime.

Body:
I have date and time stored separately in different column in a table. So I'm trying to check if the current time is 30 minutes early or late from the time in the database.

Let's say I have a list of date and time stored like this:

date         |       time

2020-05-29             00:10:00

2020-05-29             09:00:00

If my current date is 2020-05-28 and time is 23:50:00, the nearest date & time should be the 1st row 2020-05-29, 00:10:00 where the range should be from 2020-05-28, 23:35:00 - 2020-05-29, 00:35:00

I have the code done but it can only detect the range of time on the same date.

$currentTime = time();
$minTime     = date("H:i", strtotime('-30 minutes', $currentTime));
$maxTime     = date("H:i", strtotime('+30 minutes', $currentTime));

// My query to get the list of date and time on one specific date and populate to $datetimeArr
// $sql = 'SELECT id, date, time FROM table WHERE date = "'.date('Y-m-d').'"';

$datetimeArr = [
    [
        'date' => '2020-05-29',
        'time' => '00:10:00'
    ],
    [
        'date' => '2020-05-29',
        'time' => '09:00:00'
    ],
];

foreach ($datetimeArr as $k => $row) {
    if($row['time'] >= $minTime && $row['time'] <= $maxTime) {
        $nearestDate = $row;
        continue;
    }
}

So the issue is, I'm unable to get the range correctly if it is 30 minutes before of after a new day.

Body:
Why don't you do this with the mysql query that takes the data? It would be way simpler than doing it with php foreaches.

SELECT * FROM `TABLE` WHERE `time` > DATE_SUB(NOW(), INTERVAL 30 MINUTE) AND `time` < DATE_ADD(NOW(), INTERVAL 30 MINUTE)

Update with a quirky solution for your case:

SELECT * from TableName where CONCAT(date, ' ', time) between DATE_SUB(NOW(), INTERVAL 30 MINUTE) and DATE_ADD(NOW(), INTERVAL 30 MINUTE)

That would concatenate the date and time fields into a single datetime.


问:
Dynamic Programming: Child running up a staircase
I'm starting to practice Dynamic Programming and I just can't wrap my head around this question:

Question:

A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs.

The solution from the cracking the coding interview book is like this:

"If we thought about all the paths to the nth step, we could just build them off the paths to the three previous steps. We can get up to the nth stop by any of the following:

Going to the (n-1) step and hopping 1 step

Going to the (n-2) step and hopping 2 steps

Going to the (n-3) step and hopping 3 steps"

Therefor to find the solution you just add the number of these path together !

That's what loses me ! Why isn't the answer like this: add number of those paths then add 3 ? Since if you are on step n-1 or n-2 or n-3, there are 3 ways to get the nth step? I understand that if you write down the answers for the first 4 bases cases (assuming that n=0 returns 1) You can see the fibonacci-like pattern. But you may not also see it so it's difficult.

And then they came up with this code:

```<code>public static int countWaysDP(int n, int[] map) {
if (n < 0)
    return 0;
else if (n == 0)
    return 1;
else if (map[n] > -1)
    return map[n];
else {
    map[n] = countWaysDP(n - 1, map) + countWaysDP(n - 2, map) + countWaysDP(n - 3, map);
    return map[n]; }
</code>```

}

So my second question. How does it return 1 when n == 0. Even if I accept that fact, I still can't figure out a way to solve it if I return 0 when n == 1.

Hope this makes sense.

Thank you

答:
You can find the solution on
https://github.com/CrispenGari/Triple-Step-Algorithim/blob/master/main.cpp .</p>

```<code>int count_Ways(int n){
   if(n<0){
      return 0;
   }else if(n==0){
      return 1;
   }else{
      return count_Ways(n-1) +count_Ways(n-2) + count_Ways(n-3);
  }
}
int main(){
   cout<<"Enter number of stairs: ";
   int n;
   cin>>n;
   cout<<"There are "<< count_Ways(n)<<"  possible ways the child can run up
   thestairs."<<endl;
   return 0;
}
</code>```

Body:
I'm starting to practice Dynamic Programming and I just can't wrap my head around this question:

Question:

A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs.

The solution from the cracking the coding interview book is like this:

"If we thought about all the paths to the nth step, we could just build them off the paths to the three previous steps. We can get up to the nth stop by any of the following:

Going to the (n-1) step and hopping 1 step

Going to the (n-2) step and hopping 2 steps

Going to the (n-3) step and hopping 3 steps"

Therefor to find the solution you just add the number of these path together !

That's what loses me ! Why isn't the answer like this: add number of those paths then add 3 ? Since if you are on step n-1 or n-2 or n-3, there are 3 ways to get the nth step? I understand that if you write down the answers for the first 4 bases cases (assuming that n=0 returns 1) You can see the fibonacci-like pattern. But you may not also see it so it's difficult.

And then they came up with this code:

public static int countWaysDP(int n, int[] map) {
if (n < 0)
    return 0;
else if (n == 0)
    return 1;
else if (map[n] > -1)
    return map[n];
else {
    map[n] = countWaysDP(n - 1, map) + countWaysDP(n - 2, map) + countWaysDP(n - 3, map);
    return map[n]; }

}

So my second question. How does it return 1 when n == 0. Even if I accept that fact, I still can't figure out a way to solve it if I return 0 when n == 1.

Hope this makes sense.

Thank you

Body:
You can find the solution on
https://github.com/CrispenGari/Triple-Step-Algorithim/blob/master/main.cpp .

int count_Ways(int n){
   if(n<0){
      return 0;
   }else if(n==0){
      return 1;
   }else{
      return count_Ways(n-1) +count_Ways(n-2) + count_Ways(n-3);
  }
}
int main(){
   cout<<"Enter number of stairs: ";
   int n;
   cin>>n;
   cout<<"There are "<< count_Ways(n)<<"  possible ways the child can run up
   thestairs."<<endl;
   return 0;
}