问:
Angularjs minlength validation stop characters counter
I'm facing a weird "bug". I have a form with a textarea with a minlength and a maxlength validation on it.

Also, there is a super simple character left counter:

```<code><textarea ng-trim="false" ng-model="form.text" minlength="20" maxlength="240"></textarea>
<p>{{240 - form.text.length}} left</p>
</code>```

I don't know why my counter start working only after the characters reach the minlength value... While typing the counter stuck to 240. After I reach 20 characters the counter jump to 220... What is going wrong here?

Pen example

答:
The basic validation directives such as ng-minlength will block ngModel from being updated until validation is passed. It's not a bug as such, and it's useful in many cases, but it can also be less than useful in some cases. Such as this.

The way around this while still keeping the benefits of using ngModel based validation (including form validity etc) is to set the validation step 'manually' by using $setValidity. To do this you would remove the ng-minlength attribute and use an ng-change callback.

You will also need to make sure that your form element is named and part of a named form, in order to get access to the relevant ngModelController.

```<code><form name="formCtrl">
    <textarea ng-trim="false"
              ng-model="form.text"
              ng-change="checkTextLength()"
              name="formText">
    </textarea>
    <p>{{240 - form.text.length}} left</p>
</form>
</code>```

And then in your controller, assuming you are just using $scope here:

```<code>  $scope.checkTextLength = function(){
     if($scope.form.text.length < 20){
          $scope.formCtrl.formText.$setValidity('minlength', false);
     } else{
          $scope.formCtrl.formText.$setValidity('minlength', true);
     }

    if($scope.form.text.length > 240){
          $scope.formCtrl.formText.$setValidity('maxlength', false);
     } else{
          $scope.formCtrl.formText.$setValidity('maxlength', true);
     }
  }
</code>```

I forked your codepen to create a working example here. There I also added a bit to the template to show the validity state.

Body:
I'm facing a weird "bug". I have a form with a textarea with a minlength and a maxlength validation on it.

Also, there is a super simple character left counter:

<textarea ng-trim="false" ng-model="form.text" minlength="20" maxlength="240"></textarea>

{{240 - form.text.length}} left

I don't know why my counter start working only after the characters reach the minlength value... While typing the counter stuck to 240. After I reach 20 characters the counter jump to 220... What is going wrong here?

Pen example

Body:
The basic validation directives such as ng-minlength will block ngModel from being updated until validation is passed. It's not a bug as such, and it's useful in many cases, but it can also be less than useful in some cases. Such as this.

The way around this while still keeping the benefits of using ngModel based validation (including form validity etc) is to set the validation step 'manually' by using $setValidity. To do this you would remove the ng-minlength attribute and use an ng-change callback.

You will also need to make sure that your form element is named and part of a named form, in order to get access to the relevant ngModelController.

<form name="formCtrl">
    <textarea ng-trim="false"
              ng-model="form.text"
              ng-change="checkTextLength()"
              name="formText">
    </textarea>
    <p>{{240 - form.text.length}} left</p>
</form>

And then in your controller, assuming you are just using $scope here:

  $scope.checkTextLength = function(){
     if($scope.form.text.length < 20){
          $scope.formCtrl.formText.$setValidity('minlength', false);
     } else{
          $scope.formCtrl.formText.$setValidity('minlength', true);
     }

    if($scope.form.text.length > 240){
          $scope.formCtrl.formText.$setValidity('maxlength', false);
     } else{
          $scope.formCtrl.formText.$setValidity('maxlength', true);
     }
  }

I forked your codepen to create a working example here. There I also added a bit to the template to show the validity state.


来源: stackexchange

问:
is it possible to do fuzzy match merge with python pandas?
I have two DataFrames which I want to merge based on a column. However, due to alternate spellings, different number of spaces, absence/presence of diacritical marks, I would like to be able to merge as long as they are similar to one another.

