问:
How can i make this button on React.js with Material UI or other tool?
I want to make a button similiar as this image. I think is composed by a button (left side) i dont know how i can make the right side of it (the arrow figure) and inside the arrow is an image and a Typography i guess. Hope you can help me!!

答:
You can proceed like that, you create your button component and you format it with css, you create the tip of the arrow with a pseudo element.

const App = () => {

  const icon1 = "https://img.icons8.com/ios-filled/50/000000/crane.png"
  const icon2 = "https://img.icons8.com/ios-glyphs/30/000000/interstate-plow-truck.png"

  const ArrowButton = ( props ) => (

      {props.iconRef}

  )

  const handleClick = () => {
    alert('click')
  }

  return (

Arrow Button

      <ArrowButton icon={icon1} iconRef={"pl001"} click={handleClick} />
      <ArrowButton icon={icon2} iconRef={"fr005"} click={handleClick} />

  );
};

    ReactDOM.render(
      <App />, document.getElementById("react")
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: sans-serif;
  text-align: center;
}

.arrow_box {
  width: 200px;
  height: 60px;
  margin: 5px;
  cursor: pointer;
  border-top: 2px solid #c9cdd0;
  border-bottom: 2px solid #c9cdd0;
  border-left: 2px solid #c9cdd0;
  border-radius: 8px 0 0 8px;
  background-color: #ffffff;
  position: relative;
  display: flex;
  align-items: center;
  flex-direction: row;
}

.arrow_box::before {
  content: "";
  position: absolute;
  width: 40px;
  height: 40px;
  top: 50%;
  left: 89.5%;
  background-color: #ffffff;
  border-top: 2px solid #c9cdd0;
  border-right: 2px solid #c9cdd0;
  transform: rotate(45deg);
  margin-top: -21px;
}

.arrow_box:hover, .arrow_box:hover::before{
  background-color: #006eff;
}

.arrow_button {
  position: relative;
  width: 56px;
  height: 56px;
  font-size: 1.5rem;
  color: #ffffff;
  background-color: #00122c;
  border-radius: 6px 0 0 6px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.arrow_button::before {
  content: "\2716";
}

.arrow_content {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  height: 56px;
  width: 144px;
}

.arrow_content_img-box {
  height: 50px;
  width: 50px;
  border-radius: 50%;
  background-color: #ffe8aa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.arrow_content_img {
  height: 35px;
  width: auto;
  filter: invert(75%) sepia(32%) saturate(7078%) brightness(100%)
    hue-rotate(15deg) contrast(100%);
}

.arrow_content_text {
  text-transform: uppercase;
  font-size: 1.5rem;
  font-weight: bold;
}</code>```

```

Body:
You can proceed like that, you create your button component and you format it with css, you create the tip of the arrow with a pseudo element.

const App = () => {

  const icon1 = "https://img.icons8.com/ios-filled/50/000000/crane.png"
  const icon2 = "https://img.icons8.com/ios-glyphs/30/000000/interstate-plow-truck.png"

  const ArrowButton = ( props ) => (
    <div className="arrow_box" onClick={props.click} >
    <div className="arrow_button"></div>
    <div className="arrow_content">
      <div className="arrow_content_img-box">
      <img className="arrow_content_img" alt="icon" src={props.icon} />
      </div>
      <span className="arrow_content_text">{props.iconRef}</span>
    </div>
  </div>
  )

  const handleClick = () => {
    alert('click')
  }

  return (
    <div className="container">
      <h1 className="title__primary">Arrow Button</h1>
      <ArrowButton icon={icon1} iconRef={"pl001"} click={handleClick} />
      <ArrowButton icon={icon2} iconRef={"fr005"} click={handleClick} />
    </div>
  );
};

    ReactDOM.render(
      <App />, document.getElementById("react")
);

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: sans-serif;
  text-align: center;
}

.arrow_box {
  width: 200px;
  height: 60px;
  margin: 5px;
  cursor: pointer;
  border-top: 2px solid #c9cdd0;
  border-bottom: 2px solid #c9cdd0;
  border-left: 2px solid #c9cdd0;
  border-radius: 8px 0 0 8px;
  background-color: #ffffff;
  position: relative;
  display: flex;
  align-items: center;
  flex-direction: row;
}

.arrow_box::before {
  content: "";
  position: absolute;
  width: 40px;
  height: 40px;
  top: 50%;
  left: 89.5%;
  background-color: #ffffff;
  border-top: 2px solid #c9cdd0;
  border-right: 2px solid #c9cdd0;
  transform: rotate(45deg);
  margin-top: -21px;
}

.arrow_box:hover, .arrow_box:hover::before{
  background-color: #006eff;
}

