问:
Filter Python list of dictionaries based on key/value criteria
I have a python list of dictionaries that I need to filter. Specifically, I need all elements from the original list retained but filtered for a specific key/value criteria. Consider the dictionary below. I need all objects retained that have the radius_mean key value >= 13. Thanks!

my_list = [{'id': '842302', 'diagnosis': 'M', 'radius_mean': '17.99', 'texture_mean': '10.38', 'perimeter_mean': '122.8', 'area_mean': '1001', 'smoothness_mean': '0.1184', 'compactness_mean': '0.2776', 'concavity_mean': '0.3001', 'concave points_mean': '0.1471', 'symmetry_mean': '0.2419', 'fractal_dimension_mean': '0.07871', 'radius_se': '1.095', 'texture_se': '0.9053', 'perimeter_se': '8.589', 'area_se': '153.4', 'smoothness_se': '0.006399', 'compactness_se': '0.04904', 'concavity_se': '0.05373', 'concave points_se': '0.01587', 'symmetry_se': '0.03003', 'fractal_dimension_se': '0.006193', 'radius_worst': '25.38', 'texture_worst': '17.33', 'perimeter_worst': '184.6', 'area_worst': '2019', 'smoothness_worst': '0.1622', 'compactness_worst': '0.6656', 'concavity_worst': '0.7119', 'concave points_worst': '0.2654', 'symmetry_worst': '0.4601', 'fractal_dimension_worst': '0.1189'}, {'id': '842517', 'diagnosis': 'M', 'radius_mean': '20.57', 'texture_mean': '17.77', 'perimeter_mean': '132.9', 'area_mean': '1326', 'smoothness_mean': '0.08474', 'compactness_mean': '0.07864', 'concavity_mean': '0.0869', 'concave points_mean': '0.07017', 'symmetry_mean': '0.1812', 'fractal_dimension_mean': '0.05667', 'radius_se': '0.5435', 'texture_se': '0.7339', 'perimeter_se': '3.398', 'area_se': '74.08', 'smoothness_se': '0.005225', 'compactness_se': '0.01308', 'concavity_se': '0.0186', 'concave points_se': '0.0134', 'symmetry_se': '0.01389', 'fractal_dimension_se': '0.003532', 'radius_worst': '24.99', 'texture_worst': '23.41', 'perimeter_worst': '158.8', 'area_worst': '1956', 'smoothness_worst': '0.1238', 'compactness_worst': '0.1866', 'concavity_worst': '0.2416', 'concave points_worst': '0.186', 'symmetry_worst': '0.275', 'fractal_dimension_worst': '0.08902'}, {'id': '84300903', 'diagnosis': 'M', 'radius_mean': '19.69', 'texture_mean': '21.25', 'perimeter_mean': '130', 'area_mean': '1203', 'smoothness_mean': '0.1096', 'compactness_mean': '0.1599', 'concavity_mean': '0.1974', 'concave points_mean': '0.1279', 'symmetry_mean': '0.2069', 'fractal_dimension_mean': '0.05999', 'radius_se': '0.7456', 'texture_se': '0.7869', 'perimeter_se': '4.585', 'area_se': '94.03', 'smoothness_se': '0.00615', 'compactness_se': '0.04006', 'concavity_se': '0.03832', 'concave points_se': '0.02058', 'symmetry_se': '0.0225', 'fractal_dimension_se': '0.004571', 'radius_worst': '23.57', 'texture_worst': '25.53', 'perimeter_worst': '152.5', 'area_worst': '1709', 'smoothness_worst': '0.1444', 'compactness_worst': '0.4245', 'concavity_worst': '0.4504', 'concave points_worst': '0.243', 'symmetry_worst': '0.3613', 'fractal_dimension_worst': '0.08758'}, {'id': '84348301', 'diagnosis': 'M', 'radius_mean': '11.42', 'texture_mean': '20.38', 'perimeter_mean': '77.58', 'area_mean': '386.1', 'smoothness_mean': '0.1425', 'compactness_mean': '0.2839', 'concavity_mean': '0.2414', 'concave points_mean': '0.1052', 'symmetry_mean': '0.2597', 'fractal_dimension_mean': '0.09744', 'radius_se': '0.4956', 'texture_se': '1.156', 'perimeter_se': '3.445', 'area_se': '27.23', 'smoothness_se': '0.00911', 'compactness_se': '0.07458', 'concavity_se': '0.05661', 'concave points_se': '0.01867', 'symmetry_se': '0.05963', 'fractal_dimension_se': '0.009208', 'radius_worst': '14.91', 'texture_worst': '26.5', 'perimeter_worst': '98.87', 'area_worst': '567.7', 'smoothness_worst': '0.2098', 'compactness_worst': '0.8663', 'concavity_worst': '0.6869', 'concave points_worst': '0.2575', 'symmetry_worst': '0.6638', 'fractal_dimension_worst': '0.173'}, {'id': '84358402', 'diagnosis': 'M', 'radius_mean': '20.29', 'texture_mean': '14.34', 'perimeter_mean': '135.1', 'area_mean': '1297', 'smoothness_mean': '0.1003', 'compactness_mean': '0.1328', 'concavity_mean': '0.198', 'concave points_mean': '0.1043', 'symmetry_mean': '0.1809', 'fractal_dimension_mean': '0.05883', 'radius_se': '0.7572', 'texture_se': '0.7813', 'perimeter_se': '5.438', 'area_se': '94.44', 'smoothness_se': '0.01149', 'compactness_se': '0.02461', 'concavity_se': '0.05688', 'concave points_se': '0.01885', 'symmetry_se': '0.01756', 'fractal_dimension_se': '0.005115', 'radius_worst': '22.54', 'texture_worst': '16.67', 'perimeter_worst': '152.2', 'area_worst': '1575', 'smoothness_worst': '0.1374', 'compactness_worst': '0.205', 'concavity_worst': '0.4', 'concave points_worst': '0.1625', 'symmetry_worst': '0.2364', 'fractal_dimension_worst': '0.07678'}]

答:
You can filter the list using a simple inline if inside for loop

```<code>filtered_list = [i for i in my_list if float(i['radius_mean']) >= 13.0]
</code>```

Body:
You can filter the list using a simple inline if inside for loop

filtered_list = [i for i in my_list if float(i['radius_mean']) >= 13.0]


来源: stackexchange

问:
Jquery replacing text inside html
Is there a more elegant way replacing a text inside an html element than :</p>

```<code>$el = $("#myDiv");
$el.html( $el.html().replace("something", "something new") );
</code>```

答:
you can try

```<code>e1.html(function(i,oldHtml){
     return oldhtml.replace("something", "something new");
}
</code>```

its different but not sure about elegance.

ContentLicense: CC BY-SA 3.0

Title: Jquery replacing text inside html

Body:
Is there a more elegant way replacing a text inside an html element than :

$el = $("#myDiv");
$el.html( $el.html().replace("something", "something new") );

Body:
you can try

