问:
Problems with gensim WikiCorpus - aliasing chunkize to chunkize_serial; (__mp_main__ instead of __main__?)
I'm quite new to Python and coding in general, so I seem to have run into an issue.

I'm trying to run this code (credit to Matthew Mayo, whole thing can be found here):

```<code># import warnings
# warnings.filterwarnings(action = 'ignore', category = UserWarning, module = 'gensim')
import sys
from gensim.corpora import WikiCorpus

def make_corpus (in_f, out_f):
    print(0)
    output = open(out_f, 'w', encoding = 'utf-8')
    print(1)
    wiki = WikiCorpus(in_f)
    print(2)
    i = 0
    for text in wiki.get_texts():
        output.write(bytes(' '.join(text), 'utf-8').decode('utf-8') + '/n')
        i += 1
        if i % 10000 == 0:
            print('Processed {} articles!'.format(i))
    print(3)
    output.close()
    print('Process complete!')

print('start')
if __name__ == '__main__':
    if len(sys.argv) != 3:
        print('Usage: python make_wiki_corpus.py <wikipedia_dump_file> <processed_text_file>')
        sys.exit(1)
    in_f = sys.argv[1]
    out_f = sys.argv[2]
    make_corpus(in_f, out_f)
else:
    print(__name__)
</code>```

However, the function branch seems to run partly, stopping at the wiki = WikiCorpus(in_f) - it never makes it to print(2) - and then exiting and repeating the beginning of the code, yielding no results. No error actually comes up, only a warning (UserWarning: detected Windows; aliasing chunkize to chunkize_serial warnings.warn("detected Windows; aliasing chunkize to chunkize_serial")).

The output is this:

```<code>start
0
1
C:\Users\name\Anaconda3\lib\site-packages\gensim\utils.py:1254: UserWarning: detected Windows; aliasing chunkize to chunkize_serial warnings.warn("detected Windows; aliasing chunkize to chunkize_serial")
start
__mp_main__
start
__mp_main__
start
__mp_main__
</code>```

I've tried uninstalling all required packages (numpy, smart_open), as well as gensim itself (in an active conda environment), but nothing has changed.
Also, what is the difference between the main and the multiprocessing one?

-- Specifications: win64, py 3.7.3

Edit: after running logging at the DEBUG level, logging file

```<code>2020-02-16 22:49:00,061:start: :13396
2020-02-16 22:49:00,061:0 :13396
2020-02-16 22:49:00,061:1 :13396
2020-02-16 22:49:01,493:start: :22356
2020-02-16 22:49:01,493:3 :22356
2020-02-16 22:49:01,496:start: :25332
2020-02-16 22:49:01,497:3 :25332
2020-02-16 22:49:01,530:start: :7120
2020-02-16 22:49:01,530:3 :7120
2020-02-16 22:49:01,541:adding document #0 to Dictionary(0 unique tokens: []):13396
</code>```

(also, the '3' was added in the else branch:)

```<code>else:
    logging.debug('3 ')
</code>```

答:
Windows OS may be a contributing factor; a lot of things related to multiprocessing work differently there, while gensim gets a lot more use & testing elsewhere. So if it is an option to test your code under another OS, or potentially use another OS entirely, this problem & other potential future problems may become irrelevant.

Other things to check & try:

does the wiki_en.txt file get created, or receive any output, at all?

does it help if you supply processes=1 as an argument to WikiCorpus, so that only one worker process is used?

if you tested some code that doesn't try using WikiCorpus at all, by tries to read-through the raw wiki dump, using BZ2File to uncompress it, in the same style as gensim's wikicorpus.py source code, does that work, or also show a similar problem? (If there is a similar problem, then it's a usefully smaller triggering case that focuses attention on BZ2File's operation on Windows.)

are you by chance using Wikipedia's "multistream" BZ2 file, and if so, could you try the non-multistream alternative & see if the same problem persists (in case this is an issue with BZ2File & multistream on Windows)?

Body:
I'm quite new to Python and coding in general, so I seem to have run into an issue.

I'm trying to run this code (credit to Matthew Mayo, whole thing can be found here):

# import warnings
# warnings.filterwarnings(action = 'ignore', category = UserWarning, module = 'gensim')
import sys
from gensim.corpora import WikiCorpus

def make_corpus (in_f, out_f):
    print(0)
    output = open(out_f, 'w', encoding = 'utf-8')
    print(1)
    wiki = WikiCorpus(in_f)
    print(2)
    i = 0
    for text in wiki.get_texts():
        output.write(bytes(' '.join(text), 'utf-8').decode('utf-8') + '/n')
        i += 1
        if i % 10000 == 0:
            print('Processed {} articles!'.format(i))
    print(3)
    output.close()
    print('Process complete!')

print('start')
if __name__ == '__main__':
    if len(sys.argv) != 3:
        print('Usage: python make_wiki_corpus.py <wikipedia_dump_file> <processed_text_file>')
        sys.exit(1)
    in_f = sys.argv[1]
    out_f = sys.argv[2]
    make_corpus(in_f, out_f)
else:
    print(__name__)

However, the function branch seems to run partly, stopping at the wiki = WikiCorpus(in_f) - it never makes it to print(2) - and then exiting and repeating the beginning of the code, yielding no results. No error actually comes up, only a warning (UserWarning: detected Windows; aliasing chunkize to chunkize_serial warnings.warn("detected Windows; aliasing chunkize to chunkize_serial")).

The output is this:

start
0
1
C:\Users\name\Anaconda3\lib\site-packages\gensim\utils.py:1254: UserWarning: detected Windows; aliasing chunkize to chunkize_serial warnings.warn("detected Windows; aliasing chunkize to chunkize_serial")
start
__mp_main__
start
__mp_main__
start
__mp_main__

I've tried uninstalling all required packages (numpy, smart_open), as well as gensim itself (in an active conda environment), but nothing has changed.
Also, what is the difference between the main and the multiprocessing one?

-- Specifications: win64, py 3.7.3

Edit: after running logging at the DEBUG level, logging file

2020-02-16 22:49:00,061:start: :13396
2020-02-16 22:49:00,061:0 :13396
2020-02-16 22:49:00,061:1 :13396
2020-02-16 22:49:01,493:start: :22356
2020-02-16 22:49:01,493:3 :22356
2020-02-16 22:49:01,496:start: :25332
2020-02-16 22:49:01,497:3 :25332
2020-02-16 22:49:01,530:start: :7120
2020-02-16 22:49:01,530:3 :7120
2020-02-16 22:49:01,541:adding document #0 to Dictionary(0 unique tokens: []):13396

(also, the '3' was added in the else branch:)

else:
    logging.debug('3 ')


来源: stackexchange

问:
Android: How to detect parent tag of XML tags

Possible Duplicate:

  Android: How to get values in under specific xml tags

Hi guys, I want to detect the parent tags of my XML file to download and rename the correct file. I have my code on this link.

答: If you can select any node in your XML document, you can then use XPath's ancestor  axis to find all ancestors (see http://www.w3schools.com/xpath/xpath_axes.asp). Then test them, and if one doesn't have its own ancestor then it's your root element.

ContentLicense: CC BY-SA 3.0


问:
Allow optional GraphQL data in Gatsby
I'm trying to build a Type in my gatsby-node.js file that supports an optional value. Which I think is done with [String!]!.

How can I load the new Type that I've created inside gatsby-node.js on home.js?

gatsby-node.js:

```<code>const path = require('path');
exports.createSchemaCustomization = ({ actions }) => {
    const { createTypes } = actions;
    const typeDefs = `
        type markdownRemark implements Node {
            frontmatter: Features
        }
        type Features {
            title: [String!]!
            description: [String!]!
        }
    `;
    createTypes(typeDefs);
};
</code>```

pages/home/home.js:

```<code>export const query = graphql`
    query HomeQuery($path: String!) {
        markdownRemark(frontmatter: { path: { eq: $path } }) {
            html
            frontmatter {
                features {
                    title
                    description
                }
            }
        }
    }
`;
</code>```

home.md:

```<code>---
path: "/"
features:
    - title: Barns
      description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.
    - title: Private Events
      description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.
    - title: Food and Drinks
      description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.
    - title: Spa
      description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.
---
</code>```

This needs to work so that if the features array inside home.md's front matter is empty, then GraphQL doesn't throw an error.

Please don't tell me to always include at least one value in the array, because this isn't practical, my solution needs to support no values in my array.

I've spent two hours going through documentation/issues in circles trying to find a working solution, please can someone save me!

答:
From the GraphQL docs:

String! means that the field is non-nullable, meaning that the GraphQL service promises to always give you a value when you query this field. In the type language, we'll represent those with an exclamation mark.

[Episode!]! represents an array of Episode objects. Since it is also non-nullable, you can always expect an array (with zero or more items) when you query the field. And since Episode! is also non-nullable, you can always expect every item of the array to be an Episode object.

The exclamation point ! in GraphQL means non-nullable, so [String!]! means that there is a non-null array of non-null strings.

If you want a field to be optional, just leave it as it is without exclamation points !. For example [String] means that the array can be null, or any of the string values inside it can be null.

I'm also not sure that you want to be using an array in the first place, since title and description of a feature should surely just be a single string?

As per the Gatsby docs, I think what you're looking for is this:

```<code>const typeDefs = `
    type markdownRemark implements Node {
        // Use custom frontmatter type
        frontmatter: Frontmatter
    }
    // Define custom frontmatter type
    type FrontMatter {
      // Nullable array of Feature elements
      features: [Feature]
    }
    // Feature has nullable fields title and description
    type Feature {
        title: String
        description: String
    }
`;
</code>```

This means that frontmatter has a field called features that can be null (optional) and if it does exist, is an array of Feature objects. It can be empty, but if any Feature objects exist, each Feature has a nullable (optional) title and description field.

ContentLicense: CC BY-SA 4.0

Title: Allow optional GraphQL data in Gatsby

Body:
I'm trying to build a Type in my gatsby-node.js file that supports an optional value. Which I think is done with [String!]!.

How can I load the new Type that I've created inside gatsby-node.js on home.js?

gatsby-node.js:

const path = require('path');
exports.createSchemaCustomization = ({ actions }) => {
    const { createTypes } = actions;
    const typeDefs = `
        type markdownRemark implements Node {
            frontmatter: Features
        }
        type Features {
            title: [String!]!
            description: [String!]!
        }
    `;
    createTypes(typeDefs);
};

pages/home/home.js:

export const query = graphql`
    query HomeQuery($path: String!) {
        markdownRemark(frontmatter: { path: { eq: $path } }) {
            html
            frontmatter {
                features {
                    title
                    description
                }
            }
        }
    }
`;

home.md:

---
path: "/"
features:
    - title: Barns
      description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.
    - title: Private Events
      description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.
    - title: Food and Drinks
      description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.
    - title: Spa
      description: Praesent commodo cursus magna vel scelerisque nisl consectetur et. Nullam id dolor id nibh ultricies vehicula ut id elit.
---

This needs to work so that if the features array inside home.md's front matter is empty, then GraphQL doesn't throw an error.

Please don't tell me to always include at least one value in the array, because this isn't practical, my solution needs to support no values in my array.

I've spent two hours going through documentation/issues in circles trying to find a working solution, please can someone save me!

Body:
From the GraphQL docs:

String! means that the field is non-nullable, meaning that the GraphQL service promises to always give you a value when you query this field. In the type language, we'll represent those with an exclamation mark.