.arrow_button {
  position: relative;
  width: 56px;
  height: 56px;
  font-size: 1.5rem;
  color: #ffffff;
  background-color: #00122c;
  border-radius: 6px 0 0 6px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.arrow_button::before {
  content: "\2716";
}

.arrow_content {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  height: 56px;
  width: 144px;
}

.arrow_content_img-box {
  height: 50px;
  width: 50px;
  border-radius: 50%;
  background-color: #ffe8aa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.arrow_content_img {
  height: 35px;
  width: auto;
  filter: invert(75%) sepia(32%) saturate(7078%) brightness(100%)
    hue-rotate(15deg) contrast(100%);
}

.arrow_content_text {
  text-transform: uppercase;
  font-size: 1.5rem;
  font-weight: bold;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="react"></div>


来源: stackexchange

问:
How to run MSyS2 Mingw64 bash in VsCode terminal along with cmd prompt?
I have my settings set as :

```<code>"terminal.integrated.shell.windows":"C:\\msys64\\usr\\bin\\bash.exe",
    "terminal.integrated.shellArgs.windows": ["-i"],
    "terminal.integrated.env.windows": {
        "PATH": "/mingw64/bin:/usr/local/bin:/usr/bin:/bin:/c/Windows/System32:/c/Windows:/c/Windows/System32/Wbem:/c/Windows/System32/WindowsPowerShell/v1.0/"
    },
</code>```

this works fine, but to change my terminal to Cmd Prompt I have to manually change my setting to :
    "terminal.integrated.shell.windows": "C:\\Windows\\System32\\cmd.exe"

I tried using the shell launcher extension to make switching between terminals easier, but that doesn't work for mingw bash. I use the extension for running Octave gui which works fine. I guess it is because no Path is specified for the shell when launching through this extension. Is there anything else I can do?

```<code>"shellLauncher.shells.windows": [
        {
            "shell": "C:\\Windows\\System32\\cmd.exe",
            "label": "Cmd Prompt"
        },
        {
            "shell": "C:\\Windows\\<sysnative>\\WindowsPowerShell\\v1.0\\powershell.exe",
            "label": "PowerShell"
        },
        {
            "shell": "C:\\msys64\\usr\\bin\\bash.exe",
            "label": "mingw bash"
        },
        {
            "shell": "C:\\Octave\\Octave-5.2.0\\mingw64\\bin\\octave-gui.exe",
            "label": "Octave gui"
        }
    ],
</code>```

答:
```<code>{
            "shell": "C:\\msys64\\usr\\bin\\bash.exe",
            "label": "mingw bash",
            "env" : {"PATH": "/mingw64/bin:/usr/local/bin:/usr/bin:/bin:/c/Windows/System32:/c/Windows:/c/Windows/System32/Wbem:/c/Windows/System32/WindowsPowerShell/v1.0/"
            }
        }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have my settings set as :

"terminal.integrated.shell.windows":"C:\\msys64\\usr\\bin\\bash.exe",
    "terminal.integrated.shellArgs.windows": ["-i"],
    "terminal.integrated.env.windows": {
        "PATH": "/mingw64/bin:/usr/local/bin:/usr/bin:/bin:/c/Windows/System32:/c/Windows:/c/Windows/System32/Wbem:/c/Windows/System32/WindowsPowerShell/v1.0/"
    },

this works fine, but to change my terminal to Cmd Prompt I have to manually change my setting to :
    "terminal.integrated.shell.windows": "C:\\Windows\\System32\\cmd.exe"

I tried using the shell launcher extension to make switching between terminals easier, but that doesn't work for mingw bash. I use the extension for running Octave gui which works fine. I guess it is because no Path is specified for the shell when launching through this extension. Is there anything else I can do?

"shellLauncher.shells.windows": [
        {
            "shell": "C:\\Windows\\System32\\cmd.exe",
            "label": "Cmd Prompt"
        },
        {
            "shell": "C:\\Windows\\<sysnative>\\WindowsPowerShell\\v1.0\\powershell.exe",
            "label": "PowerShell"
        },
        {
            "shell": "C:\\msys64\\usr\\bin\\bash.exe",
            "label": "mingw bash"
        },
        {
            "shell": "C:\\Octave\\Octave-5.2.0\\mingw64\\bin\\octave-gui.exe",
            "label": "Octave gui"
        }
    ],


问:
How to set default value for select field in React js
I am trying to set a default value for a reactjs select option field when the page loads for the first time.

default value should be: Select Marital Status

But It doesn't set I tried many times. Can someone help me?

This is what I tried:

```<code>constructor(props) {
    super(props);
    this.state = {
      marital_status: "Select Marital Status",
    };
  }

  onChange_marital_status = (event) => {
    this.setState({
        marital_status: event.target.value
    });
  };
</code>```

and this is the field:

```<code><InputLabel id="demo-simple-select-outlined-label">
Select Marital Status
</InputLabel>
<Select
defaultValue={this.state.marital_status}
value={this.state.marital_status}
onChange={this.onChange_marital_status.bind(this)}
>
<MenuItem value={0}>Divorced</MenuItem>
<MenuItem value={1}>Married</MenuItem>
<MenuItem value={2}>Single</MenuItem>
</Select>
</code>```

It is showing like below when the page loads (attached screenshot)

答:
You add more option Select Marital Status
The
the default value for this.state.martial_status should be like this</p>

```<code>this.state = {
      marital_status: -1
    };
</code>```

Body:
I am trying to set a default value for a reactjs select option field when the page loads for the first time.

default value should be: Select Marital Status

But It doesn't set I tried many times. Can someone help me?

This is what I tried:

constructor(props) {
    super(props);
    this.state = {
      marital_status: "Select Marital Status",
    };
  }

  onChange_marital_status = (event) => {
    this.setState({
        marital_status: event.target.value
    });
  };

and this is the field:

<InputLabel id="demo-simple-select-outlined-label">
Select Marital Status
</InputLabel>
<Select
defaultValue={this.state.marital_status}
value={this.state.marital_status}
onChange={this.onChange_marital_status.bind(this)}
>
<MenuItem value={0}>Divorced</MenuItem>
<MenuItem value={1}>Married</MenuItem>
<MenuItem value={2}>Single</MenuItem>
</Select>

It is showing like below when the page loads (attached screenshot)

Body:
You add more option Select Marital Status
The
the default value for this.state.martial_status should be like this

this.state = {
      marital_status: -1
    };


问:
Evaluating boolean expression with recursive
I've wrote a program to recursively evaluate boolean expression. But when I run with input "(1|1)", in the second recursion of function S, specifically in line result = result || P() instead of step into P(), it passes the line and returns result. However it works fine with input "(~1|1)". How can I fix this?

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

char *s;
char *f;
bool P(), A();

// The grammar is:
// S -> P||S | P&&S | P
// P -> A | ~A
// A -> (S) | 0 | 1

bool S() {
    bool result = P();
    if (*s == '|') {
        s++;
        result = result || P();
    }
    else
        if (*s == '&') {
            s++;
            result = result && P();
        }
    return result;
}

bool P() {
    if (*s == '~') {
        s++;
        return !A();
    }
    else
    {
        return A();
    }
}

bool A() {
    bool result;
    if (*s == '(') {
        s++;
        result = S();
        if (*s == ')') s++;
        else {
            printf("Syntaktisch falsch! Stelle %ld, Art: Anzahl von '(' und ')' sind nicht gleich\n", s-f);
            exit(1);
        }
    }
    else
        if (*s == '1') {
            s++;
            result = true;
        }
        else
            if (*s == '0') {
                s++;
                result = false;
            }
            else {
                printf("Syntaktisch falsch! Stelle: %ld, Art: Boolscher Ausdruck fehlt\n", s-f); // Hier gibt Fehlermeldung aus, wenn Input String ist nur '~'.
                exit(1);
            }

    return result;
}

int main(int argc, char *argv[])
{
    bool result;
    if (argc != 2) exit(1);
    s = argv[1];
    f = s;
    result = S();
    printf("%d\n", result);
    return 0;
}
</code>```

答:
```<code>result = result || P();
</code>```

P will never will called if result is the true

```<code>result = result && P();
</code>```

P will never will called if result is false

so place the call first to make sure it is called.

```<code>P() || result
P() && result
</code>```

it is called https://en.wikipedia.org/wiki/Short-circuit_evaluation

Body:
I've wrote a program to recursively evaluate boolean expression. But when I run with input "(1|1)", in the second recursion of function S, specifically in line result = result || P() instead of step into P(), it passes the line and returns result. However it works fine with input "(~1|1)". How can I fix this?

#include <stdbool.h>
#include <stdlib.h>

char *s;
char *f;
bool P(), A();

// The grammar is:
// S -> P||S | P&&S | P
// P -> A | ~A
// A -> (S) | 0 | 1

bool S() {
    bool result = P();
    if (*s == '|') {
        s++;
        result = result || P();
    }
    else
        if (*s == '&') {
            s++;
            result = result && P();
        }
    return result;
}

bool P() {
    if (*s == '~') {
        s++;
        return !A();
    }
    else
    {
        return A();
    }
}

bool A() {
    bool result;
    if (*s == '(') {
        s++;
        result = S();
        if (*s == ')') s++;
        else {
            printf("Syntaktisch falsch! Stelle %ld, Art: Anzahl von '(' und ')' sind nicht gleich\n", s-f);
            exit(1);
        }
    }
    else
        if (*s == '1') {
            s++;
            result = true;
        }
        else
            if (*s == '0') {
                s++;
                result = false;
            }
            else {
                printf("Syntaktisch falsch! Stelle: %ld, Art: Boolscher Ausdruck fehlt\n", s-f); // Hier gibt Fehlermeldung aus, wenn Input String ist nur '~'.
                exit(1);
            }

    return result;
}

int main(int argc, char *argv[])
{
    bool result;
    if (argc != 2) exit(1);
    s = argv[1];
    f = s;
    result = S();
    printf("%d\n", result);
    return 0;
}

Body:
result = result || P();

P will never will called if result is the true

result = result && P();

P will never will called if result is false

so place the call first to make sure it is called.

P() || result
P() && result

it is called https://en.wikipedia.org/wiki/Short-circuit_evaluation


问:
How to reduce a string containing the same substring repeated n times to a single instace of the substring
I have strings like 'ageage' or 'feetfeetfeet' or 'cmcmcmcmcm' and would like to reduce these to 'age', 'feet', and 'cm' respectively.

This is an intermediate step in normalization for matching across different data sources of certain classes of data fields that originally also contained numbers. The numeric parts have been removed into a separate string. All the unicode letters have been transliterated to  lowercase ASCII letters with:

public static function transliterate(string $value)
{
    $transliterator = Transliterator::createFromRules(
        ':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: Lower(); :: NFC;',
        Transliterator::FORWARD
    );
    return $transliterator->transliterate($value);
}
```

Also note that pluralization doesn't matter because while the examples I've provided are in English the project is normalizing mainly Turkish strings where such words would always be singular.

I expect this can be done with regex. Though I'm not entirely sure how

答:
You can also use str_split() to convert the string into array and find its unique elements and then again return implode all the unique elements together.

```<code><?php
$str = array_unique(str_split('ageage'));
$result = implode($str);
?>
</code>```

Output

```<code>age
</code>```

Body:
I have strings like 'ageage' or 'feetfeetfeet' or 'cmcmcmcmcm' and would like to reduce these to 'age', 'feet', and 'cm' respectively.

This is an intermediate step in normalization for matching across different data sources of certain classes of data fields that originally also contained numbers. The numeric parts have been removed into a separate string. All the unicode letters have been transliterated to  lowercase ASCII letters with:

public static function transliterate(string $value)
{
    $transliterator = Transliterator::createFromRules(
        ':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: Lower(); :: NFC;',
        Transliterator::FORWARD
    );
    return $transliterator->transliterate($value);
}

Also note that pluralization doesn't matter because while the examples I've provided are in English the project is normalizing mainly Turkish strings where such words would always be singular.

I expect this can be done with regex. Though I'm not entirely sure how

Body:
You can also use str_split() to convert the string into array and find its unique elements and then again return implode all the unique elements together.

<?php
$str = array_unique(str_split('ageage'));
$result = implode($str);
?>

Output

age


问:
Populate username/password in webpage with Powershell
I'm trying to populate the username and password in a Motorola router's login page. Partial HTML of the page is below:

<form name="login" onsubmit="return loginSubmit()" action="/goform/login" method="POST">

    <some divs snipped>

    <input name="loginUsername" class="moto-username-input" onfocus="onFocusUsername()" onblur="onBlurUsername()" type="text" value="Username">

    <some divs snipped>

</form>
```

<p>I'm using PowerShell, and trying to get a handle on the value string. I can do this: </p>

```$ie.Document.IHTMLDocument3_getElementById("moto-username").innerHTML
```

<p>And get this:</p>

<pre class="lang-html prettyprint-override"><code><input name="loginUsername" class="moto-username-input" onfocus="onFocusUsername()" onblur="onBlurUsername()" type="text" value="Username">
</code>```

…but I can't see how to set the variables. Is this due to the nesting of
s?

I've tried various forms, such as:

```<code>$iePPM.Document.IHTMLDocument3_getElementById("moto-username") = "myusername"
</code>```

…but nothing is working.

TIA!

答:
I was able to successfully populate the username and password fields and click the button with:

$ie.Document.IHTMLDocument3_getElementById("loginUsername").value = "admin"
$ie.Document.IHTMLDocument3_getElementById("loginPassword").value = "password"
$Link = $ie.Document.getElementsByTagName("input") | Where-Object {$_.type -eq 'submit'}
$Link.click()

Body:
I'm trying to populate the username and password in a Motorola router's login page. Partial HTML of the page is below:

<form name="login" onsubmit="return loginSubmit()" action="/goform/login" method="POST">

    <some divs snipped>

    <input name="loginUsername" class="moto-username-input" onfocus="onFocusUsername()" onblur="onBlurUsername()" type="text" value="Username">

    <some divs snipped>

</form>

I'm using PowerShell, and trying to get a handle on the value string. I can do this:

$ie.Document.IHTMLDocument3_getElementById("moto-username").innerHTML

And get this:

<input name="loginUsername" class="moto-username-input" onfocus="onFocusUsername()" onblur="onBlurUsername()" type="text" value="Username">

…but I can't see how to set the variables. Is this due to the nesting of
s?

I've tried various forms, such as:

$iePPM.Document.IHTMLDocument3_getElementById("moto-username") = "myusername"

…but nothing is working.

TIA!


问:
What is the optimal way to start python scripts in Windows?
Since opening a console and typing "long\path\interpreter\python.exe" "long\path\project\script.py" or py "long\path\project\script.py" is bothersome, what's the best way so start a script?

The ones I have come up with:

putting the text in a bat script

copying the script to the folder

shortcut to the script

mklink soft and hard to the script from the folder

答:
Windows Search => environment variable => PATH => Add your Python Installation

or while installing python on Windows check the Box for adding Python to Path.

now you can just use python yourscript.py or python3 yourscript.py


问:
HTML.TextAreaFor - removing html tags for display only
In an MVC application I have to use @HTML.TextAreaFor to display some text from a database, the trouble is sometimes that text may have HTML tags within it and I can't see a way to remove those for display only.

Is it possible to do this in the view (maybe with CSS?) without having to strip the tags in the controller first?

EDIT

The data coming from the controller contains html tags which I do not want to remove, I just don't want to display them

Normally I would use @HTML.Raw but it has to work in a @HTML.TextAreaFor control.

答:
There's some nice rich text editors libraries like CK Editor, Quill, or TinyMCE that can display HTML while still maintaining the editor capabilities of being a text editor. All of these libraries have capabilities of being read-only as well if that's necessary.

Example from Quill -


问:
I cannot write c++ arrays now because of "error C4430: missing type specifier - int assumed. Note: C++ does not support default-int"
Hello to all the handsome people who want to save me from my pain,

I am new to c++, and after having done the usual intro stuff like strings, loops, arrays, pointers that w3schools tells you, I decided to write some code. I decided to start with a simple challenge that asks you to write some loops that will sort a few ints from highest to lowest or the other way around, without using the sort function(I was told there was something like this).

And the code is still not working. But this is normal for me as long I can understand why is it not working. (Pls don't answer why it doesn't work, just continue reading)

```<code>#include <iostream>

using namespace std;

int age[4] = { 26, 14, 6, 43};

int num = 4;

int a = 0;

double previous = 0;

int chosen = age[a];

void first() {

    while (result[0] || result[num] == 0){

        for (int i = 0; a != num; i++) {

            chosen = age[a];

            previous = age[i];

            if (chosen < (previous + 0.01) ) {

                chosen = result[a];

                a++;

                previous = age[0];

                i = 0;
            }
        }

    }

}

void last()
{

    for (int i = 0; i < num; i++) {

        cout << result[i] << "\n";

    }
}

int main() {
    first();
    last();

}

</code>```

So I tried to see if my main "if statement" was properly working and I added an already assigned value of result[0] where the variables were introduced.

```<code>int a = 0;

double previous = 0;

result[0] = 20;

int chosen = age[a];
</code>```

And then when I ran the program this errors occurred:

```<code>error C2466: cannot allocate an array of constant size 0
(18,14): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
(18,16): error C2440: 'initializing': cannot convert from 'int' to 'int [0]'
(18,12): message : There are no conversions to array types, although there are conversions to references or pointers to arrays
</code>```

(line 18 is where I assigned result[0])

When I saw this I was like "I guess I am stupid enough and I don't know how to assign arrays", but then I checked if this was the case and I think this is not the case.

And then I understood the first error because I tried changing result[0] to result[4] and it disappeared, but I had no idea what the second error was saying.

So, as one wise man probably said, "If you have coding problems that google cannot answer, go to stack overflow".

And so I did. But the article I found was with code that was equal to my knowledge of Chinese. And if you are still wondering, I do not know a single Chinese word. And I didn't find a better article that could explain how to fix the problem in pure coding for beginners. I just started coding c++ in the pandemic and I don't understand anything other than English yet.

And I would really appreciate if someone could tell me what does this error mean and how is it possible to disappear with his other error friends waiting below him.

答:
You haven't declared result.  C has the idea that using an undeclared variable causes the compiler to assume that the variable is declared extern int.  Some C++ compilers support this for backwards-compatibility, but it's not part of standard C++.

In this case, the compiler seems to support this so it assumes extern int result; since it hasn't seen a declaration for this name.

This results in two diagnostics:

The compiler is warning you about the "default int" declaration and that this is deprecated: "missing type specifier - int assumed"

Then the compiler is telling you that you can't subscript an int (result[0] makes no sense if result is an int): "cannot convert from 'int' to 'int [0]'"

Add an array declaration for result to fix this.

Body:
Hello to all the handsome people who want to save me from my pain,

I am new to c++, and after having done the usual intro stuff like strings, loops, arrays, pointers that w3schools tells you, I decided to write some code. I decided to start with a simple challenge that asks you to write some loops that will sort a few ints from highest to lowest or the other way around, without using the sort function(I was told there was something like this).

And the code is still not working. But this is normal for me as long I can understand why is it not working. (Pls don't answer why it doesn't work, just continue reading)

#include <iostream>

using namespace std;

int age[4] = { 26, 14, 6, 43};

int num = 4;

int a = 0;

double previous = 0;

int chosen = age[a];

void first() {

    while (result[0] || result[num] == 0){

        for (int i = 0; a != num; i++) {

            chosen = age[a];

            previous = age[i];

            if (chosen < (previous + 0.01) ) {

                chosen = result[a];

                a++;

                previous = age[0];

                i = 0;
            }
        }

    }

}

void last()
{

    for (int i = 0; i < num; i++) {

        cout << result[i] << "\n";

    }
}

int main() {
    first();
    last();

}

So I tried to see if my main "if statement" was properly working and I added an already assigned value of result[0] where the variables were introduced.

int a = 0;

double previous = 0;

result[0] = 20;

int chosen = age[a];

And then when I ran the program this errors occurred:

error C2466: cannot allocate an array of constant size 0
(18,14): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
(18,16): error C2440: 'initializing': cannot convert from 'int' to 'int [0]'
(18,12): message : There are no conversions to array types, although there are conversions to references or pointers to arrays

(line 18 is where I assigned result[0])

When I saw this I was like "I guess I am stupid enough and I don't know how to assign arrays", but then I checked if this was the case and I think this is not the case.

And then I understood the first error because I tried changing result[0] to result[4] and it disappeared, but I had no idea what the second error was saying.

So, as one wise man probably said, "If you have coding problems that google cannot answer, go to stack overflow".

And so I did. But the article I found was with code that was equal to my knowledge of Chinese. And if you are still wondering, I do not know a single Chinese word. And I didn't find a better article that could explain how to fix the problem in pure coding for beginners. I just started coding c++ in the pandemic and I don't understand anything other than English yet.

And I would really appreciate if someone could tell me what does this error mean and how is it possible to disappear with his other error friends waiting below him.


问:
Elegant tuple manipulation suggestions
I am working with images and pixel positions represented by tuples. I want to check if pixels are next to each other and came up with a working solution. I'm sure there is a more elegant solution than mine. Here is the function I have:

```<code>def test_neighbors(tup1, tup2):
    neighbors = lambda a, b: [(a + 1, b), (a - 1, b), (a, b + 1), (a, b - 1)]
    list1 = neighbors(tup1[0], tup1[1])
    list2 = neighbors(tup2[0], tup2[1])
    for item in list1:
        if item in list2:
            return True
    return False
</code>```

Again, this code works perfectly, so if this isn't a proper question I am sorry. Thanks in advance for the suggestions!

答:
You can just check the deltas on your coordinate axis</p>

```<code>def test_neighbors(tup1, tup2):
    x_delta = abs(tup1[0] - tup2[0])
    y_delta = abs(tup1[1] - tup2[1])
    return x_delta + y_delta == 1

</code>```

Title: Elegant tuple manipulation suggestions

Body:
I am working with images and pixel positions represented by tuples. I want to check if pixels are next to each other and came up with a working solution. I'm sure there is a more elegant solution than mine. Here is the function I have:

def test_neighbors(tup1, tup2):
    neighbors = lambda a, b: [(a + 1, b), (a - 1, b), (a, b + 1), (a, b - 1)]
    list1 = neighbors(tup1[0], tup1[1])
    list2 = neighbors(tup2[0], tup2[1])
    for item in list1:
        if item in list2:
            return True
    return False

Again, this code works perfectly, so if this isn't a proper question I am sorry. Thanks in advance for the suggestions!

Body:
You can just check the deltas on your coordinate axis

def test_neighbors(tup1, tup2):
    x_delta = abs(tup1[0] - tup2[0])
    y_delta = abs(tup1[1] - tup2[1])
    return x_delta + y_delta == 1


问:
Point in rectangle
What is the fastest way to find if a point is in a rectangle given in this form:

I have two points which are the centers of opposite sides of the rectangle, and a number which is the height of those sides. I hope this is clear.

The rectangle is (probably) not aligned with the axis. I am wondering if there may be a faster algorithm given this data then calculating the four corners, rotating, etc.

An idea I though of but am not sure how to implement (having trouble with the math) was to find the distance from the point to the line traced between the two centers, and if it is  less then half the length of the side of the rectangle and also on the line then it is in the rectangle. I don't know how to explain this better.

Maybe the picture will help explain:

A, B, C are given, as well as the length of side A/B. Basically I thought that if CD is less then half of side A and D is on AB, the point is in the rectangle. But how do I do this?

Another thought: Instead of finding D to see if it is on AB, check if angles ABC and BAC are acute, but I still don't know how to do this.

答:
The square is the intersection of 4 half-spaces.  Each half-space is derived from one side of the rectangle using the two-point line formula.  Depending on the particulars of your problem, perhaps  you can check side-by-side, possibly trivially rejecting at each step.

Is this faster than projection?  I guess that depends on the probability that you'll trivially reject after your first step!

ContentLicense: CC BY-SA 3.0

Title: Point in rectangle


问:
"leave" command and auto-disconnect after X minutes of inactivity
I'm creating a music bot and have ran into two problems.

Firstly, how would I go about implementing a /leave command? When a user who is in the channel decides they no longer want/need the bot in their channel, they simply type /leave and the bot disconnects and wipes the queue?

Secondly, how would I implement a timer which would disconnect the bot after X minutes of inactivity? For example, if the bot reaches the end of the queue and no further songs have been added and no commands executed, say after 15 minutes, the bot would automatically disconnect from the channel and wipe the queue?

答:
Making the bot disconnect from the voice channel

Not knowing how you structured your commands it's hard to give you the exact code. All I can tell you is that I would look to see whether the bot is the user's voice channel and, if so, leave it using the VoiceConnection.disconnect() method. It would look like this:

// Assuming 'message' is the message with the command
let { channelID } = message.member.voice // Get the user's voice channel ID
if (channelID) {
  // Find an existing connection to that channel
  let connection = client.voice.connections.find(conn => conn.channel.id == channelID)
  if (connection) // If you find one, use .disconnect()
    connection.disconnect()
}
```

<hr>

<h2>Creating an inactivity timer</h2>

<p>Again, I can't give you the exact code since I don't know how you set up your music bot. This is the gist of it: when the queue ends you can create a timer using <code>setTimeout()</code>, if the bot is used before the timeout ends, you can cancel it with <code>clearTimeout()</code>.<br>
Here's how I would do it:</p>

<pre class="lang-js prettyprint-override"><code>// Somewhere so that it's in an accessible scope
let timeoutID;

// After the queue has ended
timeoutID = setTimeout(() => {
  // This will run if the timeout reaches its end
  // You can adapt the code above to disconnect from the voice channel
}, 15 * 60 * 1000) // You should use the time in ms

// If the bot is used again
clearTimeout(timeoutID)
timeoutID = undefined
</code>```

Body:
Making the bot disconnect from the voice channel

Not knowing how you structured your commands it's hard to give you the exact code. All I can tell you is that I would look to see whether the bot is the user's voice channel and, if so, leave it using the VoiceConnection.disconnect() method. It would look like this:

// Assuming 'message' is the message with the command
let { channelID } = message.member.voice // Get the user's voice channel ID
if (channelID) {
  // Find an existing connection to that channel
  let connection = client.voice.connections.find(conn => conn.channel.id == channelID)
  if (connection) // If you find one, use .disconnect()
    connection.disconnect()
}

Creating an inactivity timer

Again, I can't give you the exact code since I don't know how you set up your music bot. This is the gist of it: when the queue ends you can create a timer using setTimeout(), if the bot is used before the timeout ends, you can cancel it with clearTimeout().

Here's how I would do it:

// Somewhere so that it's in an accessible scope
let timeoutID;

// After the queue has ended
timeoutID = setTimeout(() => {
  // This will run if the timeout reaches its end
  // You can adapt the code above to disconnect from the voice channel
}, 15 * 60 * 1000) // You should use the time in ms

// If the bot is used again
clearTimeout(timeoutID)
timeoutID = undefined


问:
Flutter http headers
The post request is throwing an error while setting the header map.

Here is my code

```<code>Future<GenericResponse> makePostCall(
  GenericRequest genericRequest) {String URL = "$BASE_URL/api/";

Map data = {
  "name": "name",
  "email": "email",
  "mobile": "mobile",
  "transportationRequired": false,
  "userId": 5,
};

Map userHeader = {"Content-type": "application/json", "Accept": "application/json"};

return _netUtil.post(URL, body: data, headers:userHeader).then((dynamic res) {
  print(res);
  if (res["code"] != 200) throw new Exception(res["message"][0]);
  return GenericResponse.fromJson(res);
});

}
</code>```

but I'm getting this exception with headers.

```<code>══╡ EXCEPTION CAUGHT BY GESTURE ╞═
flutter: The following assertion was thrown while handling a gesture:
flutter: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, String>'
flutter:
flutter: Either the assertion indicates an error in the framework itself, or we should provide substantially
flutter: more information in this error message to help you determine and fix the underlying cause.
flutter: In either case, please report this assertion by filing a bug on GitHub:
flutter:   https://github.com/flutter/flutter/issues/new?template=BUG.md
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0      NetworkUtil.post1 (package:saranam/network/network_util.dart:50:41)
flutter: #1      RestDatasource.bookPandit (package:saranam/network/rest_data_source.dart:204:21)
</code>```

Anybody facing this issue? I didn't find any clue with the above log.

答:
```<code>Future<String> loginApi(String url) async {

 Map<String, String> header = new Map();
 header["content-type"] =  "application/x-www-form-urlencoded";
header["token"] =  "token from device";

try {
   final response = await http.post("$url",body:{
         "email":"test@test.com",
       "password":"3efeyrett"
       },headers: header);

   Map<String,dynamic> output = jsonDecode(response.body);

        if (output["status"] == 200) {

           return "success";
        }else{
        return "error";

  } catch (e) {
    print("catch--------$e");
  return "error";
   }
return "";
</code>```

<p>}</p>

Title: Flutter http headers

Body:
The post request is throwing an error while setting the header map.

Here is my code

Future<GenericResponse> makePostCall(
  GenericRequest genericRequest) {String URL = "$BASE_URL/api/";

Map data = {
  "name": "name",
  "email": "email",
  "mobile": "mobile",
  "transportationRequired": false,
  "userId": 5,
};

Map userHeader = {"Content-type": "application/json", "Accept": "application/json"};

return _netUtil.post(URL, body: data, headers:userHeader).then((dynamic res) {
  print(res);
  if (res["code"] != 200) throw new Exception(res["message"][0]);
  return GenericResponse.fromJson(res);
});

}

but I'm getting this exception with headers.

══╡ EXCEPTION CAUGHT BY GESTURE ╞═
flutter: The following assertion was thrown while handling a gesture:
flutter: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, String>'
flutter:
flutter: Either the assertion indicates an error in the framework itself, or we should provide substantially
flutter: more information in this error message to help you determine and fix the underlying cause.
flutter: In either case, please report this assertion by filing a bug on GitHub:
flutter:   https://github.com/flutter/flutter/issues/new?template=BUG.md
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #0      NetworkUtil.post1 (package:saranam/network/network_util.dart:50:41)
flutter: #1      RestDatasource.bookPandit (package:saranam/network/rest_data_source.dart:204:21)

Anybody facing this issue? I didn't find any clue with the above log.

Body:
Future<String> loginApi(String url) async {

 Map<String, String> header = new Map();
 header["content-type"] =  "application/x-www-form-urlencoded";
header["token"] =  "token from device";

try {
   final response = await http.post("$url",body:{
         "email":"test@test.com",
       "password":"3efeyrett"
       },headers: header);

   Map<String,dynamic> output = jsonDecode(response.body);

        if (output["status"] == 200) {

           return "success";
        }else{
        return "error";

  } catch (e) {
    print("catch--------$e");
  return "error";
   }
return "";

}


问:
Find the lists that share common values
My question is closely related to the following topic.
I have a number of lists and I want to find the lists that share common values. All lists have the same size. The total number of lists is variable and can increase. Minimum number of lists is 2

```<code>a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
c = [9, 10, 11, 1]
</code>```

The expected output is:

```<code>[a, c]
</code>```

Ideally, I also want the fastest method. Thanks in advance,

答: You could cast them to sets and use the intersection() function, if it does return a value, there are some values in common</p>

Title: Find the lists that share common values

Body:
My question is closely related to the following topic.
I have a number of lists and I want to find the lists that share common values. All lists have the same size. The total number of lists is variable and can increase. Minimum number of lists is 2

a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
c = [9, 10, 11, 1]

The expected output is:

[a, c]

Ideally, I also want the fastest method. Thanks in advance,


答:
```<code>lists = []
for i in a:
    if i in b:
        lists.append([a, b])
    if i in c:
        lists.append([a, c])
for i in b:
    if i in c:
        lists.append([b, c])
print(lists)
</code>```

Title: Find the lists that share common values


问:
Missing PC1 column to a PCA rotation
I'm trying to do PCA on the classic Iris data set. This is my code:

```<code>library(tidyverse)

x <- iris[,1:4] %>% as.matrix()
pca <- prcomp(x, scale. = TRUE)
summary(pca)
</code>```

The component rotation has every value for Petal.Length, Petal.Width, etc. So I tried this:

```<code>as.data.frame(pca$rotation) %>% pivot_longer(-1, names_to = "components", values_to = "value")
</code>```

I know there must be a mistake since pca$rotation is a matrix and somehow PC1 is left out. The expected result should be:

```<code>terms          value component
   <chr>          <dbl> <chr>
 1 Sepal.Length  0.521  PC1
 2 Sepal.Width  -0.269  PC1
 3 Petal.Length  0.580  PC1
 4 Petal.Width   0.565  PC1
 5 Sepal.Length -0.377  PC2
 6 Sepal.Width  -0.923  PC2
 7 Petal.Length -0.0245 PC2
 8 Petal.Width  -0.0669 PC2
 9 Sepal.Length  0.720  PC3
10 Sepal.Width  -0.244  PC3
11 Petal.Length -0.142  PC3
12 Petal.Width  -0.634  PC3
13 Sepal.Length  0.261  PC4
14 Sepal.Width  -0.124  PC4
15 Petal.Length -0.801  PC4
16 Petal.Width   0.524  PC4
</code>```

答:
Your -1 specification of which variables to include left out the first column (you may have misread the row names, which are typically ignored by tidyverse machinery, as the first column).  How about

```<code>pca$rotation %>%
    as.data.frame() %>%
    rownames_to_column("term") %>%
    as_tibble() %>%    ## cosmetic
    pivot_longer(starts_with("PC"),
                 names_to = "components",
                 values_to = "value")
</code>```

?

Title: Missing PC1 column to a PCA rotation

Body:
I'm trying to do PCA on the classic Iris data set. This is my code:

library(tidyverse)

x <- iris[,1:4] %>% as.matrix()
pca <- prcomp(x, scale. = TRUE)
summary(pca)

The component rotation has every value for Petal.Length, Petal.Width, etc. So I tried this:

as.data.frame(pca$rotation) %>% pivot_longer(-1, names_to = "components", values_to = "value")

I know there must be a mistake since pca$rotation is a matrix and somehow PC1 is left out. The expected result should be:

terms          value component
   <chr>          <dbl> <chr>
 1 Sepal.Length  0.521  PC1
 2 Sepal.Width  -0.269  PC1
 3 Petal.Length  0.580  PC1
 4 Petal.Width   0.565  PC1
 5 Sepal.Length -0.377  PC2
 6 Sepal.Width  -0.923  PC2
 7 Petal.Length -0.0245 PC2
 8 Petal.Width  -0.0669 PC2
 9 Sepal.Length  0.720  PC3
10 Sepal.Width  -0.244  PC3
11 Petal.Length -0.142  PC3
12 Petal.Width  -0.634  PC3
13 Sepal.Length  0.261  PC4
14 Sepal.Width  -0.124  PC4
15 Petal.Length -0.801  PC4
16 Petal.Width   0.524  PC4

Body:
Your -1 specification of which variables to include left out the first column (you may have misread the row names, which are typically ignored by tidyverse machinery, as the first column).  How about

pca$rotation %>%
    as.data.frame() %>%
    rownames_to_column("term") %>%
    as_tibble() %>%    ## cosmetic
    pivot_longer(starts_with("PC"),
                 names_to = "components",
                 values_to = "value")

?


问:
webpack: when using 2 entry files, both files include the same css - is there a workaround?
I use 2 entry files, startpage.js and subpage.js, and assign them successfully to their HTML files via the HTMLWebpackPlugins chunks parameter.

But since that solution requires to include the CSS files in both the startpage.js and subpage.js, which makes for "double the trouble" (at least during the build process), I decided to create another file, app_head, and put the import 'main.css' statement there. (And I also have a vendor file that should be placed in the header of the HTML, which should happen by adding _head according to the documentation: https://github.com/architgarg/html-webpack-injector - but that does not work either...)

This is the current webpack config (excerpt):

module.exports = {
  entry: {
    app_head: './src/css/main.css',
    vendor_head: './src/scripts/vendor/_all_vendor.js',
    startpage: './src/scripts/startpage.js',
    subpage: './src/scripts/subpage.js',
  },
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, '../public'),
    publicPath: '/'
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: './src/templates/index.ejs',
      chunks: ['app_head', 'vendor_head', 'startpage'],
      chunksConfig: {
        defer: ['startpage']
      },
      excludeChunks: ['subpage'],
      bodyCss: 'is-startpage',
    }),
    new HtmlWebpackPlugin({
      filename: 'publication.html',
      template: './src/templates/publication.ejs',
      chunks: ['subpage'],
      chunksConfig: {
        defer: ['subpage']
      },
      excludeChunks: ['startpage'],
      bodyCss: 'is-subpage',
    }),
    [...]
```

The app_head.css is placed properly in the head section of the HTML, but it also generates a useless app_head.js, which only contains webpack code. Unfortunately, I do not know of any way how to exclude that file without also excluding the CSS.

Is there a better way to separate the CSS generation process without producing overhead or garbage?

答:
The problem is you did not initialized the html-webpack-injector plugin. </p>

<pre class="lang-js prettyprint-override"><code>// import above
const HtmlWebpackInjector = require('html-webpack-injector');

plugins: [
    new HtmlWebpackPlugin(...),
    new HtmlWebpackPlugin(...),
    new HtmlWebpackInjector() // add this in plugins array
</code>```

Body:
I use 2 entry files, startpage.js and subpage.js, and assign them successfully to their HTML files via the HTMLWebpackPlugins chunks parameter.

But since that solution requires to include the CSS files in both the startpage.js and subpage.js, which makes for "double the trouble" (at least during the build process), I decided to create another file, app_head, and put the import 'main.css' statement there. (And I also have a vendor file that should be placed in the header of the HTML, which should happen by adding _head according to the documentation: https://github.com/architgarg/html-webpack-injector - but that does not work either...)

This is the current webpack config (excerpt):

module.exports = {
  entry: {
    app_head: './src/css/main.css',
    vendor_head: './src/scripts/vendor/_all_vendor.js',
    startpage: './src/scripts/startpage.js',
    subpage: './src/scripts/subpage.js',
  },
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, '../public'),
    publicPath: '/'
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: './src/templates/index.ejs',
      chunks: ['app_head', 'vendor_head', 'startpage'],
      chunksConfig: {
        defer: ['startpage']
      },
      excludeChunks: ['subpage'],
      bodyCss: 'is-startpage',
    }),
    new HtmlWebpackPlugin({
      filename: 'publication.html',
      template: './src/templates/publication.ejs',
      chunks: ['subpage'],
      chunksConfig: {
        defer: ['subpage']
      },
      excludeChunks: ['startpage'],
      bodyCss: 'is-subpage',
    }),
    [...]

The app_head.css is placed properly in the head section of the HTML, but it also generates a useless app_head.js, which only contains webpack code. Unfortunately, I do not know of any way how to exclude that file without also excluding the CSS.

Is there a better way to separate the CSS generation process without producing overhead or garbage?

Body:
The problem is you did not initialized the html-webpack-injector plugin.

// import above
const HtmlWebpackInjector = require('html-webpack-injector');

plugins: [
    new HtmlWebpackPlugin(...),
    new HtmlWebpackPlugin(...),
    new HtmlWebpackInjector() // add this in plugins array


问:
Moving from Java types back to MATLAB types
I have a Java array (my_array in the example below) in my MATLAB workspace that I would like to convert back to a MATLAB array.

```<code>whos my_array

  Name       Size            Class

  my_array   20000x1            java.lang.Object[]
</code>```

I could not find how to convert Java types back to MATLAB types in the External Interfaces documentation. The only thing I found is this (the documentation about MATLAB cells) which says that I can use MATLAB cells to do this task.

Using MATLAB cells seems an overkill, specially when I am handling thousands of elements of the same type (in this case, double). Is there any other way of moving Java objects back into MATLAB's native types?

答:
note that you can use the double function in matlab to convert java neumeric types to matlab internal.

ref http://www.kxcad.net/cae_MATLAB/techdoc/matlab_external/f6671.html#bq__508-1

```<code>function rv = convertJava2DToMatlab (javaArray)
    numrows  = max (size (javaArray));
    numcols  = max (size (javaArray(1,:)));
    rv (numrows, numcols) = 1; % preallocating the matrix to optimize
    for i = 1:numrows
        for j = 1:numcols
            if (javaArray(i,j) == 1)
                rv (i,j) = double (javaArray(i,j));
            end
        end
    end
end % end of function convertJava2DtoMatlab
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a Java array (my_array in the example below) in my MATLAB workspace that I would like to convert back to a MATLAB array.

whos my_array

  Name       Size            Class

  my_array   20000x1            java.lang.Object[]

I could not find how to convert Java types back to MATLAB types in the External Interfaces documentation. The only thing I found is this (the documentation about MATLAB cells) which says that I can use MATLAB cells to do this task.

Using MATLAB cells seems an overkill, specially when I am handling thousands of elements of the same type (in this case, double). Is there any other way of moving Java objects back into MATLAB's native types?

Body:
note that you can use the double function in matlab to convert java neumeric types to matlab internal.

ref http://www.kxcad.net/cae_MATLAB/techdoc/matlab_external/f6671.html#bq__508-1

function rv = convertJava2DToMatlab (javaArray)
    numrows  = max (size (javaArray));
    numcols  = max (size (javaArray(1,:)));
    rv (numrows, numcols) = 1; % preallocating the matrix to optimize
    for i = 1:numrows
        for j = 1:numcols
            if (javaArray(i,j) == 1)
                rv (i,j) = double (javaArray(i,j));
            end
        end
    end
end % end of function convertJava2DtoMatlab


问:
how do i check if all rows have similiar data in one column
so I am working on restaurant and I have tables(I am referring to actual table not sql table) and clients in each table, I am having trouble making a query that returns the table_ID of the tables that contains only customers from the one family
for the following table named a :

```<code>costumer_name|| table_ID
-----        ||----
Levi         ||   1
Levi         ||   1
Levi         ||   1
Levi         ||   1
Cohen        ||   2
Cohen        ||   2
shalev       ||   3
shalev       ||   3
shalev       ||   3
shalev       ||   3
jacob        ||   3
</code>```

the output will be only table 1 and 2 because in table 3, there are shalev and jacob.
i have managed to make it work only with a specific table using a condition (which table_ID)
example for tablenumber 1:

```<code>select family_name,table_ID from clients
group by table_id
having table_id = '1' and count(distinct family_name) =1
</code>```

I can do it manually for each table_ID but is it possible to do it in one query?
I am having trouble doing it

答:
I am not sure about the whether it is customer_name/family_name i used customer_name.

```<code>select count(distinct customer_name) as total, table_ID
from clients
group by table_ID
having total = 1
</code>```

Body:
so I am working on restaurant and I have tables(I am referring to actual table not sql table) and clients in each table, I am having trouble making a query that returns the table_ID of the tables that contains only customers from the one family
for the following table named a :

costumer_name|| table_ID
-----        ||----
Levi         ||   1
Levi         ||   1
Levi         ||   1
Levi         ||   1
Cohen        ||   2
Cohen        ||   2
shalev       ||   3
shalev       ||   3
shalev       ||   3
shalev       ||   3
jacob        ||   3

the output will be only table 1 and 2 because in table 3, there are shalev and jacob.
i have managed to make it work only with a specific table using a condition (which table_ID)
example for tablenumber 1:

select family_name,table_ID from clients
group by table_id
having table_id = '1' and count(distinct family_name) =1

I can do it manually for each table_ID but is it possible to do it in one query?
I am having trouble doing it

Body:
I am not sure about the whether it is customer_name/family_name i used customer_name.

select count(distinct customer_name) as total, table_ID
from clients
group by table_ID
having total = 1


问:
visibility hidden on react native not working, to take space even not shown?
I have TouchableOpacity in a space between flex container that I want to take space even not shown,

My code:

```<code><TouchableOpacity
  style={showClear && { visibility: 'hidden' }}
  onPress={() => this.props.clearCompleted()}>
  <Text>Clear Completed</Text>
</TouchableOpacity>
</code>```

display: none works but it doesn't take space, the code above dont work but does in web?

答: Just setting the opacity to 0 was enough for my use case.</p>

Body:
I have TouchableOpacity in a space between flex container that I want to take space even not shown,

My code:

<TouchableOpacity
  style={showClear && { visibility: 'hidden' }}
  onPress={() => this.props.clearCompleted()}>
  <Text>Clear Completed</Text>
</TouchableOpacity>

display: none works but it doesn't take space, the code above dont work but does in web?


问:
Why is the PyGame animation is flickering
So I run the code and it just starts glitching out. I am new to pygame.

Here is the code:

```<code>import pygame

pygame.init()
# Screen (Pixels by Pixels (X and Y (X = right and left Y = up and down)))
screen = pygame.display.set_mode((1000, 1000))
running = True
# Title and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('Icon.png')
pygame.display.set_icon(icon)
# Player Icon/Image
playerimg = pygame.image.load('Player.png')
playerX = 370
playerY = 480

def player(x, y):
    # Blit means Draw
    screen.blit(playerimg, (x, y))

# Game loop (Put all code for pygame in this loop)
while running:
    screen.fill((225, 0, 0))
    pygame.display.update()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # if keystroke is pressed check whether is right or left
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                print("Left arrow is pressed")

            if event.key == pygame.K_RIGHT:
                print("Right key has been pressed")

            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                print("kEYSTROKE RELEASED")

    # RGB (screen.fill) = red green blue

    player(playerX, playerY)
    pygame.display.update()

</code>```

The image is not the glitching one as I was not able to post a video but it is what my code does

答:
The problem is caused by multiple calls to pygame.display.update(). An update of the display at the end of the application loop is sufficient. Multiple calls to pygame.display.update() or pygame.display.flip() cause flickering.

Remove all calls to pygame.display.update() from your code, but call it once at the end of the application loop:

while running:
    screen.fill((225, 0, 0))
    # pygame.display.update() <---- DELETE

    # [...]

    player(playerX, playerY)
    pygame.display.update()
```

If you update the display after screen.fill(), the display will be shown filled with the background color for a short moment. Then the player is drawn (blit) and the display is shown with the player on top of the background.

Body:
So I run the code and it just starts glitching out. I am new to pygame.

Here is the code:

import pygame

pygame.init()
# Screen (Pixels by Pixels (X and Y (X = right and left Y = up and down)))
screen = pygame.display.set_mode((1000, 1000))
running = True
# Title and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('Icon.png')
pygame.display.set_icon(icon)
# Player Icon/Image
playerimg = pygame.image.load('Player.png')
playerX = 370
playerY = 480

def player(x, y):
    # Blit means Draw
    screen.blit(playerimg, (x, y))

# Game loop (Put all code for pygame in this loop)
while running:
    screen.fill((225, 0, 0))
    pygame.display.update()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # if keystroke is pressed check whether is right or left
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                print("Left arrow is pressed")

            if event.key == pygame.K_RIGHT:
                print("Right key has been pressed")

            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                print("kEYSTROKE RELEASED")

    # RGB (screen.fill) = red green blue

    player(playerX, playerY)
    pygame.display.update()

The image is not the glitching one as I was not able to post a video but it is what my code does

Body:
The problem is caused by multiple calls to pygame.display.update(). An update of the display at the end of the application loop is sufficient. Multiple calls to pygame.display.update() or pygame.display.flip() cause flickering.

Remove all calls to pygame.display.update() from your code, but call it once at the end of the application loop:

while running:
    screen.fill((225, 0, 0))
    # pygame.display.update() <---- DELETE

    # [...]

    player(playerX, playerY)
    pygame.display.update()

If you update the display after screen.fill(), the display will be shown filled with the background color for a short moment. Then the player is drawn (blit) and the display is shown with the player on top of the background.


答:
The dot product is your trusty friend for problems like this. That and a bit of Pythagoras should give you everything you need to answer two questions:

Is the projection of AC onto AB within AB?

Is |DC| < height/2?

Work in square distances rather than doing square roots, and don't bother calculating the angle.

Title: Point in rectangle

Body:
What is the fastest way to find if a point is in a rectangle given in this form:

I have two points which are the centers of opposite sides of the rectangle, and a number which is the height of those sides. I hope this is clear.

The rectangle is (probably) not aligned with the axis. I am wondering if there may be a faster algorithm given this data then calculating the four corners, rotating, etc.

An idea I though of but am not sure how to implement (having trouble with the math) was to find the distance from the point to the line traced between the two centers, and if it is  less then half the length of the side of the rectangle and also on the line then it is in the rectangle. I don't know how to explain this better.

Maybe the picture will help explain:

A, B, C are given, as well as the length of side A/B. Basically I thought that if CD is less then half of side A and D is on AB, the point is in the rectangle. But how do I do this?

Another thought: Instead of finding D to see if it is on AB, check if angles ABC and BAC are acute, but I still don't know how to do this.


答:
To simply check if two lists share at least one value you can use...</p>
```<code>a = [1, 2, 3, 4]
b = [9, 10, 11, 1]

if any(a) == any(b):
    print(True)
</code>```

Title: Find the lists that share common values

Body:
To simply check if two lists share at least one value you can use...

a = [1, 2, 3, 4]
b = [9, 10, 11, 1]

if any(a) == any(b):
    print(True)


问:
Upload multiple files to Firebase Storage and when all uploads are finished, subscribe to forkJoin
I'm working on an upload form that need to upload all files and when all uploads are completed, I want to subscribe on them and trigger next action.

My current implementations that doesn't work:

```<code> private uploadImages(): Observable<Subscription> {
const uploadImages$: Subscription [] = [];
this.testResponse.answers.forEach(answer => {
  const filePath = `${answer.selectedImage.name.split('.').slice(0, -1).join('.')}_${new Date().getTime()}`;
  uploadImages$.push(this.testService.uploadPhoto(filePath, answer.selectedImage).subscribe((url: string) => {
      answer.imageUrl = url;
      delete answer.selectedImage;
      delete answer.id;
    }));
});
return forkJoin(uploadImages$);}

  public uploadPhoto(filePath: string, selectedImage?: UploadMetadata): Observable<string | UploadTaskSnapshot> {
return this.storage.upload(filePath, selectedImage).snapshotChanges().pipe(finalize(async () => this.getDownloadUrl(filePath))); }

  public getDownloadUrl(filePath: string): Observable<string> {
return this.storage.ref(filePath).getDownloadURL(); }
</code>```

1.How can "I wait" until the downloadUrl is provided in the pipe(finalize(async()...)?

2.Do you have a better implementation for upload files to Firebase using Angular?

答:
Hopefully this is what you're trying to achieve:</p>

```<code>forkJoin(uploadImages$).pipe(
  map((photos) => {
    return photos.map(p => p.url);
  }),
  switchMap((photoUrls) => {
    return forkJoin(photoUrls.map(photoUrl => this.getDownloadUrl(photoUrl)));
  })
)
.subscribe((downloadUrls) => {
  console.log(downloadUrls);
});
</code>```

Body:
I'm working on an upload form that need to upload all files and when all uploads are completed, I want to subscribe on them and trigger next action.

My current implementations that doesn't work:

 private uploadImages(): Observable<Subscription> {
const uploadImages$: Subscription [] = [];
this.testResponse.answers.forEach(answer => {
  const filePath = `${answer.selectedImage.name.split('.').slice(0, -1).join('.')}_${new Date().getTime()}`;
  uploadImages$.push(this.testService.uploadPhoto(filePath, answer.selectedImage).subscribe((url: string) => {
      answer.imageUrl = url;
      delete answer.selectedImage;
      delete answer.id;
    }));
});
return forkJoin(uploadImages$);}

  public uploadPhoto(filePath: string, selectedImage?: UploadMetadata): Observable<string | UploadTaskSnapshot> {
return this.storage.upload(filePath, selectedImage).snapshotChanges().pipe(finalize(async () => this.getDownloadUrl(filePath))); }

  public getDownloadUrl(filePath: string): Observable<string> {
return this.storage.ref(filePath).getDownloadURL(); }

1.How can "I wait" until the downloadUrl is provided in the pipe(finalize(async()...)?

2.Do you have a better implementation for upload files to Firebase using Angular?

Body:
Hopefully this is what you're trying to achieve:

forkJoin(uploadImages$).pipe(
  map((photos) => {
    return photos.map(p => p.url);
  }),
  switchMap((photoUrls) => {
    return forkJoin(photoUrls.map(photoUrl => this.getDownloadUrl(photoUrl)));
  })
)
.subscribe((downloadUrls) => {
  console.log(downloadUrls);
});


问:
How to use QtMqtt in CMake project?
To use Qt MQTT library in qmake project file (*.pro) QT += mqtt should be added.

What is CMake pandan for that?

答:
I am not very proficient in CMake scripts, but it should be:</p>

```<code>find_package(Qt5Mqtt REQUIRED)
</code>```

Title: How to use QtMqtt in CMake project?

Body:
I am not very proficient in CMake scripts, but it should be:

find_package(Qt5Mqtt REQUIRED)


问:
Copy HTML to clipboard
I use a simple third party library to copy something to clipboard.

The something is always some programming code. In these examples it is HTML and Python codes.

```<code><button id="copy-code-sample-3" data-code-sample-id="3" data-clipboard-text="<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset=utf-8>
  <title></title>
  <link rel="stylesheet" href="stylesheets/style.css"></style>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
</head>
<body>

</body>
</html>" class="code-sample-button">Copy (fail)</button>

<button id="copy-code-sample-1" data-code-sample-id="1" data-clipboard-text="from django import template
from code_sample.models import CodeSample
from django.utils.html import mark_safe
from general.const import CSS, SCRIPTS

register = template.Library()

class CodeSampleManager():
    def __init__(self, code_sample_obj: CodeSample):
        self.code_sample_obj = code_sample_obj

    def prepare_code(self):
        code = self.code_sample_obj.body
        breakpoints = self.code_sample_obj.breakpoints
        breakpoints = breakpoints.split(",")
        breakpoints = [int(bp) for bp in breakpoints]

        tmp = '<pre class="code">'

        lines = code.split("\r\n")
        counter = 1

        for line in lines:
            breakpoint = ""

            if counter in breakpoints:
                breakpoint = 'class="breakpoint"'

            tmp += "<code {}>{}</code>\n".format(breakpoint, line)
            counter += 1
        tmp += "```"
        return tmp" class="code-sample-button">Copy (success)</button>

```

<p>In short: whatever is placed in data-clipboard-text attribute of a button, will be copied to the clipboard.</p>

<p>Please, press a Copy button in the example and insert into a text editor what there is in the clipboard.</p>

<p>Documentation to the third party library: https://milankyncl.github.io/jquery-copy-to-clipboard/</p>

<p>https://jsfiddle.net/Nonverbis/nzx7dvm8/12/</p>

<p>Copy (fail) button copies the contents of its data-clipboard-text but it consists only of whitespace characters and line breaks. </p>

<p>Morever, when I run this at my localhost, I get this error after clicking the fail button:</p>

```Refused to apply style from 'http://localhost:8000/draft/linux/install-os-ubuntu/stylesheets/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
```

The reason seems that HTML is considered to be a real HTML. The browser looks for sources, fails and sends the error. But for my purpose this is just a string.

Could you help me understand why this situation occurs and cope with the problem of copying HTML documents.

答:
The Error

```<code>Refused to apply style from 'http://localhost:8000/draft/linux/install-os-ubuntu/stylesheets/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
</code>```

Is self-explanatory i.e

strict MIME checking is enabled from the plugin so if you remove link and script tag then it will work because of security issue MIME check is good practices.

Title: Copy HTML to clipboard

Body:
I use a simple third party library to copy something to clipboard.

The something is always some programming code. In these examples it is HTML and Python codes.

<button id="copy-code-sample-3" data-code-sample-id="3" data-clipboard-text="<!DOCTYPE html>

  <meta charset=utf-8>
  <title></title>
  <link rel="stylesheet" href="stylesheets/style.css"></style>

" class="code-sample-button">Copy (fail)</button>

<button id="copy-code-sample-1" data-code-sample-id="1" data-clipboard-text="from django import template
from code_sample.models import CodeSample
from django.utils.html import mark_safe
from general.const import CSS, SCRIPTS

register = template.Library()

class CodeSampleManager():
    def __init__(self, code_sample_obj: CodeSample):
        self.code_sample_obj = code_sample_obj

    def prepare_code(self):
        code = self.code_sample_obj.body
        breakpoints = self.code_sample_obj.breakpoints
        breakpoints = breakpoints.split(",")
        breakpoints = [int(bp) for bp in breakpoints]

        tmp = '
'

        lines = code.split("\r\n")
        counter = 1

        for line in lines:
            breakpoint = ""

            if counter in breakpoints:
                breakpoint = 'class="breakpoint"'

            tmp += "{}\n".format(breakpoint, line)
            counter += 1
        tmp += "
"
        return tmp" class="code-sample-button">Copy (success)</button>

In short: whatever is placed in data-clipboard-text attribute of a button, will be copied to the clipboard.

Please, press a Copy button in the example and insert into a text editor what there is in the clipboard.

Documentation to the third party library: https://milankyncl.github.io/jquery-copy-to-clipboard/

https://jsfiddle.net/Nonverbis/nzx7dvm8/12/

Copy (fail) button copies the contents of its data-clipboard-text but it consists only of whitespace characters and line breaks.

Morever, when I run this at my localhost, I get this error after clicking the fail button:

Refused to apply style from 'http://localhost:8000/draft/linux/install-os-ubuntu/stylesheets/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

The reason seems that HTML is considered to be a real HTML. The browser looks for sources, fails and sends the error. But for my purpose this is just a string.

Could you help me understand why this situation occurs and cope with the problem of copying HTML documents.

Body:
The Error

Refused to apply style from 'http://localhost:8000/draft/linux/install-os-ubuntu/stylesheets/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

Is self-explanatory i.e

strict MIME checking is enabled from the plugin so if you remove link and script tag then it will work because of security issue MIME check is good practices.


问:
Rotation won't work in firemonkey android app when clipchidren is active
I'm trying to rotate a TRectangle in Delphi 10.3.3. (FireMonkey App)
the Trectangle has ClipChildren set to true.
The rotation works fine in win32 but when trying in android it has a weird clipped shape.
I tried it with different Objects(TPanel,TImage & ... ) and all results same.
It seems that there is a bug with rotating shapes and clipchildren property in android.
Here is a sample fmx file which works fine in win32 platform but not in ANDROID.

```<code>object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 329
  ClientWidth = 259
  FormFactor.Width = 320
  FormFactor.Height = 480
  FormFactor.Devices = [Desktop]
  DesignerMasterStyle = 0
  object Rectangle1: TRectangle
    ClipChildren = True
    Fill.Color = claChartreuse
    Position.X = 80.000000000000000000
    Position.Y = 104.000000000000000000
    RotationAngle = 35.000000000000000000
    Size.Width = 105.000000000000000000
    Size.Height = 113.000000000000000000
    Size.PlatformDefault = False
  end
end
</code>```

Best regards,

mohsen

答: Yes, it's because on android you use GPU canvas that is a bit different from the default windows canvas. Under GPU canvas rotation and clipchildren simply not work together. I will not say it's a bug, rather than it's the way its work</p>

Body:
I'm trying to rotate a TRectangle in Delphi 10.3.3. (FireMonkey App)
the Trectangle has ClipChildren set to true.
The rotation works fine in win32 but when trying in android it has a weird clipped shape.
I tried it with different Objects(TPanel,TImage & ... ) and all results same.
It seems that there is a bug with rotating shapes and clipchildren property in android.
Here is a sample fmx file which works fine in win32 platform but not in ANDROID.

object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 329
  ClientWidth = 259
  FormFactor.Width = 320
  FormFactor.Height = 480
  FormFactor.Devices = [Desktop]
  DesignerMasterStyle = 0
  object Rectangle1: TRectangle
    ClipChildren = True
    Fill.Color = claChartreuse
    Position.X = 80.000000000000000000
    Position.Y = 104.000000000000000000
    RotationAngle = 35.000000000000000000
    Size.Width = 105.000000000000000000
    Size.Height = 113.000000000000000000
    Size.PlatformDefault = False
  end
end

Best regards,

mohsen


问:
How to avoid creation of duplicates in data.table when using aggregation operations
I am working with a data.table object to make some aggregation operations faster. The real size of my dataset is more than 100 millon rows so I include dummy data for this question. My data.table object is Sample3 (I add dput() version in the final side) which is composed of 5 variables: Date, Id, Value, Week and Day. I want to perform an aggregation task by Id and Week in order to compute Number: number of rows, Sum: total sum of value, Avg: average of value and Diff: difference between Day and maximum Date. I used next code for that task:

```<code>library(data.table)
#Compute
Summary <- Sample3[,.(Number=.N,Sum=sum(Value),Avg=mean(Value),
                                          Diff=Day-max(Date)),by = .(Id,Week)]
</code>```

The computing is correct but there is an issue, Summary has duplicated rows, when the desired output should have only 1 observation according to Id and Week. Also, Sample3 has 11 rows and Summary has the same number of rows. I am not using the := operator. This is the output I get:

```<code>       Id    Week Number       Sum      Avg   Diff
 1: 923996 48-2014      5 21.690579 4.338116 5 days
 2: 923996 48-2014      5 21.690579 4.338116 5 days
 3: 923996 48-2014      5 21.690579 4.338116 5 days
 4: 923996 48-2014      5 21.690579 4.338116 5 days
 5: 923996 48-2014      5 21.690579 4.338116 5 days
 6: 923996 49-2014      3 22.115795 7.371932 2 days
 7: 923996 49-2014      3 22.115795 7.371932 2 days
 8: 923996 49-2014      3 22.115795 7.371932 2 days
 9: 923996 50-2014      1  5.101146 5.101146 3 days
10: 923996 51-2014      2  6.086128 3.043064 1 days
11: 923996 51-2014      2  6.086128 3.043064 1 days
</code>```

The correct output for Summary should look like this:

```<code>     Id    Week Number       Sum      Avg   Diff
1: 923996 48-2014      5 21.690579 4.338116 5 days
2: 923996 49-2014      3 22.115795 7.371932 2 days
3: 923996 50-2014      1  5.101146 5.101146 3 days
4: 923996 51-2014      2  6.086128 3.043064 1 days
</code>```

I do not know why is happening this behavior with this single operation and having duplicated rows in a big dataset could lead to more time in the task of removing them. It is like every row is being updated. The dput() version of Sample3 is next:

```<code>Sample3 <- structure(list(Date = structure(c(16405, 16405, 16406, 16406,
16406, 16407, 16409, 16409, 16415, 16421, 16424), class = "Date"),
    Id = c(923996L, 923996L, 923996L, 923996L, 923996L, 923996L,
    923996L, 923996L, 923996L, 923996L, 923996L), Value = c(5.69822266467209,
    3.11110428877822, 4.74334486914574, 2.17729208527479, 5.96061541361928,
    7.60801375507644, 4.3689394081637, 10.1388420642027, 5.10114642099159,
    0.022944125999933, 6.06318436387287), Week = c("48-2014",
    "48-2014", "48-2014", "48-2014", "48-2014", "49-2014", "49-2014",
    "49-2014", "50-2014", "51-2014", "51-2014"), Day = structure(c(16411,
    16411, 16411, 16411, 16411, 16411, 16411, 16411, 16418, 16425,
    16425), class = "Date")), row.names = c(NA, -11L), class = c("data.table",
"data.frame"), .internal.selfref = <pointer: 0x0000000000311ef0>)
</code>```

I am new in the use of data.table and maybe this is a very easy solution but I have searched other posts without finding a way to amend this situation. Thanks for your help.

答:
The reason you are getting multiple rows is because this code results in a vector rather than a single value:

```<code>Diff=Day-max(Date)
</code>```

All you need is [1] (or min)

```<code>library(data.table)
Sample3[,.(Number=.N,Sum=sum(Value),Avg=mean(Value),
            Diff=Day[1]-max(Date)),by = .(Id,Week)]
#       Id    Week Number       Sum      Avg   Diff
#1: 923996 48-2014      5 21.690579 4.338116 5 days
#2: 923996 49-2014      3 22.115795 7.371932 2 days
#3: 923996 50-2014      1  5.101146 5.101146 3 days
#4: 923996 51-2014      2  6.086128 3.043064 1 days
</code>```

As @Uwe notes there are functions in data.table that may assist in optimizing the speed of your code such as first and last if your data is already arranged by Date.

Body:
I am working with a data.table object to make some aggregation operations faster. The real size of my dataset is more than 100 millon rows so I include dummy data for this question. My data.table object is Sample3 (I add dput() version in the final side) which is composed of 5 variables: Date, Id, Value, Week and Day. I want to perform an aggregation task by Id and Week in order to compute Number: number of rows, Sum: total sum of value, Avg: average of value and Diff: difference between Day and maximum Date. I used next code for that task:

library(data.table)
#Compute
Summary <- Sample3[,.(Number=.N,Sum=sum(Value),Avg=mean(Value),
                                          Diff=Day-max(Date)),by = .(Id,Week)]

The computing is correct but there is an issue, Summary has duplicated rows, when the desired output should have only 1 observation according to Id and Week. Also, Sample3 has 11 rows and Summary has the same number of rows. I am not using the := operator. This is the output I get:

       Id    Week Number       Sum      Avg   Diff
 1: 923996 48-2014      5 21.690579 4.338116 5 days
 2: 923996 48-2014      5 21.690579 4.338116 5 days
 3: 923996 48-2014      5 21.690579 4.338116 5 days
 4: 923996 48-2014      5 21.690579 4.338116 5 days
 5: 923996 48-2014      5 21.690579 4.338116 5 days
 6: 923996 49-2014      3 22.115795 7.371932 2 days
 7: 923996 49-2014      3 22.115795 7.371932 2 days
 8: 923996 49-2014      3 22.115795 7.371932 2 days
 9: 923996 50-2014      1  5.101146 5.101146 3 days
10: 923996 51-2014      2  6.086128 3.043064 1 days
11: 923996 51-2014      2  6.086128 3.043064 1 days

The correct output for Summary should look like this:

     Id    Week Number       Sum      Avg   Diff
1: 923996 48-2014      5 21.690579 4.338116 5 days
2: 923996 49-2014      3 22.115795 7.371932 2 days
3: 923996 50-2014      1  5.101146 5.101146 3 days
4: 923996 51-2014      2  6.086128 3.043064 1 days

I do not know why is happening this behavior with this single operation and having duplicated rows in a big dataset could lead to more time in the task of removing them. It is like every row is being updated. The dput() version of Sample3 is next:

Sample3 <- structure(list(Date = structure(c(16405, 16405, 16406, 16406,
16406, 16407, 16409, 16409, 16415, 16421, 16424), class = "Date"),
    Id = c(923996L, 923996L, 923996L, 923996L, 923996L, 923996L,
    923996L, 923996L, 923996L, 923996L, 923996L), Value = c(5.69822266467209,
    3.11110428877822, 4.74334486914574, 2.17729208527479, 5.96061541361928,
    7.60801375507644, 4.3689394081637, 10.1388420642027, 5.10114642099159,
    0.022944125999933, 6.06318436387287), Week = c("48-2014",
    "48-2014", "48-2014", "48-2014", "48-2014", "49-2014", "49-2014",
    "49-2014", "50-2014", "51-2014", "51-2014"), Day = structure(c(16411,
    16411, 16411, 16411, 16411, 16411, 16411, 16411, 16418, 16425,
    16425), class = "Date")), row.names = c(NA, -11L), class = c("data.table",
"data.frame"), .internal.selfref = <pointer: 0x0000000000311ef0>)

I am new in the use of data.table and maybe this is a very easy solution but I have searched other posts without finding a way to amend this situation. Thanks for your help.

Body:
The reason you are getting multiple rows is because this code results in a vector rather than a single value:

Diff=Day-max(Date)

All you need is [1] (or min)

library(data.table)
Sample3[,.(Number=.N,Sum=sum(Value),Avg=mean(Value),
            Diff=Day[1]-max(Date)),by = .(Id,Week)]
#       Id    Week Number       Sum      Avg   Diff
#1: 923996 48-2014      5 21.690579 4.338116 5 days
#2: 923996 49-2014      3 22.115795 7.371932 2 days
#3: 923996 50-2014      1  5.101146 5.101146 3 days
#4: 923996 51-2014      2  6.086128 3.043064 1 days

As @Uwe notes there are functions in data.table that may assist in optimizing the speed of your code such as first and last if your data is already arranged by Date.


问:
Python Tensorflow - Running model.fit multiple times without reinstantiating the model

Background

I am watching a popular YouTube crash course on machine learning.

At 3:35:50, he mentions that the model is likely overfit, so fits it again with less epochs.

Since he didn't reinstantiate the model, isn't this equivalent to fitting the model with that same data, thereby continuing to overtrain it?

My Question

Assume you have a model created and data ready to go.

You run:

```<code>model.fit(train_images, train_labels, epochs=10)
model.fit(train_images, train_labels, epochs=8)
</code>```

Is this equivalent to running:

```<code>model.fit(train_images, train_labels, epochs=18)
</code>```

Or:

```<code>model.fit(train_images, train_labels, epochs=8)
</code>```

If previously fitted data is overwritten, why does running model.fit a second time begin with the accuracy of the previous model?

In multiple other questions regarding saving and training models, the accepted solutions are to load the previously trained model, and run model.fit again.

If this will overwrite the pre-existing weights, doesn't that defeat the purpose of saving the model in the first place? Wouldn't training the model for the first time on the new data be equivalent?

What is the appropriate way to train a model across multiple, similar datasets while retaining accuracy across all of the data?

答:
When you run the with

```<code>model.fit(train_images, train_labels, epochs=10)
model.fit(train_images, train_labels, epochs=8)
</code>```

as you mentioned the model are not reinitialized so the model object would have the values of the previous train in it and hence continue.

Just realized that the model is being run in colab.

then when he run

```<code>model.fit(train_images, train_labels, epochs=10)
</code>```

he is training it for the first time and finds that it is overfitting,
then he aims to reduce the epoch to 8 and try it.

```<code>model.fit(train_images, train_labels, epochs=8)
</code>```

What he wanted to do was run for 8 epochs but since it was in the colab and the model.fit() from the first run was still in the object it was acting as if it's running for 18 epochs and over fitted

As to how to avoid over fitting, one of the methods is to use EarlyStopping and ModelCheckpoint .

Body:
Background

I am watching a popular YouTube crash course on machine learning.

At 3:35:50, he mentions that the model is likely overfit, so fits it again with less epochs.

Since he didn't reinstantiate the model, isn't this equivalent to fitting the model with that same data, thereby continuing to overtrain it?

My Question

Assume you have a model created and data ready to go.

You run:

model.fit(train_images, train_labels, epochs=10)
model.fit(train_images, train_labels, epochs=8)

Is this equivalent to running:

model.fit(train_images, train_labels, epochs=18)

Or:

model.fit(train_images, train_labels, epochs=8)

If previously fitted data is overwritten, why does running model.fit a second time begin with the accuracy of the previous model?

In multiple other questions regarding saving and training models, the accepted solutions are to load the previously trained model, and run model.fit again.

If this will overwrite the pre-existing weights, doesn't that defeat the purpose of saving the model in the first place? Wouldn't training the model for the first time on the new data be equivalent?

What is the appropriate way to train a model across multiple, similar datasets while retaining accuracy across all of the data?

Body:
When you run the with

model.fit(train_images, train_labels, epochs=10)
model.fit(train_images, train_labels, epochs=8)

as you mentioned the model are not reinitialized so the model object would have the values of the previous train in it and hence continue.

Just realized that the model is being run in colab.

then when he run

model.fit(train_images, train_labels, epochs=10)

he is training it for the first time and finds that it is overfitting,
then he aims to reduce the epoch to 8 and try it.

model.fit(train_images, train_labels, epochs=8)

What he wanted to do was run for 8 epochs but since it was in the colab and the model.fit() from the first run was still in the object it was acting as if it's running for 18 epochs and over fitted

As to how to avoid over fitting, one of the methods is to use EarlyStopping and ModelCheckpoint .


问:
Getting junk values within response from firebase APIs while calling getIdToken

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
// import { User } from './user.model.ts'; // optional

import { auth } from 'firebase/app';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';

import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { User } from './user';
import { HttpClient } from '@angular/common/http';
import { UserService } from './user.service';

@Injectable({ providedIn: 'root' })
export class AuthService {

  user$: Observable<User>;

  constructor(
    private userServe: UserService,
    private afAuth: AngularFireAuth,
    private afs: AngularFirestore,
    private router: Router
  ) {

    this.user$ = this.afAuth.authState.pipe(
      switchMap(user => {
        // Logged in
        if (user) {
          this.router.navigate(["user_home"]);
          return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
        } else {
          // Logged out
          return of(null);
        }
      })
    )
  }
  async googleSignin() {
    const provider = new auth.GoogleAuthProvider();
    const credential = await this.afAuth.signInWithPopup(provider);

   const token =(await this.afAuth.currentUser).getIdToken();

   console.log(token);
    // localStorage.setItem('token',JSON.stringify(token));
    // var token = credential.accessToken;
    // alert(JSON.stringify(token));
    return this.updateUserData(credential.user);
  }

  private updateUserData(user) {
    // Sets user data to firestore on login
    const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.uid}`);

    const data = {
      uid: user.uid,
      email: user.email,
      displayName: user.displayName,
      photoURL: user.photoURL,
      username: user.displayName,
      password: '',
      phone: 0,
      state: '',
      district: '',
      city: '',
      pincode: 0,
    }
    this.userServe.postUserData(data)
      .subscribe(data => {
        console.log("Account added");
      }, error => {
        console.log(error);
      }
      );
    return userRef.set(data, { merge: true })

  }

  async signOut() {
    await this.afAuth.signOut();
    // this.router.navigate(['login']);
  }

}```

I was doing a firebase authentication through google , while calling an api from service
getting values like below format,
  const token =(await this.afAuth.currentUser).getIdToken();

console.log(token);
==> "D {a: 0, i: undefined, c: D, b: null, f: null, …}  " getting an extra D , So not able to extract the token alone from this structure, Attaching the service calls above. Thanks in advance,

Please let me know anything more needed :)

答:
This worked for me

const token =(await this.afAuth.currentUser).getIdToken().then(function(idToken){
       localStorage.setItem('token',idToken);
      console.log(idToken) });

Body:
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
// import { User } from './user.model.ts'; // optional

import { auth } from 'firebase/app';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';

import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { User } from './user';
import { HttpClient } from '@angular/common/http';
import { UserService } from './user.service';

@Injectable({ providedIn: 'root' })
export class AuthService {

  user$: Observable<User>;

  constructor(
    private userServe: UserService,
    private afAuth: AngularFireAuth,
    private afs: AngularFirestore,
    private router: Router
  ) {

    this.user$ = this.afAuth.authState.pipe(
      switchMap(user => {
        // Logged in
        if (user) {
          this.router.navigate(["user_home"]);
          return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
        } else {
          // Logged out
          return of(null);
        }
      })
    )
  }
  async googleSignin() {
    const provider = new auth.GoogleAuthProvider();
    const credential = await this.afAuth.signInWithPopup(provider);

   const token =(await this.afAuth.currentUser).getIdToken();

   console.log(token);
    // localStorage.setItem('token',JSON.stringify(token));
    // var token = credential.accessToken;
    // alert(JSON.stringify(token));
    return this.updateUserData(credential.user);
  }

  private updateUserData(user) {
    // Sets user data to firestore on login
    const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.uid}`);

    const data = {
      uid: user.uid,
      email: user.email,
      displayName: user.displayName,
      photoURL: user.photoURL,
      username: user.displayName,
      password: '',
      phone: 0,
      state: '',
      district: '',
      city: '',
      pincode: 0,
    }
    this.userServe.postUserData(data)
      .subscribe(data => {
        console.log("Account added");
      }, error => {
        console.log(error);
      }
      );
    return userRef.set(data, { merge: true })

  }

  async signOut() {
    await this.afAuth.signOut();
    // this.router.navigate(['login']);
  }

}