e1.html(function(i,oldHtml){
     return oldhtml.replace("something", "something new");
}

its different but not sure about elegance.


问:
How to focus Buttons (or other widgets) with TalkBack turned ON in Android Device?
I'm implementing Accessibility in my application. Here's the scenario :

I have 4 buttons arranged horizontally at the very top of the screen (Activity). On the click of a button, I'm launching an Alert Dialog which displays something to the user. With the alert being displayed, I will still be able to perform click operations on those 4 buttons at the top of the screen. When I turn ON TalkBack (Android Accessibility Service) in Android device and click on that button, alert is getting displayed but I'm unable to move the focus (a yellow rectangular box which will be there when TalkBack feature is turned ON in Android phone) to those 4 buttons. Please help!

答:
Try to integrate voice control into your application via Accessibility TalkBack

Define 4 buttons, Alert Dialog Box as objects, selected by voice:
button 1
button 2
...

...
I am studying the limitations of voice control of Android smartphone/ device in Blind Mode ( eyes-free)

ContentLicense: CC BY-SA 4.0


问:
HTML - Background-color not changing for navbar
Apologies for the rather stupid question. I am quite new to creating HTML web pages and I am just working on a basic homepage. I can't get the navbar background-color to change to any color but the :hover and the .active appear to work. I have been stuck on this for a couple of days looking it up on internet and moving code around to see whether it makes a difference...

Please excuse all the mistakes I probably would have made and thanks in advance!

I just get a bit demotivated when I hit a wall that seems rather simple.

  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

        Home
        Services
        News and Events
        Contact
        About
        Data Protection

```

答:
IN general your code works, only problem: you are using red as a background-color for the .topnav AND as a text-color (color)  for the links in it (.topnav a). So change the link color to something else (white in my snippet)  to avoid red on red = invisible text for the links.

.header {
    background-color: white;
    padding: 15px;
    position: sticky;
    top: 0;
}

.topnav {
    background-color: red;
    padding: 14px 0;
}

.topnav a {
    color: white;
    text-align: center;
    text-decoration: none;
    font-size: 17px;
    overflow: auto;
    padding: 0 16px;

}

.topnav a:hover {
  background-color: Yellow;
  color: black;
}

.topnav a.active {
  background-color: red;
  color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">

    <!--<div class="imgstyle"><img src="C:\Users\Tony\Desktop\Website Work\google Logo\FTLOGO_Big.png" class="imgstyle"/></div>-->
     <img style="float: Left;" alt="google" src="C:\Users\Tony\Desktop\Website Work\FTLOGO_Big.png" width="70%" height="60%">

     <img style="float: right; padding-top: 15px; padding-bottom:25px;" alt="Logo" src="C:\Users\Tony\Desktop\Website Work\Vector Logo.png" width="6%" height="6%">

    <img style="display: inline; padding-bottom:10px" src="C:\Users\Tony\Desktop\Website Work\google Logo\Tagline.png" width="70%" height="70%"/>

<div class="topnav">
    Home
    Services
    News and Events
    Contact
    About
    Data Protection
</div>

</div></code>```

Body:
IN general your code works, only problem: you are using red as a background-color for the .topnav AND as a text-color (color)  for the links in it (.topnav a). So change the link color to something else (white in my snippet)  to avoid red on red = invisible text for the links.

.header {
    background-color: white;
    padding: 15px;
    position: sticky;
    top: 0;
}

.topnav {
    background-color: red;
    padding: 14px 0;
}

.topnav a {
    color: white;
    text-align: center;
    text-decoration: none;
    font-size: 17px;
    overflow: auto;
    padding: 0 16px;

}

.topnav a:hover {
  background-color: Yellow;
  color: black;
}

.topnav a.active {
  background-color: red;
  color: blue;
}

<div class="header">

    <!--<div class="imgstyle"><img src="C:\Users\Tony\Desktop\Website Work\google Logo\FTLOGO_Big.png" class="imgstyle"/></div>-->
    <a href="www.google.com"> <img style="float: Left;" alt="google" src="C:\Users\Tony\Desktop\Website Work\FTLOGO_Big.png" width="70%" height="60%"> </a>

    <a href="www.google.com"> <img style="float: right; padding-top: 15px; padding-bottom:25px;" alt="Logo" src="C:\Users\Tony\Desktop\Website Work\Vector Logo.png" width="6%" height="6%"> </a>

    <img style="display: inline; padding-bottom:10px" src="C:\Users\Tony\Desktop\Website Work\google Logo\Tagline.png" width="70%" height="70%"/>

<div class="topnav">
    <a class="active" href="#home">Home</a>
    <a href="#services">Services</a>
    <a href="#news">News and Events</a>
    <a href="#contact">Contact</a>
    <a href="#about">About</a>
    <a href="#data">Data Protection</a>
</div>

</div>


问:
why email notification in laravel doesn't work?
I have a simple dashboard to add companies and their employees, i want to send an email notification to admin if there is a new company added, and send an email to company when new employee added.
how to do this using laravel?

i tried to use laravel notification as documentation, but it didn't work.

答:
Maybe some piece of code from your project would be help us to understand.

I think the answer you looking for is can be boot method in model. If you want to check that is there any new company? Then, go to your Company model and try something like this.

```<code>public static function boot(){
     static::creating(function ($model) {
     /*add code about what do you want to do.
     Maybe notify method like this  */
    $model->notify(new NewMessage($variable ));
    });
</code>```

I am really sorry if I got you wrong, but i am just trying to help you.

Body:
Maybe some piece of code from your project would be help us to understand.

I think the answer you looking for is can be boot method in model. If you want to check that is there any new company? Then, go to your Company model and try something like this.

public static function boot(){
     static::creating(function ($model) {
     /*add code about what do you want to do.
     Maybe notify method like this  */
    $model->notify(new NewMessage($variable ));
    });

I am really sorry if I got you wrong, but i am just trying to help you.


问:
gocolly: How to Prevent duplicate crawling, restrict to unique url crawling ONCE
I was experimenting with go-colly with below code, it seems to crawl same url multiple times, how do I restrict to one time crawling?

I suspected the 'Parallellsim:2' was causing the duplicates, however, some of the crawl message urls repeated more than 10 times each.

Reproducible across different websites.

gocolly is lean and great.

func main() {
    c := colly.NewCollector(
        colly.AllowedDomains( "www.coursera.org"),
        colly.Async(true),
    )

    c.Limit(&colly.LimitRule{
        DomainGlob: "*",
         Parallelism: 2,
    })

    c.OnHTML("a[href]", func(e *colly.HTMLElement) {
        link := e.Attr("href")
        e.Request.Visit(link)
    })
    pageCount :=0
    c.OnRequest(func(r *colly.Request) {
        r.Ctx.Put("url", r.URL.String())
    })

    // Set error handler
    c.OnError(func(r *colly.Response, err error) {
        log.Println("Request URL:", r.Request.URL, "failed with response:", r, "\nError:", err)
    })

    // Print the response
    c.OnResponse(func(r *colly.Response) {
        pageCount++
        urlVisited := r.Ctx.Get("url")
        log.Println(fmt.Sprintf("%d  DONE Visiting : %s", pageCount, urlVisited))
    })

    baseUrl := "https://www.coursera.org"
    c.Visit(baseUrl)
    c.Wait()
}
```

答:
The Ctx is shared between requests if you use e.Request.Visit(link), so other requests may overwrite the data. Try to use c.Visit() in these situations. It creates new context for every request.

Also, you don't need to store the URL in the context, it is always available in the OnResponse callback using r.Request.URL.

Change your log messasge to the following to be able to see the real request url:

log.Println(fmt.Sprintf("%d  DONE Visiting : %s", pageCount, r.Request.URL))

```


问:
git-svn clone checkouts wrong repo?
So I am trying to switch to git, by using git-svn. I am having a svn repo called myrepo from which I want to clone just the project called myproject. The thing is that by running the following command:

git svn clone path-to-repo/myrepo/myproject --stdlayout --prefix=svn myproject

the whole repo myrepo is cloned rather than just myproject. I tried using -T, -t, -b as well to let git know about the layout of the project, but without any success. I always get the following output:

Using higher level of URL:  path-to-repo/myrepo/myproject =>   path-to-repo/myrepo

and tries to clone that one. Am I doing something wrong? It might be that the svn repo layout could be broken or git incompatible ?

答:
Meanwhile, I got it working with the usual -s switch:

git svn clone -s <svn_repo_url>

I also have a few git-svn references that I want to share:

http://justaddwater.dk/2009/03/09/using-git-for-svn-repositories-workflow/

http://www.viget.com/extend/effectively-using-git-with-subversion/

http://utsl.gen.nz/talks/git-svn/intro.html

http://trac.parrot.org/parrot/wiki/git-svn-tutorial

ContentLicense: CC BY-SA 2.5

Title: git-svn clone checkouts wrong repo?


问:
How to evaluate a dynamic variable in a docker-compose.yml file?
I want to suffix a file name with the current date in my docker-compose.yml file. The end goal being a file such as my_log_123456789.log, where 123456789 is the current unix date.

I tried using an .env file, but that did not evaluate as expected. My attempt was:

```<code># .env
NOW="$(date +%s)"
</code>```

```<code># docker-compose.yml
version: '3.8'
services:
  xxx:
      container_name: xxx
      image: xxx/xxx
      volumes:
        - /home/ubuntu/xxx_"$(NOW)".log:/home/ubuntu/xxx.log
      ...
</code>```

I tried a few variations of this and had the following issues:

ERROR: Invalid interpolation format for "volumes" option in service "xxx": "/home/ubuntu/xxx_$(NOW).log:/home/ubuntu/xxx.log"

A directory was created that was named 'xxx_"$(date +%s)".log'

How can I append the current date to a log file in a docker-compose.yml file?

答:
What you can do is to generate .env just before calling docker-compose:

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

cat << EOF > .env
NOW=$(date +%s)
EOF

docker-compose up
</code>```

Body:
I want to suffix a file name with the current date in my docker-compose.yml file. The end goal being a file such as my_log_123456789.log, where 123456789 is the current unix date.

I tried using an .env file, but that did not evaluate as expected. My attempt was:

# .env
NOW="$(date +%s)"

# docker-compose.yml
version: '3.8'
services:
  xxx:
      container_name: xxx
      image: xxx/xxx
      volumes:
        - /home/ubuntu/xxx_"$(NOW)".log:/home/ubuntu/xxx.log
      ...

I tried a few variations of this and had the following issues:

ERROR: Invalid interpolation format for "volumes" option in service "xxx": "/home/ubuntu/xxx_$(NOW).log:/home/ubuntu/xxx.log"

A directory was created that was named 'xxx_"$(date +%s)".log'

How can I append the current date to a log file in a docker-compose.yml file?

Body:
What you can do is to generate .env just before calling docker-compose:

#!/usr/bin/env bash

cat << EOF > .env
NOW=$(date +%s)
EOF

docker-compose up


问:
Any other reason forEach() is provided a reference to the array itself aside from scoping?
According to MDN, the callback provided to the forEach function is given 3 parameters: currentValue, index, array.

I'm trying to understand the purpose the forEach callback is provided the reference to the array itself as the 3rd parameter and the only reason I can see why is because of scoping.

1st Example:

function printLastName(value, index, array) {
  if (index === (array.length - 1)) {
    console.log(value);
  }
}

function setupNames() {
  const names = ['A', 'B', 'C'];
  names.forEach(printLastName);
}

setupNames();

```

<p>What I wish to illustrate in the 1st example above is that <code>printLastName()</code> used as the <code>forEach()</code> callback does not have a reference to the original <code>names</code> array and thus, if it needs to use the array, it needs to be provided the <code>3rd parameter</code>, hence the only reason I see why the <code>forEach</code> callback is provided a reference to the original <code>array</code>. </p>

<p>2nd Example:</p>

<pre class="lang-js prettyprint-override"><code>function setupNames() {
  const names = ['A', 'B', 'C'];
  names.forEach((value, index, array) => {
    if (index === (names.length - 1)) {
      console.log(value);
    }
  });
}

setupNames();
</code>```

In the 2nd example, the line (index === (names.length - 1)), I could have either used names or array since it's available to me. And to my understanding, there is absolutely no difference using either one.

To wrap it up, here's my question:

The callback to the forEach method is provided the array as the 3rd parameter solely because of scoping issue (1st Example) and not for any other reason, correct?

In the 2nd example, there is absolutely no difference between me using names or array in the lambda callback to forEach no matter what the lambda callback logic is, correct?

答:
All features come from specifications and proposals, so going into the ECMAScript specification.

It does not seem to have a very specific reason to exist. But as you say, when analysing different examples that may use forEach it makes sense that it is due to scoping. For example, when defining a generic function like:

function calculateSomethingThatNeedsLookupInTheArray(val, index, array. It will be much more tight in implementation if we only rely on the context, that if we just refer to the array that uses this function.

```<code>const array1 = [1 , 2, 3, 4, 5]
const array2 = [1, 2]

array1.forEach((val) => {
 something(val / array1[0]))
array2.forEach((val) => {
 something(val, array2[0]))
</code>```

vs

```<code>const array1 = [1 , 2, 3, 4, 5]
const array2 = [1, 2]

const operationCallback = (val, i, array) => {
 something(val /array[0])
}

array1.forEach(operationCallback)
array2.forEach(operationCallback)
</code>```

Also remember, we can pass any context to forEach apart from the callback, known as thisArgument, what highlights the importance of keeping the array to scope or target the current array we are using.

Body:
According to MDN, the callback provided to the forEach function is given 3 parameters: currentValue, index, array.

I'm trying to understand the purpose the forEach callback is provided the reference to the array itself as the 3rd parameter and the only reason I can see why is because of scoping.

1st Example:

function printLastName(value, index, array) {
  if (index === (array.length - 1)) {
    console.log(value);
  }
}

function setupNames() {
  const names = ['A', 'B', 'C'];
  names.forEach(printLastName);
}

setupNames();

What I wish to illustrate in the 1st example above is that printLastName() used as the forEach() callback does not have a reference to the original names array and thus, if it needs to use the array, it needs to be provided the 3rd parameter, hence the only reason I see why the forEach callback is provided a reference to the original array.

2nd Example:

function setupNames() {
  const names = ['A', 'B', 'C'];
  names.forEach((value, index, array) => {
    if (index === (names.length - 1)) {
      console.log(value);
    }
  });
}

setupNames();

In the 2nd example, the line (index === (names.length - 1)), I could have either used names or array since it's available to me. And to my understanding, there is absolutely no difference using either one.

To wrap it up, here's my question:

The callback to the forEach method is provided the array as the 3rd parameter solely because of scoping issue (1st Example) and not for any other reason, correct?

In the 2nd example, there is absolutely no difference between me using names or array in the lambda callback to forEach no matter what the lambda callback logic is, correct?

Body:
All features come from specifications and proposals, so going into the ECMAScript specification.

It does not seem to have a very specific reason to exist. But as you say, when analysing different examples that may use forEach it makes sense that it is due to scoping. For example, when defining a generic function like:

function calculateSomethingThatNeedsLookupInTheArray(val, index, array. It will be much more tight in implementation if we only rely on the context, that if we just refer to the array that uses this function.

const array1 = [1 , 2, 3, 4, 5]
const array2 = [1, 2]

array1.forEach((val) => {
 something(val / array1[0]))
array2.forEach((val) => {
 something(val, array2[0]))

vs

const array1 = [1 , 2, 3, 4, 5]
const array2 = [1, 2]

const operationCallback = (val, i, array) => {
 something(val /array[0])
}

array1.forEach(operationCallback)
array2.forEach(operationCallback)

Also remember, we can pass any context to forEach apart from the callback, known as thisArgument, what highlights the importance of keeping the array to scope or target the current array we are using.


问:
Bison shift/reduce conflict with balanced parentheses grammar
I'm doing an exercise with the grammar of the balanced parentheses:

S -> (S)

S -> SS

S -> ()

The compiler returns a shift/reduce conflict. This is my bison grammar:

```<code>%%
prog:
  srule
;

srule
    : ( srule )
    | srule srule
    | ( )
;
%%
</code>```

Can anyone explain to me the reason and how can I solve it without changing the grammar?

答:
Your grammar is ambiguous, and ambiguous grammars always produce conflicts. That's because the ambiguity means that there will come a point at which two different parses are possible, which means that two different parsing actions are possible. Which is the definition of a parsing conflict.

The ambiguity is pretty obvious. S: S S says that the concatenation of two S is a valid S. But () and ()() are both valid S. So you could make a new S by concatenating () with ()(), or you could make a new S by concatenating ()() with (). Unfortunately, those would both be the same new S, and the grammar does not specify which decomposition is to be used.

Fixing the grammar is one way to do this, and the fix is pretty simple. We just need to specify that when concatenating two balanced sentences, the first one cannot itself be a concatenation. That means that ()•()() is a valid composition, but ()()•() is not.

As you note in a comment, it's simple to modify the grammar with this requirement, by replacing the concatenation rule with S: ( S ) S. The two literal parentheses in that rule match, which means that the part of the rule before the first S cannot be a concatenation.

But we can use the normal yacc/bison mechanism for dealing with ambiguous grammars instead. All we need to do is to require that the parser always resolve a conflict in favour of the reduction action. (This is not a general solution, but it will work here.)

In order for a yacc/bison precedence rule to take effect, the right-hand side which might be reduced must have higher precedence than the lookahead character which might be shifted. The precedence of a right-hand side is specified as the precedence of the first token in the right-hand side, but unfortunately the right-hand side we are interested in -- the concatenation rule -- doesn't have any tokens at all. So we need to mark it with a %prec marker. Since we know that the lookahead symbol will always be a ( (there is no ambiguity with ), since the parser must reduce until the ) can be shifted), we can just mark the production as having the precedence of ( and then declare that ( is right-associative, meaning that reduction is preferred to shift:

```<code>%right '('
%%
%%
srule: '(' srule ')'
     | '(' ')'
     | srule srule %prec '('
</code>```

In fact, the use of %right above is completely arbitrary. Had we started with the unambiguous grammar S → S ( S ) | ε instead of S → ( S ) S | ε, we would have created a left-associative composition in which ()()() must be decomposed as ()()•() rather than ()•()(). That would be implemented by changing %right in the above Bison snippet to %left, which would lead to a more efficient use of the parser stack in the generated parser.

Body:
I'm doing an exercise with the grammar of the balanced parentheses:

S -> (S)

S -> SS

S -> ()

The compiler returns a shift/reduce conflict. This is my bison grammar:

%%
prog:
  srule
;

srule
    : ( srule )
    | srule srule
    | ( )
;
%%

Can anyone explain to me the reason and how can I solve it without changing the grammar?

Body:
Your grammar is ambiguous, and ambiguous grammars always produce conflicts. That's because the ambiguity means that there will come a point at which two different parses are possible, which means that two different parsing actions are possible. Which is the definition of a parsing conflict.

The ambiguity is pretty obvious. S: S S says that the concatenation of two S is a valid S. But () and ()() are both valid S. So you could make a new S by concatenating () with ()(), or you could make a new S by concatenating ()() with (). Unfortunately, those would both be the same new S, and the grammar does not specify which decomposition is to be used.

Fixing the grammar is one way to do this, and the fix is pretty simple. We just need to specify that when concatenating two balanced sentences, the first one cannot itself be a concatenation. That means that ()•()() is a valid composition, but ()()•() is not.

As you note in a comment, it's simple to modify the grammar with this requirement, by replacing the concatenation rule with S: ( S ) S. The two literal parentheses in that rule match, which means that the part of the rule before the first S cannot be a concatenation.

But we can use the normal yacc/bison mechanism for dealing with ambiguous grammars instead. All we need to do is to require that the parser always resolve a conflict in favour of the reduction action. (This is not a general solution, but it will work here.)

In order for a yacc/bison precedence rule to take effect, the right-hand side which might be reduced must have higher precedence than the lookahead character which might be shifted. The precedence of a right-hand side is specified as the precedence of the first token in the right-hand side, but unfortunately the right-hand side we are interested in -- the concatenation rule -- doesn't have any tokens at all. So we need to mark it with a %prec marker. Since we know that the lookahead symbol will always be a ( (there is no ambiguity with ), since the parser must reduce until the ) can be shifted), we can just mark the production as having the precedence of ( and then declare that ( is right-associative, meaning that reduction is preferred to shift:

%right '('
%%
%%
srule: '(' srule ')'
     | '(' ')'
     | srule srule %prec '('

In fact, the use of %right above is completely arbitrary. Had we started with the unambiguous grammar S → S ( S ) | ε instead of S → ( S ) S | ε, we would have created a left-associative composition in which ()()() must be decomposed as ()()•() rather than ()•()(). That would be implemented by changing %right in the above Bison snippet to %left, which would lead to a more efficient use of the parser stack in the generated parser.


问:
How to create a N-dimentional feature vector in python
I have 20 pixel values for an image, and i would like to store them in a 20D feature vector, not a 20 length feature vector. I'm new to Python, so i don't know if in Python a regular array is considered a n-dimentional vector, or i need to vectorize a single array somehow. These are the pixels value:

```<code>[245, 247, 199, 199, 210, 213, 216, 196, 225,
    199, 189, 189, 195, 221, 225, 201, 221, 201, 216, 222]
</code>```

I wish to turn them into a 20d dimentional vector, how would i proceed to do that?

答:
There are several ways to do this. You could do it while keeping it as a list:

```<code>l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

[[i] for i in l]
</code>```

Or:

```<code>list(map(lambda x: [x], l))
</code>```

Output:

```<code>Out[21]: [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]
</code>```

Or use one of many ways to add a dimension to a numpy array:

```<code>import numpy as np

arr = np.array(l)
</code>```

All of these are equivalent:

```<code>arr[Ellipsis, None]
</code>```

```<code>np.expand_dims(arr, -1)
</code>```

```<code>np.reshape(-1, 1)
</code>```

Output:

```<code>array([[ 1],
       [ 2],
       [ 3],
       [ 4],
       [ 5],
       [ 6],
       [ 7],
       [ 8],
       [ 9],
       [10]])
</code>```

Body:
I have 20 pixel values for an image, and i would like to store them in a 20D feature vector, not a 20 length feature vector. I'm new to Python, so i don't know if in Python a regular array is considered a n-dimentional vector, or i need to vectorize a single array somehow. These are the pixels value:

[245, 247, 199, 199, 210, 213, 216, 196, 225,
    199, 189, 189, 195, 221, 225, 201, 221, 201, 216, 222]

I wish to turn them into a 20d dimentional vector, how would i proceed to do that?

Body:
There are several ways to do this. You could do it while keeping it as a list:

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

[[i] for i in l]

Or:

list(map(lambda x: [x], l))

Output:

Out[21]: [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]

Or use one of many ways to add a dimension to a numpy array:

import numpy as np

arr = np.array(l)

All of these are equivalent:

arr[Ellipsis, None]

np.expand_dims(arr, -1)

np.reshape(-1, 1)

Output:

array([[ 1],
       [ 2],
       [ 3],
       [ 4],
       [ 5],
       [ 6],
       [ 7],
       [ 8],
       [ 9],
       [10]])


问:
How to Add a "Go Back" Toggle
I have a code where it allows me to go to new text if I press "next" but I also want to create another button where it would allow me to go back to the previous text I was reading.

I know I just write Previous but I don't know the javascript to go back.

$(function() {

    $('.js-button').click(function() {
      if ($('div.active').next().hasClass('hidemsg')) {
        $('div.active').next('div').addClass('active').end().removeClass('active');
      }else{
        alert('Sorry, there is no next entry');
      }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidemsg {
 display: none;
  }

  .hidemsg.active {
 display: block;
  }</code>```

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">

      1) Info here

       2) Info Here

       3) Info Here

       4) Info Here

       5) Info Here