[Episode!]! represents an array of Episode objects. Since it is also non-nullable, you can always expect an array (with zero or more items) when you query the field. And since Episode! is also non-nullable, you can always expect every item of the array to be an Episode object.

The exclamation point ! in GraphQL means non-nullable, so [String!]! means that there is a non-null array of non-null strings.

If you want a field to be optional, just leave it as it is without exclamation points !. For example [String] means that the array can be null, or any of the string values inside it can be null.

I'm also not sure that you want to be using an array in the first place, since title and description of a feature should surely just be a single string?

As per the Gatsby docs, I think what you're looking for is this:

const typeDefs = `
    type markdownRemark implements Node {
        // Use custom frontmatter type
        frontmatter: Frontmatter
    }
    // Define custom frontmatter type
    type FrontMatter {
      // Nullable array of Feature elements
      features: [Feature]
    }
    // Feature has nullable fields title and description
    type Feature {
        title: String
        description: String
    }
`;

This means that frontmatter has a field called features that can be null (optional) and if it does exist, is an array of Feature objects. It can be empty, but if any Feature objects exist, each Feature has a nullable (optional) title and description field.


问:
Sending one more value via POST PHP
It's my first post so welcome!

I'm struggling with one problem in my project. As you can see at my screenshot, i have few names which are fetched from database, and displayed in main menu. after clicking "modal" button, modal from bootstrap is showed with php form. user can type a 4 digit pin code, next step is to match this pin with database records. But 2 users can have same pin so i need to compare not only pin with database, but name too. i don`t know how to send "name" value with post. Here is my code and screenshot:

index.php:

```<code>  <?php
 $data = $worker->select_workers();
$worker->show_workers($data);
$worker->show_modal();
</code>```

worker.php:

```<code><?php
require_once('db.php');
class Worker extends db {

protected $select_workers;
    public function select_workers(){

                return $this->select_workers = $this->query('SELECT * FROM worker')->fetchAll();
    }

    public function show_workers($data){
        foreach ($data as $users) {
    echo '<p id="p_name">'.$users['name'].'</p><a id="button_modal" href="/?name='.$users['name'].'" type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Modal
</a><br>';

}
}
    public function show_modal(){
echo '<!-- Button trigger modal -->

<!-- Modal -->
<form action="test.php" id="submit_ajax" method="post">
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="modal_title" name="name"></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <input id="hidden_name" type="text" value="" name="name" />
Hasło:<input type="text" name="password"><br>

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button  type="submit" class="btn btn-primary">Przerwa/powrót</button>
        </form>
      </div>
    </div>
  </div>
</div>';
    }
</code>```

Main menu of my application

I belive that solution is really simple but like always - i waste too many times for complicated things which are not working. Sorry for my english, it's not my native language :)
Thank you

答:
Not clean solution. make for every worker a modal.</p>

```<code><?php
require_once('db.php');
class Worker extends db {

protected $select_workers;
    public function select_workers(){

                return $this->select_workers = $this->query('SELECT * FROM worker')->fetchAll();
    }

    public function show_workers($data){
        $i=0;
        foreach ($data as $users) {
        $i++;
    echo '<p id="p_name">'.$users['name'].'</p><a id="button_modal" href="/?name='.$users['name'].'" type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal'.$i.'">
  Modal
</a><br>
<!-- Button trigger modal -->

<!-- Modal -->
<form action="test.php" id="submit_ajax" method="post">
<div class="modal fade" id="exampleModal'.$i.'" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="modal_title" name="name"></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <input id="hidden_name" type="text" value="'.$users['name'].'" name="name" />
Hasło:<input type="text" name="password"><br>

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button  type="submit" class="btn btn-primary">Przerwa/powrót</button>
        </form>
      </div>
    </div>
  </div>
</div>';
    }
</code>```

Title: Sending one more value via POST PHP

Body:
It's my first post so welcome!

I'm struggling with one problem in my project. As you can see at my screenshot, i have few names which are fetched from database, and displayed in main menu. after clicking "modal" button, modal from bootstrap is showed with php form. user can type a 4 digit pin code, next step is to match this pin with database records. But 2 users can have same pin so i need to compare not only pin with database, but name too. i don`t know how to send "name" value with post. Here is my code and screenshot:

index.php:

  <?php
 $data = $worker->select_workers();
$worker->show_workers($data);
$worker->show_modal();

worker.php:

<?php
require_once('db.php');
class Worker extends db {

protected $select_workers;
    public function select_workers(){

                return $this->select_workers = $this->query('SELECT * FROM worker')->fetchAll();
    }

    public function show_workers($data){
        foreach ($data as $users) {
    echo '
'.$users['name'].'

  Modal

';

}
}
    public function show_modal(){
echo '

<form action="test.php" id="submit_ajax" method="post">

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        <input id="hidden_name" type="text" value="" name="name" />
Hasło:<input type="text" name="password">

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button  type="submit" class="btn btn-primary">Przerwa/powrót</button>
        </form>

';
    }

Main menu of my application

I belive that solution is really simple but like always - i waste too many times for complicated things which are not working. Sorry for my english, it's not my native language :)
Thank you

Body:
Not clean solution. make for every worker a modal.

<?php
require_once('db.php');
class Worker extends db {

protected $select_workers;
    public function select_workers(){

                return $this->select_workers = $this->query('SELECT * FROM worker')->fetchAll();
    }

    public function show_workers($data){
        $i=0;
        foreach ($data as $users) {
        $i++;
    echo '<p id="p_name">'.$users['name'].'</p><a id="button_modal" href="/?name='.$users['name'].'" type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal'.$i.'">
  Modal
</a><br>
<!-- Button trigger modal -->

<!-- Modal -->
<form action="test.php" id="submit_ajax" method="post">
<div class="modal fade" id="exampleModal'.$i.'" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="modal_title" name="name"></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <input id="hidden_name" type="text" value="'.$users['name'].'" name="name" />
Hasło:<input type="text" name="password"><br>

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button  type="submit" class="btn btn-primary">Przerwa/powrót</button>
        </form>
      </div>
    </div>
  </div>
</div>';
    }


问:
Delete all lines after a specific line in PowerShell
I have this .txt file

```<code>ROTHSCHILD  = 81;        // Fondation Adolphe de Rothschild          ,                          2019
ONCOPOLE    = 82;        // Oncopole - Toulouse                      ,                          2019
GHRMSA      = 83;        // GHR  Mulhouse Sud-Alsace                 ,                          2019
CHDN        = 84;        // CH   du Nord - Luxembourg                ,                          2019
CAEN        = 85;        // CHU  de Caen                             ,                          2019
MONTELIMAR  = 86;        //                                          ,                          2019
PUYENVELAY  = 87;        //                                          ,                          2019
</code>```

I want delete all lines after

```<code>CHDN        = 84;        // CH   du Nord - Luxembourg                ,                          2019
</code>```

How can I do this ?

I tried this:

```<code>get-content txt.txt | % {$_ ; if($_ -eq "CHDN        = 84;        // CH   du Nord - Luxembourg                ,                          2019") {break }}
</code>```

but break end my program, how can I do this?

答:
but break ends my program

The reason is that break in a pipeline doesn't exit the pipeline, it exits any enclosing loop (foreach, for, do, and while statements), and if there is none, the script as a whole is exited.

This longstanding feature request on GitHub asks for introducing the ability to exit pipelines prematurely, but as of PowerShell [Core] 7.0 this feature doesn't exist.

However, you could simply modify your approach to use a foreach loop, where break works as expected:

```<code># The last line to include in the output.
$stopLine = 'CHDN        = 84;        // CH   du Nord - Luxembourg                ,                          2019'

# Output all lines up to and including the stop line.
# Simply assign to a variable to capture all output lines:
#   $linesOfInterest = foreach ($line ...) { ... }
# Or wrap in $(...) to send to a file.
#   $(foreach ($line ...) { ... }) | Set-Content ...
foreach ($line in Get-Content file.txt) {
  $line
  if($line -eq $stopLine) {break }
}
</code>```

Alternatively, use a regex-based solution that captures all lines of interest as a single, multi-line string (which you could split into lines with -split '\r?\n', if needed):

```<code># The last line to include in the output.
$stopLine = 'CHDN        = 84;        // CH   du Nord - Luxembourg                ,                          2019'

# Use the -match operator with a regex that that captures everything
# from the beginning of the the file through the stop line, inclusively.
if ((Get-Content -Raw file.txt) -match '(?sm).*^{0}$' -f [regex]::Escape($stopLine)) {
  # Output what was captured.
  # Append -split '\r?\n' to split into an array of lines.
  $Matches[0]
}
</code>```

(?sm) sets inline regex options s (make . match newlines too) and m (make ^ and $ match the ends and beginnings of individual lines)

.* matches any sequence of characters, including none

^{0}$ matches the escaped stop line (via [regex]::Escape(), to ensure that it is matched literally) in full, where {0} is the placeholder for the escaped line substituted by -f, the string formatting operator

If -match, the regular-expression matching operator, succeeds, it populates the automatic $Matches variable, whose 0 entry contains what the regex matched in full.

Body:
I have this .txt file

ROTHSCHILD  = 81;        // Fondation Adolphe de Rothschild          ,                          2019
ONCOPOLE    = 82;        // Oncopole - Toulouse                      ,                          2019
GHRMSA      = 83;        // GHR  Mulhouse Sud-Alsace                 ,                          2019
CHDN        = 84;        // CH   du Nord - Luxembourg                ,                          2019
CAEN        = 85;        // CHU  de Caen                             ,                          2019
MONTELIMAR  = 86;        //                                          ,                          2019
PUYENVELAY  = 87;        //                                          ,                          2019

I want delete all lines after

CHDN        = 84;        // CH   du Nord - Luxembourg                ,                          2019

How can I do this ?

I tried this:

get-content txt.txt | % {$_ ; if($_ -eq "CHDN        = 84;        // CH   du Nord - Luxembourg                ,                          2019") {break }}

but break end my program, how can I do this?

Body:
but break ends my program

The reason is that break in a pipeline doesn't exit the pipeline, it exits any enclosing loop (foreach, for, do, and while statements), and if there is none, the script as a whole is exited.

This longstanding feature request on GitHub asks for introducing the ability to exit pipelines prematurely, but as of PowerShell [Core] 7.0 this feature doesn't exist.

However, you could simply modify your approach to use a foreach loop, where break works as expected:

# The last line to include in the output.
$stopLine = 'CHDN        = 84;        // CH   du Nord - Luxembourg                ,                          2019'

# Output all lines up to and including the stop line.
# Simply assign to a variable to capture all output lines:
#   $linesOfInterest = foreach ($line ...) { ... }
# Or wrap in $(...) to send to a file.
#   $(foreach ($line ...) { ... }) | Set-Content ...
foreach ($line in Get-Content file.txt) {
  $line
  if($line -eq $stopLine) {break }
}

Alternatively, use a regex-based solution that captures all lines of interest as a single, multi-line string (which you could split into lines with -split '\r?\n', if needed):

# The last line to include in the output.
$stopLine = 'CHDN        = 84;        // CH   du Nord - Luxembourg                ,                          2019'

# Use the -match operator with a regex that that captures everything
# from the beginning of the the file through the stop line, inclusively.
if ((Get-Content -Raw file.txt) -match '(?sm).*^{0}$' -f [regex]::Escape($stopLine)) {
  # Output what was captured.
  # Append -split '\r?\n' to split into an array of lines.
  $Matches[0]
}

(?sm) sets inline regex options s (make . match newlines too) and m (make ^ and $ match the ends and beginnings of individual lines)

.* matches any sequence of characters, including none

^{0}$ matches the escaped stop line (via [regex]::Escape(), to ensure that it is matched literally) in full, where {0} is the placeholder for the escaped line substituted by -f, the string formatting operator

If -match, the regular-expression matching operator, succeeds, it populates the automatic $Matches variable, whose 0 entry contains what the regex matched in full.


问:
Capture the click event of dynamic Buttons in Bootstrap Modal using jquery
I hava Bootstrap model as below

```<code><div class="modal fade" id="PQModel" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title " id="exampleModalLongTitle"><strong>Priority Queue Selection</strong></h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">×</span>
          </button>
        </div>
        <div class="modal-body justify-content-center">
          <div id="modal-text"></div>
        </div>
        <div class="modal-footer justify-content-center">
          <button type="button" class="btn btn-danger cancel">Cancel</button>
        </div>
      </div>
    </div>
  </div>
</code>```

In this modal I am writing some dynamic buttons accoridng to the JSON response from server as below.

```<code>var scrn = '';
          $.each(pqueueList, function(index, val)
          {

              scrn += ' <div class="row justify-content-center top-buffer">';
              scrn += '   <div class="col-6">';
              scrn += '   <div class="btn btn-block';
              if (val["fieldType"] == "EVEN"){
                scrn += ' btn-primary ';
              }
              else{
                scrn += ' btn-success ';
              }
              scrn += '" value="'+val["pqId"]+'"><h2>'+val["pqName"]+'</h2></div>'
              scrn += '   </div>';
              scrn += '</div>';

          });
          $('#modal-text').html(scrn);
          $("#PQModel").modal('show');
        }
</code>```

I am driving to capture the click event on each of the button as below.

```<code>       $("#PQModel #modal-text div.btn").on('click',function(){
          var value = $(this).attr('value');
          alert("value "+ value);
        });
</code>```

The modal is coming as expected and buttons are coming as expected. But the click I am not able to capture button click event.I am not sure, where am I going wrong. Please help me solve it out.

答:
I suspect that binding of the objects for the click function is happening before you complete the generation and display of the objects. To make sure, replace your third code block with something simple like

console.log($("#PQModel #modal-text div.btn")),

and verify that at the time where this is called that objects are actually being selected

Body:
I hava Bootstrap model as below

Priority Queue Selection

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            ×
          </button>

          <button type="button" class="btn btn-danger cancel">Cancel</button>

In this modal I am writing some dynamic buttons accoridng to the JSON response from server as below.

var scrn = '';
          $.each(pqueueList, function(index, val)
          {

              scrn += '
';
              scrn += '
';
              scrn += '

'+val["pqName"]+'

'
              scrn += '
';
              scrn += '
';

          });
          $('#modal-text').html(scrn);
          $("#PQModel").modal('show');
        }

I am driving to capture the click event on each of the button as below.

