问:
How to Match Using sed a Multi-Line Range Defined by More Than Two Bounds?
How do I...

...USE sed to match not just the standard 2-bound range, but a range characterized by a "multi-range" -- multiple (>2) submatches in some specific order...

...WHILE containing paired internal matches (e.g. ( / )) that might overlap a pair of the multi-range's bounding patterns?

The Working Simple Range Match

Say I have a pattern whose content resembles something like this in a given formatting:

```<code>           someVar: SomeObj.someFunct
                        ("name1", "name2",
                         SomeConst)
</code>```

In most cases like above, regardless of formatting for some constant SomeObj.someFunct, I could capture w/ the range pattern:

cat $file | sed -ne '/^[ \t]*[a-zA-Z0-9_\: ]*SomeObj.someFunct/,/)/ {p}'

where the dual range bounds are:

/^[ \t]*[a-zA-Z0-9_\: ]*SomeObj.someFunct/

and

/)/

So basically it's looking for the opening bit, then the closing parantheses.

Fail Cases

But this will occasionally fail  if there's stuff in between w/ ).  A simple example might be:

```<code>           someVar: SomeObj.someFunct
                        (thisTimeImCallingTheFunction(), "name2",
                         SomeConst)
</code>```

It also fails if SomeObj.someFunct is on the next line, i.e.:

```<code>           someVar:
              SomeObj.someFunct("name1", "name2",
                         SomeConst)
</code>```

A Multiply Bounded Range?

My idea is that I would like a "multi-range", or the equivalent of:

/^[ \t]*[a-zA-Z0-9_\: ]*/

and

/SomeObj.someFunct/

and

/(/

| and (optional)

|

| some arbitrary # of intermediary ( and ))

and

/)/

...so the range would have to check through at least the 4 bounds, with the final two checking for an optional intermediate to guard against interior ( / ) pairs.

What I got

Unfortunately the naive version of this w/ out even considering the optional interior matches....

cat $file | sed -ne '/^[ \t]*[a-zA-Z0-9_\: ]*/,/SomeObj.someFunct/,/(/,/)/ {p}'

does not work.

It appears that the pattern /check1/,/check2/,/check3/,/check4/ is not valid and some more complex strategy must be employed.

Summary of the Question

check a contiguous range defined by two end patterns and interior patterns in some specific order (but not necessarily on the same line)

for each additional ( encountered, skip one ) before the final match of the range ).

Note/Disclaimer

I searched for previous questions like this, figuring it was asked, but only found questions asking about multiple ranges with standard dual bounds, not a "multi range" in the sense of a single contiguous range defined by more than two bounding matches.

BONUS QUESTION:

Once I have such a multi-bound match, how can I multi-capture the following patterns:

the whitespace before someVar.

The three argument (including interiror ( / ) in the complex case.

答:
sed is for s/old/new, that is all. If you're doing anything else with it then you're using constructs that became obsolete in the 1980s when awk was invented. With GNU awk for multi-char RS and the 3rd arg to match():

```<code>$ cat tst.awk
BEGIN { RS="^$" }
match($0,/([[:blank:]]*\w*:\s*SomeObj\.someFunct\s*\()(.*)/,a) {
    str = a[1]
    while ( match(a[2],/([^\)]*\))(.*)/,a) ) {
        str = str a[1]
        if ( !index(a[1],"(") ) {
            break
        }
    }
    print str
}

$ awk -f tst.awk file
           someVar: SomeObj.someFunct
                        (thisTimeImCallingTheFunction(), "name2",
                         SomeConst)
</code>```

The above finds a string matching your starting regexp then keeps appending strings ending in ) to that string until it reaches a string ending in ) that doesn't contain a (.

Body:
How do I...

...USE sed to match not just the standard 2-bound range, but a range characterized by a "multi-range" -- multiple (>2) submatches in some specific order...

...WHILE containing paired internal matches (e.g. ( / )) that might overlap a pair of the multi-range's bounding patterns?

The Working Simple Range Match

Say I have a pattern whose content resembles something like this in a given formatting:

           someVar: SomeObj.someFunct
                        ("name1", "name2",
                         SomeConst)

In most cases like above, regardless of formatting for some constant SomeObj.someFunct, I could capture w/ the range pattern:

cat $file | sed -ne '/^[ \t]*[a-zA-Z0-9_\: ]*SomeObj.someFunct/,/)/ {p}'

where the dual range bounds are:

/^[ \t]*[a-zA-Z0-9_\: ]*SomeObj.someFunct/

and

/)/

So basically it's looking for the opening bit, then the closing parantheses.

Fail Cases

But this will occasionally fail  if there's stuff in between w/ ).  A simple example might be:

           someVar: SomeObj.someFunct
                        (thisTimeImCallingTheFunction(), "name2",
                         SomeConst)

It also fails if SomeObj.someFunct is on the next line, i.e.:

           someVar:
              SomeObj.someFunct("name1", "name2",
                         SomeConst)

A Multiply Bounded Range?

My idea is that I would like a "multi-range", or the equivalent of:

/^[ \t]*[a-zA-Z0-9_\: ]*/

and

/SomeObj.someFunct/

and

/(/

| and (optional)

|

| some arbitrary # of intermediary ( and ))

and

/)/

...so the range would have to check through at least the 4 bounds, with the final two checking for an optional intermediate to guard against interior ( / ) pairs.

What I got

Unfortunately the naive version of this w/ out even considering the optional interior matches....

cat $file | sed -ne '/^[ \t]*[a-zA-Z0-9_\: ]*/,/SomeObj.someFunct/,/(/,/)/ {p}'

does not work.

It appears that the pattern /check1/,/check2/,/check3/,/check4/ is not valid and some more complex strategy must be employed.

Summary of the Question

check a contiguous range defined by two end patterns and interior patterns in some specific order (but not necessarily on the same line)

for each additional ( encountered, skip one ) before the final match of the range ).

Note/Disclaimer

I searched for previous questions like this, figuring it was asked, but only found questions asking about multiple ranges with standard dual bounds, not a "multi range" in the sense of a single contiguous range defined by more than two bounding matches.

BONUS QUESTION:

Once I have such a multi-bound match, how can I multi-capture the following patterns:

the whitespace before someVar.

The three argument (including interiror ( / ) in the complex case.

Body:
sed is for s/old/new, that is all. If you're doing anything else with it then you're using constructs that became obsolete in the 1980s when awk was invented. With GNU awk for multi-char RS and the 3rd arg to match():

$ cat tst.awk
BEGIN { RS="^$" }
match($0,/([[:blank:]]*\w*:\s*SomeObj\.someFunct\s*\()(.*)/,a) {
    str = a[1]
    while ( match(a[2],/([^\)]*\))(.*)/,a) ) {
        str = str a[1]
        if ( !index(a[1],"(") ) {
            break
        }
    }
    print str
}

$ awk -f tst.awk file
           someVar: SomeObj.someFunct
                        (thisTimeImCallingTheFunction(), "name2",
                         SomeConst)

The above finds a string matching your starting regexp then keeps appending strings ending in ) to that string until it reaches a string ending in ) that doesn't contain a (.


来源: stackexchange

问:
MS Access 2016 UPDATE query with ALIKE
I'm trying to run the following UPDATE query in MS Access 2016 VBA:

```<code>UPDATE M_Subscriber
    SET M_Subscriber.RatingID = t.RatingID
    FROM
        ( SELECT M_Subscriber.ID AS SubscriberID, E_SubscriberRating.ID AS RatingID
              FROM M_Subscriber, E_SubscriberRating
              WHERE M_Subscriber.Labels ALIKE '%' & E_SubscriberRating.Description & '%'
        ) AS t
    WHERE M_Subscriber.ID = t.SubscriberID
</code>```

However, when trying to execute it I get a "syntax error (missing operator) in query expression" error.

I know that the SELECT part of the query by itself works just as expected (though using LIKE instead of ALIKE does not, even when using * for the wildcard...).

I've also tried this version of the query:

```<code>UPDATE M_Subscriber
    SET M_Subscriber.RatingID = E_SubscriberRating.ID
    FROM M_Subscriber
        INNER JOIN E_SubscriberRating
        ON M_Subscriber.Labels ALIKE '%' & E_SubscriberRating.Description & '%'
</code>```

But again the same error message (and again, a standalone SELECT statement using the INNER JOIN works just fine).

Some info on what I'm trying to do:

I have a field of labels (just at string of various words) for my subscribers (in M_Subscriber) and one of those words can be a rating. On the other hand I have a table (E_SubscriberRatings) of all possible words for ratings (E_SubscriberRating.Description). I'm now trying to set the M_Subscriber.RatingID field based on the ID of the SubscriberRating whose description shows up in the M_Subscriber.Labels field (if it actually contains any such description).

At this point, I've really run out of ideas what to tweak to figure out what I'm doing wrong. I've found various examples that join by column = column but none that join using LIKE.

答:
MS Access does not use FROM in UPDATE queries unlike other SQL dialects. Consider UPDATE...INNER JOIN (a method it shares with MySQL) and do so with table aliases:

UPDATE M_Subscriber m
INNER JOIN E_SubscriberRating e
ON m.Labels ALIKE '%' & e.Description & '%'
SET m.RatingID = e.ID;
```

<p>Alternatively, with <code>WHERE</code> clause: </p>

<pre class="lang-sql prettyprint-override"><code>UPDATE M_Subscriber m, E_SubscriberRating e
SET m.RatingID = e.ID
WHERE m.Labels ALIKE '%' & e.Description & '%';
</code>```

ContentLicense: CC BY-SA 3.0

Title: MS Access 2016 UPDATE query with ALIKE

Body:
I'm trying to run the following UPDATE query in MS Access 2016 VBA:

UPDATE M_Subscriber
    SET M_Subscriber.RatingID = t.RatingID
    FROM
        ( SELECT M_Subscriber.ID AS SubscriberID, E_SubscriberRating.ID AS RatingID
              FROM M_Subscriber, E_SubscriberRating
              WHERE M_Subscriber.Labels ALIKE '%' & E_SubscriberRating.Description & '%'
        ) AS t
    WHERE M_Subscriber.ID = t.SubscriberID

However, when trying to execute it I get a "syntax error (missing operator) in query expression" error.

I know that the SELECT part of the query by itself works just as expected (though using LIKE instead of ALIKE does not, even when using * for the wildcard...).

I've also tried this version of the query:

UPDATE M_Subscriber
    SET M_Subscriber.RatingID = E_SubscriberRating.ID
    FROM M_Subscriber
        INNER JOIN E_SubscriberRating
        ON M_Subscriber.Labels ALIKE '%' & E_SubscriberRating.Description & '%'

But again the same error message (and again, a standalone SELECT statement using the INNER JOIN works just fine).

Some info on what I'm trying to do:

I have a field of labels (just at string of various words) for my subscribers (in M_Subscriber) and one of those words can be a rating. On the other hand I have a table (E_SubscriberRatings) of all possible words for ratings (E_SubscriberRating.Description). I'm now trying to set the M_Subscriber.RatingID field based on the ID of the SubscriberRating whose description shows up in the M_Subscriber.Labels field (if it actually contains any such description).