Any similarity algorithm will do (soundex, Levenshtein, difflib's).

Say one DataFrame has the following data:

```<code>df1 = DataFrame([[1],[2],[3],[4],[5]], index=['one','two','three','four','five'], columns=['number'])

       number
one         1
two         2
three       3
four        4
five        5

df2 = DataFrame([['a'],['b'],['c'],['d'],['e']], index=['one','too','three','fours','five'], columns=['letter'])

      letter
one        a
too        b
three      c
fours      d
five       e
</code>```

Then I want to get the resulting DataFrame

```<code>       number letter
one         1      a
two         2      b
three       3      c
four        4      d
five        5      e
</code>```

答:
Using fuzzywuzzy

Since there are no examples with the fuzzywuzzy package, here's a function I wrote which will return all matches based on a threshold you can set as a user:

Example datframe

```<code>df1 = pd.DataFrame({'Key':['Apple', 'Banana', 'Orange', 'Strawberry']})
df2 = pd.DataFrame({'Key':['Aple', 'Mango', 'Orag', 'Straw', 'Bannanna', 'Berry']})

# df1
          Key
0       Apple
1      Banana
2      Orange
3  Strawberry

# df2
        Key
0      Aple
1     Mango
2      Orag
3     Straw
4  Bannanna
5     Berry
</code>```

Function for fuzzy matching

```<code>def fuzzy_merge(df_1, df_2, key1, key2, threshold=90, limit=2):
    """
    :param df_1: the left table to join
    :param df_2: the right table to join
    :param key1: key column of the left table
    :param key2: key column of the right table
    :param threshold: how close the matches should be to return a match, based on Levenshtein distance
    :param limit: the amount of matches that will get returned, these are sorted high to low
    :return: dataframe with boths keys and matches
    """
    s = df_2[key2].tolist()

    m = df_1[key1].apply(lambda x: process.extract(x, s, limit=limit))
    df_1['matches'] = m

    m2 = df_1['matches'].apply(lambda x: ', '.join([i[0] for i in x if i[1] >= threshold]))
    df_1['matches'] = m2

    return df_1
</code>```

Using our function on the dataframes: #1

```<code>from fuzzywuzzy import fuzz
from fuzzywuzzy import process

fuzzy_merge(df1, df2, 'Key', 'Key', threshold=80)

          Key       matches
0       Apple          Aple
1      Banana      Bannanna
2      Orange          Orag
3  Strawberry  Straw, Berry
</code>```

Using our function on the dataframes: #2

```<code>df1 = pd.DataFrame({'Col1':['Microsoft', 'Google', 'Amazon', 'IBM']})
df2 = pd.DataFrame({'Col2':['Mcrsoft', 'gogle', 'Amason', 'BIM']})

fuzzy_merge(df1, df2, 'Col1', 'Col2', 80)

        Col1  matches
0  Microsoft  Mcrsoft
1     Google    gogle
2     Amazon   Amason
3        IBM
</code>```

Installation:

Pip

```<code>pip install fuzzywuzzy
</code>```

Anaconda

```<code>conda install -c conda-forge fuzzywuzzy
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two DataFrames which I want to merge based on a column. However, due to alternate spellings, different number of spaces, absence/presence of diacritical marks, I would like to be able to merge as long as they are similar to one another.

Any similarity algorithm will do (soundex, Levenshtein, difflib's).

Say one DataFrame has the following data:

df1 = DataFrame([[1],[2],[3],[4],[5]], index=['one','two','three','four','five'], columns=['number'])

       number
one         1
two         2
three       3
four        4
five        5

df2 = DataFrame([['a'],['b'],['c'],['d'],['e']], index=['one','too','three','fours','five'], columns=['letter'])

      letter
one        a
too        b
three      c
fours      d
five       e

Then I want to get the resulting DataFrame

       number letter
one         1      a
two         2      b
three       3      c
four        4      d
five        5      e

Body:
Using fuzzywuzzy

Since there are no examples with the fuzzywuzzy package, here's a function I wrote which will return all matches based on a threshold you can set as a user:

Example datframe

df1 = pd.DataFrame({'Key':['Apple', 'Banana', 'Orange', 'Strawberry']})
df2 = pd.DataFrame({'Key':['Aple', 'Mango', 'Orag', 'Straw', 'Bannanna', 'Berry']})

# df1
          Key
0       Apple
1      Banana
2      Orange
3  Strawberry

# df2
        Key
0      Aple
1     Mango
2      Orag
3     Straw
4  Bannanna
5     Berry

Function for fuzzy matching

def fuzzy_merge(df_1, df_2, key1, key2, threshold=90, limit=2):
    """
    :param df_1: the left table to join
    :param df_2: the right table to join
    :param key1: key column of the left table
    :param key2: key column of the right table
    :param threshold: how close the matches should be to return a match, based on Levenshtein distance
    :param limit: the amount of matches that will get returned, these are sorted high to low
    :return: dataframe with boths keys and matches
    """
    s = df_2[key2].tolist()

    m = df_1[key1].apply(lambda x: process.extract(x, s, limit=limit))
    df_1['matches'] = m

    m2 = df_1['matches'].apply(lambda x: ', '.join([i[0] for i in x if i[1] >= threshold]))
    df_1['matches'] = m2

    return df_1

Using our function on the dataframes: #1

from fuzzywuzzy import fuzz
from fuzzywuzzy import process

fuzzy_merge(df1, df2, 'Key', 'Key', threshold=80)

          Key       matches
0       Apple          Aple
1      Banana      Bannanna
2      Orange          Orag
3  Strawberry  Straw, Berry

Using our function on the dataframes: #2

df1 = pd.DataFrame({'Col1':['Microsoft', 'Google', 'Amazon', 'IBM']})
df2 = pd.DataFrame({'Col2':['Mcrsoft', 'gogle', 'Amason', 'BIM']})

fuzzy_merge(df1, df2, 'Col1', 'Col2', 80)

        Col1  matches
0  Microsoft  Mcrsoft
1     Google    gogle
2     Amazon   Amason
3        IBM

Installation:

Pip

pip install fuzzywuzzy

Anaconda

conda install -c conda-forge fuzzywuzzy

ContentLicense: CC BY-SA 4.0


问:
Compare 7 input numbers with 7 Random Numbers
I'm new in C sharp but I need help about comparing my input value and random numbers, any function, method or class I have to add..</p>

```<code>List<int> lista1 = new List<int>();
for (int i = 1; i <= 7; i++)
{
    try {
        Console.Write("First Number {0}: ", i);
        int x = Convert.ToInt16(Console.ReadLine());
        lista1.Add(x);
    } catch (Exception ex){
        Console.WriteLine("The input number is incorret! It has to be whole number");
        Console.WriteLine("Error: {0}", ex.Message);
        i--;
    }
    Console.WriteLine("Random Numbers are: ");
    InitArray();
    Console.WriteLine(item);
}
</code>```

答:
If you have your inputs in a list, and your random numbers in another list, your can use the following code to know the count of what is common between your lists.</p>

```<code>
inputs.Intersect(randoms).Count

</code>```

Body:
I'm new in C sharp but I need help about comparing my input value and random numbers, any function, method or class I have to add..

List<int> lista1 = new List<int>();
for (int i = 1; i <= 7; i++)
{
    try {
        Console.Write("First Number {0}: ", i);
        int x = Convert.ToInt16(Console.ReadLine());
        lista1.Add(x);
    } catch (Exception ex){
        Console.WriteLine("The input number is incorret! It has to be whole number");
        Console.WriteLine("Error: {0}", ex.Message);
        i--;
    }
    Console.WriteLine("Random Numbers are: ");
    InitArray();
    Console.WriteLine(item);
}

Body:
If you have your inputs in a list, and your random numbers in another list, your can use the following code to know the count of what is common between your lists.

inputs.Intersect(randoms).Count


问:
Trying to parse json, can't seem to parse arrays inside of an array
I've been trying to parse a part of this JSON file: https://opendata.brussels.be/api/records/1.0/search/?dataset=traffic-volume&rows=3&facet=level_of_service

I wanna get records->fields->geo_shape->coordinates but I can't seem to print these arrays inside of the "coordinates" array.. I thought it might be because the arrays inside of the coordinates do not have names, so I don't know how to make a variable for them. Got this code currently:

```<code>import UIKit
import Foundation

struct Geoshape : Codable {
    let coordinates: Array<...>
}
struct Field : Codable {
    let geo_shape: Geoshape
    let level_of_service: String
}
struct Record: Codable {
    let fields: Field
}

struct Traffic: Codable{
    let records: Array<Record>
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func clickRefresh(_ sender: Any) {
        guard let url = URL(string: "https://opendata.brussels.be/api/records/1.0/search/?dataset=traffic-volume&rows=3&facet=level_of_service") else { return }
        let session = URLSession.shared
        let task = session.dataTask(with: url){ (data, response, error) in
            if let response = response {
                print(response)
            }
         if let data = data {

            let traffic = try? JSONDecoder().decode(Traffic.self, from: data)
            print(traffic)

            }

        }
        task.resume()
    }
}
</code>```

Clearly the Array<...> needs to be changed but I don't know to what. I've tried making an extra struct with just 1 variable (which is another array of the type Double: Double) but that does not seem to work. I was able to print everything just fine up to the point I tried to go into the coordinates array.

Anyone can help me?

答:
First of all your file in Resource contains a JSON which contains an array or Collection (typically in Swift).

One important thing: If you fail to decode an object in json you get null from all stored properties.
fail occurs when your Coding Keys does not match keys in json or type you are casting is diffrent.

In your code you fail to cast coordinates to its type.  coordinates is a collection of collections of Double.

```<code>var coordinates: [[Double]]
</code>```

If you want to fetch data into your models, you should conforms them to Decodable protocol which means that,JSON attributes can decode itself.

Based on Apple developer documentation:

Decodable is a type that can decode itself from an external representation.

also Codable protocol refers to Decodable and Encodable protocols. but current purpose is Decoding data.

```<code>typealias Codable = Decodable & Encodable
</code>```

Your code should look like:

Swift 5

Prepared for Playground, paste this into your playground

```<code>import Foundation

struct GeoShape: Decodable {
    var coordinates: [[Double]]
}

struct Field: Decodable {
    var geo_shape: GeoShape
}

struct Record: Decodable {
    var fields: Field
}

struct Traffic: Decodable {
    var records: [Record]
}

guard let url = URL.init(string: "https://opendata.brussels.be/api/records/1.0/search/?dataset=traffic-volume&rows=3&facet=level_of_service")
    else {fatalError()}

URLSession.shared.dataTask(with: url){ (data, response, error) in
    if let data = data {
        let traffic = try? JSONDecoder().decode(Traffic.self, from: data)
        print("First coordinate is: ",traffic?.records.first?.fields.geo_shape.coordinates.first)
    }
    }.resume()
</code>```

Body:
I've been trying to parse a part of this JSON file: https://opendata.brussels.be/api/records/1.0/search/?dataset=traffic-volume&rows=3&facet=level_of_service

I wanna get records->fields->geo_shape->coordinates but I can't seem to print these arrays inside of the "coordinates" array.. I thought it might be because the arrays inside of the coordinates do not have names, so I don't know how to make a variable for them. Got this code currently:

import UIKit
import Foundation

struct Geoshape : Codable {
    let coordinates: Array<...>
}
struct Field : Codable {
    let geo_shape: Geoshape
    let level_of_service: String
}
struct Record: Codable {
    let fields: Field
}

struct Traffic: Codable{
    let records: Array<Record>
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func clickRefresh(_ sender: Any) {
        guard let url = URL(string: "https://opendata.brussels.be/api/records/1.0/search/?dataset=traffic-volume&rows=3&facet=level_of_service") else { return }
        let session = URLSession.shared
        let task = session.dataTask(with: url){ (data, response, error) in
            if let response = response {
                print(response)
            }
         if let data = data {

            let traffic = try? JSONDecoder().decode(Traffic.self, from: data)
            print(traffic)

            }

        }
        task.resume()
    }
}

Clearly the Array<...> needs to be changed but I don't know to what. I've tried making an extra struct with just 1 variable (which is another array of the type Double: Double) but that does not seem to work. I was able to print everything just fine up to the point I tried to go into the coordinates array.

Anyone can help me?

Body:
First of all your file in Resource contains a JSON which contains an array or Collection (typically in Swift).

One important thing: If you fail to decode an object in json you get null from all stored properties.
fail occurs when your Coding Keys does not match keys in json or type you are casting is diffrent.

In your code you fail to cast coordinates to its type.  coordinates is a collection of collections of Double.

var coordinates: [[Double]]

If you want to fetch data into your models, you should conforms them to Decodable protocol which means that,JSON attributes can decode itself.

Based on Apple developer documentation:

Decodable is a type that can decode itself from an external representation.

also Codable protocol refers to Decodable and Encodable protocols. but current purpose is Decoding data.

typealias Codable = Decodable & Encodable

Your code should look like:

Swift 5

Prepared for Playground, paste this into your playground

import Foundation

struct GeoShape: Decodable {
    var coordinates: [[Double]]
}

struct Field: Decodable {
    var geo_shape: GeoShape
}

struct Record: Decodable {
    var fields: Field
}

struct Traffic: Decodable {
    var records: [Record]
}

guard let url = URL.init(string: "https://opendata.brussels.be/api/records/1.0/search/?dataset=traffic-volume&rows=3&facet=level_of_service")
    else {fatalError()}

URLSession.shared.dataTask(with: url){ (data, response, error) in
    if let data = data {
        let traffic = try? JSONDecoder().decode(Traffic.self, from: data)
        print("First coordinate is: ",traffic?.records.first?.fields.geo_shape.coordinates.first)
    }
    }.resume()


问:
Copy to clipboard and send keycode
The function from my Softphone (VoIP Phone on my PC) is, when I copy a phone number in clipboard and then I press "Pause" (German Keyboard), the softphone dials the number. I have created which help from some code examples in internet a copy function, which copied from a field in my database the phone number in the clipboard, when I press a button. It works perfectly. Now I wish to dials the number immediately and therefore it is necessary, the button do not copy the number only, but rather simulated the key press "Pause" after the copy.

Unfortunately my knowledge in PHP is ok, but in JavaScript it is very very bad. And therefore my request is for help me in this case.

Thank you very much in advance

Here is my script:

```<code>// in $Mobil01 is the phone number
]
<button class=copy-button id=buttonM01><i class=fa fa-copy style=font-size: 20px;></i></button>

<script>

    var telefonM01 = document.getElementById("telefonM01")

    var buttonM01 = document.getElementById("buttonM01");

    buttonM01.addEventListener("click", function (eventM01) {
        eventM01.preventDefault();
        telefonM01.select();
        document.execCommand("copy");

    });

</script>
</code>```

答:
The select event occurs only when a text is selected (marked) in a text area or a text field. So, for working with this you will have to set the element with the id telefonM01 as some input or textarea element.

An alternate way of copying text is to attach the text with the button to copy.

Title: Copy to clipboard and send keycode

Body:
The function from my Softphone (VoIP Phone on my PC) is, when I copy a phone number in clipboard and then I press "Pause" (German Keyboard), the softphone dials the number. I have created which help from some code examples in internet a copy function, which copied from a field in my database the phone number in the clipboard, when I press a button. It works perfectly. Now I wish to dials the number immediately and therefore it is necessary, the button do not copy the number only, but rather simulated the key press "Pause" after the copy.

Unfortunately my knowledge in PHP is ok, but in JavaScript it is very very bad. And therefore my request is for help me in this case.

Thank you very much in advance

Here is my script:

// in $Mobil01 is the phone number
]
<button class=copy-button id=buttonM01></button>


问:
queue programming in Java does not update the queue
I want to program a enqueue(elem) in Java, so I have programmed the following modules:

```<code>public class Node{
    public int e;
    Node next;
    public Node(int e){
        this.e=e;
    }
}
</code>```

and now I want to use a Linked List to store my elements, so I made a class with a enqueue() function like this:

```<code> public class Queue{
        Node q;        //represents a queue
        Node first;
         public void enqueue(int n){
            Node t=new Node(n);  //represents a temporal node
            if(q==null){
                first=t;
            }
            else{
                t.next=first;
                t=first;
            }
            q=t;  //to store the node into the queue
        }
}
</code>```

but when I want to print the elements of my queue:

```<code> public void print(){
            Node current=first;
            while (current!=null){
                System.out.println(current.e);
                current=current.next;
            }
        }