I was doing a firebase authentication through google , while calling an api from service
getting values like below format,
  const token =(await this.afAuth.currentUser).getIdToken();

console.log(token);
==> "D {a: 0, i: undefined, c: D, b: null, f: null, …}  " getting an extra D , So not able to extract the token alone from this structure, Attaching the service calls above. Thanks in advance,

Please let me know anything more needed :)


问:
Python card printer
I don't understand why the cards are not getting printed the second time, even though the string "Player's Hand" is getting printed again. Can someone help me to find the solution to printing them again?
Sorry for the previous errors, I just corrected them all.</p>

```<code>def printCards(playerHand):
    a = playerHand
    print("Player's Hand")
    while a[0]:
        for i in range(0,len(a)):
            card = a[i]
            print(card[:11] + " ", sep = " ", end = "")
            a[i] = card[12:]
        print("")
    print("*****************************")
    return

playerHand = [""" _________
|         |
| A       |
|         |
|    ♣    |
|         |
|       A |
|_________|""",
""" _________
|         |
| 2       |
|         |
|    ♣    |
|         |
|       2 |
|_________|""",
""" _________
|         |
| 3       |
|         |
|    ♣    |
|         |
|       3 |
|_________|"""]

printCards(playerHand)
print(" -----")
#Why are the cards not getting printed second time with the command below?
printCards(playerHand)
</code>```

