问:
Extracting filesnames in bash with regex
Can please someone help me to set up a regular expression.

I have a large LaTeX3 TeXDoc file.  LaTeX3 TeXDoc defines the macro \TestFiles{}, which should be used, to list the names of files, which itself should be used as an unit tests.  You can name more than one file between the braces.  So \TestFiles{foo-bar} and \TestFiles{foo-bar, bar+baz,foo_bar_baz} are syntactical correct use cases for this macro.

I would like to write a bash script, to extract all the uni test files, named in the \TestFiles{} macros, to compile them with pdflatex and check, if pdflatex will be able to produce an output file successfully.

I have something like this in my script:

function get_filenames () {
  ## This regex works but is not sensible enough
  # regex='\\TestFiles{(.*)}'
  ## This works also, but is again not precise enough
  regex='\\TestFiles{([0-9a-zA-Z+-_, ]*)}'
  ## This should give more than one matching group
  ## (separated by ", " or ","), but this regex doesn't
  ## work.  I have no idea why or how to modify, to get
  ## it working

  while read -r line ; do
    if [[ $line =~ $regex ]] ; then
      i=1
        while [ $i -le 3 ]; do
          echo "Match $i: \"${BASH_REMATCH[$i]}\""
          i=$(( i + 1 ))
        done
      echo
    fi
  done < mystyle.dtx
}
```
<p>Here is an excerpt of the DTX file</p>
<pre class="lang-latex prettyprint-override"><code>\TestFiles{foo-bar}

\TestFiles{foo-bar, bar+baz,foo_bar_baz}
</code>```

(You can store this as mystyle.dtx, in order to reproduce the next example.)

Using the above noted examples, my script gives me the following results:

get_filenames
Match 1: "foo-bar"
Match 2: ""
Match 3: ""

Match 1: "foo-bar, bar+baz,foo_bar_baz"
Match 2: ""
Match 3: ""

```
<p>I wasn't able, to modify my <code>regex</code> expression, to split the content of the last <code>\TestFiles{foo-bar, bar+baz,foo_bar_baz}</code> example into three matching results.</p>
<p>I tried a regular expression like this <code>regex='\\TestFiles{([[:alnum:]+-_]*)[,]+[ ]*}'</code>.  I thought the <code>[:alnum:]+-_]*</code> would match the filenames.  As far as I understand regular expressions, the <code>(...)</code> should form a group, that should be listed afterwards in the bash array <code>BASH_REMATCH[$i]</code>.</p>
<p>The part <code>[,]+</code> should reflect that every file name must be separated by at least one comma.  Between the filenames there might be some white space, so something like <code>[[:space:]]*</code> or at least <code>[ ]*</code> should represent this.  The quantifier <code>*</code> means any repetition, ranging from 0 to ..., while <code>+</code> should at least appear one or more times.</p>
<p>But that regular expression did not work at all, if had no matching results.</p>
<p>How must <code>regex</code> be defined, to store each filenames as a matching group?  I am searching for the correct regular expression, to get this result:</p>
<pre class="lang-sh prettyprint-override"><code>get_filenames
Match 1: "foo-bar"
Match 2: ""
Match 3: ""

Match 1: "foo-bar"
Match 2: "bar+baz"
Match 3: "foo_bar_baz"

</code>```

EDIT: in my real world files, there may be (and are) more than tree test files.

Thanks in advance.

答:
Use set with IFS to split each line into new positional parameters. Assign $@ to an array so that elements can be accessed by index. Trying this with $@ directly results in a bad substitution error.

get-filenames.sh

#!/usr/bin/env bash

get_filenames() {
    local IFS=' {},'
    declare -a names

    while read -r line; do
        set -- $line
        names=($@)
        test "${names[0]}" == '\TestFiles' && {
            for i in {1..3}; do
                printf "Match %i: \"%s\"\n" $i ${names[$i]}
            done
        }
        echo
    done < 'mystyle.dtx'
}

get_filenames
```
<p>mystyle.dtx</p>
```
\TestFiles{foo-bar}
\TestFiles{foo-bar, bar+baz,foo_bar_baz}
```
<p>output</p>
```
Match 1: "foo-bar"
Match 2: ""
Match 3: ""

Match 1: "foo-bar"
Match 2: "bar+baz"
Match 3: "foo_bar_baz"
```

Body:
Can please someone help me to set up a regular expression.

I have a large LaTeX3 TeXDoc file.  LaTeX3 TeXDoc defines the macro \TestFiles{}, which should be used, to list the names of files, which itself should be used as an unit tests.  You can name more than one file between the braces.  So \TestFiles{foo-bar} and \TestFiles{foo-bar, bar+baz,foo_bar_baz} are syntactical correct use cases for this macro.

I would like to write a bash script, to extract all the uni test files, named in the \TestFiles{} macros, to compile them with pdflatex and check, if pdflatex will be able to produce an output file successfully.

I have something like this in my script:

function get_filenames () {
  ## This regex works but is not sensible enough
  # regex='\\TestFiles{(.*)}'
  ## This works also, but is again not precise enough
  regex='\\TestFiles{([0-9a-zA-Z+-_, ]*)}'
  ## This should give more than one matching group
  ## (separated by ", " or ","), but this regex doesn't
  ## work.  I have no idea why or how to modify, to get
  ## it working

  while read -r line ; do
    if [[ $line =~ $regex ]] ; then
      i=1
        while [ $i -le 3 ]; do
          echo "Match $i: \"${BASH_REMATCH[$i]}\""
          i=$(( i + 1 ))
        done
      echo
    fi
  done < mystyle.dtx
}

Here is an excerpt of the DTX file

\TestFiles{foo-bar}

\TestFiles{foo-bar, bar+baz,foo_bar_baz}

(You can store this as mystyle.dtx, in order to reproduce the next example.)

Using the above noted examples, my script gives me the following results:

get_filenames
Match 1: "foo-bar"
Match 2: ""
Match 3: ""

Match 1: "foo-bar, bar+baz,foo_bar_baz"
Match 2: ""
Match 3: ""

I wasn't able, to modify my regex expression, to split the content of the last \TestFiles{foo-bar, bar+baz,foo_bar_baz} example into three matching results.

I tried a regular expression like this regex='\\TestFiles{([[:alnum:]+-_]*)[,]+[ ]*}'.  I thought the [:alnum:]+-_]* would match the filenames.  As far as I understand regular expressions, the (...) should form a group, that should be listed afterwards in the bash array BASH_REMATCH[$i].

The part [,]+ should reflect that every file name must be separated by at least one comma.  Between the filenames there might be some white space, so something like [[:space:]]* or at least [ ]* should represent this.  The quantifier * means any repetition, ranging from 0 to ..., while + should at least appear one or more times.

But that regular expression did not work at all, if had no matching results.

How must regex be defined, to store each filenames as a matching group?  I am searching for the correct regular expression, to get this result:

get_filenames
Match 1: "foo-bar"
Match 2: ""
Match 3: ""

Match 1: "foo-bar"
Match 2: "bar+baz"
Match 3: "foo_bar_baz"

EDIT: in my real world files, there may be (and are) more than tree test files.

Thanks in advance.

Body:
Use set with IFS to split each line into new positional parameters. Assign $@ to an array so that elements can be accessed by index. Trying this with $@ directly results in a bad substitution error.

get-filenames.sh

#!/usr/bin/env bash

get_filenames() {
    local IFS=' {},'
    declare -a names

    while read -r line; do
        set -- $line
        names=($@)
        test "${names[0]}" == '\TestFiles' && {
            for i in {1..3}; do
                printf "Match %i: \"%s\"\n" $i ${names[$i]}
            done
        }
        echo
    done < 'mystyle.dtx'
}

get_filenames

mystyle.dtx

\TestFiles{foo-bar}
\TestFiles{foo-bar, bar+baz,foo_bar_baz}

output

Match 1: "foo-bar"
Match 2: ""
Match 3: ""

Match 1: "foo-bar"
Match 2: "bar+baz"
Match 3: "foo_bar_baz"


来源: stackexchange

问:
How to include short signals in a Long only strategy on tradingview?
How to include short signals in a Long only strategy on tradingview?

I have a Tradingview strategy which gives only long/Buy signals as per matching conditions. I also need it to generate short signals when the conditions are suitable. How do I do it?

```<code>strategy("Varun scalp", shorttitle="Varun scalp", overlay=true)
timeframe = input('3')
box = input('Traditional')
boxsize = input(5, type=float)
reversal = input(1)
pnf = pointfigure(tickerid, 'close', box, boxsize, reversal)
pnf_open= security(pnf, timeframe , open)
pnf_close= security(pnf, timeframe , close)
p1 = plot(pnf_open, title="pnf_open", color=green)
p2 = plot(pnf_close,  title="pnf_close",color=maroon)
base = pnf_close> pnf_open? pnf_close: pnf_open
p0 = plot(base, title="base", color=gray)
fill(p0, p2, color=green, transp=70)
fill(p0, p1, color=maroon, transp=70)
entry() => (base > pnf_close)
exit() => (base > pnf_open)
alertcondition(entry(), title='buy', message='buy!')
alertcondition(exit(), title='sell', message='sell!')
strategy.risk.allow_entry_in(strategy.direction.long)
strategy.entry("Long", long=true, when=entry())
strategy.entry("close", false, when=exit())
</code>```

答:
Set the long parameter of strategy.entry() to false.

long (bool) A required parameter. Market position direction: 'true' or
'strategy.long' is for long, 'false' or 'strategy.short' is for short.

ContentLicense: CC BY-SA 4.0

Body:
How to include short signals in a Long only strategy on tradingview?

I have a Tradingview strategy which gives only long/Buy signals as per matching conditions. I also need it to generate short signals when the conditions are suitable. How do I do it?

strategy("Varun scalp", shorttitle="Varun scalp", overlay=true)
timeframe = input('3')
box = input('Traditional')
boxsize = input(5, type=float)
reversal = input(1)
pnf = pointfigure(tickerid, 'close', box, boxsize, reversal)
pnf_open= security(pnf, timeframe , open)
pnf_close= security(pnf, timeframe , close)
p1 = plot(pnf_open, title="pnf_open", color=green)
p2 = plot(pnf_close,  title="pnf_close",color=maroon)
base = pnf_close> pnf_open? pnf_close: pnf_open
p0 = plot(base, title="base", color=gray)
fill(p0, p2, color=green, transp=70)
fill(p0, p1, color=maroon, transp=70)
entry() => (base > pnf_close)
exit() => (base > pnf_open)
alertcondition(entry(), title='buy', message='buy!')
alertcondition(exit(), title='sell', message='sell!')
strategy.risk.allow_entry_in(strategy.direction.long)
strategy.entry("Long", long=true, when=entry())
strategy.entry("close", false, when=exit())


问:
can c++ using cin to read one digit like scanf
does c++ have similar measure like scanf("%1d) read only one digit in cin >>

or only #include <cstdin> and use scanf

I try to use setw() but it seem to use in string

答:
A digit is nothing else than a single character.

In order to read a single character from std::cin, you can use operator>>, or you can use std::istream::get.

Using operator>>:

```<code>char digit;
std::cin >> digit;
</code>```

Using std::istream::get:

```<code>char digit;
std::cin.get( &digit );
</code>```

In order to convert char digit to an integer, assuming that digit is in the range '0' to '9', you can write the following:

```<code>int number = digit - '0';
</code>```

You can do this because the ISO C++ standard guarantees that the characters '0' to '9' are stored consecutively in the character set. For example, in ASCII, the characters '0' to '9' have the character codes 48 to 57. Therefore, if you simply substract 48 (which is the character code for '0') from the character code, you will get a result between 0 and 9, which is the value of the digit.

Here is an example program:

```<code>#include <iostream>
#include <cstdlib>