</code>```

it only prints me the first element that I enter, for example if I put 10,20,30,40 it only prints 10. What am I doing wrong?

Thanks

答:
Your code for the class Queue should be the below. The node first will be the first element and q will be the last element.

```<code>public class Queue{
    Node q;
    Node first;
     public void enqueue(int n){
        Node t=new Node(n);
        if(q==null){
            first=t;
        }
        else{
            q.next=t;
        }
        q=t;
    }
     public void print(){
         Node current=first;
         while (current!=null){
             System.out.println(current.e);
             current = current.next;
         }
     }
}
</code>```

Body:
I want to program a enqueue(elem) in Java, so I have programmed the following modules:

public class Node{
    public int e;
    Node next;
    public Node(int e){
        this.e=e;
    }
}

and now I want to use a Linked List to store my elements, so I made a class with a enqueue() function like this:

 public class Queue{
        Node q;        //represents a queue
        Node first;
         public void enqueue(int n){
            Node t=new Node(n);  //represents a temporal node
            if(q==null){
                first=t;
            }
            else{
                t.next=first;
                t=first;
            }
            q=t;  //to store the node into the queue
        }
}

but when I want to print the elements of my queue:

 public void print(){
            Node current=first;
            while (current!=null){
                System.out.println(current.e);
                current=current.next;
            }
        }

it only prints me the first element that I enter, for example if I put 10,20,30,40 it only prints 10. What am I doing wrong?

Thanks

Body:
Your code for the class Queue should be the below. The node first will be the first element and q will be the last element.

public class Queue{
    Node q;
    Node first;
     public void enqueue(int n){
        Node t=new Node(n);
        if(q==null){
            first=t;
        }
        else{
            q.next=t;
        }
        q=t;
    }
     public void print(){
         Node current=first;
         while (current!=null){
             System.out.println(current.e);
             current = current.next;
         }
     }
}


问:
How to use Anaconda Python to execute a .py file?
I just downloaded and installed Anaconda on my Windows computer. However, I am having trouble executing .py files using the command prompt. How can I get my computer to understand that the python.exe application is in the Anaconda folder so it can execute my .py files?</p>

答:
Right click on a .py file and choose 'open with'

Scroll down through the list of applications and click something like 'use a different program'

Naviage to C:\Users\<username>\AppData\Local\Continuum\anaconda3

click on python.exe and then click on 'ok' or 'open'

Now when you double click on any .py file it will run it through Anaconda's interpreter and therefore run the python code.

I presume if you run it through the command line the same would apply but perhaps someone could correct me?


问:
How to properly concatenate string literal to string variable and reassign to variable
I'm trying to concatenate a string literal to a string variable and reassign this value to the same variable.

I've tried the += operator and something like

string = string + "another string"
```

<p>but that doesn't work.</p>

<p>Here is my code.</p>

<pre class="lang-py prettyprint-override"><code>userWord = input("Enter a word: ").upper()

# Prompt the user to enter a word and assign it to the userWord variable

for letter in userWord:
    # Loops through userWord and concatenates consonants to wordWithoutVowels and skips vowels
    if letter == "A" or letter == "E" or letter == "I" or letter == "O" or letter == "U":
        continue
    wordWithoutVowels += userWord # NameError: name "wordWithoutVowels" is not defined

print(wordWithoutVowels)
</code>```

答:
Some issues with your code

You are not initializing wordWithoutVowels before the for loop. You need to do that with wordWithoutVowels = ''

You can use the in operator to check if the letter is not present in vowels, and then only update the result string

The updated code will then be

```<code>userWord = input("Enter a word: ").upper()

#Initialize wordWithoutVowels
wordWithoutVowels = ''
for letter in userWord:
    #If letter does not fall in vowels, append that letter
    if letter not in ['A','E','I','O','U']:
        wordWithoutVowels += letter

print(wordWithoutVowels)
</code>```

The output will be

```<code>Enter a word: hello world
HLL WRLD
</code>```

Body:
I'm trying to concatenate a string literal to a string variable and reassign this value to the same variable.

I've tried the += operator and something like

string = string + "another string"

but that doesn't work.

Here is my code.

userWord = input("Enter a word: ").upper()

# Prompt the user to enter a word and assign it to the userWord variable

for letter in userWord:
    # Loops through userWord and concatenates consonants to wordWithoutVowels and skips vowels
    if letter == "A" or letter == "E" or letter == "I" or letter == "O" or letter == "U":
        continue
    wordWithoutVowels += userWord # NameError: name "wordWithoutVowels" is not defined

print(wordWithoutVowels)

Body:
Some issues with your code

You are not initializing wordWithoutVowels before the for loop. You need to do that with wordWithoutVowels = ''

You can use the in operator to check if the letter is not present in vowels, and then only update the result string

The updated code will then be

userWord = input("Enter a word: ").upper()

#Initialize wordWithoutVowels
wordWithoutVowels = ''
for letter in userWord:
    #If letter does not fall in vowels, append that letter
    if letter not in ['A','E','I','O','U']:
        wordWithoutVowels += letter

print(wordWithoutVowels)

The output will be

Enter a word: hello world
HLL WRLD


问:
How to find fontAwsome icon's name
I'm trying to use font-awesome icons in a react native app, therefore I installed it and imported it using react-native-vector-icons :

```<code>import Icon from "react-native-vector-icons/FontAwesome";
.....
<Icon name="map-pin" />
</code>```

however I don't know where to find the name of the icons, I browsed in the font awesome web site, found some icons, but when I tried to use them, it doesn't work
 for example in their website  this icon's name is  abacus, however, when I use it in my app, I get a warning and the icon doesn't display.

答: You can get the icon names from here https://expo.github.io/vector-icons/</p>

Title: How to find fontAwsome icon's name

Body:
I'm trying to use font-awesome icons in a react native app, therefore I installed it and imported it using react-native-vector-icons :

import Icon from "react-native-vector-icons/FontAwesome";
.....
<Icon name="map-pin" />

however I don't know where to find the name of the icons, I browsed in the font awesome web site, found some icons, but when I tried to use them, it doesn't work
 for example in their website  this icon's name is  abacus, however, when I use it in my app, I get a warning and the icon doesn't display.


问:
Can I pass custom data in the HTTP header?
I have a whole bunch of web services each with several web methods. The consumers of these services are varied and many. I want to augment each of these web methods with an extra optional parameter (Int64 or Int32) but adding new methods with this extra (optional parameter) is a lot of work and getting the clients to use the new methods will be even more time consuming.

So I was wondering if I could allow the clients that wanted to take advantage of the new feature that this param provides could pass this Int in the HTTP header or some other way.

So the first question is can I pass an int in the HTTP header? If so, how would one do that in C#/ASP.NET?

Otherwise, what other suggestions do you have for tackling this problem?

答: Yes it is allowed - but note that it may cut off the ability to use proxies and sometimes http aware firewalls (they tend to inspect and rewrite headers). </p>

OwnerDisplayName: Guy

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Michael Neale


问:
PHP array_search
Is there any function which will accomplish the equivalent of array_search with a $needle that is an array? Like, this would be an ideal solution:

```<code>$needle = array('first', 'second');
$haystack = array('fifth','second','third', 'first');

// Returns key 1 in haystack
$search = array_search( $needle, $haystack );
</code>```

If no function, any other functions that accept needles which may be arrays that I can use to create a custom function?

答:
```<code>$needle = array('first', 'second');
$haystack = array('fifth','second','third', 'first');

if(in_array($needle, $haystack)) {
     echo "found";
}
</code>```

Title: PHP array_search

Body:
Is there any function which will accomplish the equivalent of array_search with a $needle that is an array? Like, this would be an ideal solution:

$needle = array('first', 'second');
$haystack = array('fifth','second','third', 'first');

// Returns key 1 in haystack
$search = array_search( $needle, $haystack );

If no function, any other functions that accept needles which may be arrays that I can use to create a custom function?


问:
SQL Join 2 tables with date difference
I have 2 tables, one of which is orders and the other one is receipts. The problem i am facing is that they dont have UID, the only thing they can be joined with is the date. Problem with that is, the date is the same, but the time difference between them is approx 30 seconds. My question is, is there any way i can join these 2 tables?

So, the 1st table is in the following format

```<code>|   date        | order | price |
|1/1/13 06:05:32|  tea  |   3   |
|1/2/13 07:04:24| coffee|   2   |
|4/3/13 13:31:23|  tea  |   3   |

</code>```

And the second table has this format

```<code>|   date        | order | quantity |
|1/1/13 06:05:42|  tea  |   3      |
|1/2/13 07:04:54| coffee|   2      |
|4/3/13 13:31:56|  tea  |   3      |

</code>```

My desired output is

```<code>|   date        | order | quantity |  price |
|1/1/13 06:05:42|  tea  |   3      |    3   |
|1/2/13 07:04:54| coffee|   2      |    2   |
|4/3/13 13:31:56|  tea  |   3      |    3   |

</code>```

Basically, my goal here is to combine these 2 tables so i can see the differences between them, but i dont have an idea how to join them without unique ID's, please help guys

答:
You could enumerate by the date value and join on that:

```<code>select t2.*, t1.*
from (select t1.*, row_number() over (partition by product order by date) as seqnum
      from t1
     ) t1 join
     (select t2.*, row_number() over (partition by product order by date) as seqnum
      from t2
     ) t2
     on t1.product = t2.product and
        t1.seqnum = t2.seqnum;
</code>```

You can also join on the time difference:

```<code>select t2.*, t1.*
from t2 join
     t1
     on t2.product = t1.product and
        t2.date >= dateadd(second, -30, t1.date) and
        t2.date < dateadd(second, 30, t1.date);
</code>```

Or use apply to get the nearest time up to the time in t2:

```<code>select t2.*, t1.*
from t2 outer appy
     (select top (1) t1.*
      from t1
      where t1.product = t2.product and
            t1.date <= t2.date and
            t1.date > dateadd(second, -60, t2.date)  -- just to keep within a range
      order by t1.date desc
     ) t1;