At this point, I've really run out of ideas what to tweak to figure out what I'm doing wrong. I've found various examples that join by column = column but none that join using LIKE.

Body:
MS Access does not use FROM in UPDATE queries unlike other SQL dialects. Consider UPDATE...INNER JOIN (a method it shares with MySQL) and do so with table aliases:

UPDATE M_Subscriber m
INNER JOIN E_SubscriberRating e
ON m.Labels ALIKE '%' & e.Description & '%'
SET m.RatingID = e.ID;

Alternatively, with WHERE clause:

UPDATE M_Subscriber m, E_SubscriberRating e
SET m.RatingID = e.ID
WHERE m.Labels ALIKE '%' & e.Description & '%';


问:
Why doesn't app.component.html render?
I have the following Angular plnkr.co: https://plnkr.co/edit/xA8jU4QYDGxzohNg5NFj?p=preview.

//app.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent { name = 'Angular'; }
</code>```

//app.component.html

```<code>testing...
<router-outlet></router-outlet>
</code>```

The oputput in the browser is:

```<code>Loading AppComponent content here ...
</code>```

Why doesn't it see the app.component.html file? Or is this some other issue?

答:
Your app.component.html contains <router-outlet></router-outlet> but there are no child routes defined. This is causing the issue.

In order to fix this, either you need to remove router-outlet from app.component.html or you should define child route config in app.router.ts.

Working Example: https://plnkr.co/edit/wbW1s8PqDtu35GR8HC8D?p=preview

Visit Angular Guide for routes to read more about routing config and child routes.

Title: Why doesn't app.component.html render?

Body:
I have the following Angular plnkr.co: https://plnkr.co/edit/xA8jU4QYDGxzohNg5NFj?p=preview.

//app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent { name = 'Angular'; }

//app.component.html

testing...
<router-outlet></router-outlet>

The oputput in the browser is:

Loading AppComponent content here ...

Why doesn't it see the app.component.html file? Or is this some other issue?


问:
Extend a generic super class in a sub class
A.java

```<code>public class A<E> {

   Class cClass;

   public A(Class rClass) {
        this.cClass = rClass;
   }

   public E get() throws IllegalAccessException, InstantiationException {
        return (E) this.cClass.newInstance();
   }
}
</code>```

A1.java

```<code>public class A1 extends A {}
</code>```

I am trying to design a class A as generic and class A1 is a sub class of class A. Object creation should look something like this.

```<code>A<A1> a1 = new A<>();
</code>```

I want provide a way that no one will create an object like this

```<code>A<B1> a1 = new A<>();
</code>```

where class B1 is not a subclass of A.

How can i resolve this? Error

```<code> error: constructor Operation in class A<E> cannot be applied to given types
</code>```

答:
I don't know why you need such construction, but to make your code work, you should add class A<E extends A>, if you want

provide a way that no one will create an object like this
  A<B1> a1 = new A<>(); where class B1 is not a subclass of A.

```<code>public class A<E extends A> {

    private Class<E> cClass;

    public A() {
    }

    public A(Class<E> rClass) {
        this.cClass = rClass;
    }

    public E get() throws IllegalAccessException, InstantiationException {
        return this.cClass.newInstance();
    }

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        A<A1> a = new A<>(A1.class);

        A1 a1 = a.get();

        //error
        //A<B1> a = new A<>();
    }
}
</code>```

You can remove default constructor public A() {}, but then in your A1 class you have to add

```<code>public A1() {
    super(A1.class);
}
</code>```

UPDATE: According to your comment, you want to get a class of a generic type at runtime, and that is not possible. Take a looke at this question

Body:
A.java

public class A<E> {

   Class cClass;

   public A(Class rClass) {
        this.cClass = rClass;
   }

   public E get() throws IllegalAccessException, InstantiationException {
        return (E) this.cClass.newInstance();
   }
}

A1.java

public class A1 extends A {}

I am trying to design a class A as generic and class A1 is a sub class of class A. Object creation should look something like this.

A<A1> a1 = new A<>();

I want provide a way that no one will create an object like this

A<B1> a1 = new A<>();

where class B1 is not a subclass of A.

How can i resolve this? Error

 error: constructor Operation in class A<E> cannot be applied to given types

Body:
I don't know why you need such construction, but to make your code work, you should add class A<E extends A>, if you want

provide a way that no one will create an object like this
  A<B1> a1 = new A<>(); where class B1 is not a subclass of A.

public class A<E extends A> {

    private Class<E> cClass;

    public A() {
    }

    public A(Class<E> rClass) {
        this.cClass = rClass;
    }

    public E get() throws IllegalAccessException, InstantiationException {
        return this.cClass.newInstance();
    }

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        A<A1> a = new A<>(A1.class);

        A1 a1 = a.get();

        //error
        //A<B1> a = new A<>();
    }
}

You can remove default constructor public A() {}, but then in your A1 class you have to add

public A1() {
    super(A1.class);
}

UPDATE: According to your comment, you want to get a class of a generic type at runtime, and that is not possible. Take a looke at this question


问:
GitHub fetch update the local repository but code results still for old code
I fetch the code from GitHub. The local repository is updated and same as one on the upstream. But when I run the code it brings the results of code before update? I am using git on eclipse  </p>

答: git fetch is used for fetch branch on your local repository, but if you want to update your code with the latest, you'd do a pull in your branch. git pull <remote repository> <branch>. If you use git fetch, you'll see new branches on your local repository.


问:
OpenGL: how to use integers in glVertex3i
glBegin(GL_TRIANGLES);
    glVertex3i(100,100,0);
    glVertex3i(100,80,0);
    glVertex3i(80,80,0);
glEnd();

These calls does not work.
Only glVertex3f works, just do not know why.
But in glVertex3f, I can only put float less than 1.
Since if I put some float large than 1, the vertex will be out of the screen.

So my question is that why above calls does not work?
I think the primitves are out of the boudary, but do not know why.

答:
The fact that you don't see them on your screen doesn't mean they don't actually exist in the openGL "universe".

Try to move the camera away (with the gluLookAt method - or with translates and rotates) and place the points again. You should see them without any trouble.

Moreover, I would like to correct you on the assumption that glVertex3f only takes numbers between 0 to 1, which it doesn't. Your code could be:

glVertex3f(100.0, 100.0, 0.0);

And it would work as well, if the position of the camera allows you to see the elements you're drawing.

ContentLicense: CC BY-SA 2.5


问:
webpack-dev-server open and host opens wrong URL
Per the docs here and here, I have the following in my package.json

```<code>"scripts": {
  "start": "webpack-dev-server --host 0.0.0.0 --open",
  ...
</code>```

With just --open it opens localhost:8080 when I run npm start. When I add in --host 0.0.0.0 it still opens, but opens 0.0.0.0:8080 and gives me ERR_EMPTY_RESPONSE in the browser.  I can manually change it to localhost:8080 and it loads the page just fine.

I tried --host 0.0.0.0 --open --open-page localhost:8080 and it dutifully opens http://0.0.0.0:8080/localhost:8080 for me in the browser.

Has anyone gotten these two options to play nicely together?

答:
Below works fine for me

```<code>webpack-dev-server -p --public 127.0.0.1:9000 --host 0.0.0.0 --port 9000
</code>```

--host is the listening interface. --public is for what would be opened in the browser. And --open-page is for appending the page url after the main domain

Body:
Per the docs here and here, I have the following in my package.json

"scripts": {
  "start": "webpack-dev-server --host 0.0.0.0 --open",
  ...

With just --open it opens localhost:8080 when I run npm start. When I add in --host 0.0.0.0 it still opens, but opens 0.0.0.0:8080 and gives me ERR_EMPTY_RESPONSE in the browser.  I can manually change it to localhost:8080 and it loads the page just fine.

I tried --host 0.0.0.0 --open --open-page localhost:8080 and it dutifully opens http://0.0.0.0:8080/localhost:8080 for me in the browser.

Has anyone gotten these two options to play nicely together?

Body:
Below works fine for me

webpack-dev-server -p --public 127.0.0.1:9000 --host 0.0.0.0 --port 9000

--host is the listening interface. --public is for what would be opened in the browser. And --open-page is for appending the page url after the main domain


问:
Intercept click event on a button, ask for confirmation, then proceed
Based on a variable SomeCondition, I need to intercept a click event on a button, and ask for confirmation, if they say ok, proceed, otherwise ignore click.

So something like:

```<code>if(SomeCondition) {

// disable click on button

var isOk = window.confirm("Are you sure?");

if(isOk) {
        $("#button1").click();
}

}
</code>```

Note: button1 has already been wired up with a click event via javascript from an external .js file that I can't change.

I don't know what the click event was bound too, so I have to disable the click if SomeCondition is true, then ask for confirmation, then continue with the click.

答:
I could not get any of the answers above to work using jquery 1.9.1

here is what worked for a previously set click event

```<code>var elem = $('#button1');
var oldClick = $._data(elem[0], 'events').click[0].handler;
elem.off('click');

// Pass the original event object.
elem.click(function(e){
  if(window.confirm("Are You Sure?")){
    oldClick(e);
  } else {
    return false;
  }
});
</code>```

very similar to Jason Benson's answer above

Body:
Based on a variable SomeCondition, I need to intercept a click event on a button, and ask for confirmation, if they say ok, proceed, otherwise ignore click.

So something like:

if(SomeCondition) {

// disable click on button

var isOk = window.confirm("Are you sure?");

if(isOk) {
        $("#button1").click();
}

}

Note: button1 has already been wired up with a click event via javascript from an external .js file that I can't change.

I don't know what the click event was bound too, so I have to disable the click if SomeCondition is true, then ask for confirmation, then continue with the click.

Body:
I could not get any of the answers above to work using jquery 1.9.1

here is what worked for a previously set click event

var elem = $('#button1');
var oldClick = $._data(elem[0], 'events').click[0].handler;
elem.off('click');

// Pass the original event object.
elem.click(function(e){
  if(window.confirm("Are You Sure?")){
    oldClick(e);
  } else {
    return false;
  }
});

very similar to Jason Benson's answer above

ContentLicense: CC BY-SA 4.0


问:
How to remove week and Day view buttons from FullCalendar in laravel project?
I'm using FullCalendar in my laravel project and I want to remove week and day buttons from the header bar.

```<code>$calendar = Calendar::addEvents($data)
          ->setOptions([ //set fullcalendar options
              'firstDay' => 1,
              'height' => 'auto',
              'themeSystem' => 'bootstrap3',
              'columnHeader' => false,
              'aspectRatio' => 1,
              'allDayDefault'=> false,

          ])->setCallbacks([
    'eventRender'=> 'function (event, element, view) {
        var dateString = event.start.format("YYYY-MM-DD");

        $(view.el[0]).find(".fc-day[data-date=" + dateString +"]").css("background-color", "#FAA732");
     }'
          ]);

      $subset = $data->map(function ($data) {
          return collect($data->toArray())
              ->only(['title','start', 'end'])
              ->all();
      });
      return view('events.calendar', compact('calendar','data'));