int main()
{
    int number;
    char digit;

    //prompt user for input
    std::cout << "Please enter a digit: ";

    //attempt to read a single character
    std::cin >> digit;

    //verify that no input error occurred
    if ( !std::cin )
    {
        printf( "Input error!\n" );
        std::exit( EXIT_FAILURE );
    }

    //verify that character is in the range '0' to '9'
    if ( ! ( '0' <= digit && digit <= '9' ) )
    {
        printf( "Character is not a digit!\n" );
        std::exit( EXIT_FAILURE );
    }

    //convert digit to integer
    number = digit - '0';

    //print result
    std::cout <<
        "The digit was successfully converted to " << number << ".\n";
}
</code>```

This program has the following behavior:

Please enter a digit: 7
The digit was successfully converted to 7.
```
<p>It only accepts digits:</p>
<pre class="lang-none prettyprint-override"><code>Please enter a digit: a
Character is not a digit!
</code>```

It will only read the first digit, not a whole number:

Please enter a digit: 38
The digit was successfully converted to 3.
```

Body:
A digit is nothing else than a single character.

In order to read a single character from std::cin, you can use operator>>, or you can use std::istream::get.

Using operator>>:

char digit;
std::cin >> digit;

Using std::istream::get:

char digit;
std::cin.get( &digit );

In order to convert char digit to an integer, assuming that digit is in the range '0' to '9', you can write the following:

int number = digit - '0';

You can do this because the ISO C++ standard guarantees that the characters '0' to '9' are stored consecutively in the character set. For example, in ASCII, the characters '0' to '9' have the character codes 48 to 57. Therefore, if you simply substract 48 (which is the character code for '0') from the character code, you will get a result between 0 and 9, which is the value of the digit.

Here is an example program:

#include <iostream>
#include <cstdlib>

int main()
{
    int number;
    char digit;

    //prompt user for input
    std::cout << "Please enter a digit: ";

    //attempt to read a single character
    std::cin >> digit;

    //verify that no input error occurred
    if ( !std::cin )
    {
        printf( "Input error!\n" );
        std::exit( EXIT_FAILURE );
    }

    //verify that character is in the range '0' to '9'
    if ( ! ( '0' <= digit && digit <= '9' ) )
    {
        printf( "Character is not a digit!\n" );
        std::exit( EXIT_FAILURE );
    }

    //convert digit to integer
    number = digit - '0';

    //print result
    std::cout <<
        "The digit was successfully converted to " << number << ".\n";
}

This program has the following behavior:

Please enter a digit: 7
The digit was successfully converted to 7.

It only accepts digits:

Please enter a digit: a
Character is not a digit!

It will only read the first digit, not a whole number:

Please enter a digit: 38
The digit was successfully converted to 3.


问:
c++ : Why does my boolean store a value greater than 1?
I'm learning C++ and am right now starting with the concept of classes. And I learned that a new created object (without constructor) will have randomized attributes. So I wanted to test that and wrote a short code:

#include <iostream>
#include <vector>

class Person;
class Person {
public:
  bool const isHungry() {
    return hungry;
  }
  bool const isOld() {
    return age;
  }
private:
  bool hungry;
  bool age;
};

int main() {
  Person person1,person2,person3;
  std::vector<Person> persons {person1,person2,person3};
  for (auto i : persons) {
    std::cout << "Hungrig: " << i.isHungry() << ";\t Alt: " << i.isOld();
    std::cout << std::endl;
  }
}
```
<p>And the result were:</p>
<p>Hungrig: 96;     Alt: 147</p>
<p>Hungrig: 222;    Alt: 46</p>
<p>Hungrig: 252;    Alt: 127</p>
<p>So yes, it is randomized, but a now I got a new question:
How can that be?? It's a boolean, it should be 0 or 1!</p>
<p>Edit: I think the trouble I have with it is that I thought the boolean converts integers greater than 1 to 1. Like this:</p>
```  bool test;
  test= 32;
  std::cout << test << std::endl;
```

Result is always 1. So it puzzles me why it doesn't do it with the boolean in my class.

答:
if you didn't initialize variables, that occur random value(uninitialized).

global, static var is initialized by compiler if you didn't.
Assign false to variable, or you can consider Constructor()

Body:
I'm learning C++ and am right now starting with the concept of classes. And I learned that a new created object (without constructor) will have randomized attributes. So I wanted to test that and wrote a short code:

#include <iostream>
#include <vector>

class Person;
class Person {
public:
  bool const isHungry() {
    return hungry;
  }
  bool const isOld() {
    return age;
  }
private:
  bool hungry;
  bool age;
};

int main() {
  Person person1,person2,person3;
  std::vector<Person> persons {person1,person2,person3};
  for (auto i : persons) {
    std::cout << "Hungrig: " << i.isHungry() << ";\t Alt: " << i.isOld();
    std::cout << std::endl;
  }
}

And the result were:

Hungrig: 96;     Alt: 147

Hungrig: 222;    Alt: 46

Hungrig: 252;    Alt: 127

So yes, it is randomized, but a now I got a new question:
How can that be?? It's a boolean, it should be 0 or 1!

Edit: I think the trouble I have with it is that I thought the boolean converts integers greater than 1 to 1. Like this:

  bool test;
  test= 32;
  std::cout << test << std::endl;

Result is always 1. So it puzzles me why it doesn't do it with the boolean in my class.


问:
How to search a text inside messages in a topic in Kafka?
I would like to check if messages containing a certain event id are available in a certain kafka topic.

How can I do this from command line?

答: There is no Kafka cli tool for searching events. You'd need to pipe existing console consumer command to grep


问:
Get next element in foreach loop
I have a foreach loop and I want to see if there is a next element in the loop so I can compare the current element with the next. How can I do this? I've read about the current and next functions but I can't figure out how to use them.</p>

答:
```<code>    $next_data = $data;

    $prev_key = null;
    $prev_value = null;

    foreach($data as $key => $value)
    {
        array_shift($next_data);

        $next_key = key($next_data);
        $next_value = $next_data[$next_key] ?? null;

        // Do something here...

        $prev_key = $key;
        $prev_value = $value;
    }
</code>```

Title: Get next element in foreach loop


问:
How to do a OR in a c:if statement in jsp
How do I properly declare a or statement i try this without success:

<c:forEach var="route" items="${map.street}">
<c:if test="${route.value.type == 'road' || route.value.type == 'street'}">

答: According to http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPIntro7.html the || should work.  When using el, I generally use 'or' instead of '||' but I'm not sure why I do that.</p>

OwnerDisplayName: JorgeO

ContentLicense: CC BY-SA 2.5


问:
Jquery toggle with position absolute bottom
I've got an absolute positioned container, which is bottom aligned.

Now I would like to toggle (show/hide) some content without the container getting larger than its contents -  and preferably without setting the height explicitly.

html

```<code><div id="outer">
    <div class="expandableContent">
        <p class="toggler">Toggle</p>
        <div>
            <p>Some content here</p>
            <p>Some content there</p>
            <p>Some content everywhere</p>
        </div>
    </div>
</div>
</code>```

css

```<code>#outer {
     height: 300px;
     position: relative;
}

.expandableContent {
    position: absolute;
    bottom: 10px;
}

 .expandableContent > div {
     display: none;
 }
</code>```

jquery

```<code>$(document).ready(function () {
    $('.toggler').click( function() {
        $(this).next().toggle(1000);
    });
});
</code>```

Here's a link: http://jsfiddle.net/SunnyRed/A8pNv/1/

答:
You don't need to set the height...just the width of the explandable div. I have modified this for you in your jsfiddle.

The only thing i did was:

```<code> .expandableContent {
    position: absolute;
    bottom: 10px;
    width:200px;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've got an absolute positioned container, which is bottom aligned.

Now I would like to toggle (show/hide) some content without the container getting larger than its contents -  and preferably without setting the height explicitly.

html

Toggle

Some content here

Some content there

Some content everywhere

css

#outer {
     height: 300px;
     position: relative;
}

.expandableContent {
    position: absolute;
    bottom: 10px;
}

 .expandableContent > div {
     display: none;
 }

jquery

$(document).ready(function () {
    $('.toggler').click( function() {
        $(this).next().toggle(1000);
    });
});

Here's a link: http://jsfiddle.net/SunnyRed/A8pNv/1/

Body:
You don't need to set the height...just the width of the explandable div. I have modified this for you in your jsfiddle.

The only thing i did was:

 .expandableContent {
    position: absolute;
    bottom: 10px;
    width:200px;
}


问:
convert markdown text to html table using perl
I'm trying to convert a Markdown text to HTML table with Perl modules. I tried to use Text::Markdown, but it didn't work.

I also tried to use Markdown::Table and follow the documentation: https://metacpan.org/pod/Markdown::Table,
but same thing no result.

Here is my code:

```<code>use Markdown::Table;

my $markdown = q~
| Id | Name | Role |
+---+---+---+
| 1 | John Smith | Testrole |
| 2 | Jane Smith | Admin |
~;

my @tables = Markdown::Table->parse($markdown);

use Data::Dumper;
Core::Global::Logger::debug(Dumper( $tables[0]->get_table ) );
</code>```

Output:

can anyone help about that please ?