Next```

答:
You could add an index using data attribute and then check its value to set show hide using a next/previous method in jquery...

I set a variable for data and tehn incremented it with next() or prev() depending on where the next or previous button was clicked. Hide the previous button if the info = 1 and show next button, hide next if data = length of elements and show previous...

$(function() {
  let data;
  let len = $('.msg').length;
  $('.js-button').click(function() {

    if ($(this).hasClass('next')) {
      data = $('div.active').next().data('info');
      if ($('div.active').next().hasClass('hidemsg')) {
        $('div.active').next('div').addClass('active').end().removeClass('active');
      }
    } else if ($(this).hasClass('previous')) {
      data = $('div.active').prev().data('info');
      if ($('div.active').prev().hasClass('hidemsg')) {
        $('div.active').prev('div').addClass('active').end().removeClass('active');
      }
    }

    if (data === 1) {
      $('.previous').hide();
    }
    if(data < len){
    $('.next').show();
    }
    if (data > 1) {
      $('.previous').show();
    }
    if (data === len) {
      $('.next').hide();
    }

    console.log(len, data)

  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidemsg {
  display: none;
}

.hidemsg.active {
  display: block;
}

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

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">

    1) Info here

    2) Info Here

    3) Info Here

    4) Info Here

    5) Info Here

Next
Previous```

Title: How to Add a "Go Back" Toggle

Body:
I have a code where it allows me to go to new text if I press "next" but I also want to create another button where it would allow me to go back to the previous text I was reading.

I know I just write Previous but I don't know the javascript to go back.

$(function() {

    $('.js-button').click(function() {
      if ($('div.active').next().hasClass('hidemsg')) {
        $('div.active').next('div').addClass('active').end().removeClass('active');
      }else{
        alert('Sorry, there is no next entry');
      }
    });
});

.hidemsg {
 display: none;
  }

  .hidemsg.active {
 display: block;
  }

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">

      1) Info here

       2) Info Here

       3) Info Here

       4) Info Here

       5) Info Here