</code>```

So, I want to remove those week and day view button s from fullCalendar.

I used 'allDayDefault'=> false and also allDay='false' but both of them are not working.

答:
To disable another button then Month you can use right: 'month' in your calendar options and right: '' for get rid of month button.
you have to add this following option into your setOption parameter.:

```<code>$calendar = Calendar::addEvents($data)
          ->setOptions([ //set fullcalendar options
              'firstDay' => 1,
              'height' => 'auto',
              'themeSystem' => 'bootstrap3',
              'columnHeader' => false,
              'aspectRatio' => 1,
              'allDayDefault'=> false,
              'header' => [
                    'left' => 'today prev,next',
                    'center' =>'title',
                    'right' =>'month'],
              .......
</code>```

Body:
I'm using FullCalendar in my laravel project and I want to remove week and day buttons from the header bar.

$calendar = Calendar::addEvents($data)
          ->setOptions([ //set fullcalendar options
              'firstDay' => 1,
              'height' => 'auto',
              'themeSystem' => 'bootstrap3',
              'columnHeader' => false,
              'aspectRatio' => 1,
              'allDayDefault'=> false,

          ])->setCallbacks([
    'eventRender'=> 'function (event, element, view) {
        var dateString = event.start.format("YYYY-MM-DD");

        $(view.el[0]).find(".fc-day[data-date=" + dateString +"]").css("background-color", "#FAA732");
     }'
          ]);

      $subset = $data->map(function ($data) {
          return collect($data->toArray())
              ->only(['title','start', 'end'])
              ->all();
      });
      return view('events.calendar', compact('calendar','data'));

So, I want to remove those week and day view button s from fullCalendar.

I used 'allDayDefault'=> false and also allDay='false' but both of them are not working.

Body:
To disable another button then Month you can use right: 'month' in your calendar options and right: '' for get rid of month button.
you have to add this following option into your setOption parameter.:

$calendar = Calendar::addEvents($data)
          ->setOptions([ //set fullcalendar options
              'firstDay' => 1,
              'height' => 'auto',
              'themeSystem' => 'bootstrap3',
              'columnHeader' => false,
              'aspectRatio' => 1,
              'allDayDefault'=> false,
              'header' => [
                    'left' => 'today prev,next',
                    'center' =>'title',
                    'right' =>'month'],
              .......


问:
Regex to search for string?
The strings I want to match will always contain the phrase "START". How can I only return matches that contain this phrase?

Here is my current pattern:

"(?<=utm_name=potato\" rel=(\"carrot\"|\"*\") >)(.*?)(?=)"

Here is the string input:

&utm_name=potato" rel="" >[START] This is a sentence. &utm_name=potato" rel="carrot" >[START] This is another sentence. &utm_name=potato" rel="carrot" >[FALSE] Do not match this sentence.

Desired output:

[START] This is a sentence.

[START] This is another sentence.

Current output:

[START] This is a sentence.

[START] This is another sentence.

[FALSE] Do not match this sentence.

答:
One way to do this is to use .IndexOf() passing the search arguments on a string.

Start out with creating an int to hold the index value of search phrase, as well as the index value of where you think the phrase is going to end.

The substring you desire lies between the index of your initial search phrase, and the index of your last search phrase. In this case, the last phrase ends on another search string, i. e. .

```<code>string test = "&utm_name=potato\" rel=\"\" >[START] This is a sentence.</a> <span class=\"beans\">&utm_name=potato\" rel=\"carrot\" >[START] This is another sentence.</a> <span class=\"beans\">&utm_name=potato\" rel=\"carrot\" >[FALSE] Do not match this sentence.</a> <span class=\"beans\">";

string searchString = ">[START] ";  //start after this
string endSearchString = "</a>"; //end before this
</code>```

Ensure that when you are creating the index of the initial search phrase, you add the length of that search phrase.

```<code>//find the index of them within the sample test string
int indexOfInitial = test.IndexOf(searchString) + searchString.Length;
int indexOfEnding = test.IndexOf(endSearchString);
</code>```

Create a length for the new substring.  This is going to be the value of the index of the last search phrase subtracted by the index of the initial search phrase.  You now have what is necessary to create a substring.

```<code>//create a length for substring
int length = indexOfEnding - indexOfInitial;
//create desired substring out of search string and length between start and end phrases
string desiredSubstring = test.Substring(indexOfInitial, length);
</code>```

For an example of how this works with your string input heres a code demo:

```<code>static void Main(string[] args)
{
    //create sample test string
    string test = "&utm_name=potato\" rel=\"\" >[START] This is a sentence.</a> <span class=\"beans\">&utm_name=potato\" rel=\"carrot\" >[START] This is another sentence.</a> <span class=\"beans\">&utm_name=potato\" rel=\"carrot\" >[FALSE] Do not match this sentence.</a> <span class=\"beans\">";
    //create strings you are searching for
    string searchString = ">[START] ";
    string endSearchString = "</a>";

    Console.WriteLine("String:");
    Console.WriteLine(test);

    //find the index of them within the sample test string
    int indexOfInitial = test.IndexOf(searchString) + searchString.Length;
    int indexOfEnding = test.IndexOf(endSearchString);

    //create a length for substring
    int length = indexOfEnding - indexOfInitial;

    string desiredSubstring = test.Substring(indexOfInitial, length);

    //desired result 1
    Console.WriteLine("\nResult 1:\n\n{0}", desiredSubstring);

    //Take of everything from the indexOfEnding
    test = test.Substring(indexOfEnding+endSearchString.Length);
    Console.WriteLine("\nString:\n{0}\n",test);

    //change the search strings if needed
    //endSearchString = "</ a >"; //notice the spacing changing

    //find the index of them again within the new substring
    indexOfInitial = test.IndexOf(searchString) + searchString.Length;
    indexOfEnding = test.IndexOf(endSearchString);
    //create a length for substring
    length = indexOfEnding - indexOfInitial;
    //desired result 2
    Console.WriteLine("\nResult 2:\n\n{0}", test.Substring(indexOfInitial, length));
    Console.ReadKey();
}
</code>```

Title: Regex to search for string?

Body:
One way to do this is to use .IndexOf() passing the search arguments on a string.

Start out with creating an int to hold the index value of search phrase, as well as the index value of where you think the phrase is going to end.

The substring you desire lies between the index of your initial search phrase, and the index of your last search phrase. In this case, the last phrase ends on another search string, i. e. </a>.

string test = "&amp;utm_name=potato\" rel=\"\" >[START] This is a sentence.</a>&#32;<span class=\"beans\">&amp;utm_name=potato\" rel=\"carrot\" >[START] This is another sentence.</a>&#32;<span class=\"beans\">&amp;utm_name=potato\" rel=\"carrot\" >[FALSE] Do not match this sentence.</a>&#32;<span class=\"beans\">";

string searchString = ">[START] ";  //start after this
string endSearchString = "</a>"; //end before this

Ensure that when you are creating the index of the initial search phrase, you add the length of that search phrase.

//find the index of them within the sample test string
int indexOfInitial = test.IndexOf(searchString) + searchString.Length;
int indexOfEnding = test.IndexOf(endSearchString);

Create a length for the new substring.  This is going to be the value of the index of the last search phrase subtracted by the index of the initial search phrase.  You now have what is necessary to create a substring.

//create a length for substring
int length = indexOfEnding - indexOfInitial;
//create desired substring out of search string and length between start and end phrases
string desiredSubstring = test.Substring(indexOfInitial, length);

For an example of how this works with your string input heres a code demo:

static void Main(string[] args)
{
    //create sample test string
    string test = "&amp;utm_name=potato\" rel=\"\" >[START] This is a sentence.</a>&#32;<span class=\"beans\">&amp;utm_name=potato\" rel=\"carrot\" >[START] This is another sentence.</a>&#32;<span class=\"beans\">&amp;utm_name=potato\" rel=\"carrot\" >[FALSE] Do not match this sentence.</a>&#32;<span class=\"beans\">";
    //create strings you are searching for
    string searchString = ">[START] ";
    string endSearchString = "</a>";

    Console.WriteLine("String:");
    Console.WriteLine(test);

    //find the index of them within the sample test string
    int indexOfInitial = test.IndexOf(searchString) + searchString.Length;
    int indexOfEnding = test.IndexOf(endSearchString);

    //create a length for substring
    int length = indexOfEnding - indexOfInitial;

    string desiredSubstring = test.Substring(indexOfInitial, length);

    //desired result 1
    Console.WriteLine("\nResult 1:\n\n{0}", desiredSubstring);

    //Take of everything from the indexOfEnding
    test = test.Substring(indexOfEnding+endSearchString.Length);
    Console.WriteLine("\nString:\n{0}\n",test);

    //change the search strings if needed
    //endSearchString = "</ a >"; //notice the spacing changing

    //find the index of them again within the new substring
    indexOfInitial = test.IndexOf(searchString) + searchString.Length;
    indexOfEnding = test.IndexOf(endSearchString);
    //create a length for substring
    length = indexOfEnding - indexOfInitial;
    //desired result 2
    Console.WriteLine("\nResult 2:\n\n{0}", test.Substring(indexOfInitial, length));
    Console.ReadKey();
}


问:
Intersection of two large word lists
I have two word lists (180k and 260k), and I would like to generate a third file which is the set of words that appear in BOTH lists.

What is the best (most efficient) way of doing this? I've read forums talking about using grep, however I think the word lists are too big for this method.

答:
Presuming one word per line, I would use grep:

```<code>grep -xFf seta setb
</code>```

-x matches the whole lines (no partial matches)

-F interprets the given patterns literally (no regular expressions)

-f seta specifies the patterns to search

setb is the file to search for the contents of seta

comm will do the same thing, but requires your sets to be pre-sorted:

```<code>comm -12 <(sort seta) <(sort setb)
</code>```

Title: Intersection of two large word lists

Body:
Presuming one word per line, I would use grep:

grep -xFf seta setb

-x matches the whole lines (no partial matches)

-F interprets the given patterns literally (no regular expressions)

-f seta specifies the patterns to search

setb is the file to search for the contents of seta

comm will do the same thing, but requires your sets to be pre-sorted:

comm -12 <(sort seta) <(sort setb)


问:
JPA/Criteria Like percent character
I am trying to build dynamic query (with like condition). When I try it with raw sql into the mysql , it worked very well. Here is an example:

```<code>select * from dbiwant.want_activity m where m.want like "%bike%"
</code>```

Then,  I've tried it with the CriteriaBuilder but I couldn't achieve to get the same results in Java. Just empty result. Here is my code:

```<code>Specifications specifications = Specifications.where(specificationService.isLike("want", search));

public Specification<WantActivity> isLike(String param, String search) {
        return new Specification<WantActivity>() {
            public javax.persistence.criteria.Predicate toPredicate(Root<WantActivity> root, CriteriaQuery<?> query,
                                                                    CriteriaBuilder builder) {
                return builder.like(root.get(param) ,"%" + search + "%");
            }
        };
}
</code>```

What's the problem?

答:
try this:</p>

```<code>public Specification<WantActivity> isLike(String param, String search) {
    return new Specification<WantActivity>() {
        public javax.persistence.criteria.Predicate toPredicate(Root<WantActivity> root, CriteriaQuery<?> query,
                                                                CriteriaBuilder builder) {

final Predicate like = query.where(builder.like(root.<String> get(param), search)).getRestriction();
return like;
        }
    };
</code>```

Title: JPA/Criteria Like percent character

Body:
I am trying to build dynamic query (with like condition). When I try it with raw sql into the mysql , it worked very well. Here is an example:

select * from dbiwant.want_activity m where m.want like "%bike%"

Then,  I've tried it with the CriteriaBuilder but I couldn't achieve to get the same results in Java. Just empty result. Here is my code:

Specifications specifications = Specifications.where(specificationService.isLike("want", search));

public Specification<WantActivity> isLike(String param, String search) {
        return new Specification<WantActivity>() {
            public javax.persistence.criteria.Predicate toPredicate(Root<WantActivity> root, CriteriaQuery<?> query,
                                                                    CriteriaBuilder builder) {
                return builder.like(root.get(param) ,"%" + search + "%");
            }
        };
}

What's the problem?

Body:
try this:

public Specification<WantActivity> isLike(String param, String search) {
    return new Specification<WantActivity>() {
        public javax.persistence.criteria.Predicate toPredicate(Root<WantActivity> root, CriteriaQuery<?> query,
                                                                CriteriaBuilder builder) {

final Predicate like = query.where(builder.like(root.<String> get(param), search)).getRestriction();
return like;
        }
    };


问:
How droping a table from DB affects the views
A veiw is created on table Student.
If i drop the student table will the veiw also drop ? If not what will be the situation ? </p>

答: The view remains but is invalid.  You must explicitly drop the view.</p>


问:
Get partial tree() of a gremlin query
I am running this Gremlin query agains a Cosmos DB database. Which returns every persons 'p' for whom there exists a friend 'f' and including the friend 'f'

```<code>g.V().hasLabel('person').as('p')
     .out('friends').as('f')
     .select('f')
     .optional(outE()).tree()
</code>```

Actual result is something like

```<code>{ p1: { f1, .. }, p2: { f1, ... } }
</code>```

But how can I get only the friends 'f' and optional edges of 'f'? something like this:

```<code>{ f1, f2, ... }
</code>```

Portion of the actual result in GraphSON format:

```<code>{
  "3": {
    "key": {"id": "1",...},
    "value": {
      "2": {
        "key": {
          "id": "2",
          "label": "person",
          "type": "vertex"
        },
        "value": { ... }
      }
    }
  },
  "1": {
    "key": {"id": "1", ... },
    "value": {
      "2": {
        "key": {
          "id": "2",
          "label": "person",
          "type": "vertex"
        },
        "value": {...}
      }
    }
  }
}
</code>```

答:
unfold() the tree result and select the values. This way you can get rid of the root nodes.

```<code>g.V().hasLabel('person').
  out('friends').
  optional(outE()).tree().
  unfold().
  select(values)
</code>```

Title: Get partial tree() of a gremlin query

Body:
I am running this Gremlin query agains a Cosmos DB database. Which returns every persons 'p' for whom there exists a friend 'f' and including the friend 'f'

g.V().hasLabel('person').as('p')
     .out('friends').as('f')
     .select('f')
     .optional(outE()).tree()

Actual result is something like

{ p1: { f1, .. }, p2: { f1, ... } }

But how can I get only the friends 'f' and optional edges of 'f'? something like this:

{ f1, f2, ... }

Portion of the actual result in GraphSON format:

{
  "3": {
    "key": {"id": "1",...},
    "value": {
      "2": {
        "key": {
          "id": "2",
          "label": "person",
          "type": "vertex"
        },
        "value": { ... }
      }
    }
  },
  "1": {
    "key": {"id": "1", ... },
    "value": {
      "2": {
        "key": {
          "id": "2",
          "label": "person",
          "type": "vertex"
        },
        "value": {...}
      }
    }
  }
}

Body:
unfold() the tree result and select the values. This way you can get rid of the root nodes.

g.V().hasLabel('person').
  out('friends').
  optional(outE()).tree().
  unfold().
  select(values)


问:
NserviceBus rollback after sending
Hi I have with this code

```<code> SendMessageToMyQueue();
UpdateStatusInDbThatMessageWasSent();
</code>```

that sometimes message is processed before status is updated which I would like to avoid.

My question is if I wrap that two line with a transaction like this:

```<code>using(var tr = new TransactionScope())
{
  SendMessageToMyQueue();
UpdateStatusInDbThatMessageWasSent();
tr.Compleate();
}
</code>```

will be guaranteed that there will be a lock on MyQueue created and this lock will be not released until UpdateStatusInDbThatMessageWasSent will update the status?

also if I add try catch with rollback and updating status fails, will the message be removed from MyQueue ?

答:
There is no such thing as lock on a queue. The message, however, will be processed transactionally, if the following conditions are met. By transactionally, I mean that the message will be returned to the queue if an unhandled exception is thrown. The conditions to make this happen are:

Your database can enlist and take part in a distributed transaction. Not every database out there does. Some Document databases have none (in case of MongoDB) or sketchy (in case of RavenDB) support for DTC.

Your transport also supports distributed transactions. If you go with a broker type transports, SQL Server Transport is your best bet and on Bus type transports MSMQ is a good choice. Transports like Azure ServiceBus or RabbitMQ have very limited transactions support and do not support distributed transactions.

You'll need to run Distributed Transaction Coordinator service configured and running.

Two other things to note:

What if you're using a transport that lacks DTC support? Most of the time, you are better off if you can design your system to be idempotent. Outbox feature of NServiceBus allows you simulate DTC to some extent.

When a message is picked from the queue, processed, and returned to the queue due to an exception, it might end up being in a different place in the queue. You need to design for messages arriving out of order when designing a message-based architecture.

With all said above, exactly-once delivery guarantees are always a hot topic and disputed.

Title: NserviceBus rollback after sending

Body:
Hi I have with this code

 SendMessageToMyQueue();
UpdateStatusInDbThatMessageWasSent();

that sometimes message is processed before status is updated which I would like to avoid.

My question is if I wrap that two line with a transaction like this:

using(var tr = new TransactionScope())
{
  SendMessageToMyQueue();
UpdateStatusInDbThatMessageWasSent();
tr.Compleate();
}

will be guaranteed that there will be a lock on MyQueue created and this lock will be not released until UpdateStatusInDbThatMessageWasSent will update the status?

also if I add try catch with rollback and updating status fails, will the message be removed from MyQueue ?


问:
Conditional Attributes in Fractal laravel transformers
I'm using Fractal laravel package as a presentation and transformation layer for complex data output.

I wrote a UserTransformer like this :

```<code>public function transform(User $user)
    {
        return [
            'user_id'            => (int)$user->user_id,
            'name'               => $user->name,
            'family'             => $user->family,
            'username'           => $user->username,
            'token'              => $user->token,
            'mobile'             => $user->mobile,
            'email'              => $user->email,
            'sex'                => $user->sex,
            'tel'                => $user->tel,
            'province'           => $user->province,
            'city'               => $user->city,
            'picture'            => $user->picture,
            'birthday'           => $user->birthday,
            'wedding_date'       => $user->wedding_date,
            'wife_birthday'      => $user->wife_birthday,
            'desc'               => $user->desc,
            'active'             => (bool) $user->active,
            'supervisor'         => $user->supervisor,
            'two_factor_enabled' => (bool) $user->two_factor_enabled,
            'address'            => $user->address,
            'created_at'         => $user->created_at,
        ];
    }
</code>```

Now in some situation I want to return specific fields of User model as a collection like this :

```<code>public function index()
    {
        return $this->collection(User::get(['user_id','name','family','username','created_at']), new UserTransformer());
    }
</code>```

But in this case result is like this :

```<code>"result": [
        {
            "user_id": 1,
            "name": "ahmad",
            "family": "badpey",
            "username": "09139616246",
            "token": null,
            "mobile": null,
            "email": null,
            "sex": null,
            "tel": null,
            "province": null,
            "city": null,
            "picture": null,
            "birthday": null,
            "wedding_date": null,
            "wife_birthday": null,
            "desc": null,
            "active": false,
            "supervisor": null,
            "two_factor_enabled": false,
            "address": null,
            "created_at": {
                "date": "2017-11-15 10:01:24.000000",
                "timezone_type": 3,
                "timezone": "Asia/Tehran"
            }
        }
]
</code>```

As you can see fields that not included on selection User model, have null value and returned. But I want only included fields return. how can I do that ?

答:
Use array filter to remove them, something like this

```<code>public function transform(User $user)
    {
        return array_filter([
            'user_id'            => (int)$user->user_id,
            'name'               => $user->name,
            'family'             => $user->family,
            'username'           => $user->username,
            'token'              => $user->token,
            'mobile'             => $user->mobile,
            'email'              => $user->email,
            'sex'                => $user->sex,
            'tel'                => $user->tel,
            'province'           => $user->province,
            'city'               => $user->city,
            'picture'            => $user->picture,
            'birthday'           => $user->birthday,
            'wedding_date'       => $user->wedding_date,
            'wife_birthday'      => $user->wife_birthday,
            'desc'               => $user->desc,
            'active'             => (bool) $user->active,
            'supervisor'         => $user->supervisor,
            'two_factor_enabled' => (bool) $user->two_factor_enabled,
            'address'            => $user->address,
            'created_at'         => $user->created_at,
        ], function($item){
            return !is_null($item);
        });
    }
</code>```

As a note I don't use Laravel, however this is typically how you remove things in bulk from an array.

http://php.net/manual/en/function.array-filter.php

Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.

And

http://php.net/manual/en/function.is-null.php

Finds whether the given variable is NULL. Returns TRUE if var is null, FALSE otherwise.

Body:
I'm using Fractal laravel package as a presentation and transformation layer for complex data output.

I wrote a UserTransformer like this :

public function transform(User $user)
    {
        return [
            'user_id'            => (int)$user->user_id,
            'name'               => $user->name,
            'family'             => $user->family,
            'username'           => $user->username,
            'token'              => $user->token,
            'mobile'             => $user->mobile,
            'email'              => $user->email,
            'sex'                => $user->sex,
            'tel'                => $user->tel,
            'province'           => $user->province,
            'city'               => $user->city,
            'picture'            => $user->picture,
            'birthday'           => $user->birthday,
            'wedding_date'       => $user->wedding_date,
            'wife_birthday'      => $user->wife_birthday,
            'desc'               => $user->desc,
            'active'             => (bool) $user->active,
            'supervisor'         => $user->supervisor,
            'two_factor_enabled' => (bool) $user->two_factor_enabled,
            'address'            => $user->address,
            'created_at'         => $user->created_at,
        ];
    }

Now in some situation I want to return specific fields of User model as a collection like this :

public function index()
    {
        return $this->collection(User::get(['user_id','name','family','username','created_at']), new UserTransformer());
    }

But in this case result is like this :

"result": [
        {
            "user_id": 1,
            "name": "ahmad",
            "family": "badpey",
            "username": "09139616246",
            "token": null,
            "mobile": null,
            "email": null,
            "sex": null,
            "tel": null,
            "province": null,
            "city": null,
            "picture": null,
            "birthday": null,
            "wedding_date": null,
            "wife_birthday": null,
            "desc": null,
            "active": false,
            "supervisor": null,
            "two_factor_enabled": false,
            "address": null,
            "created_at": {
                "date": "2017-11-15 10:01:24.000000",
                "timezone_type": 3,
                "timezone": "Asia/Tehran"
            }
        }
]

As you can see fields that not included on selection User model, have null value and returned. But I want only included fields return. how can I do that ?

Body:
Use array filter to remove them, something like this

public function transform(User $user)
    {
        return array_filter([
            'user_id'            => (int)$user->user_id,
            'name'               => $user->name,
            'family'             => $user->family,
            'username'           => $user->username,
            'token'              => $user->token,
            'mobile'             => $user->mobile,
            'email'              => $user->email,
            'sex'                => $user->sex,
            'tel'                => $user->tel,
            'province'           => $user->province,
            'city'               => $user->city,
            'picture'            => $user->picture,
            'birthday'           => $user->birthday,
            'wedding_date'       => $user->wedding_date,
            'wife_birthday'      => $user->wife_birthday,
            'desc'               => $user->desc,
            'active'             => (bool) $user->active,
            'supervisor'         => $user->supervisor,
            'two_factor_enabled' => (bool) $user->two_factor_enabled,
            'address'            => $user->address,
            'created_at'         => $user->created_at,
        ], function($item){
            return !is_null($item);
        });
    }

As a note I don't use Laravel, however this is typically how you remove things in bulk from an array.

http://php.net/manual/en/function.array-filter.php

Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.

And

http://php.net/manual/en/function.is-null.php

Finds whether the given variable is NULL. Returns TRUE if var is null, FALSE otherwise.


问:
How do I split and reconstruct a variable name while holding its original value
Is it possible to split variables that have already been assigned values, and re-piece them back together to hold those same previous values?

For Example:

```<code>URLs.QA.Signin = 'https://qa.test.com'
TestEnvironment = 'QA'
CurrentURL = 'URLs.' + TestEnvironment + '.Signin'
print(CurrentURL)
</code>```

Outputs as: 'URLs.QA.Signin'

but I would like it to:

Output as: 'https://qa.test.com'

The purpose is so I can plug in any value to my 'TestEnvironment' variable and thus access any of my massive list of URL's with ease =P

I am green with Python. Your time and efforts are greatly appreciated! =)

Based upon evanrelf's answer, I tried and loved the following code!:

This is exactly what i'm looking for, I might be over complicating it, any suggestions to clean up the code?

```<code>urls = {}
environment = 'qa'
district = 'pleasanthill'
url = environment + district
urls[url] = 'https://' + environment + '.' + district + '.test.com'
print(urls[url])
</code>```

Output is: https://qa.pleasanthill.test.com

答:
I would recommend you look into Python's dictionaries.

urls = {}
urls['qa'] = 'https://qa.test.com'

test_environment = 'qa'
print(urls[test_environment])
// => https://qa.test.com
```

Body:
Is it possible to split variables that have already been assigned values, and re-piece them back together to hold those same previous values?

For Example:

URLs.QA.Signin = 'https://qa.test.com'
TestEnvironment = 'QA'
CurrentURL = 'URLs.' + TestEnvironment + '.Signin'
print(CurrentURL)

Outputs as: 'URLs.QA.Signin'

but I would like it to:

Output as: 'https://qa.test.com'

The purpose is so I can plug in any value to my 'TestEnvironment' variable and thus access any of my massive list of URL's with ease =P

I am green with Python. Your time and efforts are greatly appreciated! =)

Based upon evanrelf's answer, I tried and loved the following code!:

This is exactly what i'm looking for, I might be over complicating it, any suggestions to clean up the code?

urls = {}
environment = 'qa'
district = 'pleasanthill'
url = environment + district
urls[url] = 'https://' + environment + '.' + district + '.test.com'
print(urls[url])

Output is: https://qa.pleasanthill.test.com


问:
string with values selection based on values
I have a set with 2 values  </p>

```<code>list = [('coin unit', 9.0), ('normal margin requirements', 8.5), ('futures industry', 8.2), ('wild cryptocurrency market', 7.333333333333334), ('biggest financial institutions', 6.833333333333334), ('futures market', 1.0), ('biggest banks', 0.5), ('cryptocurrency frenzy', 0.5)]
</code>```

<p>how can I keep only those values that have score bigger than 1? </p>

答:
What about without loop :

```<code>list_1 = [('coin unit', 9.0), ('normal margin requirements', 8.5), ('futures industry', 8.2), ('wild cryptocurrency market', 7.333333333333334), ('biggest financial institutions', 6.833333333333334), ('futures market', 1.0), ('biggest banks', 0.5), ('cryptocurrency frenzy', 0.5)]

print(list(filter(lambda x:x[1]>1,list_1)))
</code>```

output:

```<code>[('coin unit', 9.0), ('normal margin requirements', 8.5), ('futures industry', 8.2), ('wild cryptocurrency market', 7.333333333333334), ('biggest financial institutions', 6.833333333333334)]
</code>```

P.S : never use list as a variable name because list is a keyword in python.

Body:
I have a set with 2 values

list = [('coin unit', 9.0), ('normal margin requirements', 8.5), ('futures industry', 8.2), ('wild cryptocurrency market', 7.333333333333334), ('biggest financial institutions', 6.833333333333334), ('futures market', 1.0), ('biggest banks', 0.5), ('cryptocurrency frenzy', 0.5)]

how can I keep only those values that have score bigger than 1?

Body:
What about without loop :

list_1 = [('coin unit', 9.0), ('normal margin requirements', 8.5), ('futures industry', 8.2), ('wild cryptocurrency market', 7.333333333333334), ('biggest financial institutions', 6.833333333333334), ('futures market', 1.0), ('biggest banks', 0.5), ('cryptocurrency frenzy', 0.5)]

print(list(filter(lambda x:x[1]>1,list_1)))

output:

[('coin unit', 9.0), ('normal margin requirements', 8.5), ('futures industry', 8.2), ('wild cryptocurrency market', 7.333333333333334), ('biggest financial institutions', 6.833333333333334)]

P.S : never use list as a variable name because list is a keyword in python.


问:
How can you find the height of text on an HTML canvas?
The spec has a context.measureText(text) function that will tell you how much width it would require to print that text, but I can't find a way to find out how tall it is. I know it's based on the font, but I don't know to convert a font string to a text height.</p>

答:
one line answer

```<code>var height = parseInt(ctx.font) * 1.2;
</code>```

CSS "line-height: normal" is between 1 and 1.2

read here for more info

Body:
one line answer

var height = parseInt(ctx.font) * 1.2;

CSS "line-height: normal" is between 1 and 1.2

read here for more info


问:
MSBuild Metadata on joined item groups
I have two item groups that I wish to join:

```<code>  <ItemGroup>
<ServerTypeA Include="ServerA;ServerB;">
  <MetaDataA>A</MetaDataA>
</ServerTypeA>
</ItemGroup>

  <ItemGroup>
<ServerTypeB Include="ServerB;ServerC;">
  <MetaDataB>B</MetaDataB>
</ServerTypeB>
</ItemGroup>
</code>```

Using the regular join will give me a collection with 4 items:

```<code>ServerA with Metadata A;
ServerB with Metadata A;
ServerB with Metadata B;
ServerC with Metadata B;
</code>```

How can I create the following collection:

```<code>ServerA with Metadata A
ServerB with Metadata A & B
ServerC with Metadata B
</code>```

答:
It's possible.  You have to can manually perform the join.

Here's an example of how to do it (msbuild 3.5 or greater required):

```<code><ItemGroup>
  <ServerTypeA Include="ServerA;ServerB;">
    <MetaDataA>A</MetaDataA>
  </ServerTypeA>

  <ServerTypeB Include="ServerB;ServerC;">
    <MetaDataB>B</MetaDataB>
  </ServerTypeB>
</ItemGroup>

<Target Name="JoinServers" DependsOnTargets="ProcessServerTypeA;ProcessServerTypeB">
  <Message Text="%(Joined.Identity) Metadata: %(Joined.MetaDataA)%(Joined.MetaDataB)"/>
</Target>

<!--Create -->
<Target Name="ProcessServerTypeA">
  <ItemGroup>
    <Joined Include="%(ServerTypeA.Identity)">
      <MetaDataA>%(ServerTypeA.MetaDataA)</MetaDataA>
    </Joined>
  </ItemGroup>
</Target>

<!--Need to batch at the target level for this to work-->
<Target Name="ProcessServerTypeB" Inputs="@(ServerTypeB)" Outputs="%(ServerTypeB.Identity)'">

  <PropertyGroup>
    <!--Create Temporary Properties for the Item Metadata-->
    <TempItemName>%(ServerTypeB.Identity)</TempItemName>
    <TempMetaDataB>%(ServerTypeB.MetaDataB)</TempMetaDataB>
    <!--Does the current item already exist?-->
    <TempIsDuplicate Condition="'%(Joined.Identity)' == '$(TempItemName)'">True</TempIsDuplicate>
  </PropertyGroup>

  <ItemGroup>
    <!--Update the existing item's metadata if this is a duplicate-->
    <!--Don't provide the include attribute.  This will allow you to update existing items metadata-->
    <!--Have to reference %(Joined.Identity) in the condtion to ensure we only update the correct item-->
    <!--You cannot directly reference metadata from ServerTypeB here.  Hence the need for the temp Properties-->
    <Joined Condition="'%(Joined.Identity)' == '$(TempItemName)'">
      <MetaDataB>$(TempMetaDataB)</MetaDataB>
    </Joined>

    <!--Create a new item if current item is not a duplicate-->
    <Joined Include="$(TempItemName)" Condition="'$(TempIsDuplicate)' != 'True'">
      <MetaDataB>$(TempMetaDataB)</MetaDataB>
    </Joined>
  </ItemGroup>
</Target>
</code>```

Running the JoinServers target will produce the following output:

```<code>ServerA Metadata: A
ServerB Metadata: AB
ServerC Metadata: B
</code>```

Update with a better answer

This question pointed me to a much simpler solution.

Basically you use Transform modifiers with %(Identity) to perform the join.

You can replace all 3 targets from above with the following to obtain the same output.

```<code><Target Name="JoinServers">
  <ItemGroup>
    <Joined Include="%(Identity)">
      <MetaDataA>@(ServerTypeA->'%(MetaDataA)')</MetaDataA>
      <MetaDataB>@(ServerTypeB->'%(MetaDataB)')</MetaDataB>
    </Joined>
  </ItemGroup>

  <Message Text="%(Joined.Identity) Metadata: %(Joined.MetaDataA)%(Joined.MetaDataB)"/>
</Target>
</code>```

Title: MSBuild Metadata on joined item groups

Body:
I have two item groups that I wish to join:

  <ItemGroup>
<ServerTypeA Include="ServerA;ServerB;">
  <MetaDataA>A</MetaDataA>
</ServerTypeA>
</ItemGroup>

  <ItemGroup>
<ServerTypeB Include="ServerB;ServerC;">
  <MetaDataB>B</MetaDataB>
</ServerTypeB>
</ItemGroup>

Using the regular join will give me a collection with 4 items:

ServerA with Metadata A;
ServerB with Metadata A;
ServerB with Metadata B;
ServerC with Metadata B;

How can I create the following collection:

ServerA with Metadata A
ServerB with Metadata A & B
ServerC with Metadata B

Body:
It's possible.  You have to can manually perform the join.

Here's an example of how to do it (msbuild 3.5 or greater required):

<ItemGroup>
  <ServerTypeA Include="ServerA;ServerB;">
    <MetaDataA>A</MetaDataA>
  </ServerTypeA>

  <ServerTypeB Include="ServerB;ServerC;">
    <MetaDataB>B</MetaDataB>
  </ServerTypeB>
</ItemGroup>

<Target Name="JoinServers" DependsOnTargets="ProcessServerTypeA;ProcessServerTypeB">
  <Message Text="%(Joined.Identity) Metadata: %(Joined.MetaDataA)%(Joined.MetaDataB)"/>
</Target>

<!--Create -->
<Target Name="ProcessServerTypeA">
  <ItemGroup>
    <Joined Include="%(ServerTypeA.Identity)">
      <MetaDataA>%(ServerTypeA.MetaDataA)</MetaDataA>
    </Joined>
  </ItemGroup>
</Target>

<!--Need to batch at the target level for this to work-->
<Target Name="ProcessServerTypeB" Inputs="@(ServerTypeB)" Outputs="%(ServerTypeB.Identity)'">

  <PropertyGroup>
    <!--Create Temporary Properties for the Item Metadata-->
    <TempItemName>%(ServerTypeB.Identity)</TempItemName>
    <TempMetaDataB>%(ServerTypeB.MetaDataB)</TempMetaDataB>
    <!--Does the current item already exist?-->
    <TempIsDuplicate Condition="'%(Joined.Identity)' == '$(TempItemName)'">True</TempIsDuplicate>
  </PropertyGroup>

  <ItemGroup>
    <!--Update the existing item's metadata if this is a duplicate-->
    <!--Don't provide the include attribute.  This will allow you to update existing items metadata-->
    <!--Have to reference %(Joined.Identity) in the condtion to ensure we only update the correct item-->
    <!--You cannot directly reference metadata from ServerTypeB here.  Hence the need for the temp Properties-->
    <Joined Condition="'%(Joined.Identity)' == '$(TempItemName)'">
      <MetaDataB>$(TempMetaDataB)</MetaDataB>
    </Joined>

    <!--Create a new item if current item is not a duplicate-->
    <Joined Include="$(TempItemName)" Condition="'$(TempIsDuplicate)' != 'True'">
      <MetaDataB>$(TempMetaDataB)</MetaDataB>
    </Joined>
  </ItemGroup>
</Target>

Running the JoinServers target will produce the following output:

ServerA Metadata: A
ServerB Metadata: AB
ServerC Metadata: B

Update with a better answer

This question pointed me to a much simpler solution.

Basically you use Transform modifiers with %(Identity) to perform the join.

You can replace all 3 targets from above with the following to obtain the same output.

<Target Name="JoinServers">
  <ItemGroup>
    <Joined Include="%(Identity)">
      <MetaDataA>@(ServerTypeA->'%(MetaDataA)')</MetaDataA>
      <MetaDataB>@(ServerTypeB->'%(MetaDataB)')</MetaDataB>
    </Joined>
  </ItemGroup>

  <Message Text="%(Joined.Identity) Metadata: %(Joined.MetaDataA)%(Joined.MetaDataB)"/>
</Target>


问:
Clearing a DateTime list in C#
I have a list of DateTime's that I am using in a foreach loop and I need to have a clear list at the beginning of every loop

I was wondering if there are any built in methods that I can use to clear it or will I have to nest a for loop in the foreach loop in order to clear the list?

I have tried these two methods but neither of them worked

```<code>    foreach( DateTime i in listname){
         listname.Remove(i);
    }

    listname.RemoveAll();
</code>```

答:
You can use clear function to clear the list

```<code>  public static void Main(string[] args)
        {
            //Your code goes here
            List<DateTime> dtList = new List<DateTime>(){
                DateTime.Now
            };

            Console.WriteLine("Before count " + dtList.Count());

            dtList.Clear();

            Console.WriteLine("After count " + dtList.Count());
        }
</code>```

here is demo https://dotnetfiddle.net/bHp30A

Title: Clearing a DateTime list in C#

Body:
I have a list of DateTime's that I am using in a foreach loop and I need to have a clear list at the beginning of every loop

I was wondering if there are any built in methods that I can use to clear it or will I have to nest a for loop in the foreach loop in order to clear the list?

I have tried these two methods but neither of them worked

    foreach( DateTime i in listname){
         listname.Remove(i);
    }

    listname.RemoveAll();

Body:
You can use clear function to clear the list

  public static void Main(string[] args)
        {
            //Your code goes here
            List<DateTime> dtList = new List<DateTime>(){
                DateTime.Now
            };

            Console.WriteLine("Before count " + dtList.Count());

            dtList.Clear();

            Console.WriteLine("After count " + dtList.Count());
        }

here is demo https://dotnetfiddle.net/bHp30A


问:
Closing a modal when click on the form submit
My modal holds a form and I want to close the modal when the user clicks the submit button. The simplified form looks like this:

```<code><div class='modal fade' id='{{ module.name }}Modal' role='dialog'>
<div class='modal-dialog modal-lg'>
    <div class='modal-content'>
        <form ng-submit='submitModule(module)'>
            <div class='modal-body'>
                ...
            </div>
            <div class='modal-footer'>
                <button type='submit' class='btn btn-primary'>Run</button>
                <button type='button' class='btn btn-default' data-dismiss='modal'>Cancel</button>
            </div>
        </form>
    </div>
</div>
</code>```

You can see the two buttons. The close button uses data-dismiss='modal' which works fine. But I can't use that on the submit button, because that "cancels" out the ng-submit=submitModule() submission function; the modal will close but the function won't get called.

Would the solution be to close the modal from the submitModule() function? But how can I get a hold of the modal from there?

答:
You can append as many method calls to the (ngSubmit) i.e

form class="well" (ngSubmit)="addUserModal.hide(); addUser(model); userForm.reset()" #userForm="ngForm"

Body:
My modal holds a form and I want to close the modal when the user clicks the submit button. The simplified form looks like this:

        <form ng-submit='submitModule(module)'>

                ...

                <button type='submit' class='btn btn-primary'>Run</button>
                <button type='button' class='btn btn-default' data-dismiss='modal'>Cancel</button>

        </form>

You can see the two buttons. The close button uses data-dismiss='modal' which works fine. But I can't use that on the submit button, because that "cancels" out the ng-submit=submitModule() submission function; the modal will close but the function won't get called.

Would the solution be to close the modal from the submitModule() function? But how can I get a hold of the modal from there?


问:
Metadata version mismatch for module... angular-flash-messages, any solution for this
ERROR in Error: Metadata version mismatch for module /Users/ip/Sites/SmartShoeApp/angular-src/node_modules/angular2-flash-messages/module/index.d.ts, found version 4, expected 3, resolving symbol AppModule in /Users/ip/Sites/SmartShoeApp/angular-src/src/app/app.module.ts, resolving symbol AppModule in /Users/ip/Sites/SmartShoeApp/angular-src/src/app/app.module.ts, resolving symbol AppModule in /Users/ip/Sites/SmartShoeApp/angular-src/src/app/app.module.ts
    at SyntaxError.BaseError [as constructor] (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@angular/compiler/bundles/compiler.umd.js:1597:31)
    at new SyntaxError (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@angular/compiler/bundles/compiler.umd.js:1795:20)
    at simplifyInContext (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@angular/compiler/bundles/compiler.umd.js:25774:27)
    at StaticReflector.simplify (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@angular/compiler/bundles/compiler.umd.js:25786:17)
    at StaticReflector.annotations (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@angular/compiler/bundles/compiler.umd.js:25282:64)
    at _getNgModuleMetadata (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@angular/compiler-cli/src/ngtools_impl.js:126:31)
    at _extractLazyRoutesFromStaticModule (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@angular/compiler-cli/src/ngtools_impl.js:101:26)
    at Object.listLazyRoutesOfModule (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@angular/compiler-cli/src/ngtools_impl.js:52:22)
    at Function.NgTools_InternalApi_NG_2.listLazyRoutes (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@angular/compiler-cli/src/ngtools_api.js:78:39)
    at AotPlugin._getLazyRoutesFromNgtools (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@ngtools/webpack/src/plugin.js:241:66)
    at _donePromise.Promise.resolve.then.then.then.then.then (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@ngtools/webpack/src/plugin.js:495:24)
    at
    at process._tickCallback (internal/process/next_tick.js:188:7)

OS: mac OS high sierra

package.json:

{
  "name": "meanauthapp",

"version": "1.0.0",

"description": "mean stack application",

"main": "app.js",

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",

```<code>"start": "node app"
</code>```

},

"dependencies": {
    "express": "*",

```<code>"mongoose": "*",

"bcryptjs": "*",

"cors": "*",

"jsonwebtoken": "*",

"body-parser": "*",

"passport": "*",

"passport-jwt": "*"
</code>```

},

"author": "ip",

"license": "ISC",

"devDependencies": {

```<code>"@angular/cli": "^1.5.5"
</code>```

}
}

答:
I've solved it today on my angular4 app.
I've set 1.0.8 version in package.json and it works for me now:</p>

```<code>"angular2-flash-messages": "1.0.8"
</code>```

Body:
ERROR in Error: Metadata version mismatch for module /Users/ip/Sites/SmartShoeApp/angular-src/node_modules/angular2-flash-messages/module/index.d.ts, found version 4, expected 3, resolving symbol AppModule in /Users/ip/Sites/SmartShoeApp/angular-src/src/app/app.module.ts, resolving symbol AppModule in /Users/ip/Sites/SmartShoeApp/angular-src/src/app/app.module.ts, resolving symbol AppModule in /Users/ip/Sites/SmartShoeApp/angular-src/src/app/app.module.ts
    at SyntaxError.BaseError [as constructor] (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@angular/compiler/bundles/compiler.umd.js:1597:31)
    at new SyntaxError (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@angular/compiler/bundles/compiler.umd.js:1795:20)
    at simplifyInContext (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@angular/compiler/bundles/compiler.umd.js:25774:27)
    at StaticReflector.simplify (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@angular/compiler/bundles/compiler.umd.js:25786:17)
    at StaticReflector.annotations (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@angular/compiler/bundles/compiler.umd.js:25282:64)
    at _getNgModuleMetadata (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@angular/compiler-cli/src/ngtools_impl.js:126:31)
    at _extractLazyRoutesFromStaticModule (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@angular/compiler-cli/src/ngtools_impl.js:101:26)
    at Object.listLazyRoutesOfModule (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@angular/compiler-cli/src/ngtools_impl.js:52:22)
    at Function.NgTools_InternalApi_NG_2.listLazyRoutes (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@angular/compiler-cli/src/ngtools_api.js:78:39)
    at AotPlugin._getLazyRoutesFromNgtools (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@ngtools/webpack/src/plugin.js:241:66)
    at _donePromise.Promise.resolve.then.then.then.then.then (/Users/ip/Sites/SmartShoeApp/angular-src/node_modules/@ngtools/webpack/src/plugin.js:495:24)
    at
    at process._tickCallback (internal/process/next_tick.js:188:7)

OS: mac OS high sierra

package.json:

{
  "name": "meanauthapp",

"version": "1.0.0",

"description": "mean stack application",

"main": "app.js",

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",

"start": "node app"

},

"dependencies": {
    "express": "*",

"mongoose": "*",

"bcryptjs": "*",

"cors": "*",

"jsonwebtoken": "*",

"body-parser": "*",

"passport": "*",

"passport-jwt": "*"

},

"author": "ip",

"license": "ISC",

"devDependencies": {

"@angular/cli": "^1.5.5"

}
}