答:
Use Text::MultiMarkdown the original Markdown doesn't support tables. And Text::Markdown only supports the orignal syntax.

Text::MultiMarkdown has additional features.

Project Site: https://fletcherpenney.net/multimarkdown/

Features: https://rawgit.com/fletcher/MultiMarkdown-6-Syntax-Guide/master/index.html

Additional you have to change the table format.

use v5.10;
use Text::MultiMarkdown qw(markdown);

my $text = q[
| Id | Name | Role |
|---|---|---|
| 1 | John Smith | Testrole |
| 2 | Jane Smith | Admin |
];

# Replace any CRLF/LF line-endings to the native Line-Ending used by Perl
$text =~ s/\R/\n/g;

my $html = markdown($text);

printf "%s\n", $html;
```
<p>will produce</p>
<pre class="lang-html prettyprint-override"><code><table>
<col />
<col />
<col />
<thead>
<tr>
        <th>Id</th>
        <th>Name</th>
        <th>Role</th>
</tr>
</thead>
<tbody>
<tr>
        <td>1</td>
        <td>John Smith</td>
        <td>Testrole</td>
</tr>
<tr>
        <td>2</td>
        <td>Jane Smith</td>
        <td>Admin</td>
</tr>
</tbody>
</table>
</code>```

Body:
I'm trying to convert a Markdown text to HTML table with Perl modules. I tried to use Text::Markdown, but it didn't work.

I also tried to use Markdown::Table and follow the documentation: https://metacpan.org/pod/Markdown::Table,
but same thing no result.

Here is my code:

use Markdown::Table;

my $markdown = q~
| Id | Name | Role |
+---+---+---+
| 1 | John Smith | Testrole |
| 2 | Jane Smith | Admin |
~;

my @tables = Markdown::Table->parse($markdown);

use Data::Dumper;
Core::Global::Logger::debug(Dumper( $tables[0]->get_table ) );

Output:

can anyone help about that please ?

Body:
Use Text::MultiMarkdown the original Markdown doesn't support tables. And Text::Markdown only supports the orignal syntax.

Text::MultiMarkdown has additional features.

Project Site: https://fletcherpenney.net/multimarkdown/

Features: https://rawgit.com/fletcher/MultiMarkdown-6-Syntax-Guide/master/index.html

Additional you have to change the table format.

use v5.10;
use Text::MultiMarkdown qw(markdown);

my $text = q[
| Id | Name | Role |
|---|---|---|
| 1 | John Smith | Testrole |
| 2 | Jane Smith | Admin |
];

# Replace any CRLF/LF line-endings to the native Line-Ending used by Perl
$text =~ s/\R/\n/g;

my $html = markdown($text);

printf "%s\n", $html;

will produce

<table>
<col />
<col />
<col />
<thead>
<tr>
        <th>Id</th>
        <th>Name</th>
        <th>Role</th>
</tr>
</thead>
<tbody>
<tr>
        <td>1</td>
        <td>John Smith</td>
        <td>Testrole</td>
</tr>
<tr>
        <td>2</td>
        <td>Jane Smith</td>
        <td>Admin</td>
</tr>
</tbody>
</table>


问:
Google foobar minion labor shifts challenge
I have a Google foobar challenge:

Write a function called answer(data, n) that takes in a list of less than 100 integers and a number n, and returns that same list but with all of the numbers that occur more than n times removed entirely. The returned list should retain the same ordering as the original list - you don't want to mix up those carefully-planned shift rotations! For instance, if data was [5, 10, 15, 10, 7] and n was 1, answer(data, n) would return the list [5, 15, 7] because 10 occurs twice, and thus was removed from the list entirely.

And this was my answer:

```<code>def answer(data=[], n=0):
    for id in data:
        num = data.count(id)
        if num > n:
            for i in data:
                if i == id:
                    data.remove (id)
                else:
                    continue
        else:
            continue
    return data
</code>```

But it didn't pass the test.

答:
you can try this one</p>
```<code>    def solution(data, n):
        # Your code here
        if len(data) < 100:
            list = filter(lambda a: data.count(a)<= n, data)
            return(list)
</code>```

Body:
I have a Google foobar challenge:

Write a function called answer(data, n) that takes in a list of less than 100 integers and a number n, and returns that same list but with all of the numbers that occur more than n times removed entirely. The returned list should retain the same ordering as the original list - you don't want to mix up those carefully-planned shift rotations! For instance, if data was [5, 10, 15, 10, 7] and n was 1, answer(data, n) would return the list [5, 15, 7] because 10 occurs twice, and thus was removed from the list entirely.

And this was my answer:

def answer(data=[], n=0):
    for id in data:
        num = data.count(id)
        if num > n:
            for i in data:
                if i == id:
                    data.remove (id)
                else:
                    continue
        else:
            continue
    return data

But it didn't pass the test.

Body:
you can try this one

    def solution(data, n):
        # Your code here
        if len(data) < 100:
            list = filter(lambda a: data.count(a)<= n, data)
            return(list)


问:
How to show selected date inside the button ---- Date picker -- Flutter
I have built a date picker where users can select the date and I want to update the selected date inside the elevated button, but when the date is updated it also starts showing the time inside the elevated button
Also, I want to keep the same format of date, I have specified above in the code
I am providing my code and snapshots

```<code>[class CashInCashOut extends StatefulWidget {
  const CashInCashOut({Key? key}) : super(key: key);

  @override
  _CashInCashOutState createState() => _CashInCashOutState();
}

class _CashInCashOutState extends State<CashInCashOut> {
  DateTime date = DateTime.now();
  late var formattedDate = DateFormat('d-MMM-yy').format(date);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Cash Out"),
        ),
        body: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            children: \[
              const TextField(
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(labelText: "Amount"),
              ),
              const TextField(
                decoration: InputDecoration(labelText: "Detail (optional)"),
              ),
              Row(
                children: \[
                  ElevatedButton(
                    child: Text(formattedDate),
                    onPressed: () async {
                      DateTime? _newDate = await showDatePicker(
                        context: context,
                        initialDate: date,
                        firstDate: DateTime(2022),
                        lastDate: DateTime(2030),
                      );
                      setState(() {
                        if (_newDate == null) {
                          return;
                        } else {
                          formattedDate = _newDate.toString();
                        }
                      });
                    },
                  ),
                  const Spacer(),
                  ReusableButton(text: "Add bills"),
                \],
              ),
            \],
          ),
        ));
  }
}
</code>```

state of my application before selecting date

state of my application after selecting the date from date picker

答:
```<code>class MyHomePage extends StatefulWidget {
    const MyHomePage({Key? key, required this.title}) : super(key: key);

    final String title;

    @override
    State<MyHomePage> createState() => _MyHomePageState();
  }

  class _MyHomePageState extends State<MyHomePage> {
    DateTime date = DateTime.now();
    late var formattedDate;
    @override
    void initState() {
      formattedDate = DateFormat('d-MMM-yy').format(date);
    }

    @override
    Widget build(BuildContext context) {

      return Scaffold(
        body: SafeArea(
          child: Center(
            child: ElevatedButton(
              child: Text(formattedDate),
              onPressed: () async {
                await showDatePicker(
                  context: context,
                  initialDate: date,
                  firstDate: DateTime(2022),
                  lastDate: DateTime(2030),
                ).then((selectedDate) {
                  if (selectedDate != null) {
                    setState(() {
                       date = selectedDate;
                       formattedDate = DateFormat('d-MMM-yy').format(selectedDate);
                    });
                  }
                }
                );

              },
            ),
          ),
        ),
      );
    }

  }
</code>```

this is how it looks when you start the app:

if you press the button and you chose for example this date 25-mar-2025 :

then click ok, the date will appear in the button :

Body:
I have built a date picker where users can select the date and I want to update the selected date inside the elevated button, but when the date is updated it also starts showing the time inside the elevated button
Also, I want to keep the same format of date, I have specified above in the code
I am providing my code and snapshots

[class CashInCashOut extends StatefulWidget {
  const CashInCashOut({Key? key}) : super(key: key);

  @override
  _CashInCashOutState createState() => _CashInCashOutState();
}

class _CashInCashOutState extends State<CashInCashOut> {
  DateTime date = DateTime.now();
  late var formattedDate = DateFormat('d-MMM-yy').format(date);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Cash Out"),
        ),
        body: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            children: \[
              const TextField(
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(labelText: "Amount"),
              ),
              const TextField(
                decoration: InputDecoration(labelText: "Detail (optional)"),
              ),
              Row(
                children: \[
                  ElevatedButton(
                    child: Text(formattedDate),
                    onPressed: () async {
                      DateTime? _newDate = await showDatePicker(
                        context: context,
                        initialDate: date,
                        firstDate: DateTime(2022),
                        lastDate: DateTime(2030),
                      );
                      setState(() {
                        if (_newDate == null) {
                          return;
                        } else {
                          formattedDate = _newDate.toString();
                        }
                      });
                    },
                  ),
                  const Spacer(),
                  ReusableButton(text: "Add bills"),
                \],
              ),
            \],
          ),
        ));
  }
}

state of my application before selecting date

state of my application after selecting the date from date picker

Body:
class MyHomePage extends StatefulWidget {
    const MyHomePage({Key? key, required this.title}) : super(key: key);

    final String title;

    @override
    State<MyHomePage> createState() => _MyHomePageState();
  }

  class _MyHomePageState extends State<MyHomePage> {
    DateTime date = DateTime.now();
    late var formattedDate;
    @override
    void initState() {
      formattedDate = DateFormat('d-MMM-yy').format(date);
    }

    @override
    Widget build(BuildContext context) {

      return Scaffold(
        body: SafeArea(
          child: Center(
            child: ElevatedButton(
              child: Text(formattedDate),
              onPressed: () async {
                await showDatePicker(
                  context: context,
                  initialDate: date,
                  firstDate: DateTime(2022),
                  lastDate: DateTime(2030),
                ).then((selectedDate) {
                  if (selectedDate != null) {
                    setState(() {
                       date = selectedDate;
                       formattedDate = DateFormat('d-MMM-yy').format(selectedDate);
                    });
                  }
                }
                );

              },
            ),
          ),
        ),
      );
    }

  }

this is how it looks when you start the app:

if you press the button and you chose for example this date 25-mar-2025 :

then click ok, the date will appear in the button :


问:
Why is it faster sending data as encoded string than sending it as bytes?
I'm playing with pyzmq for inter-process transfer of 4k HDR image data and noticed that this:

```<code>byt = np.array2string(np.random.randn(3840,2160,3)).encode()
while True:
   socket.send(byt)
</code>```

is much much faster than:

```<code>byt = np.random.randn(3840,2160,3).asbytes()
while True:
   socket.send(byt)
</code>```

Can someone explain why? I can't seem to wrap my head around it.

答:
Q : Why is it faster sending ... ? Can someone explain why ?

A :
+1 for having asked WHY -
 people who do understand WHY are those, that strive to learn to the roots of the problems, so as to truly understand the core reasons & thus can next design better systems, knowing the very WHY ( taking no shortcuts in mimicking emulating or copy/paste following someone else )

So, let's start :

 HDR is not the SDR,
 we will have "a lot of DATA" here to acquire - store - process - send,

Inventory of facts
 - in this order : DATA, process, .send(), who gets faster & WHY

DATA :
were defined to be 4K-HDR sized array of triple-data-values of a numpy provided default dtype, where ITU-T Recommendation BT-2100 HDR colourspace requires at least 10-bit for increased colour dynamics-ranges

The as-is code delivers numpy.random.randn( c4K, r4K, 3 )'s default
dtype of np.float64. Just for the sake of proper & right-sized system design, the HDR ( extending a plain 8-bit sRGB triple-byte colourspace ) shall always prefer int{10|12|16|32|...}-based storage, not to skew any numerical image post-processing in pipeline's later phase(s).

process :

Actual message-payload generating processes were defined to be
Case-A ) np.array2string( ) followed by an .encode() method

Case-B ) a numpy.ndarray-native (sic) .asbytes()-method

.send() :

ZeroMQ Scalable Formal Communication Archetype pattern (of unknown type) finally receives a process-generated message-payload, into a ( blocking-form of the ) .send()-method

Solution of WHY & tips for HOW :

The core difference is hidden in the fact, that we try to compare apples to oranges.

```<code>>>> len(                  np.random.randn( c4K, r4K, 3 ).tobytes() ) / 1E6
199.0656 [MB]

>>> len( np.array2string( np.random.randn( c4K, r4K, 3 ) )         ) / 1E6
0.001493 [MB] ... Q.E.D.
</code>```

While the (sic) .asbytes()-method produces a full copy ( incl. RAM-allocation + RAM-I/O-traffic [SPACE] + [TIME]-domains' costs ), i.e. spending some extra us before ZeroMQ starts a .send()-method ZeroCopy magicks :

```<code>print(                        np.random.randn( c4K, r4K, 3 ).tobytes.__doc__ )
a.tobytes(order='C')

   Construct Python bytes containing the raw data bytes in the array.

   Constructs Python bytes showing a copy of the raw contents of
   data memory. The bytes object is produced in C-order by default.
   This behavior is controlled by the ``order`` parameter.

   .. versionadded:: 1.9.0
</code>```

the other case, the Case-A, first throws away (!), and a lot (!)... depending here on actual numpy matrix-UI-presentation configuration settings, lot of original 4K-HDR DATA even before moving them into the .encode()-phase :

```<code> >>> print( np.array2string( np.random.randn( c4K, r4K, 3 ) ) )
 [[[ 1.54482944 -0.23189048 -0.67866246]
   ...
   [ 0.13461456  1.47855833 -1.68885902]]

  [[-0.18963557 -1.1869201   1.34843493]
   ...
   [-0.3022641  -0.44158803  0.75750368]]

  [[-1.05737969  0.864752    0.36359686]
   ...
   [ 1.70240612 -0.12574642 -1.03325878]]

  ...

  [[ 0.41776933  1.73473723  0.28723299]
   ...
   [-0.47635911  0.15901325 -0.56407537]]

  [[-1.41571874  1.66735309  0.6259928 ]
   ...
   [-0.93164127  0.95708002  1.3470873 ]]

  [[ 0.16426176 -0.00317156  0.77522962]
   ...
   [ 0.32960196 -1.74369368 -0.34177759]]]

</code>```

So, sending less-DATA means taking less time to move them.

Tips HOW :

ZeroMQ methods & the overall performance will benefit from using zmq.DONTWAIT flag, when passing a reference to the .send()-method

try to re-use the most of the great numpy-tooling, where possible, to minimise repetitive RAM-allocation(s) ( we may pre-allocate & re-use once allocated variable )

try to use as compact DATA-representation as possible, if hunting for maximum performance with minimum latency - redundancy-avoided, compact, CPU-cache-lines' hierarchy & associativity matching formats will always win in the race for ultimate performance ( using a view of internal numpy-storage area, i.e. without using any mediating methods to read-access the actual block of 4K-HDR data may help to move the whole pipeline to become ZeroCopy down to the ZeroMQ .send()-pushing the DATA-references only ( i.e. without copying or moving a single byte of DATA from / into RAM, up until loading it onto the wire ... ) ... which is the coolest performance result of our design efforts here, isn't it? )

in any case, in all critical sections, avoid effects of blocking the flow by gc.disable(), to at least defer a potential .collect() not to happen "here"

Body:
I'm playing with pyzmq for inter-process transfer of 4k HDR image data and noticed that this:

byt = np.array2string(np.random.randn(3840,2160,3)).encode()
while True:
   socket.send(byt)

is much much faster than:

byt = np.random.randn(3840,2160,3).asbytes()
while True:
   socket.send(byt)

Can someone explain why? I can't seem to wrap my head around it.

Body:
Q : Why is it faster sending ... ? Can someone explain why ?

A :
+1 for having asked WHY -
 people who do understand WHY are those, that strive to learn to the roots of the problems, so as to truly understand the core reasons & thus can next design better systems, knowing the very WHY ( taking no shortcuts in mimicking emulating or copy/paste following someone else )

So, let's start :

 HDR is not the SDR,
 we will have "a lot of DATA" here to acquire - store - process - send,

Inventory of facts
 - in this order : DATA, process, .send(), who gets faster & WHY

DATA :
were defined to be 4K-HDR sized array of triple-data-values of a numpy provided default dtype, where ITU-T Recommendation BT-2100 HDR colourspace requires at least 10-bit for increased colour dynamics-ranges

The as-is code delivers numpy.random.randn( c4K, r4K, 3 )'s default
dtype of np.float64. Just for the sake of proper & right-sized system design, the HDR ( extending a plain 8-bit sRGB triple-byte colourspace ) shall always prefer int{10|12|16|32|...}-based storage, not to skew any numerical image post-processing in pipeline's later phase(s).

process :

Actual message-payload generating processes were defined to be
Case-A ) np.array2string( ) followed by an .encode() method

Case-B ) a numpy.ndarray-native (sic) .asbytes()-method

.send() :

ZeroMQ Scalable Formal Communication Archetype pattern (of unknown type) finally receives a process-generated message-payload, into a ( blocking-form of the ) .send()-method

Solution of WHY & tips for HOW :

The core difference is hidden in the fact, that we try to compare apples to oranges.

>>> len(                  np.random.randn( c4K, r4K, 3 ).tobytes() ) / 1E6
199.0656 [MB]

>>> len( np.array2string( np.random.randn( c4K, r4K, 3 ) )         ) / 1E6
0.001493 [MB] ... Q.E.D.

While the (sic) .asbytes()-method produces a full copy ( incl. RAM-allocation + RAM-I/O-traffic [SPACE] + [TIME]-domains' costs ), i.e. spending some extra us before ZeroMQ starts a .send()-method ZeroCopy magicks :

print(                        np.random.randn( c4K, r4K, 3 ).tobytes.__doc__ )
a.tobytes(order='C')

   Construct Python bytes containing the raw data bytes in the array.

   Constructs Python bytes showing a copy of the raw contents of
   data memory. The bytes object is produced in C-order by default.
   This behavior is controlled by the ``order`` parameter.

   .. versionadded:: 1.9.0

the other case, the Case-A, first throws away (!), and a lot (!)... depending here on actual numpy matrix-UI-presentation configuration settings, lot of original 4K-HDR DATA even before moving them into the .encode()-phase :

 >>> print( np.array2string( np.random.randn( c4K, r4K, 3 ) ) )
 [[[ 1.54482944 -0.23189048 -0.67866246]
   ...
   [ 0.13461456  1.47855833 -1.68885902]]

  [[-0.18963557 -1.1869201   1.34843493]
   ...
   [-0.3022641  -0.44158803  0.75750368]]

  [[-1.05737969  0.864752    0.36359686]
   ...
   [ 1.70240612 -0.12574642 -1.03325878]]

  ...

  [[ 0.41776933  1.73473723  0.28723299]
   ...
   [-0.47635911  0.15901325 -0.56407537]]

  [[-1.41571874  1.66735309  0.6259928 ]
   ...
   [-0.93164127  0.95708002  1.3470873 ]]

  [[ 0.16426176 -0.00317156  0.77522962]
   ...
   [ 0.32960196 -1.74369368 -0.34177759]]]

So, sending less-DATA means taking less time to move them.

Tips HOW :

ZeroMQ methods & the overall performance will benefit from using zmq.DONTWAIT flag, when passing a reference to the .send()-method

try to re-use the most of the great numpy-tooling, where possible, to minimise repetitive RAM-allocation(s) ( we may pre-allocate & re-use once allocated variable )

try to use as compact DATA-representation as possible, if hunting for maximum performance with minimum latency - redundancy-avoided, compact, CPU-cache-lines' hierarchy & associativity matching formats will always win in the race for ultimate performance ( using a view of internal numpy-storage area, i.e. without using any mediating methods to read-access the actual block of 4K-HDR data may help to move the whole pipeline to become ZeroCopy down to the ZeroMQ .send()-pushing the DATA-references only ( i.e. without copying or moving a single byte of DATA from / into RAM, up until loading it onto the wire ... ) ... which is the coolest performance result of our design efforts here, isn't it? )

in any case, in all critical sections, avoid effects of blocking the flow by gc.disable(), to at least defer a potential .collect() not to happen "here"


问:
Annotations and superclasses
This is a question about best practice - consider I have the following base class module, base.py:

from __future__ import annotations
from typing import TYPE_CHECKING

if type_checking:
    from redis import Redis

class Base:
    redis: Redis

    def __init__(self, redis):
        self.redis = redis

```
<p>Assuming I want a class that inherits from <code>Base</code> - which of the following is considered better and why? Is there another way I didn't think of?</p>
<p>(1.) seems cleaner but in (2.) I declare <code>redis: Redis</code> explicitly, which might be better for type-checking tools</p>
<p>1.</p>
<pre class="lang-py prettyprint-override"><code>from base import Base

class Sub(Base):
    user_id: int

    def __init__(self, redis, user_id):
        super().__init__(redis)
        self.user_id = user_id
</code>```