Next

Body:
You could add an index using data attribute and then check its value to set show hide using a next/previous method in jquery...

I set a variable for data and tehn incremented it with next() or prev() depending on where the next or previous button was clicked. Hide the previous button if the info = 1 and show next button, hide next if data = length of elements and show previous...

$(function() {
  let data;
  let len = $('.msg').length;
  $('.js-button').click(function() {

    if ($(this).hasClass('next')) {
      data = $('div.active').next().data('info');
      if ($('div.active').next().hasClass('hidemsg')) {
        $('div.active').next('div').addClass('active').end().removeClass('active');
      }
    } else if ($(this).hasClass('previous')) {
      data = $('div.active').prev().data('info');
      if ($('div.active').prev().hasClass('hidemsg')) {
        $('div.active').prev('div').addClass('active').end().removeClass('active');
      }
    }

    if (data === 1) {
      $('.previous').hide();
    }
    if(data < len){
    $('.next').show();
    }
    if (data > 1) {
      $('.previous').show();
    }
    if (data === len) {
      $('.next').hide();
    }

    console.log(len, data)

  });
});

.hidemsg {
  display: none;
}

.hidemsg.active {
  display: block;
}

.previous {
  display: none;
}

<!DOCTYPE html>
<html lang="en" class="no-js.june">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<div data-info="1" id="msg1" class="msg hidemsg active first">
  <p class="content__item-copy-text">
    1) Info here
  </p>
</div>

<div data-info="2" id="msg2" class="msg hidemsg">
  <p class="content__item-copy-text">
    2) Info Here </p>
</div>

<div data-info="3" id="msg3" class="msg hidemsg">
  <p class="content__item-copy-text">
    3) Info Here </p>
</div>

<div data-info="4" id="msg4" class="msg hidemsg">
  <p class="content__item-copy-text">
    4) Info Here </p>
</div>

<div data-info="5" id="msg5" class="msg hidemsg last">
  <p class="content__item-copy-text">
    5) Info Here </p>
</div>
<a href="#" type="button" class="btn btn-default js-button next">Next</a>
<a href="#" type="button" class="btn btn-default js-button previous">Previous</a>


问:
JAX-WS multiple endpoints in sun-jaxws.xml
Just started using JAX-WS. I created 2 test web services in the one WAR file as follows....

```<code>package com.djs;

import javax.jws.WebService;

@WebService()
public class AddTwoInts {

    public int performAdd(int firstNum, int secondNum) {
        return firstNum + secondNum;
    }
}
</code>```

And.....

```<code>package com.djs;

import javax.jws.WebService;

@WebService()
public class SayHello {

    public String sayHello(String inwards) {
        return "Hello " + inwards;
    }
}
</code>```

This is my web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
                             http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">

    <listener>
        <listener-class>
            com.sun.xml.ws.transport.http.servlet.WSServletContextListener
        </listener-class>
    </listener>

    <servlet>
        <servlet-name>jaxws</servlet-name>
        <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>jaxws</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>
</code>```

This is the sun-jaxws.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<endpoints xmlns='http://java.sun.com/xml/ns/jax-ws/ri/runtime' version='2.0'>
    <endpoint name='performAdd' implementation='com.djs.AddTwoInts' url-pattern='/AddTwoInts' />
    <endpoint name='sayHello' implementation='com.djs.SayHello' url-pattern='/SayHello' />
</endpoints>
</code>```

I deploy into Tomcat 7 and use http://localhost:8080/MyApp/AddTwoInts?wsdl to get the WSDL for AddTwoInts OK.... But when I execute http://localhost:8080/MyApp/SayHello?wsdl I get a 404 page not found error....

Any advice appreciated.

答:
Dave,

I guess you are missing the servlet-mapping for the two end points you have.

Add the following to your web.xml and try again. Let me know if this solve the problem.

```<code><servlet>
    <servlet-name>AddTwoInts</servlet-name>
    <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>AddTwoInts</servlet-name>
    <url-pattern>/AddTwoInts</url-pattern>
</servlet-mapping>

<servlet>
    <servlet-name>SayHello</servlet-name>
    <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>SayHello</servlet-name>
    <url-pattern>/SayHello</url-pattern>
</servlet-mapping>
</code>```

Body:
Just started using JAX-WS. I created 2 test web services in the one WAR file as follows....

package com.djs;

import javax.jws.WebService;

@WebService()
public class AddTwoInts {

    public int performAdd(int firstNum, int secondNum) {
        return firstNum + secondNum;
    }
}

And.....

package com.djs;

import javax.jws.WebService;

@WebService()
public class SayHello {

    public String sayHello(String inwards) {
        return "Hello " + inwards;
    }
}

This is my web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
                             http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">

    <listener>
        <listener-class>
            com.sun.xml.ws.transport.http.servlet.WSServletContextListener
        </listener-class>
    </listener>

    <servlet>
        <servlet-name>jaxws</servlet-name>
        <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>jaxws</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

This is the sun-jaxws.xml

<?xml version="1.0" encoding="UTF-8"?>
<endpoints xmlns='http://java.sun.com/xml/ns/jax-ws/ri/runtime' version='2.0'>
    <endpoint name='performAdd' implementation='com.djs.AddTwoInts' url-pattern='/AddTwoInts' />
    <endpoint name='sayHello' implementation='com.djs.SayHello' url-pattern='/SayHello' />
</endpoints>

I deploy into Tomcat 7 and use http://localhost:8080/MyApp/AddTwoInts?wsdl to get the WSDL for AddTwoInts OK.... But when I execute http://localhost:8080/MyApp/SayHello?wsdl I get a 404 page not found error....

Any advice appreciated.

Body:
Dave,

I guess you are missing the servlet-mapping for the two end points you have.

Add the following to your web.xml and try again. Let me know if this solve the problem.

<servlet>
    <servlet-name>AddTwoInts</servlet-name>
    <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>AddTwoInts</servlet-name>
    <url-pattern>/AddTwoInts</url-pattern>
</servlet-mapping>

<servlet>
    <servlet-name>SayHello</servlet-name>
    <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>SayHello</servlet-name>
    <url-pattern>/SayHello</url-pattern>
</servlet-mapping>


答:
I believe this would be a really pythonic way:

filtered_list = filter(lambda d: float(d['radius_mean']) >= 13.0, my_list)

Title: Filter Python list of dictionaries based on key/value criteria

Body:
I have a python list of dictionaries that I need to filter. Specifically, I need all elements from the original list retained but filtered for a specific key/value criteria. Consider the dictionary below. I need all objects retained that have the radius_mean key value >= 13. Thanks!

my_list = [{'id': '842302', 'diagnosis': 'M', 'radius_mean': '17.99', 'texture_mean': '10.38', 'perimeter_mean': '122.8', 'area_mean': '1001', 'smoothness_mean': '0.1184', 'compactness_mean': '0.2776', 'concavity_mean': '0.3001', 'concave points_mean': '0.1471', 'symmetry_mean': '0.2419', 'fractal_dimension_mean': '0.07871', 'radius_se': '1.095', 'texture_se': '0.9053', 'perimeter_se': '8.589', 'area_se': '153.4', 'smoothness_se': '0.006399', 'compactness_se': '0.04904', 'concavity_se': '0.05373', 'concave points_se': '0.01587', 'symmetry_se': '0.03003', 'fractal_dimension_se': '0.006193', 'radius_worst': '25.38', 'texture_worst': '17.33', 'perimeter_worst': '184.6', 'area_worst': '2019', 'smoothness_worst': '0.1622', 'compactness_worst': '0.6656', 'concavity_worst': '0.7119', 'concave points_worst': '0.2654', 'symmetry_worst': '0.4601', 'fractal_dimension_worst': '0.1189'}, {'id': '842517', 'diagnosis': 'M', 'radius_mean': '20.57', 'texture_mean': '17.77', 'perimeter_mean': '132.9', 'area_mean': '1326', 'smoothness_mean': '0.08474', 'compactness_mean': '0.07864', 'concavity_mean': '0.0869', 'concave points_mean': '0.07017', 'symmetry_mean': '0.1812', 'fractal_dimension_mean': '0.05667', 'radius_se': '0.5435', 'texture_se': '0.7339', 'perimeter_se': '3.398', 'area_se': '74.08', 'smoothness_se': '0.005225', 'compactness_se': '0.01308', 'concavity_se': '0.0186', 'concave points_se': '0.0134', 'symmetry_se': '0.01389', 'fractal_dimension_se': '0.003532', 'radius_worst': '24.99', 'texture_worst': '23.41', 'perimeter_worst': '158.8', 'area_worst': '1956', 'smoothness_worst': '0.1238', 'compactness_worst': '0.1866', 'concavity_worst': '0.2416', 'concave points_worst': '0.186', 'symmetry_worst': '0.275', 'fractal_dimension_worst': '0.08902'}, {'id': '84300903', 'diagnosis': 'M', 'radius_mean': '19.69', 'texture_mean': '21.25', 'perimeter_mean': '130', 'area_mean': '1203', 'smoothness_mean': '0.1096', 'compactness_mean': '0.1599', 'concavity_mean': '0.1974', 'concave points_mean': '0.1279', 'symmetry_mean': '0.2069', 'fractal_dimension_mean': '0.05999', 'radius_se': '0.7456', 'texture_se': '0.7869', 'perimeter_se': '4.585', 'area_se': '94.03', 'smoothness_se': '0.00615', 'compactness_se': '0.04006', 'concavity_se': '0.03832', 'concave points_se': '0.02058', 'symmetry_se': '0.0225', 'fractal_dimension_se': '0.004571', 'radius_worst': '23.57', 'texture_worst': '25.53', 'perimeter_worst': '152.5', 'area_worst': '1709', 'smoothness_worst': '0.1444', 'compactness_worst': '0.4245', 'concavity_worst': '0.4504', 'concave points_worst': '0.243', 'symmetry_worst': '0.3613', 'fractal_dimension_worst': '0.08758'}, {'id': '84348301', 'diagnosis': 'M', 'radius_mean': '11.42', 'texture_mean': '20.38', 'perimeter_mean': '77.58', 'area_mean': '386.1', 'smoothness_mean': '0.1425', 'compactness_mean': '0.2839', 'concavity_mean': '0.2414', 'concave points_mean': '0.1052', 'symmetry_mean': '0.2597', 'fractal_dimension_mean': '0.09744', 'radius_se': '0.4956', 'texture_se': '1.156', 'perimeter_se': '3.445', 'area_se': '27.23', 'smoothness_se': '0.00911', 'compactness_se': '0.07458', 'concavity_se': '0.05661', 'concave points_se': '0.01867', 'symmetry_se': '0.05963', 'fractal_dimension_se': '0.009208', 'radius_worst': '14.91', 'texture_worst': '26.5', 'perimeter_worst': '98.87', 'area_worst': '567.7', 'smoothness_worst': '0.2098', 'compactness_worst': '0.8663', 'concavity_worst': '0.6869', 'concave points_worst': '0.2575', 'symmetry_worst': '0.6638', 'fractal_dimension_worst': '0.173'}, {'id': '84358402', 'diagnosis': 'M', 'radius_mean': '20.29', 'texture_mean': '14.34', 'perimeter_mean': '135.1', 'area_mean': '1297', 'smoothness_mean': '0.1003', 'compactness_mean': '0.1328', 'concavity_mean': '0.198', 'concave points_mean': '0.1043', 'symmetry_mean': '0.1809', 'fractal_dimension_mean': '0.05883', 'radius_se': '0.7572', 'texture_se': '0.7813', 'perimeter_se': '5.438', 'area_se': '94.44', 'smoothness_se': '0.01149', 'compactness_se': '0.02461', 'concavity_se': '0.05688', 'concave points_se': '0.01885', 'symmetry_se': '0.01756', 'fractal_dimension_se': '0.005115', 'radius_worst': '22.54', 'texture_worst': '16.67', 'perimeter_worst': '152.2', 'area_worst': '1575', 'smoothness_worst': '0.1374', 'compactness_worst': '0.205', 'concavity_worst': '0.4', 'concave points_worst': '0.1625', 'symmetry_worst': '0.2364', 'fractal_dimension_worst': '0.07678'}]