Body:
I've solved it today on my angular4 app.
I've set 1.0.8 version in package.json and it works for me now:

"angular2-flash-messages": "1.0.8"


问:
First letter in UiTextField lowercase
How do you make it so that when you start typing on the keyboard after youve clicked on a UITextfield the first letter isn't a capital automatically?</p>

答:
this code will lowercase all the text field input when you type any thing in your targeted text Field </p>

```<code>func textField(_ textFieldToChange: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
         //just change this charectar username  it's a text field
        if textFieldToChange == username {
            let characterSetNotAllowed = CharacterSet.whitespaces
            if let _ = string.rangeOfCharacter(from:NSCharacterSet.uppercaseLetters) {
                return false
            }
            if let _ = string.rangeOfCharacter(from: characterSetNotAllowed, options: .caseInsensitive) {
                return false
            } else {
                return true
            }
        }
        return true
    }
</code>```

Title: First letter in UiTextField lowercase

Body:
this code will lowercase all the text field input when you type any thing in your targeted text Field

func textField(_ textFieldToChange: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
         //just change this charectar username  it's a text field
        if textFieldToChange == username {
            let characterSetNotAllowed = CharacterSet.whitespaces
            if let _ = string.rangeOfCharacter(from:NSCharacterSet.uppercaseLetters) {
                return false
            }
            if let _ = string.rangeOfCharacter(from: characterSetNotAllowed, options: .caseInsensitive) {
                return false
            } else {
                return true
            }
        }
        return true
    }