答:
Your problem can be solved in a much more elegant way if you split each card into lines and print the lines with the same numbers at once:</p>

```<code>def printCards(playerHand):
    # Prepare the cards for printing
    lines = [card.split("\n") for card in playerHand]
    # Print one line at a time
    for line in zip(*lines):
        print(" ".join(line))
</code>```

Title: Python card printer

Body:
I don't understand why the cards are not getting printed the second time, even though the string "Player's Hand" is getting printed again. Can someone help me to find the solution to printing them again?
Sorry for the previous errors, I just corrected them all.

def printCards(playerHand):
    a = playerHand
    print("Player's Hand")
    while a[0]:
        for i in range(0,len(a)):
            card = a[i]
            print(card[:11] + " ", sep = " ", end = "")
            a[i] = card[12:]
        print("")
    print("*****************************")
    return

playerHand = [""" _________
|         |
| A       |
|         |
|    ♣    |
|         |
|       A |
|_________|""",
""" _________
|         |
| 2       |
|         |
|    ♣    |
|         |
|       2 |
|_________|""",
""" _________
|         |
| 3       |
|         |
|    ♣    |
|         |
|       3 |
|_________|"""]

printCards(playerHand)
print(" -----")
#Why are the cards not getting printed second time with the command below?
printCards(playerHand)