问:
SQL Combining multiple rows into one column
Example of what I'm trying to do:

I'm thinking either using "cases" or a pivot table can help me combine those columns. Assume first table is called "oldTable1" and new table can be called "newTable1".

Thank you!

答:
You can do conditional aggregation. The following query would work in most databases:

```<code>select
    name,
    car,
    max(case when year = 2017 then miles_driven end) miles_driven_2017,
    max(case when year = 2018 then miles_driven end) miles_driven_2018,
    max(case when year = 2019 then miles_driven end) miles_driven_2019,
    max(case when year = 2020 then miles_driven end) miles_driven_2020
from mytable
group by name, car
</code>```

In case there are multiple rows per (name, car, year), you want to use sum() instead of max().

Body:
You can do conditional aggregation. The following query would work in most databases:

select
    name,
    car,
    max(case when year = 2017 then miles_driven end) miles_driven_2017,
    max(case when year = 2018 then miles_driven end) miles_driven_2018,
    max(case when year = 2019 then miles_driven end) miles_driven_2019,
    max(case when year = 2020 then miles_driven end) miles_driven_2020
from mytable
group by name, car

In case there are multiple rows per (name, car, year), you want to use sum() instead of max().


问:
Extracting Specific numbers from text on Google Sheets?
The data is as in the form below. I am trying to extract the hour(h), and minute(m) from the text to calculate the total duration in google sheets. ex 3h 24m equals 3.4 I am not able to extract the minute part incorrectly.

I have tried the below functions which work well for the hour part but fail for the minute part.

```<code>=LEFT(c1, SEARCH("h",c1)-1)
</code>```

```<code>=IFERROR((REGEXEXTRACT(D1,"([[:print:]]+)h")),0)
</code>```

```<code>C        D
4h       2h 49m
32m 19s  2h 2m
6h 7m    3h 24m
</code>```

答:
To extract hours, minutes and seconds into separate columns, you may use three separate REGEXEXTRACT formulas:

```<code>=IFERROR(REGEXEXTRACT(C1,"(\d+)h"), "")
=IFERROR(REGEXEXTRACT(C1,"(\d+)m"), "")
=IFERROR(REGEXEXTRACT(C1,"(\d+)s"), "")
</code>```

Here, (\d+) is a capturing group that grabs 1 or more digits and the letter after is just matched, and thus, is not returned by the function.

You may also try to extract each part using optional patterns:

```<code>=REGEXEXTRACT(C1, "(?:(\d+)h)?\s*(?:(\d+)m)?\s*(?:(\d+)s)?")
</code>```

Here, all hour, minute and second patterns are optional, and minutes will still match even if hours are missing.

Details

(?:(\d+)h)? - an optional hour part wrapped with a non-capturing group:

(\d+) - Group 1: one or more digits

h - h letter

\s* - 0+ whitespaces

(?:(\d+)m)? - an optional minute part:

(\d+) - Group 2: one or more digits

m - m letter

(?:(\d+)s)? - an optional seconds part:

(\d+) - Group 3: one or more digits

s - s letter

Body:
The data is as in the form below. I am trying to extract the hour(h), and minute(m) from the text to calculate the total duration in google sheets. ex 3h 24m equals 3.4 I am not able to extract the minute part incorrectly.

I have tried the below functions which work well for the hour part but fail for the minute part.

=LEFT(c1, SEARCH("h",c1)-1)

=IFERROR((REGEXEXTRACT(D1,"([[:print:]]+)h")),0)

C        D
4h       2h 49m
32m 19s  2h 2m
6h 7m    3h 24m

Body:
To extract hours, minutes and seconds into separate columns, you may use three separate REGEXEXTRACT formulas:

=IFERROR(REGEXEXTRACT(C1,"(\d+)h"), "")
=IFERROR(REGEXEXTRACT(C1,"(\d+)m"), "")
=IFERROR(REGEXEXTRACT(C1,"(\d+)s"), "")

Here, (\d+) is a capturing group that grabs 1 or more digits and the letter after is just matched, and thus, is not returned by the function.

You may also try to extract each part using optional patterns:

=REGEXEXTRACT(C1, "(?:(\d+)h)?\s*(?:(\d+)m)?\s*(?:(\d+)s)?")

Here, all hour, minute and second patterns are optional, and minutes will still match even if hours are missing.

Details

(?:(\d+)h)? - an optional hour part wrapped with a non-capturing group:

(\d+) - Group 1: one or more digits

h - h letter

\s* - 0+ whitespaces

(?:(\d+)m)? - an optional minute part:

(\d+) - Group 2: one or more digits

m - m letter

(?:(\d+)s)? - an optional seconds part:

(\d+) - Group 3: one or more digits

s - s letter


问:
binary tree printing out with vector duplicate value
I am trying to hold vector to gather all the duplicate values in binary tree.

if binary tree has 2, 2, 5,6,7,7,8, then it would print out 2 and 7 with vector.

I realized with my recursion
1. it will only bring 2 values at most as it resets the vector every time it calls the function
2. At the end of recursive function - it does not bring any value

What am I missing in my recursive function?

```<code>#include "pch.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <string>

using namespace std;

struct node {
    int data;
    node *left, *right;
};

node* getnew(int val) {
    node *curr = new node;
    curr->data = val;
    curr->left = curr->right = nullptr;
    return curr;
}

node* insert(node* root, int val) {
    if (root == nullptr)
        return getnew(val);
    if (val > root->data)
        root->right = insert(root->right, val);
    else if (val <= root->data)
        root->left = insert(root->left, val);
    return root;
}

void print(node*root) {
    if (root != nullptr) {
        print(root->left);
        cout << root->data << " ";
        print(root->right);
    }
}

int assist(node* root, int value) {
    if(root!=nullptr){
    if (root->data == value)return value;
    return assist(root->left, value) || assist(root->right, value);
    }
    else return -5;
}

vector<int> findmode(node* root) {
    vector<int> thedup;
    //create recusion that find dup value
    //we need assistant function to find dup value
    if (root != nullptr) {
        if(assist(root->left, root->data)!=-5){
            thedup.push_back(root->data);
            return thedup;
        }
        else if(assist(root->right, root->data)!=-5){
            thedup.push_back(root->data);
        return thedup;
        }
        return thedup;
    }
    else return thedup;
}

int main() {
    node *root = nullptr;

    root = insert(root, 5);
    insert(root, 3);
    insert(root, 2);
    insert(root, 4);
    insert(root, 2);
    insert(root, 2);
    insert(root, 8);

    print(root);

    cout << endl;
    vector<int> test;

    for (int i = 0; i < test.size(); i++)
        cout << test[i] << " " << endl;

}

</code>```

答:
Here's a revised example that will traverse the tree, and then use the tree itself as an index to look for duplicates. As mentioned in the comment, you need to pass your collector by reference to avoid overwriting it. I've updated your solution to use a set instead of a vector to avoid adding duplicates (which would happen with a vector).  The updated code is below (with some commented out debugging statements), and you can also give it a try at https://repl.it/@cptndave/btreedups.

```<code>#include <iostream>
#include <vector>
#include <set>
#include <fstream>
#include <string>

using namespace std;

struct node {
    int data;
    node *left, *right;
};

node* getnew(int val) {
    node *curr = new node;
    curr->data = val;
    curr->left = curr->right = nullptr;
    // printf("New %p %d\n", curr, val);
    return curr;
}

node* insert(node* root, int val) {
    if (root == nullptr)
        return getnew(val);
    if (val > root->data)
        root->right = insert(root->right, val);
    else if (val <= root->data)
        root->left = insert(root->left, val);
    return root;
}

void print(node*root) {
    if (root != nullptr) {
        print(root->left);
        cout << root->data << " ";
        print(root->right);
    }
}

// Return true if data exists outside of ignore node
bool exists(node *root, node *target)
{
  if (root == nullptr)
    return false;
  // printf("  Looking for %d at %p\n", target->data, root);
  if (root != target && root->data == target->data)
    return true;
  if (target->data > root->data)
    return exists(root->right, target);
  else
    return exists(root->left, target);
}

// Traverse tree looking for duplicates
void finddup_helper(node *root, node *current, set<int> *dups)
{
  if (current == nullptr)
    return;
  // printf("Helper: root %p, current: %p, %d\n",  root, current, current->data);
  if (exists(root, current)) {
    // printf("dup %d\n", current->data);
    dups->insert(current->data);
  }
  finddup_helper(root, current->left, dups);
  finddup_helper(root, current->right, dups);
}

// Base function which kicks off helper from the root
set<int> finddups(node *root)
{
  set<int> dups;
  finddup_helper(root, root, &dups);
  return dups;
}

int main() {
    node *root = nullptr;

    root = insert(root, 5);
    insert(root, 3);
    insert(root, 2);
    insert(root, 4);
    insert(root, 2);
    insert(root, 2);
    insert(root, 8);
    insert(root, 5);

    cout << "Tree: ";
    print(root);

    cout << endl;
    set<int> dups = finddups(root);;

    cout << "Duplicates: ";
    for (set<int>::iterator it = dups.begin(); it != dups.end(); it++)
      cout << *it << " ";
    cout << endl;
}
</code>```

Body:
I am trying to hold vector to gather all the duplicate values in binary tree.

if binary tree has 2, 2, 5,6,7,7,8, then it would print out 2 and 7 with vector.

I realized with my recursion
1. it will only bring 2 values at most as it resets the vector every time it calls the function
2. At the end of recursive function - it does not bring any value

What am I missing in my recursive function?

#include "pch.h"
#include <iostream>
#include <vector>
#include <fstream>
#include <string>

using namespace std;