问:
onclick method does not exist error?
this is the description of the error

There should be no spaces in the onClick handler name  The onClick attribute value should be the name of a method in this View's context to invoke when the view is clicked. This name must correspond to a public method that takes exactly one parameter of type View.  Must be a string value, using '\;' to escape characters such as '\n' or '\uxxxx' for a unicode character.

```<code>btnClick = (Button) findViewById(R.id.button2);
txtBox1 = (EditText) findViewById(editText9);
txtBox2 = (EditText) findViewById(editText10);

btnClick.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        String input1 = txtBox1.getText().toString();
        byte[] bytes = input1.getBytes();
        final StringBuilder binary = new StringBuilder();
        for (byte b : bytes) {
            int val = b;
            for (int i = 0; i < 8; i++) {
                binary.append((val & 128) == 0 ? 0 : 1);
                val <<= 1;
            }
            binary.append(' ');
            txtBox2.setText(binary);
        }

btnClick = (Button) findViewById(R.id.button3);

        btnClick.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                    ClipboardManager clipboard = (ClipboardManager)
getSystemService(Context.CLIPBOARD_SERVICE);
                String text = txtBox2.getText().toString();
                ClipData clip = ClipData.newPlainText("text", text);
                clipboard.setPrimaryClip(clip);
                Toast.makeText(getApplicationContext(), "Text Copied",
                        Toast.LENGTH_SHORT).show();

            }

        });

        txtBox2 = (EditText) findViewById(editText10);
        txtBox1 = (EditText) findViewById(editText9);
        btnClick = (Button) findViewById(R.id.button5);

        btnClick.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){

                txtBox2.setText("");
                txtBox1.setText("");
            }
        });

        btnClick.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){

                txtBox2.setText("");
                String s = new String(binary);
                txtBox1.setText(s);
            }
        });
</code>```