       $("#PQModel #modal-text div.btn").on('click',function(){
          var value = $(this).attr('value');
          alert("value "+ value);
        });

The modal is coming as expected and buttons are coming as expected. But the click I am not able to capture button click event.I am not sure, where am I going wrong. Please help me solve it out.


问:
Render list - React - Javascript
I'm currently trying to render state

I see a few errors with declaring variables within the map loop.

Here is my attempt so far, Any help is welcomed

```<code>import React from "react";
import axios from "axios";

const transformHumanReadableDateToMessages = date => {
  let d = new Date(date);
  const days = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
  ];
  return {
    DayOfTheWeek: d.getDate(),
    Month: d.getMonth(),
    Day: days[d.getDay()],
    YearAtTime: d.getFullYear()
  };
};

export default class App extends React.Component {
  state = {
    messages: []
  };

  componentDidMount() {

    axios.get(`https://api.myjson.com/bins/10xva4`).then(res => {
      let result = res.data["messages"];
          result = Array.from(new Set(result.map(e => JSON.stringify(e))));
          result.reduce((accu, curr) => {
           curr.date = transformHumanReadableDateToMessages(curr["sentAt"]);
            accu.push(curr)
            return accu;
          }, []);

      this.setState({
        messages: result
      });
    });
  }

  render() {
return (
  <>
    { this.state.messages.map(message =>
       let d = new Date(date);
      const days = [
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday"
      ];
     <div className="container">
     <p>{message.content}<p/>
     <p>{message.senderUuid}</p>
     <p>DayOfTheWeek: {d.getDate()}
     <p>Month: {d.getMonth()}</p>
     <p>Day: {days[d.getDay()]}</p>
     <p>Year: {d.getFullYear()} </p>
     </div>
     )}
  </>
);
</code>```

}
    }

For example each element in the JSON that is returned looks like this:

```<code>{
  "sentAt":"2012-11-13T17:29:37.003Z",
  "uuid": "435453",
  "content": "1",
  "senderUuid": "2"
 }
</code>```

I want to make the date more readable then add it to the element for a output like this:

```<code>{
 "sentAt":"2012-11-13T17:29:37.003Z",
 "uuid": "435453",
 "content": "1",
 "senderUuid": "2",
 "DayOfTheWeek": 22,
  "Month": 4,
  "Day": 'Friday',
  "YearAtTime": 2015
 }
</code>```

答:
I can say you would need to understand map function properly.
Also, how to handle logic inside JSX.

First, You need to add return() function inside the map() function.
As long as you don't return all your content inside the map()
function, anything will not be rendered.

Second, You need to split variable assign outside of return function.
So that return() inside map() function will only have JSX element.
and other logic will be outside the return function body. Please take
a look at the below code.

Third, You also need to fix your typo for
 tags in the map
functions.

{message.content}
 <--- here typo : fix as

DayOfTheWeek</> doesn't have proper closing tag.

And last, You will need to handle if message is an empty array. so
that, if the message state is an empty array, you should render
something else.

The below example handles it.

```<code>import React from "react";
import "./styles.css";

 export default class App extends React.Component {
   state = {
    messages: []
   };

  componentDidMount() {
    //... your api call here
  }

render() {
  const { messages } = this.state;

  if (messages.length === 0) {
    return <p>No Message Found</p>;
  }

  messages.map(message => {
    let d = new Date();
    const days = [
      "Sunday",
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday"
    ];

    return (
      <div className="container">
        <p>{message.content}</p>
        <p>{message.senderUuid}</p>
        <p>DayOfTheWeek: {d.getDate()}</p>
        <p>Month: {d.getMonth()}</p>
        <p>Day: {days[d.getDay()]}</p>
        <p>Year: {d.getFullYear()} </p>
      </div>
    );
  });
}
</code>```

}

Title: Render list - React - Javascript

Body:
I'm currently trying to render state

I see a few errors with declaring variables within the map loop.

Here is my attempt so far, Any help is welcomed

import React from "react";
import axios from "axios";

const transformHumanReadableDateToMessages = date => {
  let d = new Date(date);
  const days = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
  ];
  return {
    DayOfTheWeek: d.getDate(),
    Month: d.getMonth(),
    Day: days[d.getDay()],
    YearAtTime: d.getFullYear()
  };
};

export default class App extends React.Component {
  state = {
    messages: []
  };

  componentDidMount() {

    axios.get(`https://api.myjson.com/bins/10xva4`).then(res => {
      let result = res.data["messages"];
          result = Array.from(new Set(result.map(e => JSON.stringify(e))));
          result.reduce((accu, curr) => {
           curr.date = transformHumanReadableDateToMessages(curr["sentAt"]);
            accu.push(curr)
            return accu;
          }, []);

      this.setState({
        messages: result
      });
    });
  }

  render() {
return (
  <>
    { this.state.messages.map(message =>
       let d = new Date(date);
      const days = [
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday"
      ];

{message.content}

{message.senderUuid}

DayOfTheWeek: {d.getDate()}

Month: {d.getMonth()}

Day: {days[d.getDay()]}

Year: {d.getFullYear()}

     )}
  </>
);

}
    }

For example each element in the JSON that is returned looks like this:

{
  "sentAt":"2012-11-13T17:29:37.003Z",
  "uuid": "435453",
  "content": "1",
  "senderUuid": "2"
 }

I want to make the date more readable then add it to the element for a output like this:

{
 "sentAt":"2012-11-13T17:29:37.003Z",
 "uuid": "435453",
 "content": "1",
 "senderUuid": "2",
 "DayOfTheWeek": 22,
  "Month": 4,
  "Day": 'Friday',
  "YearAtTime": 2015
 }

Body:
I can say you would need to understand map function properly.
Also, how to handle logic inside JSX.

First, You need to add return() function inside the map() function.
As long as you don't return all your content inside the map()
function, anything will not be rendered.

Second, You need to split variable assign outside of return function.
So that return() inside map() function will only have JSX element.
and other logic will be outside the return function body. Please take
a look at the below code.

Third, You also need to fix your typo for
 tags in the map
functions.

<p>{message.content}<p/> <--- here typo : fix as </p>

<p>DayOfTheWeek</> doesn't have proper closing tag.

And last, You will need to handle if message is an empty array. so
that, if the message state is an empty array, you should render
something else.

The below example handles it.

import React from "react";
import "./styles.css";

 export default class App extends React.Component {
   state = {
    messages: []
   };

  componentDidMount() {
    //... your api call here
  }

render() {
  const { messages } = this.state;

  if (messages.length === 0) {
    return <p>No Message Found</p>;
  }

  messages.map(message => {
    let d = new Date();
    const days = [
      "Sunday",
      "Monday",
      "Tuesday",
      "Wednesday",
      "Thursday",
      "Friday",
      "Saturday"
    ];

    return (
      <div className="container">
        <p>{message.content}</p>
        <p>{message.senderUuid}</p>
        <p>DayOfTheWeek: {d.getDate()}</p>
        <p>Month: {d.getMonth()}</p>
        <p>Day: {days[d.getDay()]}</p>
        <p>Year: {d.getFullYear()} </p>
      </div>
    );
  });
}

}


问:
how to read the output of a function as an object
Here is the output of my function sam() in HTML:

```<code>["2020-02-14", 324.7300, 325.9800, 322.8500, 324.9500, 20028447],
["2020-02-13", 324.1900, 326.2200, 323.3500, 324.8700, 23686892],
["2020-02-12", 321.4700, 327.2200, 321.4700, 327.2000, 28432573],
["2020-02-11", 323.6000, 323.9000, 318.7100, 319.6100, 23580780],
["2020-02-10", 314.1800, 321.5500, 313.8500, 321.5500, 27337215],
</code>```

I am trying to get that very output of sam() to be read as an object in this line of code below.

```<code>"data": [
           sam()   ],
</code>```

At the moment sam() in that location keeps outputting that above sequence of dates and price numbers. I need for sam() in that location to be read so that the above sequence would be integrated into the stock chart that I am working on. If I add all of that code as a non-string into the "data"[     ], it will print out the stock chart with the dates and prices, but when I simply use the function sam() in there, it doesn't print out the chart. It only does dates and numbers

答:
Here is the entire code that uses the sam() function. When you execute it, it will output a sequence of dates and numbers. When you copy and paste that output into the line of code near the bottom labeled "data" : [      ], it will output a nice looking stock chart using the dates and numbers. I need a function that can do the same.