</code>```

Title: SQL Join 2 tables with date difference

Body:
I have 2 tables, one of which is orders and the other one is receipts. The problem i am facing is that they dont have UID, the only thing they can be joined with is the date. Problem with that is, the date is the same, but the time difference between them is approx 30 seconds. My question is, is there any way i can join these 2 tables?

So, the 1st table is in the following format

|   date        | order | price |
|1/1/13 06:05:32|  tea  |   3   |
|1/2/13 07:04:24| coffee|   2   |
|4/3/13 13:31:23|  tea  |   3   |

And the second table has this format

|   date        | order | quantity |
|1/1/13 06:05:42|  tea  |   3      |
|1/2/13 07:04:54| coffee|   2      |
|4/3/13 13:31:56|  tea  |   3      |

My desired output is

|   date        | order | quantity |  price |
|1/1/13 06:05:42|  tea  |   3      |    3   |
|1/2/13 07:04:54| coffee|   2      |    2   |
|4/3/13 13:31:56|  tea  |   3      |    3   |

Basically, my goal here is to combine these 2 tables so i can see the differences between them, but i dont have an idea how to join them without unique ID's, please help guys

Body:
You could enumerate by the date value and join on that:

select t2.*, t1.*
from (select t1.*, row_number() over (partition by product order by date) as seqnum
      from t1
     ) t1 join
     (select t2.*, row_number() over (partition by product order by date) as seqnum
      from t2
     ) t2
     on t1.product = t2.product and
        t1.seqnum = t2.seqnum;

You can also join on the time difference:

select t2.*, t1.*
from t2 join
     t1
     on t2.product = t1.product and
        t2.date >= dateadd(second, -30, t1.date) and
        t2.date < dateadd(second, 30, t1.date);

Or use apply to get the nearest time up to the time in t2:

select t2.*, t1.*
from t2 outer appy
     (select top (1) t1.*
      from t1
      where t1.product = t2.product and
            t1.date <= t2.date and
            t1.date > dateadd(second, -60, t2.date)  -- just to keep within a range
      order by t1.date desc
     ) t1;


问:
How to use some of bootstrap's mobile first classes
I am having trouble understanding bootstrap 4's mobile first behavior. I have always designed for desktops first and moved down from there.

Text centering is one such place where I don't know how to proceed.

For example, I want a paragraph to be centered on screens smaller than 768px.

So I looked up the documentation https://getbootstrap.com/docs/4.0/utilities/text/ and found out the class text-md-center and thought this is what I need. It centers text on medium width screens which are not larger than 768px.

However on using it did the opposite of what I thought - It centered the text for screen size larger than 768px.

I am assuming this is what is called 'mobile first'. Is this not mean for desktop first design? How do I center text only on smaller width devices?

答:
Never been a fan of frontend frameworks such as Twitter Bootstrap.

Anyway, this is basically what it does under the hood

```<code>@media screen and (min-width: 768px) {
    .text-md-center {
        text-align: center;
    }
}
</code>```

So you could add your own class like this.

```<code>@media screen and (max-width: 768px) {
    .mobile-text-center-md {
        text-align: center;
    }
}
</code>```

Just an example anyway. Then use the .mobile-text-center-md class to center text on devices, less than 768px wide.

Body:
Never been a fan of frontend frameworks such as Twitter Bootstrap.

Anyway, this is basically what it does under the hood

@media screen and (min-width: 768px) {
    .text-md-center {
        text-align: center;
    }
}

So you could add your own class like this.

@media screen and (max-width: 768px) {
    .mobile-text-center-md {
        text-align: center;
    }
}

Just an example anyway. Then use the .mobile-text-center-md class to center text on devices, less than 768px wide.


答:
There are many ways to accomplish that, but a simple way is to use a for loop inside of another for loop. i.e</p>

```<code>int[] userInputNumbers = {1,2,3,4,5,6,7};
int[] numbersToCompareTo = {1,9,11,12,4,6,16};
int countOfNumbersThatAreTheSame = 0;
for(int i=0; i<userInputNumbers.Length; i++)
{
   for(int j=0; j<numbersToCompareTo.Length; j++)
   {
       if(userInputNumbers[i] == numbersToCompareTo[j])
       {
           countOfNumbersThatAreTheSame++;
       }
   }
}

Console.Write(countOfNumbersThatAreTheSame);
Console.Read();
</code>```

Title: Compare 7 input numbers with 7 Random Numbers

Body:
There are many ways to accomplish that, but a simple way is to use a for loop inside of another for loop. i.e

int[] userInputNumbers = {1,2,3,4,5,6,7};
int[] numbersToCompareTo = {1,9,11,12,4,6,16};
int countOfNumbersThatAreTheSame = 0;
for(int i=0; i<userInputNumbers.Length; i++)
{
   for(int j=0; j<numbersToCompareTo.Length; j++)
   {
       if(userInputNumbers[i] == numbersToCompareTo[j])
       {
           countOfNumbersThatAreTheSame++;
       }
   }
}

Console.Write(countOfNumbersThatAreTheSame);
Console.Read();


问:
Why function's return statement is not usual int[ ]
I have just started to use Dlang and it seems to be ideal for people who want a safer C language. In addition it has modern paradigms also like functional programming.

I am trying following code to convert a list of numbers as strings to list of integers:

```<code>import std.stdio;
import std.array;
import std.conv;

int[] list_str2int(char[][] slist){     // this function should convert a list of numbers as char[] to integers
    int[100] intcol;
    int N = cast(int)slist.length;
    foreach(int i; 0..N){
        char[] temp = slist[i];
        temp = split(temp, ".")[0];   // effectively this is floor; to!int does not work if '.' is there;
        intcol[i] = to!int(temp);   // not working;
    }
    return intcol;                  // error from this statement;
}

void main(){
    char[][] strlist = cast(char[][])["1.1","2.1","3.2","4.4"];
    int[] newintlist = list_str2int(strlist);
    writeln("Converted list: ", newintlist);
}
</code>```

But getting following error:

```<code>testing.d(13): Error: returning cast(int[])intcol escapes a reference to local variable intcol
Failed: ["/usr/bin/dmd", "-v", "-o-", "testing.d", "-I."]
</code>```

I cannot understand why there is error on return line of the first function where the variable is int[].

Where is the problem and how can it be solved? Thanks for your help.

答:
int[100] is a static array (a value type), and is located on list_str2int's stack frame - therefore it will cease to exist once the function returns. The function's return value, int[], is a slice (a reference type), which does not hold any data, but refers to a contiguous number of integers somewhere in memory. The statement return intcol; thus takes a slice of the static array, however, returning it is invalid because the slice would point to memory that would no longer be valid after the function returns.

You have a few options:

Declare the return type as int[100] also. Making it a value type, the integers will be copied to the caller's stack frame.

Allocate the array in the program's heap by declaring and initializing the array as auto intcol = new int[100];. This will make intcol a slice of memory in the heap. Memory in the heap is owned by the garbage collector, and has effectively infinite lifetime.

An option that's further from the above but more idiomatic to modern D is to use ranges. Your program could be rewritten to a single statement as follows:

```<code>import std.algorithm.iteration;
import std.stdio;
import std.array;
import std.conv;