from __future__ import annotations
from typing import TYPE_CHECKING
from base import Base

if TYPE_CHECKING:
    from redis import Redis

class Sub(Base):
    redis: Redis
    user_id: int

    def __init__(self, redis, user_id):
        super().__init__(redis)
        self.user_id = user_id
```

答:
As covered, not re-declaring things in the subclass is preferable.  Since we're talking about best practices, though, I'll also suggest that if you're not using dataclasses and your instance attributes are being set in your __init__, that's where you should put your type annotations instead:

```<code>class Base:
    def __init__(self, redis: Redis):
        self.redis = redis

class Sub(Base):
    def __init__(self, redis: Redis, user_id: int):
        super().__init__(redis)
        self.user_id = user_id
</code>```

This is briefer since you don't need to declare each attribute in multiple places, and it gives you correct typechecking when you construct an instance:

```<code>s = Sub(Redis(), 42)
reveal_type(s.redis)    # note: Revealed type is "Redis"
reveal_type(s.user_id)  # note: Revealed type is "builtins.int"
t = Sub("redis", 42)    # error: Argument 1 to "Sub" has incompatible type "str"; expected "Redis"
</code>```

If the parameters aren't annotated, then you get the "correct" revealed type on the attributes, but it's very easy for them to have the wrong actual types at runtime:

```<code>t = Sub("redis", 42)   # no error (oops!)
reveal_type(t.redis)   # note: Revealed type is "Redis"
print(type(t.redis))   # <class 'str'>  (oops!)
</code>```

Title: Annotations and superclasses

Body:
This is a question about best practice - consider I have the following base class module, base.py:

from __future__ import annotations
from typing import TYPE_CHECKING

if type_checking:
    from redis import Redis

class Base:
    redis: Redis

    def __init__(self, redis):
        self.redis = redis

Assuming I want a class that inherits from Base - which of the following is considered better and why? Is there another way I didn't think of?

(1.) seems cleaner but in (2.) I declare redis: Redis explicitly, which might be better for type-checking tools

1.

from base import Base

class Sub(Base):
    user_id: int

    def __init__(self, redis, user_id):
        super().__init__(redis)
        self.user_id = user_id

from __future__ import annotations
from typing import TYPE_CHECKING
from base import Base

if TYPE_CHECKING:
    from redis import Redis

class Sub(Base):
    redis: Redis
    user_id: int

    def __init__(self, redis, user_id):
        super().__init__(redis)
        self.user_id = user_id

Body:
As covered, not re-declaring things in the subclass is preferable.  Since we're talking about best practices, though, I'll also suggest that if you're not using dataclasses and your instance attributes are being set in your __init__, that's where you should put your type annotations instead:

class Base:
    def __init__(self, redis: Redis):
        self.redis = redis

class Sub(Base):
    def __init__(self, redis: Redis, user_id: int):
        super().__init__(redis)
        self.user_id = user_id

This is briefer since you don't need to declare each attribute in multiple places, and it gives you correct typechecking when you construct an instance:

s = Sub(Redis(), 42)
reveal_type(s.redis)    # note: Revealed type is "Redis"
reveal_type(s.user_id)  # note: Revealed type is "builtins.int"
t = Sub("redis", 42)    # error: Argument 1 to "Sub" has incompatible type "str"; expected "Redis"

If the parameters aren't annotated, then you get the "correct" revealed type on the attributes, but it's very easy for them to have the wrong actual types at runtime:

t = Sub("redis", 42)   # no error (oops!)
reveal_type(t.redis)   # note: Revealed type is "Redis"
print(type(t.redis))   # <class 'str'>  (oops!)


问:
Pinescript timeframe since last crossover
I'm quite new to pinescript v5 and can't figure out how to get the timeframe between MA crossovers.

For example, an ma crossover indicates a downtrend,  I need the timeframe(candles) since last crossover indicating an uptrend.

Sounds like there should be a simple solution, yet I can't find one.

答:
You can use the ta.barssince() function or a simple counter for that.

ta.barssince: Counts the number of bars since the last time the
condition was true.

```<code>bars_since_ma_crossover = ta.barssince(ta.crossover(ma1, ma2))
</code>```

Body:
You can use the ta.barssince() function or a simple counter for that.

ta.barssince: Counts the number of bars since the last time the
condition was true.

bars_since_ma_crossover = ta.barssince(ta.crossover(ma1, ma2))


问:
How catch(intercept) and hide a UserNotificationCenter's message ("The disk was not ejected properly")?
I know that I can stop the UserNotificationCenter service temporarily, but this is a bad way. Perhaps, if the a different programmably way to hide or to intercept this message without stopping the service?</p>

答: In order to cancel a UserNotificationCenter message, you need the associated CFUserNotificationRef object, which you're unable to get because you're not the process that originally created the notification.


问:
useState react error Too many re-renders mergin state props input
I am having problems with updating state by mergin selected input props in one string in order to pass a proper path with values to API.

I have something like this in logic :

```<code>    const [data, setData] = useState({ certificate: '', year: '' })

    const merge = () =>{if(data.certificate!==''){(setData(Object.values(data).join("")))}}
      merge()

  useEffect(() => {
    (async () => {
      try {
        const params = {
          data,
        }
        const result = await service.getBackendData({ params})

        if (result.error) throw result.error

        setList(result)
      } catch ({ message }) {
        console.error('error', message)
      }
    })()
  }, [data])
</code>```

The purpose of the code is to get two strings values from the form component (I am using Formik) and this actually works just fine.
But then, two values inside the state (certificate and year props) must be merged in one string in order to send a proper path to API and get response.

useEffect part also works, if i use values separetely, but in this particular matter i must find a way to connect these two above in one string.

I tried to create a merge function under condition that user select and thus pass a certificate value, but that only delayed a render error. After the value is selected, function ofcourse works and join two values, but an infitie loop is created.

I read that changing state in a rendering phase is not a good idea (to put it mildly), so i cannot do this in that way.
So far i run out of ideas. What I am missing ?

Below the part of the Form code, concerning these values. While clicking, user pass from selected options a certificate value, and then i must merge it with year value in one string.

```<code>  const initialValue = {
    CERTIFICATE: '',
    YEAR: '&0',
  }
                     <S.CustomSelect
                      name={certificateInput.certificate.name}
                      placeholder={certificateInput.certificate.placeholder}
                      onClick={setData((prevState) => ({
                        ...prevState,
                        certificate: values.CERTIFICATE,
                      }))}
                    >
                      {certificatesValues.map((item) => (
                        <Option key={item.name} value={item.symbol}>
                          {item.name}
                        </Option>
                      ))}
                    </S.CustomSelect>
</code>```

答: When onClick event triggers you're setting state and react initiate re-evaluation process and re-render the component, as re-render happens, merge() would be called and this time your if conditions get true and call the setData() to set data state, react again re-render your component, merge() will again be called and this cycle goes on. Move merge() inside useEffect() to make this work</p>

Body:
I am having problems with updating state by mergin selected input props in one string in order to pass a proper path with values to API.

I have something like this in logic :

    const [data, setData] = useState({ certificate: '', year: '' })

    const merge = () =>{if(data.certificate!==''){(setData(Object.values(data).join("")))}}
      merge()

  useEffect(() => {
    (async () => {
      try {
        const params = {
          data,
        }
        const result = await service.getBackendData({ params})

        if (result.error) throw result.error

        setList(result)
      } catch ({ message }) {
        console.error('error', message)
      }
    })()
  }, [data])

The purpose of the code is to get two strings values from the form component (I am using Formik) and this actually works just fine.
But then, two values inside the state (certificate and year props) must be merged in one string in order to send a proper path to API and get response.

useEffect part also works, if i use values separetely, but in this particular matter i must find a way to connect these two above in one string.

I tried to create a merge function under condition that user select and thus pass a certificate value, but that only delayed a render error. After the value is selected, function ofcourse works and join two values, but an infitie loop is created.

I read that changing state in a rendering phase is not a good idea (to put it mildly), so i cannot do this in that way.
So far i run out of ideas. What I am missing ?

Below the part of the Form code, concerning these values. While clicking, user pass from selected options a certificate value, and then i must merge it with year value in one string.

  const initialValue = {
    CERTIFICATE: '',
    YEAR: '&0',
  }
                     <S.CustomSelect
                      name={certificateInput.certificate.name}
                      placeholder={certificateInput.certificate.placeholder}
                      onClick={setData((prevState) => ({
                        ...prevState,
                        certificate: values.CERTIFICATE,
                      }))}
                    >
                      {certificatesValues.map((item) => (
                        <Option key={item.name} value={item.symbol}>
                          {item.name}
                        </Option>
                      ))}
                    </S.CustomSelect>


问:
Flutter Stream Builder Triggered when Navigator Pop or Push is Called
I have a stream builder in the app's home/root page. This stream builder gets triggered whenever I do a page-navigation elsewhere, which has nothing to do with the stream itself.

My understanding, according to here and here, is when a page is popped/pushed in the navigator, it triggers a rebuild on the app, so the stream builder gets re-attached and so it fires. However this seems inefficient, so is there a way to prevent the stream builder from firing when a page is popped/pushed?

Additionally, according to the logs, when I push a page, the page is built and shown first, then the stream builder gets fired. However the stream builder's widget/page does not show at all, even though clearly the logs/debugger show that the stream builder's widget has been returned. Where did it go? How does it work in the Flutter framework?

Below is the full code and logs. The code uses Firebase auth as a the stream builder.

Code:

```<code>import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: AppHomePage(),
    );
  }
}

class AppHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final FirebaseAuth auth = FirebaseAuth.instance;
    return StreamBuilder<FirebaseUser>(
      stream: auth.onAuthStateChanged,
      builder: (_, AsyncSnapshot<FirebaseUser> snapshot) {
        if (snapshot.connectionState == ConnectionState.active) {
          final FirebaseUser user = snapshot.data;
          if (user == null) {
            debugPrint("User is NULL.");
            return SignInPage();
          } else {
            debugPrint("User exists.");
            return MainPage();
          }
        } else {
          debugPrint("In waiting state.");
          return Scaffold(
            body: Center(
              child: CircularProgressIndicator(),
            ),
          );
        }
      },
    );
  }
}

class MainPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    debugPrint("Building main page.");
    return Scaffold(
      body: Center(
        child: Text("Welcome to our app!"),
      ),
    );
  }
}

class SignInPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    debugPrint("Building sign-in page.");
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            FlatButton(
              color: Colors.blue,
              child: Text('Sign In as Anonymous'),
              onPressed: () {
                debugPrint("Anonymous");
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => MainPage()),
                );
              },
            ),
            FlatButton(
              color: Colors.red,
              child: Text('Sign In with Google'),
              onPressed: () => debugPrint("Google"),
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

Logs, where the 4th line indicates a button is pressed to do a navigator.pop():

```<code>I/flutter (22339): In waiting state.
I/flutter (22339): User is NULL.
I/flutter (22339): Building sign-in page.
I/flutter (22339): Anonymous
I/flutter (22339): Building main page.
I/flutter (22339): User is NULL.
I/flutter (22339): Building sign-in page.
</code>```

答:
I faced the same issue in my HomeScreen which is a StatefulWidget and it was fixed after adding 'const' keyword.</p>
```<code>Scaffold(
      bottomNavigationBar: BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          fixedColor: Colors.black,
          currentIndex: _selectedIndex,
          selectedFontSize: 10.0,
          unselectedFontSize: 10.0,
          onTap: (i) => setState(() {
                _selectedIndex = i;
              }),
          items: const [
            BottomNavigationBarItem(
                icon: Icon(Icons.home_outlined),
                activeIcon: Icon(Icons.home),
                label: 'Home'),
            BottomNavigationBarItem(
                icon: Icon(Icons.explore_outlined),
                activeIcon: Icon(Icons.explore),
                label: 'Explore')
  ]),
      body: Stack(
        children: _screens.asMap().map((i, screen) => MapEntry(i, Offstage(
          offstage: _selectedIndex !=i,
          child: screen,
        ))).values.toList(),
      ),
      drawer: CustomDrawer(),
    );

final _screens = [
       const HomeScreen(),
       Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.white,
          elevation: 0,
          leading: IconButton(
            iconSize: 30,
            color: Colors.black,
             icon: const Icon(Icons.close),
            onPressed: () => _navigateTo(0),
           ),),
        body: const Center(
          child: Text('Explore'),
        ),
      ),
</code>```

Body:
I have a stream builder in the app's home/root page. This stream builder gets triggered whenever I do a page-navigation elsewhere, which has nothing to do with the stream itself.

My understanding, according to here and here, is when a page is popped/pushed in the navigator, it triggers a rebuild on the app, so the stream builder gets re-attached and so it fires. However this seems inefficient, so is there a way to prevent the stream builder from firing when a page is popped/pushed?

Additionally, according to the logs, when I push a page, the page is built and shown first, then the stream builder gets fired. However the stream builder's widget/page does not show at all, even though clearly the logs/debugger show that the stream builder's widget has been returned. Where did it go? How does it work in the Flutter framework?

Below is the full code and logs. The code uses Firebase auth as a the stream builder.

Code:

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: AppHomePage(),
    );
  }
}

class AppHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final FirebaseAuth auth = FirebaseAuth.instance;
    return StreamBuilder<FirebaseUser>(
      stream: auth.onAuthStateChanged,
      builder: (_, AsyncSnapshot<FirebaseUser> snapshot) {
        if (snapshot.connectionState == ConnectionState.active) {
          final FirebaseUser user = snapshot.data;
          if (user == null) {
            debugPrint("User is NULL.");
            return SignInPage();
          } else {
            debugPrint("User exists.");
            return MainPage();
          }
        } else {
          debugPrint("In waiting state.");
          return Scaffold(
            body: Center(
              child: CircularProgressIndicator(),
            ),
          );
        }
      },
    );
  }
}

class MainPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    debugPrint("Building main page.");
    return Scaffold(
      body: Center(
        child: Text("Welcome to our app!"),
      ),
    );
  }
}

class SignInPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    debugPrint("Building sign-in page.");
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            FlatButton(
              color: Colors.blue,
              child: Text('Sign In as Anonymous'),
              onPressed: () {
                debugPrint("Anonymous");
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => MainPage()),
                );
              },
            ),
            FlatButton(
              color: Colors.red,
              child: Text('Sign In with Google'),
              onPressed: () => debugPrint("Google"),
            ),
          ],
        ),
      ),
    );
  }
}

Logs, where the 4th line indicates a button is pressed to do a navigator.pop():

I/flutter (22339): In waiting state.
I/flutter (22339): User is NULL.
I/flutter (22339): Building sign-in page.
I/flutter (22339): Anonymous
I/flutter (22339): Building main page.
I/flutter (22339): User is NULL.
I/flutter (22339): Building sign-in page.

Body:
I faced the same issue in my HomeScreen which is a StatefulWidget and it was fixed after adding 'const' keyword.

Scaffold(
      bottomNavigationBar: BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          fixedColor: Colors.black,
          currentIndex: _selectedIndex,
          selectedFontSize: 10.0,
          unselectedFontSize: 10.0,
          onTap: (i) => setState(() {
                _selectedIndex = i;
              }),
          items: const [
            BottomNavigationBarItem(
                icon: Icon(Icons.home_outlined),
                activeIcon: Icon(Icons.home),
                label: 'Home'),
            BottomNavigationBarItem(
                icon: Icon(Icons.explore_outlined),
                activeIcon: Icon(Icons.explore),
                label: 'Explore')
  ]),
      body: Stack(
        children: _screens.asMap().map((i, screen) => MapEntry(i, Offstage(
          offstage: _selectedIndex !=i,
          child: screen,
        ))).values.toList(),
      ),
      drawer: CustomDrawer(),
    );

final _screens = [
       const HomeScreen(),
       Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.white,
          elevation: 0,
          leading: IconButton(
            iconSize: 30,
            color: Colors.black,
             icon: const Icon(Icons.close),
            onPressed: () => _navigateTo(0),
           ),),
        body: const Center(
          child: Text('Explore'),
        ),
      ),


问:
Boost Serialization, need help understanding
I've attached the boost sample serialization code below. I see that they create an output archive and then write the class to the output archive. Then later, they create an input archive and read from the input archive into a new class instance. My question is, how does the input archive know which output archive its reading data from? For example, say I have multiple output archives. How does the input archive that is created know which output archive to read from? I'm not understanding how this is working. Thanks for your help!

```<code>#include <fstream>

// include headers that implement a archive in simple text format
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

/////////////////////////////////////////////////////////////
// gps coordinate
//
// illustrates serialization for a simple type
//
class gps_position
{
private:
    friend class boost::serialization::access;
    // When the class Archive corresponds to an output archive, the
    // & operator is defined similar to <<.  Likewise, when the class Archive
    // is a type of input archive the & operator is defined similar to >>.
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & degrees;
        ar & minutes;
        ar & seconds;
    }
    int degrees;
    int minutes;
    float seconds;
public:
    gps_position(){};
    gps_position(int d, int m, float s) :
        degrees(d), minutes(m), seconds(s)
    {}
};

int main() {
    // create and open a character archive for output
    std::ofstream ofs("filename");

    // create class instance
    const gps_position g(35, 59, 24.567f);

    // save data to archive
    {
        boost::archive::text_oarchive oa(ofs);
        // write class instance to archive
        oa << g;
        // archive and stream closed when destructors are called
    }

    // ... some time later restore the class instance to its orginal state
    gps_position newg;
    {
        // create and open an archive for input
        std::ifstream ifs("filename");
        boost::archive::text_iarchive ia(ifs);
        // read class state from archive
        ia >> newg;
        // archive and stream closed when destructors are called
    }
    return 0;
}
</code>```

Example 2

```<code>void save_load_with_binary_archive()
{
    // binary archive with stringstream
    std::ostringstream oss;
    boost::archive::binary_oarchive oa(oss);

    Camera cam;
    cam.id = 100;
    cam.name = "new camera";
    cam.pos = 99.88;

    oa & (cam);

    // get binary content
    std::string str_data = oss.str();
    std::istringstream iss(str_data);
    boost::archive::binary_iarchive ia(iss);
    Camera new_cam;
    ia & (new_cam);
    std::cout << new_cam << std::endl;
}

</code>```

答:
Like others said, you can set up a stream from existing content. That can be from memory (say istringstream) or from a file (say ifstream).

All that matters is what content you stream from. Here's you first example modified to save 10 different streams, which can be read back in any order, or not at all:

Live On Coliru

```<code>#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <fstream>
#include <iostream>

/////////////////////////////////////////////////////////////
// gps coordinate
//
// illustrates serialization for a simple type
//
class gps_position {
  public:
    gps_position(int d = 0, int m = 0, float s = 0)
        : degrees(d)
        , minutes(m)
        , seconds(s) {}

  private:
    friend class boost::serialization::access;
    template<class Archive>
    void serialize(Archive & ar, unsigned )
    {
        ar& degrees& minutes& seconds;
    }
    int degrees;
    int minutes;
    float seconds;

    friend std::ostream& operator<<(std::ostream& os, gps_position const& gps) {
        return os << gps.degrees << "°" << gps.minutes << "′" << gps.seconds << "″";
    }
};

int main() {
    for (int i = 1; i <= 10; ++i) {
        gps_position const g(7 * i, 12 * i - 1, i * 24.567f / 5);

        // save data to archive
        {
            std::ofstream                 ofs("filename" + std::to_string(i));
            boost::archive::text_oarchive oa(ofs);
            // write class instance to archive
            oa << g;
        }
    }

    for (int i = 10; i > 0; --i) {
        // create and open an archive for input
        std::ifstream                 ifs("filename" + std::to_string(i));
        boost::archive::text_iarchive ia(ifs);

        gps_position newg;
        ia >> newg;

        std::cout << " i:" << i << " - " << newg << "\n";
    }
}
</code>```

Prints

```<code> i:10 - 70°119′49.134″
 i:9 - 63°107′44.2206″
 i:8 - 56°95′39.3072″
 i:7 - 49°83′34.3938″
 i:6 - 42°71′29.4804″
 i:5 - 35°59′24.567″
 i:4 - 28°47′19.6536″
 i:3 - 21°35′14.7402″
 i:2 - 14°23′9.8268″
 i:1 - 7°11′4.9134″
</code>```

After finishing, the contents of each stream will persist in the files:

```<code>==> filename1 <==
22 serialization::archive 19 0 0 7 11 4.913399696e+00

==> filename10 <==
22 serialization::archive 19 0 0 70 119 4.913399887e+01

==> filename2 <==
22 serialization::archive 19 0 0 14 23 9.826799393e+00

==> filename3 <==
22 serialization::archive 19 0 0 21 35 1.474019909e+01

==> filename4 <==
22 serialization::archive 19 0 0 28 47 1.965359879e+01

==> filename5 <==
22 serialization::archive 19 0 0 35 59 2.456699944e+01

==> filename6 <==
22 serialization::archive 19 0 0 42 71 2.948039818e+01

==> filename7 <==
22 serialization::archive 19 0 0 49 83 3.439379883e+01

==> filename8 <==
22 serialization::archive 19 0 0 56 95 3.930719757e+01

==> filename9 <==
22 serialization::archive 19 0 0 63 107 4.422060013e+01
</code>```

SIDENOTE: The comment // archive and stream closed when destructors are called was misleading in your question code because ofs was declared outside that scope block. This difference is important.

Body:
I've attached the boost sample serialization code below. I see that they create an output archive and then write the class to the output archive. Then later, they create an input archive and read from the input archive into a new class instance. My question is, how does the input archive know which output archive its reading data from? For example, say I have multiple output archives. How does the input archive that is created know which output archive to read from? I'm not understanding how this is working. Thanks for your help!

#include <fstream>

// include headers that implement a archive in simple text format
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

/////////////////////////////////////////////////////////////
// gps coordinate
//
// illustrates serialization for a simple type
//
class gps_position
{
private:
    friend class boost::serialization::access;
    // When the class Archive corresponds to an output archive, the
    // & operator is defined similar to <<.  Likewise, when the class Archive
    // is a type of input archive the & operator is defined similar to >>.
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & degrees;
        ar & minutes;
        ar & seconds;
    }
    int degrees;
    int minutes;
    float seconds;
public:
    gps_position(){};
    gps_position(int d, int m, float s) :
        degrees(d), minutes(m), seconds(s)
    {}
};

int main() {
    // create and open a character archive for output
    std::ofstream ofs("filename");

    // create class instance
    const gps_position g(35, 59, 24.567f);

    // save data to archive
    {
        boost::archive::text_oarchive oa(ofs);
        // write class instance to archive
        oa << g;
        // archive and stream closed when destructors are called
    }

    // ... some time later restore the class instance to its orginal state
    gps_position newg;
    {
        // create and open an archive for input
        std::ifstream ifs("filename");
        boost::archive::text_iarchive ia(ifs);
        // read class state from archive
        ia >> newg;
        // archive and stream closed when destructors are called
    }
    return 0;
}

Example 2

void save_load_with_binary_archive()
{
    // binary archive with stringstream
    std::ostringstream oss;
    boost::archive::binary_oarchive oa(oss);

    Camera cam;
    cam.id = 100;
    cam.name = "new camera";
    cam.pos = 99.88;

    oa & (cam);

    // get binary content
    std::string str_data = oss.str();
    std::istringstream iss(str_data);
    boost::archive::binary_iarchive ia(iss);
    Camera new_cam;
    ia & (new_cam);
    std::cout << new_cam << std::endl;
}

Body:
Like others said, you can set up a stream from existing content. That can be from memory (say istringstream) or from a file (say ifstream).

All that matters is what content you stream from. Here's you first example modified to save 10 different streams, which can be read back in any order, or not at all:

Live On Coliru

#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <fstream>
#include <iostream>

/////////////////////////////////////////////////////////////
// gps coordinate
//
// illustrates serialization for a simple type
//
class gps_position {
  public:
    gps_position(int d = 0, int m = 0, float s = 0)
        : degrees(d)
        , minutes(m)
        , seconds(s) {}

  private:
    friend class boost::serialization::access;
    template<class Archive>
    void serialize(Archive & ar, unsigned )
    {
        ar& degrees& minutes& seconds;
    }
    int degrees;
    int minutes;
    float seconds;

    friend std::ostream& operator<<(std::ostream& os, gps_position const& gps) {
        return os << gps.degrees << "°" << gps.minutes << "′" << gps.seconds << "″";
    }
};

int main() {
    for (int i = 1; i <= 10; ++i) {
        gps_position const g(7 * i, 12 * i - 1, i * 24.567f / 5);

        // save data to archive
        {
            std::ofstream                 ofs("filename" + std::to_string(i));
            boost::archive::text_oarchive oa(ofs);
            // write class instance to archive
            oa << g;
        }
    }

    for (int i = 10; i > 0; --i) {
        // create and open an archive for input
        std::ifstream                 ifs("filename" + std::to_string(i));
        boost::archive::text_iarchive ia(ifs);

        gps_position newg;
        ia >> newg;

        std::cout << " i:" << i << " - " << newg << "\n";
    }
}

Prints

 i:10 - 70°119′49.134″
 i:9 - 63°107′44.2206″
 i:8 - 56°95′39.3072″
 i:7 - 49°83′34.3938″
 i:6 - 42°71′29.4804″
 i:5 - 35°59′24.567″
 i:4 - 28°47′19.6536″
 i:3 - 21°35′14.7402″
 i:2 - 14°23′9.8268″
 i:1 - 7°11′4.9134″

After finishing, the contents of each stream will persist in the files:

==> filename1 <==
22 serialization::archive 19 0 0 7 11 4.913399696e+00

==> filename10 <==
22 serialization::archive 19 0 0 70 119 4.913399887e+01

==> filename2 <==
22 serialization::archive 19 0 0 14 23 9.826799393e+00

==> filename3 <==
22 serialization::archive 19 0 0 21 35 1.474019909e+01

==> filename4 <==
22 serialization::archive 19 0 0 28 47 1.965359879e+01

==> filename5 <==
22 serialization::archive 19 0 0 35 59 2.456699944e+01

==> filename6 <==
22 serialization::archive 19 0 0 42 71 2.948039818e+01

==> filename7 <==
22 serialization::archive 19 0 0 49 83 3.439379883e+01

==> filename8 <==
22 serialization::archive 19 0 0 56 95 3.930719757e+01

==> filename9 <==
22 serialization::archive 19 0 0 63 107 4.422060013e+01

SIDENOTE: The comment // archive and stream closed when destructors are called was misleading in your question code because ofs was declared outside that scope block. This difference is important.


问:
Python: How to solve bracket not closed error
following a tutorial I'm getting error "(" is not closed while using the exact same code:

```<code>compiled_sol = compile_standard(
  {
      "language": "Solidity",
      "sources": {"SimpleStorage.sol": {"content" = simple_storage_file}}
  }
)
</code>```

don't know where it's going wrong getting these errors:

```<code>"{" was not closedPylance
Expected parameter namePylance
</code>```

and

```<code>Expected parameter namePylance
</code>```

答:
Thing is you can't have an "=" in a dict, where you construct it from {} and not this dict()

Here's examples of both

1.

compiled_sol = compile_standard(
    {
        "language": "Solidity",
        "sources": {
            "SimpleStorage.sol": {
                "content": simple_storage_file
            }
        }
    }
)
```
<p>You cannot use a "=" sign in above constructor
2.</p>
<pre class="lang-py prettyprint-override"><code>compiled_sol = compile_standard(
    dict(
        languages="Solidity",
        sources = dict(
            SimpleStorage.sol = dict(
                content = simple_storage_file)
        )
    )
)
</code>```

In your case the second method will not work, because you have a . in SimpleStorage when you have a . in something Python thinks it is like a module or class
So that's why this method won't work for this case

But it's handy to know

Body:
following a tutorial I'm getting error "(" is not closed while using the exact same code:

compiled_sol = compile_standard(
  {
      "language": "Solidity",
      "sources": {"SimpleStorage.sol": {"content" = simple_storage_file}}
  }
)

don't know where it's going wrong getting these errors:

"{" was not closedPylance
Expected parameter namePylance

and

Expected parameter namePylance

Body:
Thing is you can't have an "=" in a dict, where you construct it from {} and not this dict()

Here's examples of both

1.

compiled_sol = compile_standard(
    {
        "language": "Solidity",
        "sources": {
            "SimpleStorage.sol": {
                "content": simple_storage_file
            }
        }
    }
)

You cannot use a "=" sign in above constructor
2.

compiled_sol = compile_standard(
    dict(
        languages="Solidity",
        sources = dict(
            SimpleStorage.sol = dict(
                content = simple_storage_file)
        )
    )
)

In your case the second method will not work, because you have a . in SimpleStorage when you have a . in something Python thinks it is like a module or class
So that's why this method won't work for this case

But it's handy to know


问:
Excepted end of statement error in ASP
When inserting data into a database, the following error occurs

"Excepted end of statement"

```<code> sqlstr = "INSERT INTO tblContact (Email,FirstName,LastName,Comments) VALUES ('" & Email & "', '" & First Name & "','" & Last Name & "','" & Comments & "')"
 objConn.Execute sqlstr
</code>```

答:
Try using single-word identifiers for your first-name and last-name variables:

```<code>sqlstr = "INSERT INTO tblContact (Email,FirstName,LastName,Comments) " & _
         " VALUES ('" & Email & "', '" & FirstName & "','" & LastName & "','" & Comments & "')"
 objConn.Execute sqlstr
</code>```

Assuming you've got variables with those names in your VBScript, that'll solve your current problem with Expected end of statement.

Your second problem is your code's vulnerability to SQL injection.

To help fix that problem, see:

Classic ASP SQL Injection Protection

http://www.stardeveloper.com/articles/display.html?article=2008112501&page=1

Title: Excepted end of statement error in ASP

Body:
When inserting data into a database, the following error occurs

"Excepted end of statement"

 sqlstr = "INSERT INTO tblContact (Email,FirstName,LastName,Comments) VALUES ('" & Email & "', '" & First Name & "','" & Last Name & "','" & Comments & "')"
 objConn.Execute sqlstr

Body:
Try using single-word identifiers for your first-name and last-name variables:

sqlstr = "INSERT INTO tblContact (Email,FirstName,LastName,Comments) " & _
         " VALUES ('" & Email & "', '" & FirstName & "','" & LastName & "','" & Comments & "')"
 objConn.Execute sqlstr

Assuming you've got variables with those names in your VBScript, that'll solve your current problem with Expected end of statement.

Your second problem is your code's vulnerability to SQL injection.

To help fix that problem, see:

Classic ASP SQL Injection Protection

http://www.stardeveloper.com/articles/display.html?article=2008112501&page=1


问:
Multiple primary_key for has_many relation
There is a model Company that has many Disclosure and Statement.