struct node {
    int data;
    node *left, *right;
};

node* getnew(int val) {
    node *curr = new node;
    curr->data = val;
    curr->left = curr->right = nullptr;
    return curr;
}

node* insert(node* root, int val) {
    if (root == nullptr)
        return getnew(val);
    if (val > root->data)
        root->right = insert(root->right, val);
    else if (val <= root->data)
        root->left = insert(root->left, val);
    return root;
}

void print(node*root) {
    if (root != nullptr) {
        print(root->left);
        cout << root->data << " ";
        print(root->right);
    }
}

int assist(node* root, int value) {
    if(root!=nullptr){
    if (root->data == value)return value;
    return assist(root->left, value) || assist(root->right, value);
    }
    else return -5;
}

vector<int> findmode(node* root) {
    vector<int> thedup;
    //create recusion that find dup value
    //we need assistant function to find dup value
    if (root != nullptr) {
        if(assist(root->left, root->data)!=-5){
            thedup.push_back(root->data);
            return thedup;
        }
        else if(assist(root->right, root->data)!=-5){
            thedup.push_back(root->data);
        return thedup;
        }
        return thedup;
    }
    else return thedup;
}

int main() {
    node *root = nullptr;

    root = insert(root, 5);
    insert(root, 3);
    insert(root, 2);
    insert(root, 4);
    insert(root, 2);
    insert(root, 2);
    insert(root, 8);

    print(root);

    cout << endl;
    vector<int> test;

    for (int i = 0; i < test.size(); i++)
        cout << test[i] << " " << endl;

}

Body:
Here's a revised example that will traverse the tree, and then use the tree itself as an index to look for duplicates. As mentioned in the comment, you need to pass your collector by reference to avoid overwriting it. I've updated your solution to use a set instead of a vector to avoid adding duplicates (which would happen with a vector).  The updated code is below (with some commented out debugging statements), and you can also give it a try at https://repl.it/@cptndave/btreedups.

#include <iostream>
#include <vector>
#include <set>
#include <fstream>
#include <string>

using namespace std;

struct node {
    int data;
    node *left, *right;
};

node* getnew(int val) {
    node *curr = new node;
    curr->data = val;
    curr->left = curr->right = nullptr;
    // printf("New %p %d\n", curr, val);
    return curr;
}

node* insert(node* root, int val) {
    if (root == nullptr)
        return getnew(val);
    if (val > root->data)
        root->right = insert(root->right, val);
    else if (val <= root->data)
        root->left = insert(root->left, val);
    return root;
}

void print(node*root) {
    if (root != nullptr) {
        print(root->left);
        cout << root->data << " ";
        print(root->right);
    }
}

// Return true if data exists outside of ignore node
bool exists(node *root, node *target)
{
  if (root == nullptr)
    return false;
  // printf("  Looking for %d at %p\n", target->data, root);
  if (root != target && root->data == target->data)
    return true;
  if (target->data > root->data)
    return exists(root->right, target);
  else
    return exists(root->left, target);
}

// Traverse tree looking for duplicates
void finddup_helper(node *root, node *current, set<int> *dups)
{
  if (current == nullptr)
    return;
  // printf("Helper: root %p, current: %p, %d\n",  root, current, current->data);
  if (exists(root, current)) {
    // printf("dup %d\n", current->data);
    dups->insert(current->data);
  }
  finddup_helper(root, current->left, dups);
  finddup_helper(root, current->right, dups);
}

// Base function which kicks off helper from the root
set<int> finddups(node *root)
{
  set<int> dups;
  finddup_helper(root, root, &dups);
  return dups;
}

int main() {
    node *root = nullptr;

    root = insert(root, 5);
    insert(root, 3);
    insert(root, 2);
    insert(root, 4);
    insert(root, 2);
    insert(root, 2);
    insert(root, 8);
    insert(root, 5);

    cout << "Tree: ";
    print(root);

    cout << endl;
    set<int> dups = finddups(root);;

    cout << "Duplicates: ";
    for (set<int>::iterator it = dups.begin(); it != dups.end(); it++)
      cout << *it << " ";
    cout << endl;
}


问:
Text revision comparison StackOverflow-style for ASP.NET MVC?
I'd like to show revisions of text, and I love how StackOverflow does it (e.g. see below). Is there an open source .NET code that can receive two texts and output such a result? If you know of a paid solution that may also be relevant, thanks.

答: You may checkout the following javascript library by John Resig.</p>


问:
Handler is not getting invoked from a role in Ansible
I am trying to restart tomcat by invoking handler and that i need to invoke based on the condition of a variable. Somehow it's not getting invoked.

```<code> - block:
    - debug:
        msg: "Configuration changes detected but no deployment, So proceeding with tomcat restart !!!!"
      notify:
        - Restart tomcat
    - meta: end_play
   when: config_var.changed  == true and myvm_release_version == current_release
</code>```

I can see the message being displayed which means that the when condition is satisfying but after that handler is not invoked.

Output -

```<code>Sunday 31 May 2020  20:54:53 +0100 (0:00:00.084)       0:00:06.902 ************
  server1 ok: {
    "changed": false,
    "msg": "Configuration changes detected but no deployment, So proceeding with tomcat restart !!!!"
}
</code>```

答:
You have to keep in mind that handlers are executed at the very end of the playbook unless they are explicitly flushed with meta.

You can add a meta to flush_handlers if you need immediate handler execution.

Body:
I am trying to restart tomcat by invoking handler and that i need to invoke based on the condition of a variable. Somehow it's not getting invoked.

 - block:
    - debug:
        msg: "Configuration changes detected but no deployment, So proceeding with tomcat restart !!!!"
      notify:
        - Restart tomcat
    - meta: end_play
   when: config_var.changed  == true and myvm_release_version == current_release

I can see the message being displayed which means that the when condition is satisfying but after that handler is not invoked.

Output -

Sunday 31 May 2020  20:54:53 +0100 (0:00:00.084)       0:00:06.902 ************
  server1 ok: {
    "changed": false,
    "msg": "Configuration changes detected but no deployment, So proceeding with tomcat restart !!!!"
}


问:
Variable not assigning on void Start() (noob question)
I have a code to make a cube move back and forth within a certain range of it's original placed position.

The script is directly on the cube and it does move, but around 0,0,0 coordinates, not it's original position.

Here is my code:

```<code>using UnityEngine;

public class ObstacleResonator : MonoBehaviour
{
    public float xspeed = 0f;
    public float yspeed = 0f;
    public float zspeed = 0f;

    public float xrange = 0f;
    public float yrange = 0f;
    public float zrange = 0f;

    float StartX;
    float StartY;
    float StartZ;

    Vector3 desiredPosition;
    void Start()
    {
        // this is what i think is the problem, the variables are not getting assigned
        float StartX = transform.position.x;
        float StartY = transform.position.y;
        float StartZ = transform.position.z;
    }

    // Update is called once per frame
    void Update()
    {
        // the following is to make it reverse once it is out of range in any of the axes
        if (transform.position.x > xrange + StartX)
        {
            xspeed = -xspeed;
        }
        if (transform.position.x < -xrange + StartX)
        {
            xspeed = -xspeed;
        }

        if (transform.position.y > yrange + StartY)
        {
            yspeed = -yspeed;
        }
        if (transform.position.y < -yrange + StartY)
        {
            yspeed = -yspeed;
        }

        if (transform.position.z > zrange + StartZ)
        {
            zspeed = -zspeed;
        }
        if (transform.position.z < -zrange + StartZ)
        {
            zspeed = -zspeed;
        }

        // the following actually moves the cube
        desiredPosition.x = transform.position.x + xspeed * Time.deltaTime;

        desiredPosition.y = transform.position.y + yspeed * Time.deltaTime;

        desiredPosition.z = transform.position.z + zspeed * Time.deltaTime;

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

There probably is a more compact way to write it.

The cube is moving around 0,0,0 instead of it's original transform position. I tried assigning the StartX, StartY, StartZ values manually, and it worked perfectly, but they just dont seem to get assigned by on the start.

答:
The problem is that you declare NEW variables within the Start() function, they go out of scope as soon as the function is executed. You don't update the class variables.

Use this instead:

```<code>void Start()
{
    StartX = transform.position.x;
    StartY = transform.position.y;
    StartZ = transform.position.z;
}
</code>```

Body:
I have a code to make a cube move back and forth within a certain range of it's original placed position.

The script is directly on the cube and it does move, but around 0,0,0 coordinates, not it's original position.

Here is my code:

using UnityEngine;

public class ObstacleResonator : MonoBehaviour
{
    public float xspeed = 0f;
    public float yspeed = 0f;
    public float zspeed = 0f;

    public float xrange = 0f;
    public float yrange = 0f;
    public float zrange = 0f;

    float StartX;
    float StartY;
    float StartZ;

    Vector3 desiredPosition;
    void Start()
    {
        // this is what i think is the problem, the variables are not getting assigned
        float StartX = transform.position.x;
        float StartY = transform.position.y;
        float StartZ = transform.position.z;
    }

    // Update is called once per frame
    void Update()
    {
        // the following is to make it reverse once it is out of range in any of the axes
        if (transform.position.x > xrange + StartX)
        {
            xspeed = -xspeed;
        }
        if (transform.position.x < -xrange + StartX)
        {
            xspeed = -xspeed;
        }

        if (transform.position.y > yrange + StartY)
        {
            yspeed = -yspeed;
        }
        if (transform.position.y < -yrange + StartY)
        {
            yspeed = -yspeed;
        }

        if (transform.position.z > zrange + StartZ)
        {
            zspeed = -zspeed;
        }
        if (transform.position.z < -zrange + StartZ)
        {
            zspeed = -zspeed;
        }

        // the following actually moves the cube
        desiredPosition.x = transform.position.x + xspeed * Time.deltaTime;

        desiredPosition.y = transform.position.y + yspeed * Time.deltaTime;

        desiredPosition.z = transform.position.z + zspeed * Time.deltaTime;

        transform.position = desiredPosition;
    }
}

There probably is a more compact way to write it.

The cube is moving around 0,0,0 instead of it's original transform position. I tried assigning the StartX, StartY, StartZ values manually, and it worked perfectly, but they just dont seem to get assigned by on the start.

Body:
The problem is that you declare NEW variables within the Start() function, they go out of scope as soon as the function is executed. You don't update the class variables.

Use this instead:

void Start()
{
    StartX = transform.position.x;
    StartY = transform.position.y;
    StartZ = transform.position.z;
}


问:
using libtool e gdb
I'm working on a project that uses GNU autotools, so in order to debug the code using gdb, I'm running gdb from within libtool:

```<code>libtool --mode=execute gdbtui foobar
</code>```

Is it possible to reload a modified version of the project without the annoyance of having to quit gdb/libtool and restart?

答:
Based on @Ilia's answer (and this answer on how to parse the executable name to a gdb variable) a solution is to define the following custom make command in ~/.gdbinit:

```<code>define lmake
  python gdb.execute('set $f = "' + str(gdb.selected_inferior().progspace.filename) + '"')
  make
  eval "file %s", $f