void main()
{
    ["1.1", "2.1", "3.2", "4.4"]
        .map!(item => item
            .split(".")[0]
            .to!int
        )
        .array // optional, writeln and co can write ranges
        .writefln!"Converted list: %s";
}
</code>```

Body:
I have just started to use Dlang and it seems to be ideal for people who want a safer C language. In addition it has modern paradigms also like functional programming.

I am trying following code to convert a list of numbers as strings to list of integers:

import std.stdio;
import std.array;
import std.conv;

int[] list_str2int(char[][] slist){     // this function should convert a list of numbers as char[] to integers
    int[100] intcol;
    int N = cast(int)slist.length;
    foreach(int i; 0..N){
        char[] temp = slist[i];
        temp = split(temp, ".")[0];   // effectively this is floor; to!int does not work if '.' is there;
        intcol[i] = to!int(temp);   // not working;
    }
    return intcol;                  // error from this statement;
}

void main(){
    char[][] strlist = cast(char[][])["1.1","2.1","3.2","4.4"];
    int[] newintlist = list_str2int(strlist);
    writeln("Converted list: ", newintlist);
}

But getting following error:

testing.d(13): Error: returning cast(int[])intcol escapes a reference to local variable intcol
Failed: ["/usr/bin/dmd", "-v", "-o-", "testing.d", "-I."]

I cannot understand why there is error on return line of the first function where the variable is int[].

Where is the problem and how can it be solved? Thanks for your help.

Body:
int[100] is a static array (a value type), and is located on list_str2int's stack frame - therefore it will cease to exist once the function returns. The function's return value, int[], is a slice (a reference type), which does not hold any data, but refers to a contiguous number of integers somewhere in memory. The statement return intcol; thus takes a slice of the static array, however, returning it is invalid because the slice would point to memory that would no longer be valid after the function returns.

You have a few options:

Declare the return type as int[100] also. Making it a value type, the integers will be copied to the caller's stack frame.

Allocate the array in the program's heap by declaring and initializing the array as auto intcol = new int[100];. This will make intcol a slice of memory in the heap. Memory in the heap is owned by the garbage collector, and has effectively infinite lifetime.

An option that's further from the above but more idiomatic to modern D is to use ranges. Your program could be rewritten to a single statement as follows:

import std.algorithm.iteration;
import std.stdio;
import std.array;
import std.conv;

void main()
{
    ["1.1", "2.1", "3.2", "4.4"]
        .map!(item => item
            .split(".")[0]
            .to!int
        )
        .array // optional, writeln and co can write ranges
        .writefln!"Converted list: %s";
}


问:
Problem with Android project
When I attempt to create a Android Project for the first time, I get an error saying "an SDK Target must be specified. I looked on the internet, and I couldn't find a fix to my problem. In the Android SDK manager, I have downloaded almost every available package, and none of htem fixed my problem.

At the console window at the bottom of eclipse, I get these errors:

[2011-04-11 20:09:57 - SDK Manager] Warning: Ignoring platform 'android-11': android.jar is missing.

[2011-04-11 20:22:22 - com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper] Unable to read C:\Program Files (x86)\Android\android-sdk\AndroidManifest.xml: java.io.FileNotFoundException: C:\Program Files (x86)\Android\android-sdk\AndroidManifest.xml (The system cannot find the file specified)

Did something not install correctly?

Thanks

答:
In the Preferences window, select Android in the menu on the left. On the
right side of the window, click Browse, find the location of the Android SDK on your
hard drive, and enter it in the SDK Location field. Eclipse needs this information to be
able to access all the tools that are supplied with Android, such as the emulator.

while starting a new project, dont forget to select the build of the android OS you will be using.
Best luck.

Title: Problem with Android project


问:
AttributeError: 'module' object has no attribute 'maketrans'
I've been doing some previous research about this error. There are some explanations here in StackOverflow related, the solutions suggested are quite unrelated though.

When I try to import Gtk from gi.repository, it crashes with the following output:

    bash-4.2$ python3
    Python 3.2 (r32:88445, Feb 21 2011, 21:11:06)
    [GCC 4.6.0 20110212 (Red Hat 4.6.0-0.7)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.

```<code>>>> from gi.repository import Gtk

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python3.2/site-packages/gi/importer.py", line 76, in load_module
dynamic_module._load()
File "/usr/lib64/python3.2/site-packages/gi/module.py", line 251, in _load
overrides_modules = __import__('gi.overrides', fromlist=[self._namespace])
File "/usr/lib64/python3.2/site-packages/gi/overrides/Gtk.py", line 400, in <module>
class MessageDialog(Gtk.MessageDialog, Dialog):
File "/usr/lib64/python3.2/site-packages/gi/overrides/Gtk.py", line 404, in
MessageDialog
type=Gtk.MessageType.INFO,
File "/usr/lib64/python3.2/site-packages/gi/module.py", line 127, in __getattr__
ascii_upper_trans = string.maketrans(
AttributeError: 'module' object has no attribute 'maketrans'
</code>```

Since this is an import straight from python console and not by executing a python file script I don't even have a clue how to handle this.

答:
Just replace string.maketrans with str.maketrans

As said by Искрен Станиславов in a answer below.

Body:
I've been doing some previous research about this error. There are some explanations here in StackOverflow related, the solutions suggested are quite unrelated though.

When I try to import Gtk from gi.repository, it crashes with the following output:

    bash-4.2$ python3
    Python 3.2 (r32:88445, Feb 21 2011, 21:11:06)
    [GCC 4.6.0 20110212 (Red Hat 4.6.0-0.7)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.

>>> from gi.repository import Gtk

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python3.2/site-packages/gi/importer.py", line 76, in load_module
dynamic_module._load()
File "/usr/lib64/python3.2/site-packages/gi/module.py", line 251, in _load
overrides_modules = __import__('gi.overrides', fromlist=[self._namespace])
File "/usr/lib64/python3.2/site-packages/gi/overrides/Gtk.py", line 400, in <module>
class MessageDialog(Gtk.MessageDialog, Dialog):
File "/usr/lib64/python3.2/site-packages/gi/overrides/Gtk.py", line 404, in
MessageDialog
type=Gtk.MessageType.INFO,
File "/usr/lib64/python3.2/site-packages/gi/module.py", line 127, in __getattr__
ascii_upper_trans = string.maketrans(
AttributeError: 'module' object has no attribute 'maketrans'

Since this is an import straight from python console and not by executing a python file script I don't even have a clue how to handle this.


答:
int[] is a slice, it can use dynamic allocation.

The int[100] is an array of 100 elements. It is allocated on the stack

Just like in C, you can't return local memory from a function, you can't return intcol, as the memory behind it becomes invalid after the function returns.

It seems unknown to me, if you want to use dynamic arrays or static. If you want to use dynamic arrays, then stick to them.

```<code>import std.stdio;
import std.array;
import std.conv;

int[] list_str2int(char[][] slist){     // this function should convert a list of numbers as char[] to integers
    int N = cast(int)slist.length;
    int[] intcol = new int[N];
    foreach(int i; 0..N){
        char[] temp = slist[i];
        temp = split(temp, ".")[0];   // effectively this is floor; to!int does not work if '.' is there;
        intcol[i] = to!int(temp);   // not working;
    }
    return intcol;                  // error from this statement;
}

void main(){
    char[][] strlist = cast(char[][])["1.1","2.1","3.2","4.4"];
    int[] newintlist = list_str2int(strlist);
    writeln("Converted list: ", newintlist);
}
</code>```

will output:

```<code> Converted list: [1, 2, 3, 4]
</code>```

Title: Why function's return statement is not usual int[ ]

Body:
int[] is a slice, it can use dynamic allocation.

The int[100] is an array of 100 elements. It is allocated on the stack

Just like in C, you can't return local memory from a function, you can't return intcol, as the memory behind it becomes invalid after the function returns.

It seems unknown to me, if you want to use dynamic arrays or static. If you want to use dynamic arrays, then stick to them.

import std.stdio;
import std.array;
import std.conv;

int[] list_str2int(char[][] slist){     // this function should convert a list of numbers as char[] to integers
    int N = cast(int)slist.length;
    int[] intcol = new int[N];
    foreach(int i; 0..N){
        char[] temp = slist[i];
        temp = split(temp, ".")[0];   // effectively this is floor; to!int does not work if '.' is there;
        intcol[i] = to!int(temp);   // not working;
    }
    return intcol;                  // error from this statement;
}

void main(){
    char[][] strlist = cast(char[][])["1.1","2.1","3.2","4.4"];
    int[] newintlist = list_str2int(strlist);
    writeln("Converted list: ", newintlist);
}

will output:

 Converted list: [1, 2, 3, 4]


问:
Saving a constantly changing score in an android app
I'm creating an android app in java, the score in the game changes all the time, multiple times every second. I want to create a save file to be able to keep track of the score when the user comes back to the app, the thing is how should I go about saving it? Seems extremely inefficient to write to the save file multiple times every second whenever the score changes. I thought about saving it in the onDestroy() method, but I heard it's not guaranteed that it would be called...

So what would be a guaranteed way for the score to be saved while not having to access file multiple times every second?

答:
You can have a SharedPreferences used to store data that belong to an app.

To add value to the SharedPreferences

```<code>//Whenever you update the score call this function
void updateScore(int score){

    SharedPreferences mySharedPref = getSharedPreferences("give Any Name", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = mySharedPref.edit();
    editor.putInt("score", score);
    editor.apply();  //this function will commit asynchronously

}
</code>```

If you need to get the score at any time call this function.

```<code>//Whenever you update the score call this function
public int getScore(){

    SharedPreferences mySharedPref = getSharedPreferences("give Any Name", Context.MODE_PRIVATE);
    return mySharedPref.getInt("score", -1); //-1 is the default value that is returned if the value is not set using putInt

}
</code>```

Body:
You can have a SharedPreferences used to store data that belong to an app.

To add value to the SharedPreferences

//Whenever you update the score call this function
void updateScore(int score){

    SharedPreferences mySharedPref = getSharedPreferences("give Any Name", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = mySharedPref.edit();
    editor.putInt("score", score);
    editor.apply();  //this function will commit asynchronously

}

If you need to get the score at any time call this function.

//Whenever you update the score call this function
public int getScore(){

    SharedPreferences mySharedPref = getSharedPreferences("give Any Name", Context.MODE_PRIVATE);
    return mySharedPref.getInt("score", -1); //-1 is the default value that is returned if the value is not set using putInt

}


问:
MYSQL - Check from Select "itself" possible?
I just started with mysql and I don't know if the way to make that check is the correct or I am going in the wrong direction.

I have a varchar named user_num in a table. and I need to check that when I do INSERT, the value of user_num_list have to be between [1, n] being "n" the quantiti of Objects that have the same Group has new Object.

I'm not English speaking and I'm sure it's a bit hard to understand, and for me to express myself, so there is some code:

```<code>create table player(
group varchar(15),
user_num int(15),
CONSTRAINT ck_player_user CHECK( user_num > 0 AND user_num < SELECT count(*) FROM player WHERE player.group=group)
)ENGINE=InnoDB;
</code>```

I don't know if i can "SELECT" inside a CHECK statement and also i dont know how to express "player.group=group" meaning that group(new INSERT player_group) have to be same has player.group

Thank you.

答:
The problem with subqueries in the CHECK condition is that it's practically impossible to implement. Consider what happens when you delete a row in this table. The count for the corresponding group will decrease, which might violate a CHECK constraint for another row. The system would need to reevaluate the checks for every row. If you now have one million rows in the table, one million queries need to be executed every time you INSERT, DELETE or UPDATE a row. If you would also permit cross table statements, all checks in the database need to be reevaluated on any change of data.

In theorie it would be possible to generate a "reverse check". The system would need to determine, which operations can possibly violate a check. In your case that would be deleting a row or updating a group. The "reverse check" could be

```<code>NOT EXISTS (
    SELECT *
    FROM player p
    WHERE p.group = OLD.group
      AND p.user_num > (SELECT COUNT(*) from player p WHERE p.group = OLD.group)
)
</code>```

I think you would agree, that it would be hard to implement a system, that is able to generate a reverse check like this. Queries can be much more complicated than yours. And for some queries there might not even exist a reverse check. If you look at how long it has taken to implement the CHECK constraint - I wouldn't expect any subqueries to be permitted in the next decade.

So I would say - Your options are:

Implement your checks in triggers

Implement your checks in application code

Change the requirements

I'd prefer the last one.

Body:
I just started with mysql and I don't know if the way to make that check is the correct or I am going in the wrong direction.

I have a varchar named user_num in a table. and I need to check that when I do INSERT, the value of user_num_list have to be between [1, n] being "n" the quantiti of Objects that have the same Group has new Object.

I'm not English speaking and I'm sure it's a bit hard to understand, and for me to express myself, so there is some code:

create table player(
group varchar(15),
user_num int(15),
CONSTRAINT ck_player_user CHECK( user_num > 0 AND user_num < SELECT count(*) FROM player WHERE player.group=group)
)ENGINE=InnoDB;

I don't know if i can "SELECT" inside a CHECK statement and also i dont know how to express "player.group=group" meaning that group(new INSERT player_group) have to be same has player.group

Thank you.

Body:
The problem with subqueries in the CHECK condition is that it's practically impossible to implement. Consider what happens when you delete a row in this table. The count for the corresponding group will decrease, which might violate a CHECK constraint for another row. The system would need to reevaluate the checks for every row. If you now have one million rows in the table, one million queries need to be executed every time you INSERT, DELETE or UPDATE a row. If you would also permit cross table statements, all checks in the database need to be reevaluated on any change of data.

In theorie it would be possible to generate a "reverse check". The system would need to determine, which operations can possibly violate a check. In your case that would be deleting a row or updating a group. The "reverse check" could be

NOT EXISTS (
    SELECT *
    FROM player p
    WHERE p.group = OLD.group
      AND p.user_num > (SELECT COUNT(*) from player p WHERE p.group = OLD.group)
)

I think you would agree, that it would be hard to implement a system, that is able to generate a reverse check like this. Queries can be much more complicated than yours. And for some queries there might not even exist a reverse check. If you look at how long it has taken to implement the CHECK constraint - I wouldn't expect any subqueries to be permitted in the next decade.

So I would say - Your options are:

Implement your checks in triggers

Implement your checks in application code

Change the requirements

I'd prefer the last one.


问:
Italic and bold Latin, and Greek letters using custom unicode font in gnuplot to produce (e)ps or pdf
I would like to create a postscript or pdf figure with enhanced notations, italic or bold Latin characters, and sometimes (regular) Greek characters. How to do that in general?

Let's say I downloaded CMU Sans Serif, a font that has glyphs for all the strange characters I ever want to use. I converted them to pfa with an online tool and copied the files to the path of working directory.

Expectations

Let's say I'd like to produce the following notation somewhere.

What I tried: original

I create a gnuplot script encoded in a utf-8 file (without BOM) with the content

```<code>set term postscript eps enhanced "CMUSansSerif" 15 fontfile add 'CMUSansSerif.pfa' fontfile add 'CMUSansSerif-Oblique.pfa' fontfile add 'CMUSansSerif-Bold.pfa'
set encoding utf8
set o "print.eps"

p x t "Label: {/CMUSansSerif-Bold important }{/CMUSansSerif-Oblique note}: ∫⟨α₂ + β²⟩ = äßű"
set o
</code>```

and executed with the newest gnuplot, version 5.2.6.

What I got

I used a vector graphics editor to open the eps file and relevant part looks like this:

What I also tried

According to Ethan's answer I added adobeglyphnames to the termoptions. It made at least the letters available but other Unicode symbols are still unavailable. The result is:

Question

What went wrong? How could I produce the desired output?

So many possibilities, where things can go wrong: Is the font not suitable for this task? Did I download a wrong version of it? Did the pfa converter do a bad job? Did I include the font files incorrectly? Was there something wrong with the set encoding? Do I use a bad vector graphics editor? Do I have wrong fonts installed and the vector graphics editor tries to use them?

答: It seems that CMU Sans Serif doesn't contain the UTF-8 characters you are asking for. Check the font with a font editor like Birdfont. Although the webpage shows symbols you want to use, the font itself does not contain them. However, your browser may show symbols, but they are just fallback representations from other fonts.</p>

Body:
I would like to create a postscript or pdf figure with enhanced notations, italic or bold Latin characters, and sometimes (regular) Greek characters. How to do that in general?

Let's say I downloaded CMU Sans Serif, a font that has glyphs for all the strange characters I ever want to use. I converted them to pfa with an online tool and copied the files to the path of working directory.

Expectations

Let's say I'd like to produce the following notation somewhere.

What I tried: original

I create a gnuplot script encoded in a utf-8 file (without BOM) with the content

set term postscript eps enhanced "CMUSansSerif" 15 fontfile add 'CMUSansSerif.pfa' fontfile add 'CMUSansSerif-Oblique.pfa' fontfile add 'CMUSansSerif-Bold.pfa'
set encoding utf8
set o "print.eps"

p x t "Label: {/CMUSansSerif-Bold important }{/CMUSansSerif-Oblique note}: ∫⟨α₂ + β²⟩ = äßű"
set o

and executed with the newest gnuplot, version 5.2.6.

What I got

I used a vector graphics editor to open the eps file and relevant part looks like this:

What I also tried

According to Ethan's answer I added adobeglyphnames to the termoptions. It made at least the letters available but other Unicode symbols are still unavailable. The result is:

Question

What went wrong? How could I produce the desired output?

So many possibilities, where things can go wrong: Is the font not suitable for this task? Did I download a wrong version of it? Did the pfa converter do a bad job? Did I include the font files incorrectly? Was there something wrong with the set encoding? Do I use a bad vector graphics editor? Do I have wrong fonts installed and the vector graphics editor tries to use them?


问:
Nested routing in angular 7, using modules and lazy loading
I am having trouble creating angular routes. I have implemented feature modules and I am using routing for each of those modules. I want the routes to go from app to layout to dashboard and then to accounts. The route is not created properly, it seems dashboard is being skipped and route goes directly to accounts. Here is what it looks like when i use augury to debug the routes.

Here is my code for each route. each route is in a module of its own. I would really like to keep the routes separated in modules. Any suggestions would be greatly appreciated.

//app routes

const appRoutes: Routes = [
  { path: "login", component: LoginComponent },
  {
    path: "",
    canActivate: [AuthGaurdService],
    loadChildren: "./layouts/layouts.module#LayoutsModule"
  },
  { path: "**", component: PageNotFoundComponent }
];

//layout routes

const LayoutRoutes: Routes = [
  {
    path: "",
    component: LayoutsComponent,
    canActivate: [AuthGaurdService],
    children: [
      {
        path: "",
        canActivateChild: [AuthGaurdService],
        children: [
          {
            path: "account-information",
            loadChildren: "../account-information/account-information.module#AccountInformationModule"
          },
          {
            path: "",
            loadChildren: "../dashboard/dashboard.module#DashboardModule"
          },
        ]
      }

    ]
  }
];

//dashboard routes

const routes: Routes = [
  {
    path: "",
    component: DashboardComponent,
    canActivate: [AuthGaurdService],
    children: [{
      path: "",
      canActivateChild: [AuthGaurdService],
      children: [
        {
          path: "accounts",
          loadChildren: "./accounts/accounts.module#AccountsModule"
        },
        {
          path: "",
          component: HomeComponent
        }
      ]
    }]
  }
];

//account routes

const AccountsRoutes: Routes = [
  {
    path: "accounts",
    component: AccountsComponent,
    canActivate: [AuthGaurdService],
    children: [
      {
        path: "",
        canActivateChild: [AuthGaurdService],
        children: [
          { path: "transactions", component: TransactionsComponent },
          { path: "summary", component: SummaryComponent },
          { path: "earnings", component: EarningsComponent }
        ]
      }

    ]
  }
];```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--app.html -->
<router-outlet></router-outlet>

<!-- layout.html -->
<div class="page-container">
  <app-navbar></app-navbar>
  <div class="page-content-wrapper ">
    <div class="content">
      <router-outlet></router-outlet>
    </div>
    <div class="container-fluid container-fixed-lg footer">
      <app-footer></app-footer>
    </div>
  </div>
</div>

<!-- dashboard.html -->
<div class="page-container">
  <app-navbar></app-navbar>
  <div class="page-content-wrapper ">
    <div class="content">
      <router-outlet></router-outlet>
    </div>
    <div class="container-fluid container-fixed-lg footer">
      <app-footer></app-footer>
    </div>
  </div>
</div>

<!-- accounts -->
<router-outlet></router-outlet></code>```

this is what my page looks like when i to home

this is the for accounts/summary

and my side menu looks like this
let retail: Array<Menu> = [
  {
    name: "Home",
    router_link: "",
    submenu: [],
    toggle_submenu: false,
    icon: ""
  },
  {
    name: "Accounts",
    router_link: "accounts/summary",
    toggle_submenu: false,
    icon: "",
    submenu: [
      {
        name: "Summary",
        router_link: "accounts/summary",
        toggle_submenu: false,
        icon: "",
        submenu: []
      },
      {
        name: "Tansactions",
        router_link: "accounts/transactions",
        toggle_submenu: false,
        icon: "",
        submenu: []
      },
      {
        name: "Earnings",
        router_link: "accounts/earnings",
        toggle_submenu: false,
        icon: "",
        submenu: []
      }
    ]
  },
  {
    name: "Sales",
    router_link: "sales",
    toggle_submenu: false,
    icon: "",
    submenu: []
  },
  {
    name: "Inventory",
    router_link: "inventory",
    toggle_submenu: false,
    icon: "",
    submenu: []
  },
  {
    name: "Upload",
    router_link: "upload",
    toggle_submenu: false,
    icon: "",
    submenu: []
  }
];

答:
Hello friends i figured out the issue. I removed the import of accounts module in dashboard module. This made sure that when routes where generated accounts route was placed after dashboard. This is because I am lazy loading the modules. This is what my routes looked like after
This is what my routes looked like after

Also make sure to add / in the child routes, so angular appends this route to its parent, ie accounts summary routerlink looks like this in my sidebar '/accounts/summary'.

Every thing else stayed the same. Now my accounts summary component was placed inside of my dashboard router link and i displayed next to my sidebar

Body:
I am having trouble creating angular routes. I have implemented feature modules and I am using routing for each of those modules. I want the routes to go from app to layout to dashboard and then to accounts. The route is not created properly, it seems dashboard is being skipped and route goes directly to accounts. Here is what it looks like when i use augury to debug the routes.

Here is my code for each route. each route is in a module of its own. I would really like to keep the routes separated in modules. Any suggestions would be greatly appreciated.

//app routes

const appRoutes: Routes = [
  { path: "login", component: LoginComponent },
  {
    path: "",
    canActivate: [AuthGaurdService],
    loadChildren: "./layouts/layouts.module#LayoutsModule"
  },
  { path: "**", component: PageNotFoundComponent }
];

//layout routes

const LayoutRoutes: Routes = [
  {
    path: "",
    component: LayoutsComponent,
    canActivate: [AuthGaurdService],
    children: [
      {
        path: "",
        canActivateChild: [AuthGaurdService],
        children: [
          {
            path: "account-information",
            loadChildren: "../account-information/account-information.module#AccountInformationModule"
          },
          {
            path: "",
            loadChildren: "../dashboard/dashboard.module#DashboardModule"
          },
        ]
      }

    ]
  }
];

//dashboard routes

const routes: Routes = [
  {
    path: "",
    component: DashboardComponent,
    canActivate: [AuthGaurdService],
    children: [{
      path: "",
      canActivateChild: [AuthGaurdService],
      children: [
        {
          path: "accounts",
          loadChildren: "./accounts/accounts.module#AccountsModule"
        },
        {
          path: "",
          component: HomeComponent
        }
      ]
    }]
  }
];

//account routes

const AccountsRoutes: Routes = [
  {
    path: "accounts",
    component: AccountsComponent,
    canActivate: [AuthGaurdService],
    children: [
      {
        path: "",
        canActivateChild: [AuthGaurdService],
        children: [
          { path: "transactions", component: TransactionsComponent },
          { path: "summary", component: SummaryComponent },
          { path: "earnings", component: EarningsComponent }
        ]
      }

    ]
  }
];

<router-outlet></router-outlet>

  <app-navbar></app-navbar>

      <router-outlet></router-outlet>

      <app-footer></app-footer>

  <app-navbar></app-navbar>

      <router-outlet></router-outlet>

      <app-footer></app-footer>

<router-outlet></router-outlet>

this is what my page looks like when i to home

this is the for accounts/summary

and my side menu looks like this
let retail: Array<Menu> = [
  {
    name: "Home",
    router_link: "",
    submenu: [],
    toggle_submenu: false,
    icon: ""
  },
  {
    name: "Accounts",
    router_link: "accounts/summary",
    toggle_submenu: false,
    icon: "",
    submenu: [
      {
        name: "Summary",
        router_link: "accounts/summary",
        toggle_submenu: false,
        icon: "",
        submenu: []
      },
      {
        name: "Tansactions",
        router_link: "accounts/transactions",
        toggle_submenu: false,
        icon: "",
        submenu: []
      },
      {
        name: "Earnings",
        router_link: "accounts/earnings",
        toggle_submenu: false,
        icon: "",
        submenu: []
      }
    ]
  },
  {
    name: "Sales",
    router_link: "sales",
    toggle_submenu: false,
    icon: "",
    submenu: []
  },
  {
    name: "Inventory",
    router_link: "inventory",
    toggle_submenu: false,
    icon: "",
    submenu: []
  },
  {
    name: "Upload",
    router_link: "upload",
    toggle_submenu: false,
    icon: "",
    submenu: []
  }
];


问:
Segemented Control for iPhone not working
I have a segmented control with the following code in its action method:

```<code>-(IBAction)toggleControls:(id)sender{
    if([sender selectedSegmentIndex] == kSwitchesSegmentIndex){
        leftSwitch.hidden = NO;
        rightSwitch.hidden = NO;
        doSomethingButton.hidden = YES;
    }

    else{
        leftSwitch.hidden = YES;
        rightSwitch.hidden = YES;
        doSomethingButton.hidden = NO;
    }
}
</code>```

However, when I run the program I'm getting an error with kSwitchesSegmentIndex. It's saying that kSwitchesSegmentIndex is an undeclared identifier. Can anyone help me with what's wrong here?

答:
You haven't declared the kSwitchesSegmentIndex in your code ,

Do Something

```<code>#define kSwitchesSegmentIndex 0
</code>```

Body:
I have a segmented control with the following code in its action method:

-(IBAction)toggleControls:(id)sender{
    if([sender selectedSegmentIndex] == kSwitchesSegmentIndex){
        leftSwitch.hidden = NO;
        rightSwitch.hidden = NO;
        doSomethingButton.hidden = YES;
    }

    else{
        leftSwitch.hidden = YES;
        rightSwitch.hidden = YES;
        doSomethingButton.hidden = NO;
    }
}

However, when I run the program I'm getting an error with kSwitchesSegmentIndex. It's saying that kSwitchesSegmentIndex is an undeclared identifier. Can anyone help me with what's wrong here?

Body:
You haven't declared the kSwitchesSegmentIndex in your code ,

Do Something

#define kSwitchesSegmentIndex 0


问:
RxSwift can't find flatMapObservable

Single.flatMapObservable

in RxSwift is it called differently or it just doesn't exist?

答:
To convert Single<E> into Observable<E>, simply the flatMap operator is what you're looking for.

On the other hand if you want to convert from Observable<E> to Single<E>, you can do so like this:

```<code>Observable<Int>.just(1)
  .flatMap { number -> Single<Int> in
    return Single<Int>.just(number)
  }
  // it's Single<Int> from now on..
</code>```

Title: RxSwift can't find flatMapObservable

Body:
To convert Single<E> into Observable<E>, simply the flatMap operator is what you're looking for.

On the other hand if you want to convert from Observable<E> to Single<E>, you can do so like this:

Observable<Int>.just(1)
  .flatMap { number -> Single<Int> in
    return Single<Int>.just(number)
  }
  // it's Single<Int> from now on..


问:
Middleman loop through files in data folder
I am trying to figure out the right syntax for calling a range of files within the /data folder.

For example, I have a handful of files in /data, each formatted as article1.yml, article2.yml, etc. How might I loop through them in my template? I assume the most direct way would be calling an increment of numbers in the filename like this:

<% data.article-[1,2,3].each do |article| %>

<<%= article.title %>

<% end %>

I've seen others ask similar questions but haven't found a good example to look at that either loops through all available files, or like in my example loops through an increment of numbers.

答:
Using Middleman 4.3.2, I was able to iterate through multiple files within a data folder like so:

```<code><% data.article.each do |article| %>
  <p><%= data.article.fetch(article[0]).title %></p>
<% end %>
</code>```

In the code above, article is set to some Array, like so: ['article_name', '#'], so I was able to grab the first item in the array to fetch the specific article data.

Body:
Using Middleman 4.3.2, I was able to iterate through multiple files within a data folder like so:

<% data.article.each do |article| %>
  <p><%= data.article.fetch(article[0]).title %></p>
<% end %>

In the code above, article is set to some Array, like so: ['article_name', '#'], so I was able to grab the first item in the array to fetch the specific article data.


问:
Failed to load class "org.slf4j.impl.StaticLoggerBinder" in kafka stream?
I am implementing apache kafka stream application program in Java inside GCP machine. I am  using kafka version 2.12
Reference URL -
https://kafka.apache.org/22/documentation/streams/tutorial

Here I am able to setup maven project. then I am able to see tree structure of stream.example in my kafka directory.In the next step, I am trying to execute Pipe java class But here I got stuck in this step.
I am able to execute mvn clean package which is giving Build success.
next command is mvn exec:java -Dexec.mainClass=myapps.Pipe which is giving warning and got stuck... see attached screenshot.

Here we can see my pom.xml file

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>streams.examples</groupId>
<artifactId>streams.examples</artifactId>
<version>0.1</version>
<packaging>jar</packaging>

<name>Kafka Streams Quickstart :: Java</name>

<properties>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <kafka.version>2.2.0</kafka.version>
    <slf4j.version>1.7.7</slf4j.version>
    <log4j.version>1.2.17</log4j.version>
</properties>

<repositories>
    <repository>
        <id>apache.snapshots</id>
        <name>Apache Development Snapshot Repository</name>
        <url>https://repository.apache.org/content/repositories/snapshots/</url>
        <releases>
            <enabled>false</enabled>
        </releases>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
</repositories>

<!--
            Execute "mvn clean package -Pbuild-jar"
            to build a jar file out of this project!
    -->

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
             <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>

    <pluginManagement>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerId>jdt</compilerId>
                </configuration>
                <dependencies>
                     <dependency>
                         <groupId>org.slf4j</groupId>
                         <artifactId>slf4j-simple</artifactId>
                         <version>1.7.25</version>
                     </dependency>
                     <dependency>
                        <groupId>org.eclipse.tycho</groupId>
                        <artifactId>tycho-compiler-jdt</artifactId>
                        <version>0.21.0</version>
                    </dependency>
                    </dependencies>
            </plugin>
            <plugin>
                <groupId>org.eclipse.m2e</groupId>
                <artifactId>lifecycle-mapping</artifactId>
                <version>1.0.0</version>
                <configuration>
                    <lifecycleMappingMetadata>
                        <pluginExecutions>
                            <pluginExecution>
                                <pluginExecutionFilter>
                                    <groupId>org.apache.maven.plugins</groupId>
                                    <artifactId>maven-assembly-plugin</artifactId>
                                    <versionRange>[2.4,)</versionRange>
                                    <goals>
                                        <goal>single</goal>
                                    </goals>
                                </pluginExecutionFilter>
                                <action>
                                    <ignore/>
                                </action>
                            </pluginExecution>
                            <pluginExecution>
                                <pluginExecutionFilter>
                                    <groupId>org.apache.maven.plugins</groupId>
                                    <artifactId>maven-compiler-plugin</artifactId>
                                    <versionRange>[3.1,)</versionRange>
                                    <goals>
                                        <goal>testCompile</goal>
                                        <goal>compile</goal>
                                    </goals>
                                    </pluginExecutionFilter>
                                <action>
                                    <ignore/>
                                </action>
                            </pluginExecution>
                        </pluginExecutions>
                    </lifecycleMappingMetadata>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

<dependencies>
    <!-- Apache Kafka dependencies -->
    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka-streams</artifactId>
        <version>${kafka.version}</version>
    </dependency>
</dependencies>
</code>```

答:
First refer to the following link for more clarity.

StaticLogBinder

To Quote, it says

This warning message is reported when the
  org.slf4j.impl.StaticLoggerBinder class could not be loaded into
  memory. This happens when no appropriate SLF4J binding could be found
  on the class path. Placing one (and only one) of slf4j-nop.jar
  slf4j-simple.jar, slf4j-log4j12.jar, slf4j-jdk14.jar or
  logback-classic.jar on the class path should solve the problem.

As part of solution, I will suggest you to use logback.

In maven pom.xml, add the following dependency.

```<code><!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.26</version>
</dependency>

<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.3</version>
    <scope>test</scope>
</dependency>
</code>```

Create a logback.xml file and put it inside your project src/main/resources

If you do not want to use logback, then simply add the following dependency along with slf4j api.

```<code><!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-nop -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-nop</artifactId>
    <version>1.7.26</version>
    <scope>test</scope>
</dependency>
</code>```

Body:
I am implementing apache kafka stream application program in Java inside GCP machine. I am  using kafka version 2.12
Reference URL -
https://kafka.apache.org/22/documentation/streams/tutorial

Here I am able to setup maven project. then I am able to see tree structure of stream.example in my kafka directory.In the next step, I am trying to execute Pipe java class But here I got stuck in this step.
I am able to execute mvn clean package which is giving Build success.
next command is mvn exec:java -Dexec.mainClass=myapps.Pipe which is giving warning and got stuck... see attached screenshot.

Here we can see my pom.xml file

<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>streams.examples</groupId>
<artifactId>streams.examples</artifactId>
<version>0.1</version>
<packaging>jar</packaging>

<name>Kafka Streams Quickstart :: Java</name>

<properties>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <kafka.version>2.2.0</kafka.version>
    <slf4j.version>1.7.7</slf4j.version>
    <log4j.version>1.2.17</log4j.version>
</properties>

<repositories>
    <repository>
        <id>apache.snapshots</id>
        <name>Apache Development Snapshot Repository</name>
        <url>https://repository.apache.org/content/repositories/snapshots/</url>
        <releases>
            <enabled>false</enabled>
        </releases>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
</repositories>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
             <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>

    <pluginManagement>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerId>jdt</compilerId>
                </configuration>
                <dependencies>
                     <dependency>
                         <groupId>org.slf4j</groupId>
                         <artifactId>slf4j-simple</artifactId>
                         <version>1.7.25</version>
                     </dependency>
                     <dependency>
                        <groupId>org.eclipse.tycho</groupId>
                        <artifactId>tycho-compiler-jdt</artifactId>
                        <version>0.21.0</version>
                    </dependency>
                    </dependencies>
            </plugin>
            <plugin>
                <groupId>org.eclipse.m2e</groupId>
                <artifactId>lifecycle-mapping</artifactId>
                <version>1.0.0</version>
                <configuration>
                    <lifecycleMappingMetadata>
                        <pluginExecutions>
                            <pluginExecution>
                                <pluginExecutionFilter>
                                    <groupId>org.apache.maven.plugins</groupId>
                                    <artifactId>maven-assembly-plugin</artifactId>
                                    <versionRange>[2.4,)</versionRange>
                                    <goals>
                                        <goal>single</goal>
                                    </goals>
                                </pluginExecutionFilter>
                                <action>
                                    <ignore/>
                                </action>
                            </pluginExecution>
                            <pluginExecution>
                                <pluginExecutionFilter>
                                    <groupId>org.apache.maven.plugins</groupId>
                                    <artifactId>maven-compiler-plugin</artifactId>
                                    <versionRange>[3.1,)</versionRange>
                                    <goals>
                                        <goal>testCompile</goal>
                                        <goal>compile</goal>
                                    </goals>
                                    </pluginExecutionFilter>
                                <action>
                                    <ignore/>
                                </action>
                            </pluginExecution>
                        </pluginExecutions>
                    </lifecycleMappingMetadata>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

<dependencies>

    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka-streams</artifactId>
        <version>${kafka.version}</version>
    </dependency>
</dependencies>

Body:
First refer to the following link for more clarity.

StaticLogBinder

To Quote, it says

This warning message is reported when the
  org.slf4j.impl.StaticLoggerBinder class could not be loaded into
  memory. This happens when no appropriate SLF4J binding could be found
  on the class path. Placing one (and only one) of slf4j-nop.jar
  slf4j-simple.jar, slf4j-log4j12.jar, slf4j-jdk14.jar or
  logback-classic.jar on the class path should solve the problem.

As part of solution, I will suggest you to use logback.

In maven pom.xml, add the following dependency.

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.26</version>
</dependency>

<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.2.3</version>
    <scope>test</scope>
</dependency>

Create a logback.xml file and put it inside your project src/main/resources

If you do not want to use logback, then simply add the following dependency along with slf4j api.

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-nop -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-nop</artifactId>
    <version>1.7.26</version>
    <scope>test</scope>
</dependency>


答:
If you can make sure order of data in both table will be always same, I mean row number X is in table1 always belongs to row number X in table2, you can then use row_number and JOIN both table using ROW_NUMBER. This could be an option.</p>

```<code>SELECT A.Date, A.Order, A.Price, B.quantity
FROM
(
    SELECT  Date, Order, Price,
    ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) RN
    FROM Table1
)A
INNER JOIN
(
        SELECT  Date, Order, quantity,
        ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) RN
)B ON A.RN = B.RN
</code>```

Title: SQL Join 2 tables with date difference

Body:
I have 2 tables, one of which is orders and the other one is receipts. The problem i am facing is that they dont have UID, the only thing they can be joined with is the date. Problem with that is, the date is the same, but the time difference between them is approx 30 seconds. My question is, is there any way i can join these 2 tables?

So, the 1st table is in the following format

|   date        | order | price |
|1/1/13 06:05:32|  tea  |   3   |
|1/2/13 07:04:24| coffee|   2   |
|4/3/13 13:31:23|  tea  |   3   |

And the second table has this format

|   date        | order | quantity |
|1/1/13 06:05:42|  tea  |   3      |
|1/2/13 07:04:54| coffee|   2      |
|4/3/13 13:31:56|  tea  |   3      |

My desired output is

|   date        | order | quantity |  price |
|1/1/13 06:05:42|  tea  |   3      |    3   |
|1/2/13 07:04:54| coffee|   2      |    2   |
|4/3/13 13:31:56|  tea  |   3      |    3   |

Basically, my goal here is to combine these 2 tables so i can see the differences between them, but i dont have an idea how to join them without unique ID's, please help guys

Body:
If you can make sure order of data in both table will be always same, I mean row number X is in table1 always belongs to row number X in table2, you can then use row_number and JOIN both table using ROW_NUMBER. This could be an option.

SELECT A.Date, A.Order, A.Price, B.quantity
FROM
(
    SELECT  Date, Order, Price,
    ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) RN
    FROM Table1
)A
INNER JOIN
(
        SELECT  Date, Order, quantity,
        ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) RN
)B ON A.RN = B.RN