```<code>class Company < ActiveRecord::Base
  has_many :disclosures
  has_many :statements
end
</code>```

Disclosure and Statement both have date column.

And the Statement have a method like this:

```<code>def disclosures
  Disclosure.where(date: date, company_id: company_id)
end
</code>```

It work's fine. But I think this kind of relation should write by has_many notation. But I couldn't find way to use multiple primary_key with has_many.

Is there a way to use multiple primary key?

答:
A bit late I know, but maybe this is interesting for others. To stick with your example you can try to build a custom scope, something along the lines of:

```<code>has_many :disclosures,
         -> (statement) { where("date = ? AND company_id = ?",
                                statement.date, statement.company_id) }
</code>```

In case you don't want to look for statement_id in the Disclosure, use unscope(where: :statement_id).where(...) in the block.

Body:
There is a model Company that has many Disclosure and Statement.

class Company < ActiveRecord::Base
  has_many :disclosures
  has_many :statements
end

Disclosure and Statement both have date column.

And the Statement have a method like this:

def disclosures
  Disclosure.where(date: date, company_id: company_id)
end

It work's fine. But I think this kind of relation should write by has_many notation. But I couldn't find way to use multiple primary_key with has_many.

Is there a way to use multiple primary key?

Body:
A bit late I know, but maybe this is interesting for others. To stick with your example you can try to build a custom scope, something along the lines of:

has_many :disclosures,
         -> (statement) { where("date = ? AND company_id = ?",
                                statement.date, statement.company_id) }

In case you don't want to look for statement_id in the Disclosure, use unscope(where: :statement_id).where(...) in the block.


问:
Uncaught PDOException: SQLSTATE[HY000] [2002 How to fix this?
I need help with connection MySQL, I have a problem connecting to the database, what I am doing wrong ? Please send me an answer because I searched solution for about 2h and nothing.

This is a picture of the full error.

```<code><?php
class Db {
   private $connection;

   public function __construct($servername, $dbname, $username, $password) {

       $this->connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
   }

   public function query($sql, $args = []) {
       if (!$args) {
           return $this->connection->query($sql);
       }

       $stmt = $this->connection->prepare($sql);
       $stmt->execute($args);
       return $stmt;
   }

   public function entryExists($table, $id) {
       $row = $this->query("SELECT * FROM $table WHERE id = $id")->fetch();

       if (!$row) {
           return false;;
       }
       else {
           return true;
       }
   }

   public function getRows($sql, $values = []) {
       $stmt = $this->query($sql, $values);
       return $stmt->fetchAll();
   }

   public function getFirstMatch($sql) {
       $stmt = $this->query($sql);
       return $stmt->fetch();
   }
}
?>

</code>```

答: I think or are you sending empty values in your constructor function? Maybe you should try entering the values that it should take by default :) I hope my answer will help you. Excuse my English.</p>

Body:
I need help with connection MySQL, I have a problem connecting to the database, what I am doing wrong ? Please send me an answer because I searched solution for about 2h and nothing.

This is a picture of the full error.

<?php
class Db {
   private $connection;

   public function __construct($servername, $dbname, $username, $password) {

       $this->connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
   }

   public function query($sql, $args = []) {
       if (!$args) {
           return $this->connection->query($sql);
       }

       $stmt = $this->connection->prepare($sql);
       $stmt->execute($args);
       return $stmt;
   }

   public function entryExists($table, $id) {
       $row = $this->query("SELECT * FROM $table WHERE id = $id")->fetch();

       if (!$row) {
           return false;;
       }
       else {
           return true;
       }
   }

   public function getRows($sql, $values = []) {
       $stmt = $this->query($sql, $values);
       return $stmt->fetchAll();
   }

   public function getFirstMatch($sql) {
       $stmt = $this->query($sql);
       return $stmt->fetch();
   }
}
?>


问:
Converting text into list where it has spaces
How can I convert text into separate lists where it has a spaces?</p>
```<code>text=input('Input your text: ')
length=len(text.split())
print(length)
list(text)
</code>```

答:
yes you can by doing :

text = input('Input your text: ')
split_text = text.split()
length=len(split_text)
print(length)
print(split_text)
a = input('')
```

Body:
How can I convert text into separate lists where it has a spaces?

text=input('Input your text: ')
length=len(text.split())
print(length)
list(text)


问:
How to fix java.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.1 400 Bad Request"?
When calling HttpURLConnection.getOutputStream() I get this IOException:

Unable to tunnel through proxy. Proxy returns "HTTP/1.1 400 Bad Request"

Code snippet:

```<code>public static void main(String[] args) throws MalformedURLException, IOException {
        HttpURLConnection conn = (HttpURLConnection) new URL("https://example.com")
                .openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("88.198.50.103", 3128)));
        conn.setDoOutput(true);

        try (OutputStream os = conn.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os)) {
            osw.write("Hello");
            osw.flush();
        } catch (IOException e) {
            System.err.println("Caught exception while opening outputstream.");
            e.printStackTrace();
        }
        System.out.println("Response: " + conn.getResponseMessage());
    }
</code>```

Produced output:

```<code>Caught exception while opening outputstream.
java.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.1 400 Bad Request"
    at sun.net.www.protocol.http.HttpURLConnection.doTunneling(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unknown Source)
    at application.Main.main(Main.java:31)
Response: Bad Request
</code>```

I tried random free proxies I found on the internet and all had the same output.

Is this something related to my computer? Or is my code for using proxies wrong?

答:
I encountered the same problem. I think it will not work if the proxy server represents a proxy for high level protocols such as HTTP or FTP. Try changing to Proxy.Type.SOCKS.

I discovered that it may be a bug in old JDK versions including 1.4 or 1.6, however I use JDK 8.

Body:
When calling HttpURLConnection.getOutputStream() I get this IOException:

Unable to tunnel through proxy. Proxy returns "HTTP/1.1 400 Bad Request"

Code snippet:

public static void main(String[] args) throws MalformedURLException, IOException {
        HttpURLConnection conn = (HttpURLConnection) new URL("https://example.com")
                .openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("88.198.50.103", 3128)));
        conn.setDoOutput(true);

        try (OutputStream os = conn.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os)) {
            osw.write("Hello");
            osw.flush();
        } catch (IOException e) {
            System.err.println("Caught exception while opening outputstream.");
            e.printStackTrace();
        }
        System.out.println("Response: " + conn.getResponseMessage());
    }

Produced output:

Caught exception while opening outputstream.
java.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.1 400 Bad Request"
    at sun.net.www.protocol.http.HttpURLConnection.doTunneling(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unknown Source)
    at application.Main.main(Main.java:31)
Response: Bad Request

I tried random free proxies I found on the internet and all had the same output.

Is this something related to my computer? Or is my code for using proxies wrong?


问:
iPad Launch image landscape
I keep getting a warning that my ipad launch image landscape isnt 1024x748, while it actually is that size. When i do compile with the 'wrong' size, it gives me a bloated portrait image.</p>

答:
If you're on Xcode 4.0.2+ then the landscape iPad launch image needs to be 748 * 1024. This is how it works in one of my apps.

Good luck!

Title: iPad Launch image landscape


问:
Event Driven Architecture - Response to Mobile/Web Clients
I have the following use case in my microservices

User Experience: A contact details popup asking the user to confirm the contact details, email address & other relevant details on the UI. Once the user submits the data - The user should see contact details saved successfully/failed message on the screen.

Whenever contact details are updated, a unique comment should also be added in the background.

The downstream system exposes a couple of CRUD API endpoints for creating, retrieving, updating & deleting the contact details and the similar CRUD API endpoints for comments.

As each of these API endpoints is independent. I'm thinking of going down the route of implementing SAGA's (Choregraphy/Orchestration) with events to ensure atomicity.

A REST API endpoint(Spring Boot) on my side captures all the data modified by the user from UI as JSON and publishes an event Update_Contact_Details to a Kafka message topic.

Update_Contact_Details Consumer will read the message from the topic, call the downstream update contact details API, and write back either Contact_Details_Updated/Contact_Details_Update_Failed events.

In the happy path scenario :
The Contact_Details_Updated Message will be read by Comments Listener and makes a call to downstream API to add a comment.

In the failure Scenario:
The Contact_Details_Update_Failed will be read by the Contacts Detailed Failed Listener and makes a call to the Delete Contact Details API.

In either case, as the first capture from UI to API endpoint is REST API - How do I send back the success/failed responses to clients(web/mobile) as the whole process related to orchestrating the above-mentioned flow is asynchronous.

答:
You are basically trying to fit the request-response (synchronous) model to async. We have multiple options here:

Block sending the response to the client till the flow completes.
This is pretty straight-forward and easy to implement but it comes with a cost and is dependent upon the time taken by the whole system to process the chain of events.

Use a callback and notify the consumers over that callback API.
In this case, the listener will send a callback to the interested client that invoked the Update_Contact_Details API endpoint. This requires change in your client side code.

Use polling. Write an endpoint that queries the status of the update (failed/succeeded) depending on whether the message is received by your failed/success listener and let your client keep polling the endpoint periodically. This require changes in your client side code.

If you have ever used like Kinesis (AWS), you might have noticed that creation/update of resources don't happen immediately. You would see a notification bar on the top saying "Creating kinesis stream" and a gif keeps rotating and after sometime, you see the message that stream is successfully created.

With such long or asynchronous processes, the server typically should give a callback or the client should poll for the result instead of blocking on the response indefinitely.

In the case of AWS, the user understands that creation or alteration of resources doesn't happen in milliseconds like Google search, so [s]he doesn't expect the response immediately.

Anyways, going to the root of the design, you can also consider asking the following questions:

1. Do you really require 2 DBs?
You have contact details and comments  (to be added to the contacts), why would you require two databases for contact details and comments? If you use a single database (RDBMS), then there is no need for SAGA pattern.

This pattern is applicable only when there are multiple databases (either because the dbs are already existent prior or there are special use-cases).

2. Do you really require Kafka for your use-case?
You have tagged apache-kafka in the question, so I suppose you have downstream consumers that require this information as "events", if not there is  no use of using Kafka, so the question is "if you really require kafka?"

This being the case, you can update the DB in your UI-facing REST, return the response to the UI once the data is successfully stored in the DB and use CDC (Changed-Data-Capture) to stream DB changes to Kafka.

This ensures that your DB and Kafka are in sync and thereby your Kafka downstream consumers are notified of changes and you update the UI also immediately. If employing CDC is not feasible, then you can schedule a background thread that polls the database for new updates and push them to Kafka.