答: you have used same name btnClick for different  3 Button. may be this is the problem. use different name.

Title: onclick method does not exist error?

Body:
this is the description of the error

There should be no spaces in the onClick handler name  The onClick attribute value should be the name of a method in this View's context to invoke when the view is clicked. This name must correspond to a public method that takes exactly one parameter of type View.  Must be a string value, using '\;' to escape characters such as '\n' or '\uxxxx' for a unicode character.

btnClick = (Button) findViewById(R.id.button2);
txtBox1 = (EditText) findViewById(editText9);
txtBox2 = (EditText) findViewById(editText10);

btnClick.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        String input1 = txtBox1.getText().toString();
        byte[] bytes = input1.getBytes();
        final StringBuilder binary = new StringBuilder();
        for (byte b : bytes) {
            int val = b;
            for (int i = 0; i < 8; i++) {
                binary.append((val & 128) == 0 ? 0 : 1);
                val <<= 1;
            }
            binary.append(' ');
            txtBox2.setText(binary);
        }

btnClick = (Button) findViewById(R.id.button3);

        btnClick.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                    ClipboardManager clipboard = (ClipboardManager)
getSystemService(Context.CLIPBOARD_SERVICE);
                String text = txtBox2.getText().toString();
                ClipData clip = ClipData.newPlainText("text", text);
                clipboard.setPrimaryClip(clip);
                Toast.makeText(getApplicationContext(), "Text Copied",
                        Toast.LENGTH_SHORT).show();

            }

        });

        txtBox2 = (EditText) findViewById(editText10);
        txtBox1 = (EditText) findViewById(editText9);
        btnClick = (Button) findViewById(R.id.button5);

        btnClick.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){

                txtBox2.setText("");
                txtBox1.setText("");
            }
        });

        btnClick.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){

                txtBox2.setText("");
                String s = new String(binary);
                txtBox1.setText(s);
            }
        });