问:
[Vue warn]: Unknown custom element: <network> - did you register the component correctly? vue-social-share
Trying to use the vue-social-sharing (latest version 2.4.3) library but keep getting the following:

[Vue warn]: Unknown custom element:  - did you register the component correctly? For recursive components, make sure to provide the "name" option.

I've followed the guides looked at code examples. But, can't seem to figure out what I'm missing or getting wrong.

I've created a separate component and just followed the sample provided by vue-social-share. But still keep getting the error.

Here is my main.js:

```<code>import Vue from 'vue'
import './plugins/vuetify'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false;

let SocialSharing = require('vue-social-sharing');
Vue.use(SocialSharing);

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app');
</code>```

Here is my component (SocialSharingTest.vue):

<template>
<social-sharing url="https://vuejs.org/"
                      title="The Progressive JavaScript Framework"
                      description="Intuitive, Fast and Composable MVVM for building interactive interfaces."
                      quote="Vue is a progressive framework for building user interfaces."
                      hashtags="vuejs,javascript,framework"
                      twitter-user="vuejs"
                      inline-template>

      <network network="email">
           Email
      </network>
      <network network="facebook">
        <v-icon class="mr-3" style="color: #3b5998">fab fa-facebook</v-icon>
      </network>
      <network network="googleplus">
         Google +
      </network>