Body:
Your problem can be solved in a much more elegant way if you split each card into lines and print the lines with the same numbers at once:

def printCards(playerHand):
    # Prepare the cards for printing
    lines = [card.split("\n") for card in playerHand]
    # Print one line at a time
    for line in zip(*lines):
        print(" ".join(line))


问:
'import matplotlib' gives 'module not found error'
pip install matplotlib
says requirement already satisfied.
I'm on a Mac and have looked through tons of answers online but can't get matplotlib to work. I'd appreciate any suggestions.

答:
maybe your Interpreter is set to python not python3 ?

if you using pip3 it'S working ?


问:
how to deploy web.config modifications in a Sharepoint web application?
I have a website in Sharepoint 2007. We use a wsp to deploy our projects. We can deploy dlls, usercontrols, features, but i don't know how to include new lines in the web.config.

Which would be a possible way to make changes in web.config?

Another thing, how can I include resources (resx) in the wsp?

答:
there is a very easy way to add safe control entries via Solution. The following snippet added to the manifest.xml will make the relevant modifications to the web.config file.  To set other values you should do it in a feature receiver using the SPWebConfigModification class.</p>

```<code><Assemblies>
  <Assembly ...>
     <SafeControl Namespace=".." Assembly="..." Type="..." Safe="True" />
  </Assembly>
  ....
</Assemblies>
</code>```