end

</code>```

Title: using libtool e gdb

Body:
I'm working on a project that uses GNU autotools, so in order to debug the code using gdb, I'm running gdb from within libtool:

libtool --mode=execute gdbtui foobar

Is it possible to reload a modified version of the project without the annoyance of having to quit gdb/libtool and restart?

Body:
Based on @Ilia's answer (and this answer on how to parse the executable name to a gdb variable) a solution is to define the following custom make command in ~/.gdbinit:

define lmake
  python gdb.execute('set $f = "' + str(gdb.selected_inferior().progspace.filename) + '"')
  make
  eval "file %s", $f
end


问:
mongoose virtual populate infinite loop
I'm trying to populate a tag with the tutorials that are related to it, when I use .populate() on the query it works, but when I do it directly on the model I have an inifite loop.

Here's my code:

Tag.js

```<code>const mongoose = require("mongoose");

const tagSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      unique: true,
      trim: true
    }
  },
  {
    toObject: { virtuals: true },
    toJSON: { virtuals: true }
  }
);

tagSchema.virtual("tutorials", {
  ref: "Tutorial",
  foreignField: "tags",
  localField: "_id"
});

tagSchema.pre(/^find/, function(next) {
  // That's the code that causes an infinite loop
  this.populate({
    path: "tutorials",
    select: "-__v"
  });

  next();
});

const Tag = mongoose.model("Tag", tagSchema);

module.exports = Tag;
</code>```

Tutorial.js

```<code>const mongoose = require('mongoose');

const tutorialSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
    unique: true,
    trim: true
  },
  tags: {
    type: [
      {
        type: mongoose.Schema.ObjectId,
        ref: 'Tag'
      }
    ]
  }
});

const Tutorial = mongoose.model('Tutorial', tutorialSchema);

module.exports = Tutorial;
</code>```

I'd like to know what causes the infinite loop and why does it work on the query but not on the model ? Thanks !

Edit

Here's the code that works

Tag.js

```<code>const mongoose = require("mongoose");

const tagSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      unique: true,
      trim: true
    }
  },
  {
    toObject: { virtuals: true },
    toJSON: { virtuals: true }
  }
);

tagSchema.virtual("tutorials", {
  ref: "Tutorial",
  foreignField: "tags",
  localField: "_id"
});

const Tag = mongoose.model("Tag", tagSchema);

module.exports = Tag;
</code>```

Tutorial.js

```<code>const mongoose = require('mongoose');

const tutorialSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
    unique: true,
    trim: true
  },
  tags: {
    type: [
      {
        type: mongoose.Schema.ObjectId,
        ref: 'Tag'
      }
    ]
  }
});

const Tutorial = mongoose.model('Tutorial', tutorialSchema);

module.exports = Tutorial;
</code>```

TagController.js

```<code>const Tag = require('./../models/tagModel');

exports.getAllTags = async (req, res) => {
  try {
    const docs = await Tag.find().populate({
      path: 'tutorials',
      select: '-__v'
    });

    res.status(200).json({
      // some code
    });
  } catch(err) => {
    // some code
  }
});
</code>```

答: I ran into the same problem recently and spent quite a while to figure it out, in my case two queries are populating each other and causes infinite loop.</p>

Title: mongoose virtual populate infinite loop

Body:
I'm trying to populate a tag with the tutorials that are related to it, when I use .populate() on the query it works, but when I do it directly on the model I have an inifite loop.

Here's my code:

Tag.js

const mongoose = require("mongoose");

const tagSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      unique: true,
      trim: true
    }
  },
  {
    toObject: { virtuals: true },
    toJSON: { virtuals: true }
  }
);

tagSchema.virtual("tutorials", {
  ref: "Tutorial",
  foreignField: "tags",
  localField: "_id"
});

tagSchema.pre(/^find/, function(next) {
  // That's the code that causes an infinite loop
  this.populate({
    path: "tutorials",
    select: "-__v"
  });

  next();
});

const Tag = mongoose.model("Tag", tagSchema);

module.exports = Tag;

Tutorial.js

const mongoose = require('mongoose');

const tutorialSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
    unique: true,
    trim: true
  },
  tags: {
    type: [
      {
        type: mongoose.Schema.ObjectId,
        ref: 'Tag'
      }
    ]
  }
});

const Tutorial = mongoose.model('Tutorial', tutorialSchema);

module.exports = Tutorial;

I'd like to know what causes the infinite loop and why does it work on the query but not on the model ? Thanks !

Edit

Here's the code that works

Tag.js

const mongoose = require("mongoose");

const tagSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      unique: true,
      trim: true
    }
  },
  {
    toObject: { virtuals: true },
    toJSON: { virtuals: true }
  }
);

tagSchema.virtual("tutorials", {
  ref: "Tutorial",
  foreignField: "tags",
  localField: "_id"
});

const Tag = mongoose.model("Tag", tagSchema);

module.exports = Tag;

Tutorial.js

const mongoose = require('mongoose');

const tutorialSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
    unique: true,
    trim: true
  },
  tags: {
    type: [
      {
        type: mongoose.Schema.ObjectId,
        ref: 'Tag'
      }
    ]
  }
});

const Tutorial = mongoose.model('Tutorial', tutorialSchema);

module.exports = Tutorial;

TagController.js

const Tag = require('./../models/tagModel');

exports.getAllTags = async (req, res) => {
  try {
    const docs = await Tag.find().populate({
      path: 'tutorials',
      select: '-__v'
    });

    res.status(200).json({
      // some code
    });
  } catch(err) => {
    // some code
  }
});


问:
Delimited file "|" with paragraph text including line breaks spanning multiple lines
I have a large TXT dataset that is delimited by | but there is a field that allows for paragraph text, which contains line breaks and blank lines. All lines that are not part of the paragraph text start with AA|. When I try to import into R via readr these values become NA because it doesn't follow the structure

Is there a way to use sed or awk to take a line if it doesn't start with AA| then to append it to the prior line that does with a space?

Input:

```<code>AA|5904060|9001084471200270|9000263372600200|Result Comment:
No (1, 3) Beta-D-Glucan detected.

This assay does not detect certain fungi, including
Cryptococcus species, which produce very low levels of (1,
3) Beta-D-Glucan (BDG) and the Mucorales (e.g., Lichthemia,
Mucor and Rhizopus), which are not known to produce BDG.
Additionally, the yeast phase of Blastomyces dermatitidis
produces little BDG and may not be detected by this assay.
|North Building|0|0
</code>```

Goal Output:

```<code>AA|5904060|9001084471200270|9000263372600200|Result Comment: No (1, 3) Beta-D-Glucan detected.  This assay does not detect certain fungi, including Cryptococcus species, which produce very low levels of (1, 3) Beta-D-Glucan (BDG) and the Mucorales (e.g., Lichthemia, Mucor and Rhizopus), which are not known to produce BDG. Additionally, the yeast phase of Blastomyces dermatitidis produces little BDG and may not be detected by this assay.|North Building|0|0
</code>```

答:
With gawk I would do something like this:

```<code>awk 'BEGIN {RS="(\n|^)AA\\|"} NR>1 {print "AA|" gensub("\n"," ","g")}' myfile.txt
</code>```

Explanation: Make the literal string AA|, only when found at the beginning of a line, the record separator. Assuming the very first line will begin with AA|, this will cause an empty record to be found first, and we discard it;  processing is done on records from 2 to end (NR > 1). In each record (delimited by this odd delimiter) replace every newline with a space, and print the record with AA| prepended to it (recall that the AA| that existed in the input file is the record separator, so it is no longer in the record itself).

The newline at the end of each record (right before AA| on the next line) is swallowed by the record separator, so you won't have errant spaces at the end of each output line - except for the last record, which is not terminated with "newline AA|" separator. The very last newline in the file survives and is converted to a space in the output; if this extra space at the end of the last record messes up your data, it must be fixed. (Not shown above.)

Body:
I have a large TXT dataset that is delimited by | but there is a field that allows for paragraph text, which contains line breaks and blank lines. All lines that are not part of the paragraph text start with AA|. When I try to import into R via readr these values become NA because it doesn't follow the structure

Is there a way to use sed or awk to take a line if it doesn't start with AA| then to append it to the prior line that does with a space?

Input:

AA|5904060|9001084471200270|9000263372600200|Result Comment:
No (1, 3) Beta-D-Glucan detected.

This assay does not detect certain fungi, including
Cryptococcus species, which produce very low levels of (1,
3) Beta-D-Glucan (BDG) and the Mucorales (e.g., Lichthemia,
Mucor and Rhizopus), which are not known to produce BDG.
Additionally, the yeast phase of Blastomyces dermatitidis
produces little BDG and may not be detected by this assay.
|North Building|0|0

Goal Output:

AA|5904060|9001084471200270|9000263372600200|Result Comment: No (1, 3) Beta-D-Glucan detected.  This assay does not detect certain fungi, including Cryptococcus species, which produce very low levels of (1, 3) Beta-D-Glucan (BDG) and the Mucorales (e.g., Lichthemia, Mucor and Rhizopus), which are not known to produce BDG. Additionally, the yeast phase of Blastomyces dermatitidis produces little BDG and may not be detected by this assay.|North Building|0|0

Body:
With gawk I would do something like this:

awk 'BEGIN {RS="(\n|^)AA\\|"} NR>1 {print "AA|" gensub("\n"," ","g")}' myfile.txt

Explanation: Make the literal string AA|, only when found at the beginning of a line, the record separator. Assuming the very first line will begin with AA|, this will cause an empty record to be found first, and we discard it;  processing is done on records from 2 to end (NR > 1). In each record (delimited by this odd delimiter) replace every newline with a space, and print the record with AA| prepended to it (recall that the AA| that existed in the input file is the record separator, so it is no longer in the record itself).

The newline at the end of each record (right before AA| on the next line) is swallowed by the record separator, so you won't have errant spaces at the end of each output line - except for the last record, which is not terminated with "newline AA|" separator. The very last newline in the file survives and is converted to a space in the output; if this extra space at the end of the last record messes up your data, it must be fixed. (Not shown above.)


问:
Enabling the Windows 10 dictation toolbar programmatically?
Is it possible to activate the new dictation toolbar (the one available since W10 Falls Creators Update) programmatically? I'd like to use dictation in a C# winforms app, but I don't want the user to use windows key+H, I want to activate the dictation toolbar from a button or depending on the context, I don't seem to find an API for that. Per se, dictation works everywhere, even non .net old win32 programs.</p>

答:
One option would be to simulate the key press for WIN+H. You can use the InputSimulator nuget package.

```<code>InputSimulator input = new InputSimulator();
input.Keyboard.ModifiedKeyStroke(VirtualKeyCode.LWIN, VirtualKeyCode.VK_H);
</code>```

The process that is started is 'WindowsInternal.ComposableShell.Experiences.TextInput.InputApp.exe', which you can programmatically start using the registered protocol handler 'ms-inputapp'. But this will not show the UI, it will just start the application if it is not running. This is probably not necessary, since using the hotkey will launch the application if it is not already running, but I wanted to mention this just incase it gives you some additional results when you research this topic.

Body:
One option would be to simulate the key press for WIN+H. You can use the InputSimulator nuget package.

InputSimulator input = new InputSimulator();
input.Keyboard.ModifiedKeyStroke(VirtualKeyCode.LWIN, VirtualKeyCode.VK_H);

The process that is started is 'WindowsInternal.ComposableShell.Experiences.TextInput.InputApp.exe', which you can programmatically start using the registered protocol handler 'ms-inputapp'. But this will not show the UI, it will just start the application if it is not running. This is probably not necessary, since using the hotkey will launch the application if it is not already running, but I wanted to mention this just incase it gives you some additional results when you research this topic.


问:
How to set a variable before calling default constructor in java?
I have the following class:

```<code>public class MyGLSurfaceView extends GLSurfaceView {

    MyRenderer mRenderer;

    public MyGLSurfaceView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        init();
    }