```<code><html>

<head>
<script data-require="jquery@2.1.4" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
  <script data-require="highstock@0.0.1" data-semver="0.0.1" src="http://code.highcharts.com/stock/highstock.js"></script>
  <script data-require="highstock@0.0.1" data-semver="0.0.1" src="http://code.highcharts.com/stock/modules/exporting.js"></script>
    <title>
        How to get the array of dates between
        two dates in JavaScript ?
    </title>
</head>

<body style = "text-align:center;">
 <div id="myData"></div>

  <div id="demo"></div>
<div id="demo1"></div>
<script>var tday=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var tmonth=["-01-","-02-","-03-","-04-","-05-","-06-","-07-","-08-","-09-","-10-","-11-","-12-"];

function GetClock(){
var d=new Date();
var nday=d.getDay(),nmonth=d.getMonth(),ndate=d.getDate(),nyear=d.getFullYear();
var nhour=d.getHours(),nmin=d.getMinutes(),nsec=d.getSeconds(),ap;

if(nhour==0){ap=" AM";nhour=12;}
else if(nhour<12){ap=" AM";}
else if(nhour==12){ap=" PM";}
else if(nhour>12){ap=" PM";nhour-=12;}

if(nmin<=9) nmin="0"+nmin;
if(nsec<=9) nsec="0"+nsec;

var clocktext=""+nyear +tmonth[nmonth] +ndate +"";
document.getElementById('clockbox').innerHTML= clocktext;

}

GetClock();
setInterval(GetClock,1000);</script>

    <script>
function heavy(){
        var today = new Date("2014-10-01"); //YYYY-MM-DD

var startDate = new Date("2014-10-01");

var endDate = new Date("2016-10-10" );

     //YYYY-MM-DD

var getDateArray = function(start, end) {
    var arr = new Array();

     while (startDate < end) {
        arr.push(new Date(startDate));
        startDate.setDate(startDate.getDate() + 1);

    }

    return arr.reverse().toLocaleString().replace(new RegExp('/', 'g'), '-').replace(new RegExp("8:", 'g'), '').replace(new RegExp("00", 'g'), '').replace(new RegExp("PM", 'g'), '').replace(new RegExp("AM", 'g'), '').replace(new RegExp(",", 'g'), '').replace(new RegExp(":", 'g'), '');
}

var dateArr = getDateArray(startDate, endDate);

// Output

for (var i = 0; i < dateArr.length; i++) {

  document.write(  dateArr[i]   );

}

}
    </script>
<script>
function heavy1(){
  var cars = [["2020-02-13"], ["2020-02-12"]];
  var text = "";
  var i;
  for (i = 0; i < cars.length; i++) {
    text += cars[i] + "<br>";
  }
  document.getElementById("demo").innerHTML = text;}

</script>
<script>

    function sam(){
        fetch('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&outputsize=full&apikey=demo')
            .then(function (response) {
                return response.json();
            })
            .then(function (data) {
                appendData(data);
            })
            .catch(function (err) {
                console.log('error: ' + err);
            });

        function appendData(data) {
            var mainContainer = document.getElementById("myData");
var arrw = ["2020-02-14",
    "2020-02-13",
    "2020-02-12",
    "2020-02-11",
    "2020-02-10",
    "2020-02-07",
    "2020-02-06",
    "2020-02-05",
    "2020-02-04",
    "2020-02-03",
    "2020-01-31",
    "2020-01-30",
    "2020-01-29",
    "2020-01-28",
    "2020-01-27",
    "2020-01-24",
    "2020-01-23",
    "2020-01-22",
    "2020-01-21",];
            for (var i = 0; i < arrw.length; i++) {

               var joe = '[' +"\""+ arrw[i]+ "\"" +  "," + "     "  + data['Time Series (Daily)'][arrw[i]]['1. open']+"," + "   " +data['Time Series (Daily)'][arrw[i]]['2. high']+","  + "   " +data['Time Series (Daily)'][arrw[i]]['3. low']+","+ "   " +data['Time Series (Daily)'][arrw[i]]['4. close']+","+ "   " +data['Time Series (Daily)'][arrw[i]]['5. volume' ] + ']' +  ","  ;
                document.write(joe);

        }}}
    </script>
<div id="container"></div>
  <script>

    var json = {
      "dataset": {

        "data": [
          sam()
        ],

      }
    };

    var hiJson = json.dataset.data.map(function(d) {
      return [new Date(d[0]).getTime(), d[4]]
    });

    // Create the chart
    $('#container').highcharts('StockChart', {
      rangeSelector: {
        selected: 1
      },
      title: {
        text: 'MS Stock Price'
      },
      series: [{
        name: 'MS',
        data: hiJson,
        tooltip: {
          valueDecimals: 2
        }
      }]
    });
  </script>
</body>

</html>

</code>```

Body:
Here is the output of my function sam() in HTML:

["2020-02-14", 324.7300, 325.9800, 322.8500, 324.9500, 20028447],
["2020-02-13", 324.1900, 326.2200, 323.3500, 324.8700, 23686892],
["2020-02-12", 321.4700, 327.2200, 321.4700, 327.2000, 28432573],
["2020-02-11", 323.6000, 323.9000, 318.7100, 319.6100, 23580780],
["2020-02-10", 314.1800, 321.5500, 313.8500, 321.5500, 27337215],

I am trying to get that very output of sam() to be read as an object in this line of code below.

"data": [
           sam()   ],

At the moment sam() in that location keeps outputting that above sequence of dates and price numbers. I need for sam() in that location to be read so that the above sequence would be integrated into the stock chart that I am working on. If I add all of that code as a non-string into the "data"[     ], it will print out the stock chart with the dates and prices, but when I simply use the function sam() in there, it doesn't print out the chart. It only does dates and numbers

Body:
Here is the entire code that uses the sam() function. When you execute it, it will output a sequence of dates and numbers. When you copy and paste that output into the line of code near the bottom labeled "data" : [      ], it will output a nice looking stock chart using the dates and numbers. I need a function that can do the same.

<html>

<head>
<script data-require="jquery@2.1.4" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
  <script data-require="highstock@0.0.1" data-semver="0.0.1" src="http://code.highcharts.com/stock/highstock.js"></script>
  <script data-require="highstock@0.0.1" data-semver="0.0.1" src="http://code.highcharts.com/stock/modules/exporting.js"></script>
    <title>
        How to get the array of dates between
        two dates in JavaScript ?
    </title>
</head>

<body style = "text-align:center;">
 <div id="myData"></div>

  <div id="demo"></div>
<div id="demo1"></div>
<script>var tday=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var tmonth=["-01-","-02-","-03-","-04-","-05-","-06-","-07-","-08-","-09-","-10-","-11-","-12-"];

function GetClock(){
var d=new Date();
var nday=d.getDay(),nmonth=d.getMonth(),ndate=d.getDate(),nyear=d.getFullYear();
var nhour=d.getHours(),nmin=d.getMinutes(),nsec=d.getSeconds(),ap;

if(nhour==0){ap=" AM";nhour=12;}
else if(nhour<12){ap=" AM";}
else if(nhour==12){ap=" PM";}
else if(nhour>12){ap=" PM";nhour-=12;}

if(nmin<=9) nmin="0"+nmin;
if(nsec<=9) nsec="0"+nsec;

var clocktext=""+nyear +tmonth[nmonth] +ndate +"";
document.getElementById('clockbox').innerHTML= clocktext;

}

GetClock();
setInterval(GetClock,1000);</script>

    <script>
function heavy(){
        var today = new Date("2014-10-01"); //YYYY-MM-DD

var startDate = new Date("2014-10-01");

var endDate = new Date("2016-10-10" );

     //YYYY-MM-DD

var getDateArray = function(start, end) {
    var arr = new Array();

     while (startDate < end) {
        arr.push(new Date(startDate));
        startDate.setDate(startDate.getDate() + 1);

    }

    return arr.reverse().toLocaleString().replace(new RegExp('/', 'g'), '-').replace(new RegExp("8:", 'g'), '').replace(new RegExp("00", 'g'), '').replace(new RegExp("PM", 'g'), '').replace(new RegExp("AM", 'g'), '').replace(new RegExp(",", 'g'), '').replace(new RegExp(":", 'g'), '');
}

var dateArr = getDateArray(startDate, endDate);

// Output

for (var i = 0; i < dateArr.length; i++) {

  document.write(  dateArr[i]   );

}

}
    </script>
<script>
function heavy1(){
  var cars = [["2020-02-13"], ["2020-02-12"]];
  var text = "";
  var i;
  for (i = 0; i < cars.length; i++) {
    text += cars[i] + "<br>";
  }
  document.getElementById("demo").innerHTML = text;}

</script>
<script>

    function sam(){
        fetch('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&outputsize=full&apikey=demo')
            .then(function (response) {
                return response.json();
            })
            .then(function (data) {
                appendData(data);
            })
            .catch(function (err) {
                console.log('error: ' + err);
            });

        function appendData(data) {
            var mainContainer = document.getElementById("myData");
var arrw = ["2020-02-14",
    "2020-02-13",
    "2020-02-12",
    "2020-02-11",
    "2020-02-10",
    "2020-02-07",
    "2020-02-06",
    "2020-02-05",
    "2020-02-04",
    "2020-02-03",
    "2020-01-31",
    "2020-01-30",
    "2020-01-29",
    "2020-01-28",
    "2020-01-27",
    "2020-01-24",
    "2020-01-23",
    "2020-01-22",
    "2020-01-21",];
            for (var i = 0; i < arrw.length; i++) {

               var joe = '[' +"\""+ arrw[i]+ "\"" +  "," + "     "  + data['Time Series (Daily)'][arrw[i]]['1. open']+"," + "   " +data['Time Series (Daily)'][arrw[i]]['2. high']+","  + "   " +data['Time Series (Daily)'][arrw[i]]['3. low']+","+ "   " +data['Time Series (Daily)'][arrw[i]]['4. close']+","+ "   " +data['Time Series (Daily)'][arrw[i]]['5. volume' ] + ']' +  ","  ;
                document.write(joe);

        }}}
    </script>
<div id="container"></div>
  <script>

    var json = {
      "dataset": {

        "data": [
          sam()
        ],

      }
    };

    var hiJson = json.dataset.data.map(function(d) {
      return [new Date(d[0]).getTime(), d[4]]
    });

    // Create the chart
    $('#container').highcharts('StockChart', {
      rangeSelector: {
        selected: 1
      },
      title: {
        text: 'MS Stock Price'
      },
      series: [{
        name: 'MS',
        data: hiJson,
        tooltip: {
          valueDecimals: 2
        }
      }]
    });
  </script>
</body>

</html>