OwnerDisplayName: netadictos

Body:
there is a very easy way to add safe control entries via Solution. The following snippet added to the manifest.xml will make the relevant modifications to the web.config file.  To set other values you should do it in a feature receiver using the SPWebConfigModification class.

<Assemblies>
  <Assembly ...>
     <SafeControl Namespace=".." Assembly="..." Type="..." Safe="True" />
  </Assembly>
  ....
</Assemblies>

OwnerDisplayName: Jason


问:
Zend bootstrap, including javascript files for certain pages only
I'm loading javascript files in the bootstrap as usual, but there's a file that I want to have included only if it's a page that has a form

```<code>->appendFile('http://myurl.com/js/formscript.js');
</code>```

Is there a way to detect the page being loaded, from the bootstrap so I can decide whether or not to include this file?

I thought about passing a variable from the Form to the view, and then checking for that variable in the bootstrap, but it's not working.

This would be in my form

```<code>$layout = new Zend_Layout();
$view = $layout->getView();
$view->formscript = true;
</code>```

and this would be in my bootstrap

```<code>if ($view->formscript)
</code>```

but var_dump($view->formscript) give me null, so any other ideas to activate js files only in specific conditions?

答:
It is possible, but you do not need your bootstrap. You can just access the variable from your layout:

```<code>//form
$view = Zend_Layout::getMvcInstance()->getView();
$view->formscript = TRUE;

//layout
if($this->formscript)
{
  $this->headScript()->appendFile('http://myurl.com/js/formscript.js');
}
echo $this->headScript();
</code>```

Do not use getView() in your form as it will return the view object for the form, not for your application. This has tripped me up more than a couple of times >.>

Body:
I'm loading javascript files in the bootstrap as usual, but there's a file that I want to have included only if it's a page that has a form

->appendFile('http://myurl.com/js/formscript.js');

Is there a way to detect the page being loaded, from the bootstrap so I can decide whether or not to include this file?

I thought about passing a variable from the Form to the view, and then checking for that variable in the bootstrap, but it's not working.

This would be in my form

$layout = new Zend_Layout();
$view = $layout->getView();
$view->formscript = true;

and this would be in my bootstrap

if ($view->formscript)

but var_dump($view->formscript) give me null, so any other ideas to activate js files only in specific conditions?

Body:
It is possible, but you do not need your bootstrap. You can just access the variable from your layout:

//form
$view = Zend_Layout::getMvcInstance()->getView();
$view->formscript = TRUE;

//layout
if($this->formscript)
{
  $this->headScript()->appendFile('http://myurl.com/js/formscript.js');
}
echo $this->headScript();

Do not use getView() in your form as it will return the view object for the form, not for your application. This has tripped me up more than a couple of times >.>