问:
How to set initialState in @ngrx/core with a promise from indexedDB
I wanted to set the initial state in ngrx using the idb package which uses promise to fetch data, but am getting an error every time I tried to set it up. I read that @ngrx is synchronous does that mean it does not work with promises.
The different methods I tried:

this is my wrapper method for idb that loads in the data it works fine

```<code>export function getInitialState(): Promise<any> {
  return StorageService.dB.loadInitialState('app-state');
}
</code>```

and the different methods I tried set the initial state

method: 1

```<code>StoreModule.forRoot(reducers, {initialState: getInitialState})
</code>```

method: 2

```<code> import { INITIAL_STATE } from '@ngrx/store';
{ provide: INITIAL_STATE, useFactory: getInitialState }
</code>```

method: 3

```<code>export function logger(reducer: ActionReducer<State>): ActionReducer<State> {
  return function (state: State, action: any): State {
   if(action.type === '@ngrx/store/init') {

   }
    return reducer(state, action);
  };

}
</code>```

The init state gets set to this

```<code>ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)}
</code>```

and I get this error

```<code>ERROR TypeError: Cannot assign to read only property '__zone_symbol__state' of object '[object Object]'
    at resolvePromise (zone.js:810)
    at eval (zone.js:876)
    at ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.js:4747)
    at ZoneDelegate.invokeTask (zone.js:424)
    at Zone.runTask (zone.js:192)
    at drainMicroTaskQueue (zone.js:602)
    at ZoneTask.invokeTask [as invoke] (zone.js:503)
    at invokeTask (zone.js:1540)
    at IDBRequest.globalZoneAwareCallback (zone.js:1566)
</code>```

*******Update*******

I got it now as dee zg pointed out every state can have an init function in their effects that will be fired as they are loaded, I thought it was a global one time event at first. Here is one I use for Auth state

```<code> @Effect()
  init$: Observable<Action> = defer(() => {
    return from(StorageService.readItem('app', Auth.AUTH_KEY)).pipe(
       map((data: any) => {
        return new Auth.AuthInit(data.state);
      })
    );
  });
</code>```

答:
There is an init action in effects which fires when effects get ran. There you can dispatch your action, get data and fill initial state.
Check Init Action section here:
https://github.com/ngrx/platform/blob/master/MIGRATION.md

Body:
I wanted to set the initial state in ngrx using the idb package which uses promise to fetch data, but am getting an error every time I tried to set it up. I read that @ngrx is synchronous does that mean it does not work with promises.
The different methods I tried:

this is my wrapper method for idb that loads in the data it works fine

export function getInitialState(): Promise<any> {
  return StorageService.dB.loadInitialState('app-state');
}

and the different methods I tried set the initial state

method: 1

StoreModule.forRoot(reducers, {initialState: getInitialState})

method: 2

 import { INITIAL_STATE } from '@ngrx/store';
{ provide: INITIAL_STATE, useFactory: getInitialState }

method: 3

export function logger(reducer: ActionReducer<State>): ActionReducer<State> {
  return function (state: State, action: any): State {
   if(action.type === '@ngrx/store/init') {

   }
    return reducer(state, action);
  };

}

The init state gets set to this

ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)}

and I get this error

ERROR TypeError: Cannot assign to read only property '__zone_symbol__state' of object '[object Object]'
    at resolvePromise (zone.js:810)
    at eval (zone.js:876)
    at ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.js:4747)
    at ZoneDelegate.invokeTask (zone.js:424)
    at Zone.runTask (zone.js:192)
    at drainMicroTaskQueue (zone.js:602)
    at ZoneTask.invokeTask [as invoke] (zone.js:503)
    at invokeTask (zone.js:1540)
    at IDBRequest.globalZoneAwareCallback (zone.js:1566)

*******Update*******

I got it now as dee zg pointed out every state can have an init function in their effects that will be fired as they are loaded, I thought it was a global one time event at first. Here is one I use for Auth state

 @Effect()
  init$: Observable<Action> = defer(() => {
    return from(StorageService.readItem('app', Auth.AUTH_KEY)).pipe(
       map((data: any) => {
        return new Auth.AuthInit(data.state);
      })
    );
  });


问:
JQuery vs ExtJS
We are planning the development of completely new GUI. We were very happy with JQuery which we used in our old product. It was easy, classy and fast.

We have heard about ExtJS. It also has AJAX and a large list of other features.

We want to use only one of them.

Which is best based on your experience?

答:
I have used jQuery extensively and love it. I have reviewed ExtJS on several occasions and would love to have the chance to use this library at some point. This is my take.

jQuery

The junk drawer of javascript programming. They got everything you need in there, if you're willing to dig, use some duct tape and super glue, and in general have a group of developers able and willing to hammer code. jQuery is great!