问:
Google Spreadsheet Query IF(ISBLANK(), PARSE_ERROR:
With this Query I get this result. The idea is i have a date of the product that is sold. When check if the date is between date_start and date_end of the marketing table, if so put that price in the marketingprice.

In some cases there is no end. This mean it's still running and has no end date. We still use them.
Because there is no end date I want to use the date of today. So if E (date_end) is empty , use the today date if not then use E

```<code>=query(Marketing!$B$2:E,
"select C,D  where  B='" & D2 & "' and
D<=date '"&TEXT(E2,"yyyy-MM-dd")&"' and
date'"&TEXT(today(),"yyyy-MM-dd")&"'>=date '"&TEXT(E2,"yyyy-MM-dd")&"' ")

+------------+---------------+--------+-----------------+----------+----------------+
| product_no | product_price | amount | deliver_country |  datum   | marketingprice |
+------------+---------------+--------+-----------------+----------+----------------+
|       1001 |           2.8 |      2 | de              | 2-1-2020 |                |
+------------+---------------+--------+-----------------+----------+----------------+
+-----+------------+
| 3.2 | 01-01-2020 |
| 1.2 | 02-01-2020 |
+-----+------------+
</code>```

I want to use IF(isblank(E),date'"&TEXT(TODAY(),"yyyy-MM-dd")&"', E)

Then the code will be

```<code>=query(Marketing!$B$2:E,
"select C,D  where  B='" & D2 & "' and
D<=date '"&TEXT(E2,"yyyy-MM-dd")&"' and
IF(isblank(E),date'"&TEXT(today(),"yyyy-MM-dd")&"',E)>=date '"&TEXT(E2,"yyyy-MM-dd")&"' ")
</code>```

Then I get a error:

QUERY: PARSE_ERROR: Encountered "  "IF "" at line 1, column 58.
  Was expecting one of: "(" ... "(" ...

Marketing Table

```<code>+---------+---------+-------+-------------+------------+
| channel | country | price | date_start  |  date_end  |
+---------+---------+-------+-------------+------------+
| Google  | de      |   3.2 | 01-01-2020  | 01-01-2020 |
| Google  | de      |   1.2 | 02-01-2020  |            |
| Amazon  | en      |   5.4 | 01-01-2020  |            |
+---------+---------+-------+-------------+------------+
</code>```

Output how it should be

```<code>+------------+---------------+--------+-----------------+----------+----------------+
| product_no | product_price | amount | deliver_country |  datum   | marketingprice |
+------------+---------------+--------+-----------------+----------+----------------+
|       1001 |           2.8 |      2 | de              | 2-1-2020 |            1.2 |
|       1002 |           3.8 |      4 | en              | 3-1-2020 |            5.4 |
|       1001 |           2.8 |      1 | de              | 1-1-2020 |            3.2 |
+------------+---------------+--------+-----------------+----------+----------------+
</code>```

In mysql I use this code :

```<code>b.start_date                <= date(i.system_created)                                           AND
coalesce(b.end_date,now())  >= date(i.system_created)
</code>```

Solution i found myself:

```<code>=QUERY(Marketing!$B$2:$E;IF(Marketing!E$2:E="";
"select E where  B ='"&D2&"' and D <=date'"&TEXT(E2;"yyyy-MM-dd")&"' and date'"&TEXT(VANDAAG();"yyyy-MM-dd")&"' >=date'"&TEXT(E2;"yyyy-MM-dd")&"' limit 1";
"select E where  B ='"&D2&"' and D <=date'"&TEXT(E2;"yyyy-MM-dd")&"' and E >=date'"&TEXT(E2;"yyyy-MM-dd")&"'"
);0)
</code>```

答:
try:</p>

```<code>=ARRAYFORMULA(IFERROR(QUERY(
 {Marketing!B$2:D\ IF(Marketing!E$2:E=""; TODAY(); Marketing!E$2:E)};
 "select Col2
  where Col1 = '"&D2&"'
    and Col3 <= date '"&TEXT(E2;"yyyy-MM-dd")&"'
    and Col4 <= "&TODAY()&"
  limit 1"; 0)))
</code>```

Body:
With this Query I get this result. The idea is i have a date of the product that is sold. When check if the date is between date_start and date_end of the marketing table, if so put that price in the marketingprice.

In some cases there is no end. This mean it's still running and has no end date. We still use them.
Because there is no end date I want to use the date of today. So if E (date_end) is empty , use the today date if not then use E

=query(Marketing!$B$2:E,
"select C,D  where  B='" & D2 & "' and
D<=date '"&TEXT(E2,"yyyy-MM-dd")&"' and
date'"&TEXT(today(),"yyyy-MM-dd")&"'>=date '"&TEXT(E2,"yyyy-MM-dd")&"' ")

+------------+---------------+--------+-----------------+----------+----------------+
| product_no | product_price | amount | deliver_country |  datum   | marketingprice |
+------------+---------------+--------+-----------------+----------+----------------+
|       1001 |           2.8 |      2 | de              | 2-1-2020 |                |
+------------+---------------+--------+-----------------+----------+----------------+
+-----+------------+
| 3.2 | 01-01-2020 |
| 1.2 | 02-01-2020 |
+-----+------------+

I want to use IF(isblank(E),date'"&TEXT(TODAY(),"yyyy-MM-dd")&"', E)

Then the code will be

=query(Marketing!$B$2:E,
"select C,D  where  B='" & D2 & "' and
D<=date '"&TEXT(E2,"yyyy-MM-dd")&"' and
IF(isblank(E),date'"&TEXT(today(),"yyyy-MM-dd")&"',E)>=date '"&TEXT(E2,"yyyy-MM-dd")&"' ")

Then I get a error:

QUERY: PARSE_ERROR: Encountered "  "IF "" at line 1, column 58.
  Was expecting one of: "(" ... "(" ...

Marketing Table

+---------+---------+-------+-------------+------------+
| channel | country | price | date_start  |  date_end  |
+---------+---------+-------+-------------+------------+
| Google  | de      |   3.2 | 01-01-2020  | 01-01-2020 |
| Google  | de      |   1.2 | 02-01-2020  |            |
| Amazon  | en      |   5.4 | 01-01-2020  |            |
+---------+---------+-------+-------------+------------+

Output how it should be

+------------+---------------+--------+-----------------+----------+----------------+
| product_no | product_price | amount | deliver_country |  datum   | marketingprice |
+------------+---------------+--------+-----------------+----------+----------------+
|       1001 |           2.8 |      2 | de              | 2-1-2020 |            1.2 |
|       1002 |           3.8 |      4 | en              | 3-1-2020 |            5.4 |
|       1001 |           2.8 |      1 | de              | 1-1-2020 |            3.2 |
+------------+---------------+--------+-----------------+----------+----------------+

In mysql I use this code :

b.start_date                <= date(i.system_created)                                           AND
coalesce(b.end_date,now())  >= date(i.system_created)

Solution i found myself:

=QUERY(Marketing!$B$2:$E;IF(Marketing!E$2:E="";
"select E where  B ='"&D2&"' and D <=date'"&TEXT(E2;"yyyy-MM-dd")&"' and date'"&TEXT(VANDAAG();"yyyy-MM-dd")&"' >=date'"&TEXT(E2;"yyyy-MM-dd")&"' limit 1";
"select E where  B ='"&D2&"' and D <=date'"&TEXT(E2;"yyyy-MM-dd")&"' and E >=date'"&TEXT(E2;"yyyy-MM-dd")&"'"
);0)

Body:
try:

=ARRAYFORMULA(IFERROR(QUERY(
 {Marketing!B$2:D\ IF(Marketing!E$2:E=""; TODAY(); Marketing!E$2:E)};
 "select Col2
  where Col1 = '"&D2&"'
    and Col3 <= date '"&TEXT(E2;"yyyy-MM-dd")&"'
    and Col4 <= "&TODAY()&"
  limit 1"; 0)))


问:
Does binding to ngValue set a max length on the string value it holds?
I have an ngFor directive bound to a list of objects with an option element. I bound the id property of the object to ngValue to be used later. The odd thing I've noticed is that when I get the value in the .ts file, part of the id is missing from the value I got from the database. When I use the value attribute instead, I get the whole id.

The picture shows the difference between the two attributes in the last 6 characters.

Anyone know why this is happening? Is there something about ng-reflect that limits the length of a string?

答:
I suppose the answer may be here:
What does the "ng-reflect-*" attribute do in Angular2/4?

As for me the better way to store such kind of properties is using data-attribute:

```<code><option [attr.data-id]="id"></option>
</code>```

Body:
I suppose the answer may be here:
What does the "ng-reflect-*" attribute do in Angular2/4?

As for me the better way to store such kind of properties is using data-attribute:

<option [attr.data-id]="id"></option>


问:
Xcode, Swift Could not cast value of type '__NSCFNumber' (0x7fff87c511a0) to 'NSString' (0x7fff87d0eee8)
Im facing with error : Could not cast value of type '__NSCFNumber' (0x7fff87c511a0) to 'NSString' (0x7fff87d0eee8).

```<code>the line : self.setNewMessagesCount(newMessagesCount: Int((Response["newMessagesCount"] as? String)!)!)
</code>```

what im doing wrong? (im using newer version of xcode)

thank you for help and have a good day! :)

答:
The phrase Int((Response["newMessagesCount"] as? String)!)! means:

look up the value for the key "newMessagesCount" in Response;

check whether that's a String, if so then keep a String reference to it, otherwise keep nil;

the first ! then says "oh, but I assume I didn't get nil even though I allowed for it just then, act as if I definitely have a reference to a String now, otherwise raise an exception";

the Int wrapping then attempts to parse what you've now guaranteed is a String to an Int;

the final ! then basically says: assume that conversion definitely worked, and raise an exception if not.

So you might at least neaten that to:

```<code>Int(Response["newMessagesCount"] as! String)!
</code>```

... but it looks like you're parsing content you've received from elsewhere, so actually the error is in using ! at all, anywhere, since you're failing to validate your input.

You probably want something more like:

```<code>if let newMessagesCountResponse = Response["newMessagesCount"] as? String,
   let newMessagesCount = Int(newMessagesCountResponse) {
   print("\(newMessagesCount) new messages")
} else {
   print("newMessagesCount wasn't present in the dictionary,",
         "or its value wasn't a string,",
         "or the string couldn't be parsed as an int")
}
</code>```

Body:
Im facing with error : Could not cast value of type '__NSCFNumber' (0x7fff87c511a0) to 'NSString' (0x7fff87d0eee8).

the line : self.setNewMessagesCount(newMessagesCount: Int((Response["newMessagesCount"] as? String)!)!)

what im doing wrong? (im using newer version of xcode)

thank you for help and have a good day! :)

Body:
The phrase Int((Response["newMessagesCount"] as? String)!)! means:

look up the value for the key "newMessagesCount" in Response;

check whether that's a String, if so then keep a String reference to it, otherwise keep nil;

the first ! then says "oh, but I assume I didn't get nil even though I allowed for it just then, act as if I definitely have a reference to a String now, otherwise raise an exception";

the Int wrapping then attempts to parse what you've now guaranteed is a String to an Int;

the final ! then basically says: assume that conversion definitely worked, and raise an exception if not.

So you might at least neaten that to:

Int(Response["newMessagesCount"] as! String)!

... but it looks like you're parsing content you've received from elsewhere, so actually the error is in using ! at all, anywhere, since you're failing to validate your input.

You probably want something more like:

if let newMessagesCountResponse = Response["newMessagesCount"] as? String,
   let newMessagesCount = Int(newMessagesCountResponse) {
   print("\(newMessagesCount) new messages")
} else {
   print("newMessagesCount wasn't present in the dictionary,",
         "or its value wasn't a string,",
         "or the string couldn't be parsed as an int")
}


问:
Move a button in the screen
I have an UIButton and I want to move that button by touching and swiping it in the screen. When I release the touch it will be in the current position. Explain clearly, please.

答:
You can move a view by using touch moved event. There is a sample tutorial MoveMe by Apple  which drags a view and after releasing the touch animate the view. Check specially the touch events (touchesBegan, touchesMoved, touchesEnded) in MoveMeView.m to get the idea how they have moved placardView. You can move your button just like the placardView.

Taken from 'drag' move a uibutton so it acts like uiScrollView

Title: Move a button in the screen


问:
What IP Ranges Are Used By The Azure Resource Manager When Reading Linked ARM Templates in Blob Containers
I have setup an Azure storage account, setting the Firewalls and virtual networks to allow access from Selected networks. The account is connected to a VNet and subnet where my self-hosted release VMs are connected. When attempting to execute a new deployment with linked ARM templates, the release VMs are able to upload the ARM templates to the blob containers and obtain a SAS token, but the Azure Resource Manager reports "Error: Code=InvalidContentLink; Message=Unable to download deployment content from 'https://...".

All of the Allow exceptions are enabled.

If I change the firewall setting back to All networks, the execution completes successfully.

Is there a list of IP address that I should add? For example, Azure DevOps publishes a similar list that I've had to use at https://learn.microsoft.com/en-us/azure/devops/organizations/security/allow-list-ip-url?view=azure-devops#ip-addresses-and-range-restrictions

答:
See: https://social.technet.microsoft.com/wiki/contents/articles/50886.azure-get-datacenter-ip-address-ranges-via-api.aspx

One challenge here is that there are more IP ranges than we allow whitelisting for, so you need to restrict somehow (e.g. location) for this to work well in prod.  We're working on an alternative solution but don't have an ETA yet.

One option some customers use is to have a separate storage account used only for staging when the files are transient.  That doesn't work for all scenarios (e.g. longer term sharing of files) but may offer some short-term relief.  Happy to chat offline in more detail about options here if it helps.


问:
How to create a new .txt file on Mac when using CLion
How do I create a .txt file in cLion compiler?</p>

答:
found the answer
control+click on folder </p>


问:
Cannot decide about condition in while loop
I am making a program about inputting 'n' number of integers from the user and calculating the even and odd sums respectively. However, I am being confused about the condition I should put in while loop. Other than that the sums of even and odd numbers are being calculated perfectly.</p>

```<code>#include <stdio.h>
int main()
{
    int i, n, number, sum = 0, summ = 0, count;
    printf("Enter Number of Integers:");
    scanf("%d", &n);
    while (i <= n)
    {
        i = number;
        printf("Enter Number:");
        scanf("%d", &number);
        i++;
        if (number % 2 == 0)
        {
            sum = sum + number;
            number++;
        }
        else if (number % 2 != 0)
        {
            summ = summ + number;
            number++;
        }
    }
    printf("Sum of Even Numbers: %d", sum);
    printf("\nSum of Odd Numbers: %d", summ);
}
</code>```

答:
For starters it is better to declare the variable that holds the number of integers as having the type unsigned int.

For example

```<code>unsigned int n = 0;

printf( "Enter Number of Integers: " );
scanf( "%u", &n );
</code>```

then the loop can look like

```<code>int success = 1;

while ( success && n-- )
{
    int number;

    printf( "Enter Number: " );
    success = scanf( "%d", &number ) == 1;

    if ( success )
    {
        if ( number % 2 == 0 ) sum += number;
        else summ += number;
    }
}

printf( "Sum of Even Numbers: %d\n", sum );
printf("\nSum of Odd Numbers: %d\n", summ );
</code>```

Pay attention to that the user can interrupt the input. You should process such a case in the program.

Here is a demonstrative program.

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

int main(void)
{
    int sum = 0, summ = 0;
    unsigned int n = 0;

    printf( "Enter Number of Integers: " );
    scanf( "%u", &n );

    int success = 1;

    while ( success && n-- )
    {
        int number;

        printf( "Enter Number: " );
        success = scanf( "%d", &number ) == 1;

        if ( success )
        {
            if ( number % 2 == 0 ) sum += number;
            else summ += number;
        }
    }

    printf( "\nSum of Even Numbers: %d\n", sum );
    printf( "Sum of Odd Numbers: %d\n", summ );
}
</code>```

Its output might look like

```<code>Enter Number of Integers: 10
Enter Number: 1
Enter Number: 2
Enter Number: 3
Enter Number: 4
Enter Number: 5
Enter Number: 6
Enter Number: 7
Enter Number: 8
Enter Number: 9
Enter Number: 10

Sum of Even Numbers: 30

Sum of Odd Numbers: 25
</code>```

Body:
I am making a program about inputting 'n' number of integers from the user and calculating the even and odd sums respectively. However, I am being confused about the condition I should put in while loop. Other than that the sums of even and odd numbers are being calculated perfectly.

#include <stdio.h>
int main()
{
    int i, n, number, sum = 0, summ = 0, count;
    printf("Enter Number of Integers:");
    scanf("%d", &n);
    while (i <= n)
    {
        i = number;
        printf("Enter Number:");
        scanf("%d", &number);
        i++;
        if (number % 2 == 0)
        {
            sum = sum + number;
            number++;
        }
        else if (number % 2 != 0)
        {
            summ = summ + number;
            number++;
        }
    }
    printf("Sum of Even Numbers: %d", sum);
    printf("\nSum of Odd Numbers: %d", summ);
}

Body:
For starters it is better to declare the variable that holds the number of integers as having the type unsigned int.

For example

unsigned int n = 0;

printf( "Enter Number of Integers: " );
scanf( "%u", &n );

then the loop can look like

int success = 1;

while ( success && n-- )
{
    int number;

    printf( "Enter Number: " );
    success = scanf( "%d", &number ) == 1;

    if ( success )
    {
        if ( number % 2 == 0 ) sum += number;
        else summ += number;
    }
}

printf( "Sum of Even Numbers: %d\n", sum );
printf("\nSum of Odd Numbers: %d\n", summ );

Pay attention to that the user can interrupt the input. You should process such a case in the program.

Here is a demonstrative program.

#include <stdio.h>

int main(void)
{
    int sum = 0, summ = 0;
    unsigned int n = 0;

    printf( "Enter Number of Integers: " );
    scanf( "%u", &n );

    int success = 1;

    while ( success && n-- )
    {
        int number;

        printf( "Enter Number: " );
        success = scanf( "%d", &number ) == 1;

        if ( success )
        {
            if ( number % 2 == 0 ) sum += number;
            else summ += number;
        }
    }

    printf( "\nSum of Even Numbers: %d\n", sum );
    printf( "Sum of Odd Numbers: %d\n", summ );
}

Its output might look like

Enter Number of Integers: 10
Enter Number: 1
Enter Number: 2
Enter Number: 3
Enter Number: 4
Enter Number: 5
Enter Number: 6
Enter Number: 7
Enter Number: 8
Enter Number: 9
Enter Number: 10

Sum of Even Numbers: 30

Sum of Odd Numbers: 25


问:
Is there a way to interchange mathematical operators in a while or for loop?
I am trying to write a program in C to try out how 6 numbers, that get input by the user (that's no problem so far), are combined in every possible way.

I tried using the search function but I am not quite sure what to look for.

It should do kind of like that:

...
temp[i] = a + b + c + d - e - f;
i++;
temp[i] = a + b + c - d - e - f;
i++;
temp[i] = a + b - c - d - e - f;
i++;
...
```

Also with multiplying and dividing.

It would be nice to also implement all ways of putting in brackets and not using all the numbers.

So like brute forcing all possible results from these numbers.

Is there any way to achieve this without coding in every combination by hand?

答:
Here is a simple solution to print and evaluate all combinations of the 4 operators +, -, * and / between the numbers. For this code, all operators have the same precedence.

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

void print_combination(unsigned mask, int *values, int n) {
    int x = values[0];
    printf("%d", values[0]);
    for (int i = 1; i < n; i++, mask /= 4) {
        switch (mask % 4) {
        case 0: x += values[i]; printf(" + %d", values[i]); break;
        case 1: x -= values[i]; printf(" - %d", values[i]); break;
        case 2: x *= values[i]; printf(" * %d", values[i]); break;
        case 3: x /= values[i]; printf(" / %d", values[i]); break;
        }
    }
    printf(" = %d\n", x);
}

int main(int argc, char *argv[]) {
    int n = argc - 1;
    int values[n];
    for (int i = 0; i < n; i++) {
        values[i] = strtol(argv[i + 1], NULL, 0);
    }
    for (unsigned i = 0, mask = 1U << (2 * (n - 1)); i < mask; i++) {
        print_combination(i, values, n);
    }
    return 0;
}
```

<p>Here is a more elaborated version that handles all permutations of the data set:</p>

<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <stdlib.h>

void print_combination(unsigned mask, int *values, int n) {
    int x = values[0];
    printf("%d", values[0]);
    for (int i = 1; i < n; i++, mask /= 4) {
        switch (mask % 4) {
        case 0: x += values[i]; printf(" + %d", values[i]); break;
        case 1: x -= values[i]; printf(" - %d", values[i]); break;
        case 2: x *= values[i]; printf(" * %d", values[i]); break;
        case 3: x /= values[i]; printf(" / %d", values[i]); break;
        }
    }
    printf(" = %d\n", x);
}

unsigned print_combinations(int *values, int n) {
    unsigned i, mask;
    for (i = 0, mask = 1U << (2 * (n - 1)); i < mask; i++) {
        print_combination(i, values, n);
    }
    return mask;
}

unsigned perm(const int *src, int len, int *dest, int *bits, int n) {
    if (n == len) {
        return print_combinations(dest, len);
    } else {
        unsigned count = 0;
        for (int i = 0; i < len; i++) {
            if (bits[i] == 0) {
                bits[i] = 1;
                dest[n] = src[i];
                count += perm(src, len, dest, bits, n + 1);
                bits[i] = 0;
            }
        }
        return count;
    }
}

int main(int argc, char *argv[]) {
    int n = argc - 1;
    int values[n], dest[n], bits[n];
    for (int i = 0; i < n; i++) {
        values[i] = strtol(argv[i + 1], NULL, 0);
        bits[i] = 0;
    }
    printf("%u combinations\n", perm(values, n, dest, bits, 0));
    return 0;
}
</code>```

Body:
I am trying to write a program in C to try out how 6 numbers, that get input by the user (that's no problem so far), are combined in every possible way.

I tried using the search function but I am not quite sure what to look for.

It should do kind of like that:

...
temp[i] = a + b + c + d - e - f;
i++;
temp[i] = a + b + c - d - e - f;
i++;
temp[i] = a + b - c - d - e - f;
i++;
...

Also with multiplying and dividing.

It would be nice to also implement all ways of putting in brackets and not using all the numbers.

So like brute forcing all possible results from these numbers.

Is there any way to achieve this without coding in every combination by hand?

Body:
Here is a simple solution to print and evaluate all combinations of the 4 operators +, -, * and / between the numbers. For this code, all operators have the same precedence.

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

void print_combination(unsigned mask, int *values, int n) {
    int x = values[0];
    printf("%d", values[0]);
    for (int i = 1; i < n; i++, mask /= 4) {
        switch (mask % 4) {
        case 0: x += values[i]; printf(" + %d", values[i]); break;
        case 1: x -= values[i]; printf(" - %d", values[i]); break;
        case 2: x *= values[i]; printf(" * %d", values[i]); break;
        case 3: x /= values[i]; printf(" / %d", values[i]); break;
        }
    }
    printf(" = %d\n", x);
}

int main(int argc, char *argv[]) {
    int n = argc - 1;
    int values[n];
    for (int i = 0; i < n; i++) {
        values[i] = strtol(argv[i + 1], NULL, 0);
    }
    for (unsigned i = 0, mask = 1U << (2 * (n - 1)); i < mask; i++) {
        print_combination(i, values, n);
    }
    return 0;
}

Here is a more elaborated version that handles all permutations of the data set:

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

void print_combination(unsigned mask, int *values, int n) {
    int x = values[0];
    printf("%d", values[0]);
    for (int i = 1; i < n; i++, mask /= 4) {
        switch (mask % 4) {
        case 0: x += values[i]; printf(" + %d", values[i]); break;
        case 1: x -= values[i]; printf(" - %d", values[i]); break;
        case 2: x *= values[i]; printf(" * %d", values[i]); break;
        case 3: x /= values[i]; printf(" / %d", values[i]); break;
        }
    }
    printf(" = %d\n", x);
}

unsigned print_combinations(int *values, int n) {
    unsigned i, mask;
    for (i = 0, mask = 1U << (2 * (n - 1)); i < mask; i++) {
        print_combination(i, values, n);
    }
    return mask;
}

unsigned perm(const int *src, int len, int *dest, int *bits, int n) {
    if (n == len) {
        return print_combinations(dest, len);
    } else {
        unsigned count = 0;
        for (int i = 0; i < len; i++) {
            if (bits[i] == 0) {
                bits[i] = 1;
                dest[n] = src[i];
                count += perm(src, len, dest, bits, n + 1);
                bits[i] = 0;
            }
        }
        return count;
    }
}

int main(int argc, char *argv[]) {
    int n = argc - 1;
    int values[n], dest[n], bits[n];
    for (int i = 0; i < n; i++) {
        values[i] = strtol(argv[i + 1], NULL, 0);
        bits[i] = 0;
    }
    printf("%u combinations\n", perm(values, n, dest, bits, 0));
    return 0;
}


答:
"Limit the size of the value as otherwise the DOM just gets polluted."
https://github.com/angular/angular/blob/master/packages/core/src/util/ng_reflect.ts

Generally ngValue is used for objects.

Title: Does binding to ngValue set a max length on the string value it holds?

Body:
I have an ngFor directive bound to a list of objects with an option element. I bound the id property of the object to ngValue to be used later. The odd thing I've noticed is that when I get the value in the .ts file, part of the id is missing from the value I got from the database. When I use the value attribute instead, I get the whole id.

The picture shows the difference between the two attributes in the last 6 characters.

Anyone know why this is happening? Is there something about ng-reflect that limits the length of a string?


问:
Style appliance in combobox
I have simple window:

```<code><Window.Resources>
    <Style TargetType="{x:Type TextBlock}">
        <Setter Property="Foreground" Value="Red"/>
    </Style>
</Window.Resources>

<StackPanel>
    <ComboBox VerticalAlignment="Top" HorizontalAlignment="Left">
        <ComboBoxItem IsSelected="True" Content="1"/>
        <ComboBoxItem Content="2"/>
        <ComboBoxItem Content="3"/>
    </ComboBox>
</StackPanel>
</code>```

But this style is not applyed to combobox. If I move it to app.xaml it starts works.
Could someone to explain this strange behaviour?

答:
You can do like this</p>

```<code>    <Window.Resources>
<Style TargetType="{x:Type Control}" x:Key="TextStyle">
            <Setter Property="Foreground" Value="Red"/>
        </Style>
        <Style TargetType="{x:Type ComboBox}" BasedOn="{StaticResource TextStyle}">
        </Style>
    </Window.Resources>
</code>```

Title: Style appliance in combobox

Body:
I have simple window:

<Window.Resources>

</Window.Resources>

<StackPanel>
    <ComboBox VerticalAlignment="Top" HorizontalAlignment="Left">
        <ComboBoxItem IsSelected="True" Content="1"/>
        <ComboBoxItem Content="2"/>
        <ComboBoxItem Content="3"/>
    </ComboBox>
</StackPanel>

But this style is not applyed to combobox. If I move it to app.xaml it starts works.
Could someone to explain this strange behaviour?

Body:
You can do like this

    <Window.Resources>
<Style TargetType="{x:Type Control}" x:Key="TextStyle">
            <Setter Property="Foreground" Value="Red"/>
        </Style>
        <Style TargetType="{x:Type ComboBox}" BasedOn="{StaticResource TextStyle}">
        </Style>
    </Window.Resources>


问:
Not all properties visible in Visual Studio IntelliSense for UIAutomation's AutomationElement class
The docs page for AutomationElement class at Microsoft indicates that the class has six properties.  In my Visual Studio C# solution, IntelliSense shows only four; FocusedElement and RootElement are missing.  When I look at the metadata, the properties are listed, so that tells me the documentation is not out-of-date:

I tried it in the Immediate window, and the result is the same, showing only four out of six properties:

Am I doing something wrong?  If not, why is this happening?

I am on Windows 10 Professional using Visual Studio 2019 Enterprise with the latest build.

答: The two missing properties are static and they are not accessible by the class object.


答:
You're attaching a click event before the DOM elements exist. This means the event listener is attaching to nothing.

You would want to use event delegation to properly handle this situation. This attaches an event listener to the parent container, and whenever there is a click inside of it, it determines if the element matches the secondary selector provided (div.btn)

```<code> $("#PQModel #modal-text").on('click','div.btn', function(){
          var value = $(this).attr('value');
          alert("value "+ value);
 });
</code>```

Event Delegation JQuery Docs

Title: Capture the click event of dynamic Buttons in Bootstrap Modal using jquery

Body:
I hava Bootstrap model as below

Priority Queue Selection

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            ×
          </button>

          <button type="button" class="btn btn-danger cancel">Cancel</button>

In this modal I am writing some dynamic buttons accoridng to the JSON response from server as below.

var scrn = '';
          $.each(pqueueList, function(index, val)
          {

              scrn += '
';
              scrn += '
';
              scrn += '

'+val["pqName"]+'

'
              scrn += '
';
              scrn += '
';

          });
          $('#modal-text').html(scrn);
          $("#PQModel").modal('show');
        }

I am driving to capture the click event on each of the button as below.

       $("#PQModel #modal-text div.btn").on('click',function(){
          var value = $(this).attr('value');
          alert("value "+ value);
        });

The modal is coming as expected and buttons are coming as expected. But the click I am not able to capture button click event.I am not sure, where am I going wrong. Please help me solve it out.

Body:
You're attaching a click event before the DOM elements exist. This means the event listener is attaching to nothing.

You would want to use event delegation to properly handle this situation. This attaches an event listener to the parent container, and whenever there is a click inside of it, it determines if the element matches the secondary selector provided (div.btn)

 $("#PQModel #modal-text").on('click','div.btn', function(){
          var value = $(this).attr('value');
          alert("value "+ value);
 });

Event Delegation JQuery Docs


问:
VBA generating a random unique alpha-numeric string
I need to create a Unique-ID (string) for each record as I am developing an application which allows users to access a unique URL like:

http://URL.com/BXD31F

The code below works to create the URLIDs:

```<code>Public Function getURLID(ID As Double) As String

Randomize
Dim rgch As String
rgch = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"

Dim i As Long
For i = 1 To 5
    getURLID = getURLID & Mid$(rgch, Int(Rnd() * Len(rgch) + 1), 1)
Next

End Function
</code>```

How can I ensure that the URLID created is unique?  Do I need to query the database to ensure it has not been generated before?  The table has 5 million records.  A dlookup query would exceed the limitations of my MSAccess database.

I have considered using the timestring to generate the URLID:

```<code> Format(Now, "yymmddhhmmss")
</code>```

However, I only want a simple 5 character string.

答:
I managed to solve my own problem.  We need to check to see if the URLID already exists in the table.  The challenge is that the URLID is not written into the table until the query has completely executed.  Using 6 of the possible 24 characters will give us about 191 million possibilities (24 to the power of 6). As we only need to create 5 million IDs, there is a small chance for duplicate records.

This is how I did it:

Step 1 - Generate Random a URLID for the 5 million rows using the original code

Step 2 - Identify duplicates and update to null using query below

```<code> UPDATE URLIDs SET URLIDs.URL = Null
 WHERE (((URLIDs.URL) In (SELECT [URL] FROM [URLIDs] As Tmp GROUP BY [URL] HAVING
 Count(*)>1 )));
</code>```

Step 3 - Generate new URLID for the nulls identified in Step 2.  This time, checking to see if they already exist in the table.  See code below:

```<code>Public Function getURLID(roll As Double) As String
Randomize
Dim rgch As String
rgch = "ABCDEFGHJKLMNPQRSTUVWXYZ"
Dim i As Long

For i = 1 To 6
        getURLID = getURLID & Mid$(rgch, Int(Rnd() * Len(rgch) + 1), 1)
Next

Do Until URLIDExists(getURLID) = False
    getURLID = ""

    For i = 1 To 6
        getURLID = getURLID & Mid$(rgch, Int(Rnd() * Len(rgch) + 1), 1)
    Next
Loop
End Function
</code>```

Function below used to see if URL exists

```<code>Public Function URLIDExists(URLID As String) As Boolean
Dim RS1
Dim strQuery As String
strQuery = "SELECT * from [URLIDs] where [URL]='" & URLID & "'"
Set RS1 = CurrentDb.OpenRecordset(strQuery)
If RS1.RecordCount > 0 Then
URLIDExists = True
Else
URLIDExists = False
End If
Set RS1 = Nothing
End Function
</code>```

I repeated steps 2 and 3 until there are were no more duplicates.  Each time checking against the existence of the already confirmed URLID.  Eventually there will be no more duplicate URLIDs.

Body:
I need to create a Unique-ID (string) for each record as I am developing an application which allows users to access a unique URL like:

http://URL.com/BXD31F

The code below works to create the URLIDs:

Public Function getURLID(ID As Double) As String

Randomize
Dim rgch As String
rgch = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"

Dim i As Long
For i = 1 To 5
    getURLID = getURLID & Mid$(rgch, Int(Rnd() * Len(rgch) + 1), 1)
Next

End Function

How can I ensure that the URLID created is unique?  Do I need to query the database to ensure it has not been generated before?  The table has 5 million records.  A dlookup query would exceed the limitations of my MSAccess database.

I have considered using the timestring to generate the URLID:

 Format(Now, "yymmddhhmmss")

However, I only want a simple 5 character string.

Body:
I managed to solve my own problem.  We need to check to see if the URLID already exists in the table.  The challenge is that the URLID is not written into the table until the query has completely executed.  Using 6 of the possible 24 characters will give us about 191 million possibilities (24 to the power of 6). As we only need to create 5 million IDs, there is a small chance for duplicate records.

This is how I did it:

Step 1 - Generate Random a URLID for the 5 million rows using the original code

Step 2 - Identify duplicates and update to null using query below

 UPDATE URLIDs SET URLIDs.URL = Null
 WHERE (((URLIDs.URL) In (SELECT [URL] FROM [URLIDs] As Tmp GROUP BY [URL] HAVING
 Count(*)>1 )));

Step 3 - Generate new URLID for the nulls identified in Step 2.  This time, checking to see if they already exist in the table.  See code below:

Public Function getURLID(roll As Double) As String
Randomize
Dim rgch As String
rgch = "ABCDEFGHJKLMNPQRSTUVWXYZ"
Dim i As Long

For i = 1 To 6
        getURLID = getURLID & Mid$(rgch, Int(Rnd() * Len(rgch) + 1), 1)
Next

Do Until URLIDExists(getURLID) = False
    getURLID = ""

    For i = 1 To 6
        getURLID = getURLID & Mid$(rgch, Int(Rnd() * Len(rgch) + 1), 1)
    Next
Loop
End Function

Function below used to see if URL exists

Public Function URLIDExists(URLID As String) As Boolean
Dim RS1
Dim strQuery As String
strQuery = "SELECT * from [URLIDs] where [URL]='" & URLID & "'"
Set RS1 = CurrentDb.OpenRecordset(strQuery)
If RS1.RecordCount > 0 Then
URLIDExists = True
Else
URLIDExists = False
End If
Set RS1 = Nothing
End Function

I repeated steps 2 and 3 until there are were no more duplicates.  Each time checking against the existence of the already confirmed URLID.  Eventually there will be no more duplicate URLIDs.


问:
Unity - trying to add items at specific locations in Mapbox
I´ve followed a tutorial on YouTube where the developer added items spawning around the player at a certain interval with a max distance on the tile in MapBox. What I am trying to achieve is to add them at specific longitude and latitudes.

The changes I made was to to loop through the max amount of items I want to add, incrementing an i variable. Then instead of spawning the item around the player like newLat = getPlayerPosition() + random; I hardcoded the lat and lon like: case 0: newLat = 48.30791f; newLon = 18.08611f; millenium_item.tag = "MI0"; break;

And each item is added to a list of items.
The behaviour I am expecting is to add each item to the list and then spawn them on the map, but instead only one item gets added, the one that has the exact same latitude and longitude as the player:

```<code>case 3: newLat = 48.32232f; newLon = 18.09462f; millenium_item.tag = "MI3"; break;
</code>```

Case 3 gets added as it has the same Lat and Lon as my player (where the phone actually is).

```<code>case 4: newLat = 48.32232f; newLon = 18.09538f; millenium_item.tag = "MI4"; break;
</code>```

Case 4 doesnt get added, but as you can see it is pretty close to the location of Case 3.

I dont know what I am doing wrong. Full code:

```<code>void SpawnItems() {

        itemindex = 100;
        for(int i = 0; i < count; i++)
        {
            if (googleSignIn.locationdata[i] == false)
            {
            MilleniumItemType type = (MilleniumItemType)(int)UnityEngine.Random.Range(0, Enum.GetValues(typeof(MilleniumItemType)).Length);
            float newLat = 0;
            float newLon = 0;

            MilleniumPuzzle prefab = Resources.Load("MilleniumItems/puzzle", typeof(MilleniumPuzzle)) as MilleniumPuzzle;
            MilleniumPuzzle millenium_item = Instantiate(prefab, Vector3.zero, Quaternion.Euler(-100, 0, 0)) as MilleniumPuzzle;
            millenium_item.tileManager = tileManager;

                switch (i)
                {
                     ...
                case 3: newLat = 48.32232f; newLon = 18.09462f; millenium_item.tag = "MI3"; break;
                case 4: newLat = 48.32232f; newLon = 18.09538f; millenium_item.tag = "MI4"; break;
                case 5: newLat = 48.32310f; newLon = 18.09536f; millenium_item.tag = "MI5"; break;
                     ...
                }
                /// OUR LAT: 48.32232 OUR LON: 18.09462

                    millenium_item.Init(newLat, newLon);
                    items.Add(millenium_item);
        }
        }
</code>```

Then Init looks like this:

```<code>public void Init(float _lat, float _lon) {
    lat = _lat;
    lon = _lon;
    UpdatePosition ();
}
</code>```

and:

```<code>public void UpdatePosition() {
    float x, y;
    Vector3 position = Vector3.zero;

    geodeticOffsetInv (tileManager.getLat * Mathf.Deg2Rad, tileManager.getLon * Mathf.Deg2Rad, lat * Mathf.Deg2Rad, lon * Mathf.Deg2Rad, out x, out y);

    if ((lat - tileManager.getLat) < 0 && (lon - tileManager.getLon) > 0 || (lat - tileManager.getLat) > 0 && (lon - tileManager.getLon) < 0) {
        position = new Vector3(x, .5f, y);
    }
    else {
        position = new Vector3 (-x, .5f, -y);
    }

    position.x *= 0.300122f;
    position.z *= 0.123043f;

    Debug.Log("Position of inited millenium puzzle: " + position.x + " z: " + position.z);

    transform.position = position;
}
</code>```

答:
I was able to solve the issue myself. Adding the items at exact coordinates never worked, so instead I am saving the item coordinates in an array. Then in update() I am comparing the position of the player with the coordinates where the items should be. If the difference between the positions are between constant numbers that I defined, then the items will appear around the player, although not exactly at the building, but in my case I don´t mind.
Example:

```<code>   `public void SpawnItems() {

    itemindex = 100;
    for(int i = 0; i < count; i++)
    {

        if (googleSignIn.locationdata[i] == false && spawnedItem[i] == false)
        {
            if(tileManager.getLat - itemLats[i] < 0.003f && tileManager.getLat - itemLats[i] > -0.003f && tileManager.getLon - itemLons[i] < 0.00103f && tileManager.getLon - itemLons[i] > -0.00103f)
            {
                    MilleniumItemType type = (MilleniumItemType)(int)UnityEngine.Random.Range(0, Enum.GetValues(typeof(MilleniumItemType)).Length);

                    MilleniumPuzzle prefab = Resources.Load("MilleniumItems/puzzle", typeof(MilleniumPuzzle)) as MilleniumPuzzle;
                    MilleniumPuzzle millenium_item = Instantiate(prefab, Vector3.zero, Quaternion.Euler(-100, 0, 0)) as MilleniumPuzzle;
                    millenium_item.tileManager = tileManager;

                    float newLat = tileManager.getLat + UnityEngine.Random.Range(-0.0001f, 0.0001f);
                    float newLon = tileManager.getLon + UnityEngine.Random.Range(-0.0001f, 0.0001f);

                    if(newLat == previousLat || newLon == previousLon)
                {
                     newLat = tileManager.getLat + UnityEngine.Random.Range(-0.0001f, 0.0001f);
                     newLon = tileManager.getLon + UnityEngine.Random.Range(-0.0001f, 0.0001f);
                }

                previousLon = newLon;
                previousLat = newLat;

                    spawnedItem[i] = true;

                    millenium_item.tag = "MI" + i;

                    millenium_item.Init(newLat, newLon);
                    items.Add(millenium_item);
            }
    }
    }
}`
</code>```

Body:
I´ve followed a tutorial on YouTube where the developer added items spawning around the player at a certain interval with a max distance on the tile in MapBox. What I am trying to achieve is to add them at specific longitude and latitudes.

The changes I made was to to loop through the max amount of items I want to add, incrementing an i variable. Then instead of spawning the item around the player like newLat = getPlayerPosition() + random; I hardcoded the lat and lon like: case 0: newLat = 48.30791f; newLon = 18.08611f; millenium_item.tag = "MI0"; break;

And each item is added to a list of items.
The behaviour I am expecting is to add each item to the list and then spawn them on the map, but instead only one item gets added, the one that has the exact same latitude and longitude as the player:

case 3: newLat = 48.32232f; newLon = 18.09462f; millenium_item.tag = "MI3"; break;

Case 3 gets added as it has the same Lat and Lon as my player (where the phone actually is).

case 4: newLat = 48.32232f; newLon = 18.09538f; millenium_item.tag = "MI4"; break;

Case 4 doesnt get added, but as you can see it is pretty close to the location of Case 3.

I dont know what I am doing wrong. Full code:

void SpawnItems() {

        itemindex = 100;
        for(int i = 0; i < count; i++)
        {
            if (googleSignIn.locationdata[i] == false)
            {
            MilleniumItemType type = (MilleniumItemType)(int)UnityEngine.Random.Range(0, Enum.GetValues(typeof(MilleniumItemType)).Length);
            float newLat = 0;
            float newLon = 0;

            MilleniumPuzzle prefab = Resources.Load("MilleniumItems/puzzle", typeof(MilleniumPuzzle)) as MilleniumPuzzle;
            MilleniumPuzzle millenium_item = Instantiate(prefab, Vector3.zero, Quaternion.Euler(-100, 0, 0)) as MilleniumPuzzle;
            millenium_item.tileManager = tileManager;

                switch (i)
                {
                     ...
                case 3: newLat = 48.32232f; newLon = 18.09462f; millenium_item.tag = "MI3"; break;
                case 4: newLat = 48.32232f; newLon = 18.09538f; millenium_item.tag = "MI4"; break;
                case 5: newLat = 48.32310f; newLon = 18.09536f; millenium_item.tag = "MI5"; break;
                     ...
                }
                /// OUR LAT: 48.32232 OUR LON: 18.09462

                    millenium_item.Init(newLat, newLon);
                    items.Add(millenium_item);
        }
        }

Then Init looks like this:

public void Init(float _lat, float _lon) {
    lat = _lat;
    lon = _lon;
    UpdatePosition ();
}

and:

public void UpdatePosition() {
    float x, y;
    Vector3 position = Vector3.zero;

    geodeticOffsetInv (tileManager.getLat * Mathf.Deg2Rad, tileManager.getLon * Mathf.Deg2Rad, lat * Mathf.Deg2Rad, lon * Mathf.Deg2Rad, out x, out y);

    if ((lat - tileManager.getLat) < 0 && (lon - tileManager.getLon) > 0 || (lat - tileManager.getLat) > 0 && (lon - tileManager.getLon) < 0) {
        position = new Vector3(x, .5f, y);
    }
    else {
        position = new Vector3 (-x, .5f, -y);
    }

    position.x *= 0.300122f;
    position.z *= 0.123043f;

    Debug.Log("Position of inited millenium puzzle: " + position.x + " z: " + position.z);

    transform.position = position;
}

Body:
I was able to solve the issue myself. Adding the items at exact coordinates never worked, so instead I am saving the item coordinates in an array. Then in update() I am comparing the position of the player with the coordinates where the items should be. If the difference between the positions are between constant numbers that I defined, then the items will appear around the player, although not exactly at the building, but in my case I don´t mind.
Example:

   `public void SpawnItems() {

    itemindex = 100;
    for(int i = 0; i < count; i++)
    {

        if (googleSignIn.locationdata[i] == false && spawnedItem[i] == false)
        {
            if(tileManager.getLat - itemLats[i] < 0.003f && tileManager.getLat - itemLats[i] > -0.003f && tileManager.getLon - itemLons[i] < 0.00103f && tileManager.getLon - itemLons[i] > -0.00103f)
            {
                    MilleniumItemType type = (MilleniumItemType)(int)UnityEngine.Random.Range(0, Enum.GetValues(typeof(MilleniumItemType)).Length);

                    MilleniumPuzzle prefab = Resources.Load("MilleniumItems/puzzle", typeof(MilleniumPuzzle)) as MilleniumPuzzle;
                    MilleniumPuzzle millenium_item = Instantiate(prefab, Vector3.zero, Quaternion.Euler(-100, 0, 0)) as MilleniumPuzzle;
                    millenium_item.tileManager = tileManager;

                    float newLat = tileManager.getLat + UnityEngine.Random.Range(-0.0001f, 0.0001f);
                    float newLon = tileManager.getLon + UnityEngine.Random.Range(-0.0001f, 0.0001f);

                    if(newLat == previousLat || newLon == previousLon)
                {
                     newLat = tileManager.getLat + UnityEngine.Random.Range(-0.0001f, 0.0001f);
                     newLon = tileManager.getLon + UnityEngine.Random.Range(-0.0001f, 0.0001f);
                }

                previousLon = newLon;
                previousLat = newLat;

                    spawnedItem[i] = true;

                    millenium_item.tag = "MI" + i;

                    millenium_item.Init(newLat, newLon);
                    items.Add(millenium_item);
            }
    }
    }
}`