</code>```

I want to add the following constructor:

```<code>public MyGLSurfaceView(Context context, MyRenderer myRenderer) {
</code>```

I tried:

```<code>public class MyGLSurfaceView extends GLSurfaceView {

    MyRenderer mRenderer;
    static AttributeSet attributeSet = null;

    public MyGLSurfaceView(Context context, MyRenderer mRenderer) {
        this.mRenderer = mRenderer;
        this(context, attributeSet);

    }

    public MyGLSurfaceView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        init();
    }
</code>```

but it wont let me set the renderer before calling the default constructor of MyGLSurfaceView.

How to set a variable before calling the default constructor?

答:
Before you can set any fields, you must finish calling any base constructor (whether that's defined in this class or in the super class). So if you need mRenderer set before init() is called, the best you can do is to separate your two constructors (something like this):

```<code>public class MyGLSurfaceView extends GLSurfaceView {

    MyRenderer mRenderer;
    static AttributeSet attributeSet = null;

    public MyGLSurfaceView(Context context, MyRenderer mRenderer) {
        super(context, attributeSet);
        this.mRenderer = mRenderer;
        init();
    }

    public MyGLSurfaceView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        init();
    }
}
</code>```

Body:
I have the following class:

public class MyGLSurfaceView extends GLSurfaceView {

    MyRenderer mRenderer;

    public MyGLSurfaceView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        init();
    }

I want to add the following constructor:

public MyGLSurfaceView(Context context, MyRenderer myRenderer) {

I tried:

public class MyGLSurfaceView extends GLSurfaceView {

    MyRenderer mRenderer;
    static AttributeSet attributeSet = null;

    public MyGLSurfaceView(Context context, MyRenderer mRenderer) {
        this.mRenderer = mRenderer;
        this(context, attributeSet);

    }

    public MyGLSurfaceView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        init();
    }

but it wont let me set the renderer before calling the default constructor of MyGLSurfaceView.

How to set a variable before calling the default constructor?

Body:
Before you can set any fields, you must finish calling any base constructor (whether that's defined in this class or in the super class). So if you need mRenderer set before init() is called, the best you can do is to separate your two constructors (something like this):

public class MyGLSurfaceView extends GLSurfaceView {

    MyRenderer mRenderer;
    static AttributeSet attributeSet = null;

    public MyGLSurfaceView(Context context, MyRenderer mRenderer) {
        super(context, attributeSet);
        this.mRenderer = mRenderer;
        init();
    }

    public MyGLSurfaceView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        init();
    }
}


问:
Setting Hyperlink and Image URL from database -SQL/VB.Net
I have a table which will always just have 3 rows in it which are updated each week. I need to read them and populate 3 ImageUrl's and 3 associated Hyperlinks. However, i'm getting the error :

```<code>System.IndexOutOfRangeException: hyperlink1
</code>```

I'm probably way off here as I'm still learning but here we go.. I select them simply with..

```<code>SELECT
    (SELECT hyperlink As hyperlink1 WHERE productNo=1),
    (SELECT imageUrl As imageUrl1 WHERE productNo=1),
    (SELECT hyperlink As hyperlink2 WHERE productNo=2),
    (SELECT imageUrl As imageUrl2 WHERE productNo=2),
    (SELECT hyperlink As hyperlink3  WHERE productNo=3),
    (SELECT imageUrl As imageUrl3 WHERE productNo=3)
</code>```

FROM tblAmazonProducts
END

Then the VB Code..

    Public Function GetAmazonProducts()
        Dim DBConnectAm As New DBConn
        Using db As DbConnection = DBConnectAm.Conn("DBConnectionString")
            Dim cmd As SqlCommand = DBConnectAm.Command(db, "SelectAmazonProducts")
            'cmd.Parameters.Add(New SqlParameter("productNo", SqlDbType.Int, ParameterDirection.Input)).Value = productNo
            db.Open()
            Dim DR As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
                hypAmazonProduct1.navigateurl=DR("hyperlink1")
                imghypAmazonProduct1.ImageUrl=DR("imageUrl1")
                hypAmazonProduct2.navigateurl=DR("hyperlink2")
                imghypAmazonProduct2.ImageUrl=DR("imageUrl2")
                hypAmazonProduct3.navigateurl=DR("hyperlink3")
                imghypAmazonProduct3.ImageUrl=DR("imageUrl3")
            DR.Close()
            DR = Nothing
            cmd.Dispose()
            cmd = Nothing
            db.Dispose()
            db.Close()
        End Using
   End Function
```

答:
I put the Do While back in and then jiggled the SELECT statement around in each line to look like this:

```<code>SELECT
    (SELECT hyperlink FROM tblAmazonProducts WHERE productNo=1)As hyperlink1,
    (SELECT imageUrl FROM tblAmazonProducts WHERE productNo=1) As imageUrl1,
    (SELECT hyperlink FROM tblAmazonProducts WHERE productNo=2) As hyperlink2,
    (SELECT imageUrl FROM tblAmazonProducts WHERE productNo=2) As imageUrl2,
    (SELECT hyperlink FROM tblAmazonProducts  WHERE productNo=3) As hyperlink3,
    (SELECT imageUrl FROM tblAmazonProducts WHERE productNo=3) As imageUrl3
</code>```

VB..

    Dim DBConnectAm As New DBConn
    Using db As DbConnection = DBConnectAm.Conn("DBConnectionString")
        Dim cmd As SqlCommand = DBConnectAm.Command(db, "SelectAmazonProducts")
        'cmd.Parameters.Add(New SqlParameter("productNo", SqlDbType.Int, ParameterDirection.Input)).Value = productNo
        db.Open()
        Dim DR As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
        While DR.Read
            hypAmazonProduct1.navigateurl=DR("hyperlink1")
            imghypAmazonProduct1.ImageUrl=DR("imageUrl1")
            hypAmazonProduct2.navigateurl=DR("hyperlink2")
            imghypAmazonProduct2.ImageUrl=DR("imageUrl2")
            hypAmazonProduct3.navigateurl=DR("hyperlink3")
            imghypAmazonProduct3.ImageUrl=DR("imageUrl3")
        End While
        DR.Close()
        DR = Nothing
        cmd.Dispose()
        cmd = Nothing
        db.Dispose()
        db.Close()
    End Using
```

Body:
I have a table which will always just have 3 rows in it which are updated each week. I need to read them and populate 3 ImageUrl's and 3 associated Hyperlinks. However, i'm getting the error :

System.IndexOutOfRangeException: hyperlink1

I'm probably way off here as I'm still learning but here we go.. I select them simply with..

SELECT
    (SELECT hyperlink As hyperlink1 WHERE productNo=1),
    (SELECT imageUrl As imageUrl1 WHERE productNo=1),
    (SELECT hyperlink As hyperlink2 WHERE productNo=2),
    (SELECT imageUrl As imageUrl2 WHERE productNo=2),
    (SELECT hyperlink As hyperlink3  WHERE productNo=3),
    (SELECT imageUrl As imageUrl3 WHERE productNo=3)

FROM tblAmazonProducts
END

Then the VB Code..

    Public Function GetAmazonProducts()
        Dim DBConnectAm As New DBConn
        Using db As DbConnection = DBConnectAm.Conn("DBConnectionString")
            Dim cmd As SqlCommand = DBConnectAm.Command(db, "SelectAmazonProducts")
            'cmd.Parameters.Add(New SqlParameter("productNo", SqlDbType.Int, ParameterDirection.Input)).Value = productNo
            db.Open()
            Dim DR As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
                hypAmazonProduct1.navigateurl=DR("hyperlink1")
                imghypAmazonProduct1.ImageUrl=DR("imageUrl1")
                hypAmazonProduct2.navigateurl=DR("hyperlink2")
                imghypAmazonProduct2.ImageUrl=DR("imageUrl2")
                hypAmazonProduct3.navigateurl=DR("hyperlink3")
                imghypAmazonProduct3.ImageUrl=DR("imageUrl3")
            DR.Close()
            DR = Nothing
            cmd.Dispose()
            cmd = Nothing
            db.Dispose()
            db.Close()
        End Using
   End Function

Body:
I put the Do While back in and then jiggled the SELECT statement around in each line to look like this:

SELECT
    (SELECT hyperlink FROM tblAmazonProducts WHERE productNo=1)As hyperlink1,
    (SELECT imageUrl FROM tblAmazonProducts WHERE productNo=1) As imageUrl1,
    (SELECT hyperlink FROM tblAmazonProducts WHERE productNo=2) As hyperlink2,
    (SELECT imageUrl FROM tblAmazonProducts WHERE productNo=2) As imageUrl2,
    (SELECT hyperlink FROM tblAmazonProducts  WHERE productNo=3) As hyperlink3,
    (SELECT imageUrl FROM tblAmazonProducts WHERE productNo=3) As imageUrl3

VB..

    Dim DBConnectAm As New DBConn
    Using db As DbConnection = DBConnectAm.Conn("DBConnectionString")
        Dim cmd As SqlCommand = DBConnectAm.Command(db, "SelectAmazonProducts")
        'cmd.Parameters.Add(New SqlParameter("productNo", SqlDbType.Int, ParameterDirection.Input)).Value = productNo
        db.Open()
        Dim DR As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
        While DR.Read
            hypAmazonProduct1.navigateurl=DR("hyperlink1")
            imghypAmazonProduct1.ImageUrl=DR("imageUrl1")
            hypAmazonProduct2.navigateurl=DR("hyperlink2")
            imghypAmazonProduct2.ImageUrl=DR("imageUrl2")
            hypAmazonProduct3.navigateurl=DR("hyperlink3")
            imghypAmazonProduct3.ImageUrl=DR("imageUrl3")
        End While
        DR.Close()
        DR = Nothing
        cmd.Dispose()
        cmd = Nothing
        db.Dispose()
        db.Close()
    End Using