It's used in way more places than you think. However, like Drupal and other community-supported frameworks/libraries, when you get free support, you get what you pay for. You can get it all done with jQuery, but sometimes you need a shovel, flashlight and perseverance.

Additionally, very good documentation (on par with PHP's online docs), and tons, literally tons, of example code and blog entries out there.

Will appeal to tinkerers and "advanced scripters" who are not shy to Google a phrase to find an example that can be used to scaffold a problem and speed development.

ExtJS

Professionally developed by a for-profit company, these are more akin to controls (in the context of Visual Studios) than widgets or plugins. Intentionally complete and robust, with an eye for detail and a higher-level organizational structure than I think exists in the wilds of jQuery, ExtJS is a get what you pay for: A professionally-developed and supported product that lives and dies by it's ability to return value.

Will appeal to professionally-trained "programmers" expecting extensive testing and a higher-order or rigorousness in the development of the controls.

Final Recommendation

It really has to do with your shop and customers. If your group is more DIY and likes to glue together things and get it out the door, go with jQuery. It's robust for any situation. If you have a very ordered and professional shop, ExtJS might be a good choice, but jQuery will also be viable. I don't see the need to split your knowledgebase and use both, but really, if you do, use ExtJS for the client-facing portion and jQuery for the admin consoles. I don't see the benefit the other way around.

Also, for you admin consoles, look into TIBCO. Possibly overkill, but very interesting.

Title: JQuery vs ExtJS


问:
How Do I show a users Email address from MYSQL?

I'm trying to get it where, when the user goes to their profile, it will show them their email address. I have it where it shows their username by using $_SESSION['username'] but when I try that for the EMAIL address it doesn't work. Any Ideas on how I can get it to SELECT the email address from the Database? Thank You In Advance!! :)

It's showing their current Email address: and then the code.
Here's my PHP:

Includes/config.php is getting the DATABASE INFO.

```<code><?php require('includes/config.php');

//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php?action=login'); }

 ?>
</code>```

Includes/config.php

```<code><?php
ob_start();
session_start();

//set timezone
date_default_timezone_set('Europe/London');

//database credentials
define('DBHOST','localhost');
define('DBUSER','xxxxx');
define('DBPASS','xxxxx');
define('DBNAME','bigfellamembers');

//application address
define('DIR','http://xxxxxxxxxxx.com');
define('SITEEMAIL','noreply@domain.com');

try {

    //create PDO connection
    $db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch(PDOException $e) {
    //show error
    echo '<p class="bg-danger">'.$e->getMessage().'</p>';
    exit;
}

//include the user class, pass in the database connection
include('classes/user.php');
include('classes/phpmailer/mail.php');
$user = new User($db);
?>
</code>```

Here's my database table.

Heres: some of my HTML:

```<code>   <!-- row -->
                <div class="row">
                    <div class="col-md-12">
                        <div class="white-box">
                            <div class="user-bg"><img width="100%" alt="user" src="login-bg.jpg">
                                <div class="overlay-box">
                                    <div class="user-content">
                                        <a href="javascript:void(0)"><img src="uploads/<?php echo $_SESSION['username']; ?>.jpg" class="thumb-lg img-circle" alt="img"></a>
                                         <h4 class="text-white">Current Username: <?php echo $_SESSION['username']; ?> </h4>
                                        <h5 class="text-white">Current Email Address:    <?php  echo $_SESSION['email']; ?>

                                   </div>
                                </div>
                            </div>
</code>```

答:
You first need to get the user Email from database, Let's say

Query:

"SELECT email from user WHERE username ='$username' ";

After running the query and fetching your data from database, you can then do these: $_SESSION['email'] = $result['email'];

Body:
I'm trying to get it where, when the user goes to their profile, it will show them their email address. I have it where it shows their username by using $_SESSION['username'] but when I try that for the EMAIL address it doesn't work. Any Ideas on how I can get it to SELECT the email address from the Database? Thank You In Advance!! :)

It's showing their current Email address: and then the code.
Here's my PHP:

Includes/config.php is getting the DATABASE INFO.

<?php require('includes/config.php');

//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php?action=login'); }

 ?>

Includes/config.php

<?php
ob_start();
session_start();

//set timezone
date_default_timezone_set('Europe/London');

//database credentials
define('DBHOST','localhost');
define('DBUSER','xxxxx');
define('DBPASS','xxxxx');
define('DBNAME','bigfellamembers');

//application address
define('DIR','http://xxxxxxxxxxx.com');
define('SITEEMAIL','noreply@domain.com');

try {

    //create PDO connection
    $db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch(PDOException $e) {
    //show error
    echo '
'.$e->getMessage().'
';
    exit;
}

//include the user class, pass in the database connection
include('classes/user.php');
include('classes/phpmailer/mail.php');
$user = new User($db);
?>

Here's my database table.

Heres: some of my HTML:

                                        <img src="uploads/<?php echo $_SESSION['username']; ?>.jpg" class="thumb-lg img-circle" alt="img">

Current Username: <?php echo $_SESSION['username']; ?>

Current Email Address:    <?php  echo $_SESSION['email']; ?>


问:
correlation of 2 all vs all matrices on same variables R
I have a set of samples eg Sample1, Sample2, Sample3, Sample4

I have two distance matrices eg:

```<code>    S1    S2    S3    S4
S1  0     10    14    20

S2  52    0     100   30

S3  3     4      0    10

S4  55    100    2     0
</code>```

I need to take the distance between each sample from both tables and correlate these eg with a scatter graph/linear regression (which I know how to do, it is just getting data out of the distance matrices (which are pre-computed from elsewhere) which I am struggling with.

答:
I am not complete sure what you want to do with the data. However to get the two matrix triangles you can use upper.tri and lower.tri like

```<code>m <- matrix(1:16, nrow=4)
m[upper.tri(m)]
m[lower.tri(m)]
</code>```

Is this what you were looking for ?

Body:
I have a set of samples eg Sample1, Sample2, Sample3, Sample4

I have two distance matrices eg:

    S1    S2    S3    S4
S1  0     10    14    20

S2  52    0     100   30

S3  3     4      0    10

S4  55    100    2     0

I need to take the distance between each sample from both tables and correlate these eg with a scatter graph/linear regression (which I know how to do, it is just getting data out of the distance matrices (which are pre-computed from elsewhere) which I am struggling with.

Body:
I am not complete sure what you want to do with the data. However to get the two matrix triangles you can use upper.tri and lower.tri like

m <- matrix(1:16, nrow=4)
m[upper.tri(m)]
m[lower.tri(m)]

Is this what you were looking for ?


问:
Writing a function in C to scan different number of args based upon initial character
Some background to my problem: we have a board filled with blank spaces, and the user can input one of 9 different commands using the first letter of the command, followed by the required number of arguments (if any). For example, user can enter 'q' to quit, 'h' to display help information. Those two examples don't need anything after them, but for commands like "write" or "erase", the user inputs "w startRow endRow startCol endCol" where the latter 4 args are integers.

I'm having trouble figuring out how to account for the fact that there are different numbers of args that I need to read. Here are the functions I have right now (note: these functions are not in main.c, they are in a separate source file, which is why command is a char*):

```<code>void getUserInput(char** board, const int numRows, const int numCols, char* command) {
  int numArgsRead;
  const int numArgsNeeded = 1;

  do {
    printf("Enter your command: ");
    numArgsRead = scanf("%c", command);

  } while (!isMoveValid(board, numArgsNeeded, numArgsRead, numRows, numCols, *command));

}

bool isMoveValid(char** board, const int numArgsNeeded, const int numArgsRead, int numRows, int numCols, char command) {

  if (!isValidFormat(numArgsRead, numArgsNeeded)) {
    return false;
  }
  else {
    return true;
  }

}

bool isValidFormat(const int numArgsRead, const int numArgsNeeded) {
  bool valid = (numArgsRead == numArgsNeeded);
  char c;

  do {
    scanf("%c", &c);
    if (!isspace(c)) {
      valid = false;
    }
  } while (c != '\n');
  return valid;
}
</code>```

Note: it may seem redundant right now, but I'm going to add another function isOnBoard to an else if statement in the isMoveValid function.

The issue I'm having right now is that after reading the initial command character, the isValidFormat function scans through all the rest of the args that have been inputted, so I can't scan them again and assign them to variables. However, I need that function there bc it checks if I've hit a newline, and makes sure I don't scanf the newline on the next iteration of entering a command. How can I get around this so that I can read the values that are entered by the user?

答:
The best way to go about these would be to read the whole line using fgets and then parse it accordingly. Suppose you have a command like

```<code>A 1 2 3 4
</code>```

You get the whole line and check which command it is. Now you will know how many arguments should be there. You tokenize the string using strtok and then convert them to integer or whatever format you need it.

Now next question how to pass it. Take two variables, one of them should be the argCount denoting the number of inputs to the command and then an array argVector which stores that many number of arguments.

Body:
Some background to my problem: we have a board filled with blank spaces, and the user can input one of 9 different commands using the first letter of the command, followed by the required number of arguments (if any). For example, user can enter 'q' to quit, 'h' to display help information. Those two examples don't need anything after them, but for commands like "write" or "erase", the user inputs "w startRow endRow startCol endCol" where the latter 4 args are integers.

I'm having trouble figuring out how to account for the fact that there are different numbers of args that I need to read. Here are the functions I have right now (note: these functions are not in main.c, they are in a separate source file, which is why command is a char*):

void getUserInput(char** board, const int numRows, const int numCols, char* command) {
  int numArgsRead;
  const int numArgsNeeded = 1;

  do {
    printf("Enter your command: ");
    numArgsRead = scanf("%c", command);

  } while (!isMoveValid(board, numArgsNeeded, numArgsRead, numRows, numCols, *command));

}

bool isMoveValid(char** board, const int numArgsNeeded, const int numArgsRead, int numRows, int numCols, char command) {

  if (!isValidFormat(numArgsRead, numArgsNeeded)) {
    return false;
  }
  else {
    return true;
  }

}

bool isValidFormat(const int numArgsRead, const int numArgsNeeded) {
  bool valid = (numArgsRead == numArgsNeeded);
  char c;

  do {
    scanf("%c", &c);
    if (!isspace(c)) {
      valid = false;
    }
  } while (c != '\n');
  return valid;
}

Note: it may seem redundant right now, but I'm going to add another function isOnBoard to an else if statement in the isMoveValid function.

The issue I'm having right now is that after reading the initial command character, the isValidFormat function scans through all the rest of the args that have been inputted, so I can't scan them again and assign them to variables. However, I need that function there bc it checks if I've hit a newline, and makes sure I don't scanf the newline on the next iteration of entering a command. How can I get around this so that I can read the values that are entered by the user?

Body:
The best way to go about these would be to read the whole line using fgets and then parse it accordingly. Suppose you have a command like

A 1 2 3 4

You get the whole line and check which command it is. Now you will know how many arguments should be there. You tokenize the string using strtok and then convert them to integer or whatever format you need it.

Now next question how to pass it. Take two variables, one of them should be the argCount denoting the number of inputs to the command and then an array argVector which stores that many number of arguments.