</social-sharing>
</template>

```

Component isn't working as expected and keeping getting the **[Vue Warn] as described above. I see a working example here for what I would expect to see:

https://codesandbox.io/s/3yv7q36lq?from-embed

答:
```<code>import SocialSharing from 'vue-social-sharing';

import Vue from 'vue'
const VueSelect = {
  install(Vue, options) {
    Vue.component('SocialSharing', SocialSharing)
  }
};
Vue.use(VueSelect)
</code>```

Can you try this and see if it works?

Body:
Trying to use the vue-social-sharing (latest version 2.4.3) library but keep getting the following:

[Vue warn]: Unknown custom element:  - did you register the component correctly? For recursive components, make sure to provide the "name" option.

I've followed the guides looked at code examples. But, can't seem to figure out what I'm missing or getting wrong.

I've created a separate component and just followed the sample provided by vue-social-share. But still keep getting the error.

Here is my main.js:

import Vue from 'vue'
import './plugins/vuetify'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false;

let SocialSharing = require('vue-social-sharing');
Vue.use(SocialSharing);

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app');

Here is my component (SocialSharingTest.vue):

<template>
<social-sharing url="https://vuejs.org/"
                      title="The Progressive JavaScript Framework"
                      description="Intuitive, Fast and Composable MVVM for building interactive interfaces."
                      quote="Vue is a progressive framework for building user interfaces."
                      hashtags="vuejs,javascript,framework"
                      twitter-user="vuejs"
                      inline-template>

      <network network="email">
           Email
      </network>
      <network network="facebook">
        <v-icon class="mr-3" style="color: #3b5998">fab fa-facebook</v-icon>
      </network>
      <network network="googleplus">
         Google +
      </network>

</social-sharing>
</template>

Component isn't working as expected and keeping getting the **[Vue Warn] as described above. I see a working example here for what I would expect to see:

https://codesandbox.io/s/3yv7q36lq?from-embed

Body:
import SocialSharing from 'vue-social-sharing';

import Vue from 'vue'
const VueSelect = {
  install(Vue, options) {
    Vue.component('SocialSharing', SocialSharing)
  }
};
Vue.use(VueSelect)

Can you try this and see if it works?


问:
How to remove URLs with certain strings from Notepad++?
I have a very large list of URLs in a Notepad++ file that I would like to cut down. Specifically, I want to remove all URLs with text after the URL's third backslash (after HTTPS).

So my urls in this text document look like this (example URL of course):

https://www.google.com/goo/google/extra
I want to remove URLs with text after that third backslash. So delete all URLs from this document with anything where "extra" is, but not target the third backslash itself. So lines like this would be deleted
https://www.google.com/goo/google/deleted
and lines like this
https://www.google.com/goo/google/
would be saved.
I hope I explained this well it really is more complicated in my head than I think it is to actually execute.

答:
You can use a regular-expression search-and-replace: Use Ctrl-H to open the Replace dialog, use Alt-G to set the Search mode to Regular expression, use the expression

```<code>`https://[^/\s]+/[^/\s]+/[^/\s]+/[^\s]+\r?\n?`
</code>```

as Find what and leave Replace with empty. Then click on Replace all.

The expression searches for https URLs with the wanted number of minimum slashes (and non-slash and non-space characters between them) and replaces it, including any line ending characters, with nothing. This assumes you have one URL per line. If URLs could occur anywhere in text, you probably want to remove the \r?\n? part from the end of the expression.

Body:
You can use a regular-expression search-and-replace: Use Ctrl-H to open the Replace dialog, use Alt-G to set the Search mode to Regular expression, use the expression

`https://[^/\s]+/[^/\s]+/[^/\s]+/[^\s]+\r?\n?`

as Find what and leave Replace with empty. Then click on Replace all.

The expression searches for https URLs with the wanted number of minimum slashes (and non-slash and non-space characters between them) and replaces it, including any line ending characters, with nothing. This assumes you have one URL per line. If URLs could occur anywhere in text, you probably want to remove the \r?\n? part from the end of the expression.