问:
My app icon is not showing on some devices
I just published my app on play store and I notice that some Samsung device does not display the icon of my app. They assert the default icon of android studio.  Have you an idea what can cause that? i'm confused</p>
```<code><application
android:name=".MyApp"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:theme="@style/AppTheme">
 ....
</application>
</code>```

答: My issue was solved by restarting the phone.</p>

Body:
I just published my app on play store and I notice that some Samsung device does not display the icon of my app. They assert the default icon of android studio.  Have you an idea what can cause that? i'm confused

<application
android:name=".MyApp"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:theme="@style/AppTheme">
 ....
</application>


来源: stackexchange

问:
What is the purpose of using JSON.stringify()?
I'm using JSON.stringify in my react redux application. What's the purpose of JSON.stringify in the following context? Even without JSON.stringify it works, but yet I've been advised to use JSON.stringify.

```<code>if (JSON.stringify(earlyBird.eBird) !== JSON.stringify(prevProps.earlyBird.eBird)) {
</code>```

答:
This is, because how js comparison works Comparisor

Two distinct objects are never equal for either strict or abstract comparisons.

Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.

In the example below you can see that objects with same attributes will not return true, however converting them to strings does the trick. However, have in mind that order matters and in case attributes are not in the same order equality will not work as expected.

console.log({ x: 5, y:6 } === { x:5, y:6 });
console.log(JSON.stringify({ x: 5, y: 6 }) === JSON.stringify({ x: 5, y: 6 }));
console.log(JSON.stringify({ y: 6, x: 5 }) === JSON.stringify({ x: 5, y: 6 }));```

ContentLicense: CC BY-SA 4.0

Body:
I'm using JSON.stringify in my react redux application. What's the purpose of JSON.stringify in the following context? Even without JSON.stringify it works, but yet I've been advised to use JSON.stringify.

if (JSON.stringify(earlyBird.eBird) !== JSON.stringify(prevProps.earlyBird.eBird)) {


问:
What is the efficient way to read big tables in pandas Python?
I have a table in MySql of shape 40 million rows x 54 Columns. I tried reading the table in chunks using read_sql but it goes out of memory (I am working with 32 gb, 8 Core EC2 instance). Then I tried Limit and Offset method but it is really slow.

Is there any efficient way to read the table without losing memory and reading the table faster.

I looked into some Big Data techniques but since I am not familiar with Big Data I am not able to decide which one to go for.

Currently I am using this to read tables but it is really slow and certainly not very efficient.

```<code>def read_sql_chunked(query, con, nrows, chunksize=10000):
    start = 1
    dfs = []
    while start < nrows:
        df = pd.read_sql("%s LIMIT %s OFFSET %s" % (query, chunksize, start), con)
        dfs.append(df)
        print(start, chunksize)
        start += chunksize
    return pd.concat(dfs, ignore_index=True)
dt = read_sql_chunked(query=query, con=conn, nrows=40000000)
</code>```

答: How may rows does your table have? Sounds like that your table is just too big to fit in the amount of memory that you have. If you want to sumarize the data, you are probably better off doing that in sql first.</p>

Body:
I have a table in MySql of shape 40 million rows x 54 Columns. I tried reading the table in chunks using read_sql but it goes out of memory (I am working with 32 gb, 8 Core EC2 instance). Then I tried Limit and Offset method but it is really slow.

Is there any efficient way to read the table without losing memory and reading the table faster.

I looked into some Big Data techniques but since I am not familiar with Big Data I am not able to decide which one to go for.

Currently I am using this to read tables but it is really slow and certainly not very efficient.

def read_sql_chunked(query, con, nrows, chunksize=10000):
    start = 1
    dfs = []
    while start < nrows:
        df = pd.read_sql("%s LIMIT %s OFFSET %s" % (query, chunksize, start), con)
        dfs.append(df)
        print(start, chunksize)
        start += chunksize
    return pd.concat(dfs, ignore_index=True)
dt = read_sql_chunked(query=query, con=conn, nrows=40000000)


问:
Problem with printing - Inheritance, Polymorphism and toString
I am practicing how to use toString(), polymorphism and inheritance. Right now I have the code below and it has all the information that I want to print and it does print but I have some unwanted lines.

I just need the 1st and 3rd line but I'm not so sure why it's printing out the other 3 lines.

```<code>public class Test_toString{
    public static void main(String[] args){
        Car c = new Car();
        System.out.println(c.toString());

        NamedCar c2 = new NamedCar(160, 8, "green", "Pony");
        System.out.println(c2.toString());
    }
}

class Car{
    int speed;
    int gear;
    public String color;

    public Car(){
        speed = 100;
        gear = 5;
        color = "silver";
    }

    public Car(int speed, int gear, String color){
        this.speed = speed;
        this.gear = gear;
        this.color = color;
    }

    public String toString(){
        return "Car: " + speed + "km/h " + gear + " gears " +
        color + "\n" + super.toString();
    }
}

class NamedCar extends Car{
    public String name;

    public NamedCar(String name){
        super();
        this.name = name;
    }

    public NamedCar(int speed, int gear, String color, String name){
        this.speed = speed;
        this.gear = gear;
        this.color = color;
        this.name = name;
    }

    public String toString(){
        return "Car: " + speed + "km/h " + gear + " gears " +
        color + " " +  name + "\n" + super.toString();
    }
}
</code>```

答:
Just remove method call super.toString() from toString() method in both classes.
When you make that call you are calling toString() method from parent class. So when it is called from NamedCar class, it calls toString() method from Car class and when it is called from Car class it calls toString() from object class.</p>

Body:
I am practicing how to use toString(), polymorphism and inheritance. Right now I have the code below and it has all the information that I want to print and it does print but I have some unwanted lines.

I just need the 1st and 3rd line but I'm not so sure why it's printing out the other 3 lines.

public class Test_toString{
    public static void main(String[] args){
        Car c = new Car();
        System.out.println(c.toString());

        NamedCar c2 = new NamedCar(160, 8, "green", "Pony");
        System.out.println(c2.toString());
    }
}

class Car{
    int speed;
    int gear;
    public String color;

    public Car(){
        speed = 100;
        gear = 5;
        color = "silver";
    }

    public Car(int speed, int gear, String color){
        this.speed = speed;
        this.gear = gear;
        this.color = color;
    }

    public String toString(){
        return "Car: " + speed + "km/h " + gear + " gears " +
        color + "\n" + super.toString();
    }
}

class NamedCar extends Car{
    public String name;

    public NamedCar(String name){
        super();
        this.name = name;
    }

    public NamedCar(int speed, int gear, String color, String name){
        this.speed = speed;
        this.gear = gear;
        this.color = color;
        this.name = name;
    }

    public String toString(){
        return "Car: " + speed + "km/h " + gear + " gears " +
        color + " " +  name + "\n" + super.toString();
    }
}


问:
Arrays.asList(array) in java add unwanted spaces between comma separated string?
I have a string array that I convert to ArrayList and remove an item from it. Then use that updated ArrayList.

Problem
Initial Input:

```<code>String[] arr = {"467","470","464","410"};
List<String> idList = new LinkedList<>(Arrays.asList(arr));
</code>```

After converting and removing item it prints

```<code>[467, 470, 464]
</code>```

It adds unwanted leading white spaces between the elements of list, which causes trouble as then I operate on it using

```<code>if (idList.toString().contains(userId)) {
      idList.remove(userId);
}
</code>```

So if userId="470" and in this list it is " 470", it doesn't match due to white space's issue and code fails.

It tried few things like using integer array instead of string, but it makes no difference.

or

```<code>List<String> idList = new LinkedList<>(Arrays.asList(arr));
System.out.println("==>"+idList);

List afterRemovingWhiteSpace = new ArrayList<>();
idList.forEach(e -> afterRemovingWhiteSpace.add(e.trim()));
System.out.println("Updated==>"+afterRemovingWhiteSpace);
</code>```

or

```<code>String[] arr = {"467", "470", "464"};
List<String> idList = new LinkedList<>(Arrays.asList(arr));
System.out.println("==>"+idList);
String regex = "^\\s+";
idList.forEach(e -> e.replaceAll(regex, ""));
System.out.println("Updated==>"+idList);
</code>```

But none works. Any idea how to do it efficiently, I don't want use array and remove an item from it, as list can contain large number of elements and that will become very costly operation.

答:
You're printing out a list, the default toString will add spaces between elements.

```<code>System.out.println("[" + idList.stream().collect( Collectors.joining(",")) + "]");
</code>```

That will concatenate the list without spaces.

This:

```<code>System.out.println("==>"+idList);
</code>```

Adds spaces to the printed string only, not the elements of the list. So do both of these.

```<code>System.out.println("Updated==>"+afterRemovingWhiteSpace);
System.out.println("Updated==>"+idList);
</code>```

The elements of the list were not changed

Another misconception you seem to be having.

```<code>"[123, 456]".contains("456");
"[123,456]".contains("456");
</code>```

Both strings will contain 456, the spaces won't change that.

Body:
I have a string array that I convert to ArrayList and remove an item from it. Then use that updated ArrayList.

Problem
Initial Input:

String[] arr = {"467","470","464","410"};
List<String> idList = new LinkedList<>(Arrays.asList(arr));

After converting and removing item it prints

[467, 470, 464]

It adds unwanted leading white spaces between the elements of list, which causes trouble as then I operate on it using

if (idList.toString().contains(userId)) {
      idList.remove(userId);
}

So if userId="470" and in this list it is " 470", it doesn't match due to white space's issue and code fails.

It tried few things like using integer array instead of string, but it makes no difference.

or

List<String> idList = new LinkedList<>(Arrays.asList(arr));
System.out.println("==>"+idList);

List afterRemovingWhiteSpace = new ArrayList<>();
idList.forEach(e -> afterRemovingWhiteSpace.add(e.trim()));
System.out.println("Updated==>"+afterRemovingWhiteSpace);

or

String[] arr = {"467", "470", "464"};
List<String> idList = new LinkedList<>(Arrays.asList(arr));
System.out.println("==>"+idList);
String regex = "^\\s+";
idList.forEach(e -> e.replaceAll(regex, ""));
System.out.println("Updated==>"+idList);

But none works. Any idea how to do it efficiently, I don't want use array and remove an item from it, as list can contain large number of elements and that will become very costly operation.

Body:
You're printing out a list, the default toString will add spaces between elements.

System.out.println("[" + idList.stream().collect( Collectors.joining(",")) + "]");

That will concatenate the list without spaces.

This:

System.out.println("==>"+idList);

Adds spaces to the printed string only, not the elements of the list. So do both of these.

System.out.println("Updated==>"+afterRemovingWhiteSpace);
System.out.println("Updated==>"+idList);

The elements of the list were not changed

Another misconception you seem to be having.

"[123, 456]".contains("456");
"[123,456]".contains("456");

Both strings will contain 456, the spaces won't change that.


问:
How to redirect to a certain screen when opening a dynamic link?
I'm developing an app that can receive Firebase's Dynamic Link. What I want is when a user click a Dynamic Link, the app redirects it to a certain UIViewController. So I have a code that looks like this on my AppDelegate.swift file:

```<code>@available(iOS 9.0, *)
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {
        //return GIDSignIn.sharedInstance().handle(url)
        return application(app, open: url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: "")
    }

    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        // On progress
        if let dynamicLink = DynamicLinks.dynamicLinks().dynamicLink(fromCustomSchemeURL: url) {
            print("open url = open dynamic link activity")
            print("url = \(dynamicLink)")
            let destinationVC = UIStoryboard(name: "DynamicLink", bundle: nil).instantiateViewController(withIdentifier: "DynamicLinkView") as? DynamicLinkVC
            self.window?.rootViewController?.navigationController?.pushViewController(destinationVC!, animated: true)
        } else {
            print("open url = none")
        }
        return GIDSignIn.sharedInstance().handle(url)
    }

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        // On progress
        let handled = DynamicLinks.dynamicLinks().handleUniversalLink(userActivity.webpageURL!) { (dynamiclink, error) in
            print("dynamic link = \(dynamiclink)")
        }

        if handled {
            let destinationVC = UIStoryboard(name: "DynamicLink", bundle: nil).instantiateViewController(withIdentifier: "DynamicLinkView") as? DynamicLinkVC
            self.window?.rootViewController?.navigationController?.pushViewController(destinationVC!, animated: true)
        }

        return handled
    }
</code>```

So what happened when I click the link the app opens up immediately but it doesn't redirects to the desired UIViewController that I wanted (in this case destinationVC). It directly went to the login page as usual. But in the debug area, the link appears like this =

dynamic link = Optional(https://xxxx], match type: unique, minimumAppVersion: N/A, match message: (null)>)

Unfortunately I couldn't record the log messages when the app is not built by Xcode.

I'm very confused by this, what's wrong with my code? I'm new to iOS development so I'm not sure where did I do wrong. If you need more information feel free to ask and I will provide it to you. Any help would be appreciated. Thank you.

答:
If your rest-of-code is working fine, and you are just facing issue while navigating to another view controller, then this solution will work for you.

If you want to open particular ViewController, while clicking on dynamic link, then update your code written within restorationHandler, below updated code will help you to redirect/navigate to particular View Controller

```<code>func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        // On progress
        let handled = DynamicLinks.dynamicLinks().handleUniversalLink(userActivity.webpageURL!) { (dynamiclink, error) in
            print("dynamic link = \(dynamiclink)")
        }

    if handled {

             let mainStoryboardIpad : UIStoryboard = UIStoryboard(name: "DynamicLink", bundle: nil)
             if let initialViewController : UIViewController = (mainStoryboardIpad.instantiateViewController(withIdentifier: "DynamicLinkView") as? DynamicLinkVC) {
                    self.window = UIWindow(frame: UIScreen.main.bounds)
                    self.window?.rootViewController = initialViewController
                    self.window?.makeKeyAndVisible()
               }

        return handled
    }

</code>```

Hope this will resolve your issue.

Body:
I'm developing an app that can receive Firebase's Dynamic Link. What I want is when a user click a Dynamic Link, the app redirects it to a certain UIViewController. So I have a code that looks like this on my AppDelegate.swift file:

@available(iOS 9.0, *)
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {
        //return GIDSignIn.sharedInstance().handle(url)
        return application(app, open: url, sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation: "")
    }

    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        // On progress
        if let dynamicLink = DynamicLinks.dynamicLinks().dynamicLink(fromCustomSchemeURL: url) {
            print("open url = open dynamic link activity")
            print("url = \(dynamicLink)")
            let destinationVC = UIStoryboard(name: "DynamicLink", bundle: nil).instantiateViewController(withIdentifier: "DynamicLinkView") as? DynamicLinkVC
            self.window?.rootViewController?.navigationController?.pushViewController(destinationVC!, animated: true)
        } else {
            print("open url = none")
        }
        return GIDSignIn.sharedInstance().handle(url)
    }

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        // On progress
        let handled = DynamicLinks.dynamicLinks().handleUniversalLink(userActivity.webpageURL!) { (dynamiclink, error) in
            print("dynamic link = \(dynamiclink)")
        }

        if handled {
            let destinationVC = UIStoryboard(name: "DynamicLink", bundle: nil).instantiateViewController(withIdentifier: "DynamicLinkView") as? DynamicLinkVC
            self.window?.rootViewController?.navigationController?.pushViewController(destinationVC!, animated: true)
        }

        return handled
    }

So what happened when I click the link the app opens up immediately but it doesn't redirects to the desired UIViewController that I wanted (in this case destinationVC). It directly went to the login page as usual. But in the debug area, the link appears like this =

dynamic link = Optional(https://xxxx], match type: unique, minimumAppVersion: N/A, match message: (null)>)

Unfortunately I couldn't record the log messages when the app is not built by Xcode.

I'm very confused by this, what's wrong with my code? I'm new to iOS development so I'm not sure where did I do wrong. If you need more information feel free to ask and I will provide it to you. Any help would be appreciated. Thank you.

Body:
If your rest-of-code is working fine, and you are just facing issue while navigating to another view controller, then this solution will work for you.

If you want to open particular ViewController, while clicking on dynamic link, then update your code written within restorationHandler, below updated code will help you to redirect/navigate to particular View Controller

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        // On progress
        let handled = DynamicLinks.dynamicLinks().handleUniversalLink(userActivity.webpageURL!) { (dynamiclink, error) in
            print("dynamic link = \(dynamiclink)")
        }

    if handled {

             let mainStoryboardIpad : UIStoryboard = UIStoryboard(name: "DynamicLink", bundle: nil)
             if let initialViewController : UIViewController = (mainStoryboardIpad.instantiateViewController(withIdentifier: "DynamicLinkView") as? DynamicLinkVC) {
                    self.window = UIWindow(frame: UIScreen.main.bounds)
                    self.window?.rootViewController = initialViewController
                    self.window?.makeKeyAndVisible()
               }

        return handled
    }

Hope this will resolve your issue.


问:
Parsing URL jQuery AJAX form
Basically i'm trying to send a video along with other info through jQuery to PHP to be written to a txt file to be read later.

There is a way of inputting a video url into this. I've got everything working except one thing.

If i put this through: http://www.youtube.com/watch?v=g1lBwbhlPtM
it works fine.

but this: http://www.youtube.com/watch?v=g1lBwbhlPtM&feature=feedu
doesn't.

I've done some tests and it's because when i send the second url through &feature=feedu gets read as a separate $_POST value.

This is the problem:

```<code>    var dataString = 'title='+title+'&content='+content+'&date='+date+'&Submit=YES';
</code>```

because its reading like

var dataString = 'title='+title+'&content='+IMAGES, TEXT AND STUFF+'&feature=feedu OTHER IMAGES AND STUFF&date='+date+'&Submit=YES';

it's out of a textarea that could include images or text and stuff so im looking for something like htmlspecialchars() to sort out that & before sending it through ajax

Any ideas how to solve this?

EDIT:
Here's the full code that's the problem:

```<code>    var title = $('input#title').val();
    var content = $('textarea#content').val();
    var date = $('input#date').val();
    var dataString = 'title='+title+'&content='+content+'&date='+date+'&Submit=YES';
    //alert (dataString);return false;
    $.ajax({
     type: "POST",
     url: "./inc/php/file.php",
     dataType: "json",
     data: dataString,
     success: function(data) {
        if(data.error == true){
             $('.errordiv').show().html(data.message);
        }else{
             $('.errordiv').show().html(data.message);
             $(':input','#addstuff')
                .not(':button, :submit, :reset, :hidden')
                .val('')
                .removeAttr('checked')
                .removeAttr('selected');
        }
       },
       error: function(data) {
        $('.errordiv').html(data.message+' --- SCRIPT ERROR');
       }

    })
    return false;
</code>```

if content equals:

```<code>&content= <br>Text 1<br> <img>http://someimage.com/image.jpg</img>
<br> Text2<br> <vid>http://www.youtube.com/watch?v=isDIHIHI&feature=feedu</vid>
<br>Text 3<br>
</code>```

the content variable gets put through the ajax call as:

```<code>&content= <br>Text 1<br> <img>http://someimage.com/image.jpg</img>
<br> Text2<br> <vid>http://www.youtube.com/watch?v=isDIHIHI
</code>```

with an extra variable that is

```<code>&feature=feedu</vid>
<br>Text 3<br>
</code>```

So how do u stop the ajax reading &feature as a separate $_POST variable?

答:
Did you encodeURI() before pass the your video url?

If you need it in PHP then URLEncode

ContentLicense: CC BY-SA 3.0

Title: Parsing URL jQuery AJAX form

Body:
Basically i'm trying to send a video along with other info through jQuery to PHP to be written to a txt file to be read later.

There is a way of inputting a video url into this. I've got everything working except one thing.

If i put this through: http://www.youtube.com/watch?v=g1lBwbhlPtM
it works fine.

but this: http://www.youtube.com/watch?v=g1lBwbhlPtM&feature=feedu
doesn't.

I've done some tests and it's because when i send the second url through &feature=feedu gets read as a separate $_POST value.

This is the problem:

    var dataString = 'title='+title+'&content='+content+'&date='+date+'&Submit=YES';

because its reading like

var dataString = 'title='+title+'&content='+IMAGES, TEXT AND STUFF+'&feature=feedu OTHER IMAGES AND STUFF&date='+date+'&Submit=YES';

it's out of a textarea that could include images or text and stuff so im looking for something like htmlspecialchars() to sort out that & before sending it through ajax

Any ideas how to solve this?

EDIT:
Here's the full code that's the problem:

    var title = $('input#title').val();
    var content = $('textarea#content').val();
    var date = $('input#date').val();
    var dataString = 'title='+title+'&content='+content+'&date='+date+'&Submit=YES';
    //alert (dataString);return false;
    $.ajax({
     type: "POST",
     url: "./inc/php/file.php",
     dataType: "json",
     data: dataString,
     success: function(data) {
        if(data.error == true){
             $('.errordiv').show().html(data.message);
        }else{
             $('.errordiv').show().html(data.message);
             $(':input','#addstuff')
                .not(':button, :submit, :reset, :hidden')
                .val('')
                .removeAttr('checked')
                .removeAttr('selected');
        }
       },
       error: function(data) {
        $('.errordiv').html(data.message+' --- SCRIPT ERROR');
       }

    })
    return false;

if content equals:

&content=
Text 1
 http://someimage.com/image.jpg

 Text2
 <vid>http://www.youtube.com/watch?v=isDIHIHI&feature=feedu</vid>

Text 3

the content variable gets put through the ajax call as:

&content=
Text 1
 http://someimage.com/image.jpg

 Text2
 <vid>http://www.youtube.com/watch?v=isDIHIHI

with an extra variable that is

&feature=feedu</vid>

Text 3

So how do u stop the ajax reading &feature as a separate $_POST variable?


问:
Find the Last Cell Value of the 2nd Column Set for each 1st Column Cell in EXCEL
I have the following structured table in excel where 1000s of rows included.

I want to return the Last Cell Value of Column B for Each value in Column A.

For example:

For Cell A1 -> I want to return the Cell B5.

For Cell A6 -> I want to return the Cell B9.

I have tried with VLOOKUP, HLOOKUP, INDEX likewise so many formulas where I ended with more conflict situations. Can anyone please write down a Formula to give my requirement a life?

答:
Array formula (Press Control + Shift + Enter while entering the formula) in cell C1 and copy it down.

```<code>=IF(A1="","",IFERROR(INDEX($A2:$B$20,MATCH(FALSE,ISBLANK($A2:$A$20),0)-1,2),LOOKUP(2,1/(B2:$B$20),B2:$B$20)))
</code>```

Body:
Array formula (Press Control + Shift + Enter while entering the formula) in cell C1 and copy it down.

=IF(A1="","",IFERROR(INDEX($A2:$B$20,MATCH(FALSE,ISBLANK($A2:$A$20),0)-1,2),LOOKUP(2,1/(B2:$B$20),B2:$B$20)))


问:
How to use the absolute path of a file on another hard drive with Oracle (sqlplus)?
I am surprised I did not find anything about this anywhere, but how do I execute a file with sqlplus with the absolute path of the file? In the internet it says

```<code>sqlplus databaseURL @sqlFile
</code>```

This works if I use it as relative File and have the SQL File in the same directory. But using a path after the "@" just doesn't work and it says "file does not exist" when I run the command. The file surely is in the specified path and I am on Windows.

How do I make this work?

EDIT: Example of relative path:

```<code>sqlplus -l user/pw@localhost:1521/service @test.sql;
</code>```

Example of absolute path

```<code>sqlplus -l user/pw@localhost:1521/service @D:/folder/test.sql;
</code>```

答:
There is another possibility: to set the SQLPATH environment variable to specify where SQL*Plus should look for SQL files:

Doc. says

The SQLPATH registry entry specifies the location of SQL scripts.
  SQL*Plus searches for SQL scripts in the current directory and then in
  the directories specified by the SQLPATH registry entry, and in the
  subdirectories of SQLPATH directories.

The HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\HOME0 registry subkey (or the HOMEn directory for the associated ORACLE_HOME) contains the
  SQLPATH registry entry. SQLPATH is created with a default value of
  ORACLE_HOME\DBS. You can specify any directories on any drive as valid
  values for SQLPATH.

When setting the SQLPATH registry entry, you can concatenate directories with a semicolon (;). For example:

```<code>c:\oracle\ora12\database;c:\oracle\ora12\dbs
</code>```

See the Registry Editor's help system for instructions on how to edit the SQLPATH registry entry.

Body:
I am surprised I did not find anything about this anywhere, but how do I execute a file with sqlplus with the absolute path of the file? In the internet it says

sqlplus databaseURL @sqlFile

This works if I use it as relative File and have the SQL File in the same directory. But using a path after the "@" just doesn't work and it says "file does not exist" when I run the command. The file surely is in the specified path and I am on Windows.

How do I make this work?

EDIT: Example of relative path:

sqlplus -l user/pw@localhost:1521/service @test.sql;

Example of absolute path

sqlplus -l user/pw@localhost:1521/service @D:/folder/test.sql;

Body:
There is another possibility: to set the SQLPATH environment variable to specify where SQL*Plus should look for SQL files:

Doc. says

The SQLPATH registry entry specifies the location of SQL scripts.
  SQL*Plus searches for SQL scripts in the current directory and then in
  the directories specified by the SQLPATH registry entry, and in the
  subdirectories of SQLPATH directories.

The HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE\HOME0 registry subkey (or the HOMEn directory for the associated ORACLE_HOME) contains the
  SQLPATH registry entry. SQLPATH is created with a default value of
  ORACLE_HOME\DBS. You can specify any directories on any drive as valid
  values for SQLPATH.

When setting the SQLPATH registry entry, you can concatenate directories with a semicolon (;). For example:

c:\oracle\ora12\database;c:\oracle\ora12\dbs

See the Registry Editor's help system for instructions on how to edit the SQLPATH registry entry.


问:
Using Adobe Alchemy to get the OpenGL image from c++ code to flash app
I have C++ application that use OpenGL. Need to convert this app to flash app. Is it possible to do this with Adobe Alchemy? Is it will be possible to get from that swc current image (for example, with glDrawPixels) and print it on screen</p>

答: There's a similar thread here on SO already, seems that Mesa3D could be a good starting point, but it's going to be a lot of work :)</p>


问:
S3 - What Exactly Is A Prefix? And what Ratelimits apply?
I was wondering if anyone knew what exactly an s3 prefix was and how it interacts with amazon's published s3 rate limits:

Amazon S3 automatically scales to high request rates. For example,
  your application can achieve at least 3,500 PUT/POST/DELETE and 5,500
  GET requests per second per prefix in a bucket. There are no limits to
  the number of prefixes in a bucket.

While that's really clear I'm not quite certain what a prefix is?

Does a prefix require a delimiter?

If we have a bucket where we store all files at the "root" level (completely flat, without any prefix/delimters) does that count as single "prefix" and is it subject to the rate limits posted above?

The way I'm interpreting amazon's documentation suggests to me that this IS the case, and that the flat structure would be considered a single "prefix". (ie it would be subject to the published rate limits above)

Suppose that your bucket (admin-created) has four objects with the
  following object keys:

Development/Projects1.xls

Finance/statement1.pdf

Private/taxdocument.pdf

s3-dg.pdf

The s3-dg.pdf key does not have a prefix, so its object appears
  directly at the root level of the bucket. If you open the Development/
  folder, you see the Projects.xlsx object in it.

In the above example would s3-dg.pdf be subject to a different rate limit (5500 GET requests /second) than each of the other prefixes (Development/Finance/Private)?

What's more confusing is I've read a couple of blogs about amazon using the first N bytes as a partition key and encouraging about using high cardinality prefixes, I'm just not sure how that interacts with a bucket with a "flat file structure".

答:
S3 prefixes used to be determined by the first 6-8 characters;

This has changed mid-2018 - see announcement
https://aws.amazon.com/about-aws/whats-new/2018/07/amazon-s3-announces-increased-request-rate-performance/

But that is half-truth. Actually prefixes (in old definition) still matter.

S3 is not a traditional “storage” - each directory/filename is a separate object in a key/value object store. And also the data has to be partitioned/ sharded to scale to quadzillion of objects. So yes this new sharding is kinda of “automatic”, but not really if you created a new process that writes to it with crazy parallelism to different subdirectories. Before the S3 learns from the new access pattern, you may run into S3 throttling before it reshards/ repartitions data accordingly.

Learning new access patterns takes time. Repartitioning of the data takes time.

Things did improve in mid-2018 (~10x throughput-wise for a new bucket with no statistics), but it's still not what it could be if data is partitioned properly. Although to be fair, this may not be applied to you if you don't have a ton of data, or pattern how you access data is not hugely parallel (e.g. running a Hadoop/Spark cluster on many Tbs of data in S3 with hundreds+ of tasks accessing same bucket in parallel).

TLDR:

"Old prefixes" still do matter.
Write data to root of your bucket, and first-level directory there will determine "prefix" (make it random for example)

"New prefixes" do work, but not initially. It takes time to accommodate to load.

PS. Another approach - you can reach out to your AWS TAM (if you have one) and ask them to pre-partition a new S3 bucket if you expect a ton of data to be flooding it soon.


问:
Using GraphServiceClient to retrieve group info of Azure Ad members
i want to retrieve all members of a Azure Ad group within my backend application. I followed the steps here and here and here is my code:

But I always get this error when using the method:
  Microsoft.Graph.ServiceException: Code: generalException Message: An
  error occurred sending the request.

---> Microsoft.Graph.Auth.AuthenticationException: Code:
  authenticationChallengeRequired Message: Authentication challange is
  required.

Can someone help me with that? I didn't find this specific error.

答:
Obviously these parameters(clientId/tenantId/clientSecret/groupId) need to be replaced with specific strings.

You could find clientId and tenantId via App registrations-> Overview:

clientSecret via App registrations-> Certificates & secrets:

groupId via Azure Active Directory -> Groups:

You could also store the specific strings in a profile and read the strings in the file.
And the sample will help you to understand it.

AccountController.cs :

```<code>IConfidentialClientApplication daemonClient;
                daemonClient = ConfidentialClientApplicationBuilder.Create(Startup.clientId)
                    .WithAuthority(string.Format(AuthorityFormat, tenantId))
                    .WithRedirectUri(Startup.redirectUri)
                    .WithClientSecret(Startup.clientSecret)
                    .Build();
</code>```

Web.config :

```<code>  <add key="ida:ClientId" value="[Enter your client ID]" />
  <add key="ida:ClientSecret" value="[Enter your client secret]" />
</code>```

Startup.Auth.cs :

```<code>public static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
public static string clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];
public static string redirectUri = "https://localhost:44316/";
</code>```

Body:
Obviously these parameters(clientId/tenantId/clientSecret/groupId) need to be replaced with specific strings.

You could find clientId and tenantId via App registrations-> Overview:

clientSecret via App registrations-> Certificates & secrets:

groupId via Azure Active Directory -> Groups:

You could also store the specific strings in a profile and read the strings in the file.
And the sample will help you to understand it.

AccountController.cs :

IConfidentialClientApplication daemonClient;
                daemonClient = ConfidentialClientApplicationBuilder.Create(Startup.clientId)
                    .WithAuthority(string.Format(AuthorityFormat, tenantId))
                    .WithRedirectUri(Startup.redirectUri)
                    .WithClientSecret(Startup.clientSecret)
                    .Build();

Web.config :

  <add key="ida:ClientId" value="[Enter your client ID]" />
  <add key="ida:ClientSecret" value="[Enter your client secret]" />

Startup.Auth.cs :

public static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
public static string clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];
public static string redirectUri = "https://localhost:44316/";


问:
Paramiko: Creating a PKey from a public key string
I'm trying to use the SSH protocol at a low level (i.e. I don't want to start a shell or anything, I just want to pass data). Thus, I am using Paramiko's Transport class directly.

I've got the server side done, but now I'm hitting a wall over something silly. For the client to connect to the server, the Transport's connect method takes as two PKey objects as argument: The private key of the client (pkey), and the public key of the server (hostkey).

The PKey class is described as "Base class for public keys". Yet the problem is that I can't figure out how to create such a PKey object out of just an ssh public key (i.e. a string ssh-whatever AAblablabla). It has methods for building such an object out of a private key, but obviously I don't want the client to know the server's private key.

I feel like I'm overlooking something simple, but I can't find info on doing that on the web; most tutorials out there use the higher-level SSHClient class which loads the system's known_hosts keys.

答:
To add onto the solution provided for the Transport Client. Here is my solution for adding a string public key to the SSH Client:</p>

```<code>my_pub_key = "xx.xx.xx.xx ecdsa-sha2-nistp256 mlzdHAyNT....."
my_host = my_pub_key.split(' ')[0]
password = 'myFavortitePassword'
username = 'myUsername'

ssh_client=paramiko.SSHClient()

host_key_policy = paramiko.MissingHostKeyPolicy()
host_key_policy.missing_host_key(ssh_client, my_host, my_pub_key)

ssh_client.connect(hostname= my_host
                            ,username=username
                            ,password=password
                            ,port=22
                            ,look_for_keys=False)
</code>```

Body:
To add onto the solution provided for the Transport Client. Here is my solution for adding a string public key to the SSH Client:

my_pub_key = "xx.xx.xx.xx ecdsa-sha2-nistp256 mlzdHAyNT....."
my_host = my_pub_key.split(' ')[0]
password = 'myFavortitePassword'
username = 'myUsername'

ssh_client=paramiko.SSHClient()

host_key_policy = paramiko.MissingHostKeyPolicy()
host_key_policy.missing_host_key(ssh_client, my_host, my_pub_key)

ssh_client.connect(hostname= my_host
                            ,username=username
                            ,password=password
                            ,port=22
                            ,look_for_keys=False)


问:
Apply a column containing polygon to Polygon() shapely
I have a dataframe with a column called NewPolygon :

```<code>NewPolygon
[(1.23,10),(4.4, 10)...]
[(16.0,10),(8.1, 10)...]
[(2.2,10),(0, 10)...]
</code>```

My code :

```<code>from shapely.geometry import Point
from shapely.geometry.polygon import Polygon

polygon = pd.read_csv(file_path)

point = Point(10, 1.1)

polygon = Polygon() ####How to apply the value from column `NewPolygon` here iteratively
print(polygon.contains(point))
</code>```

How can I apply all values from NewPolygon to Polygon() iteratively?
Polygon() take a list of tuple as value such as Polygon([(1.23,10),(4.4, 10)...])

答:
Simply, use, Series.transform:

```<code>df['NewPolygon'] = df['NewPolygon'].transform(Polygon)
</code>```

To use methods on polygon objects stored inside NewPolygon column, Use:

```<code>df['NewPolygon'].apply(lambda p : p.contains(point))
</code>```

Body:
I have a dataframe with a column called NewPolygon :

NewPolygon
[(1.23,10),(4.4, 10)...]
[(16.0,10),(8.1, 10)...]
[(2.2,10),(0, 10)...]

My code :

from shapely.geometry import Point
from shapely.geometry.polygon import Polygon

polygon = pd.read_csv(file_path)

point = Point(10, 1.1)

polygon = Polygon() ####How to apply the value from column `NewPolygon` here iteratively
print(polygon.contains(point))

How can I apply all values from NewPolygon to Polygon() iteratively?
Polygon() take a list of tuple as value such as Polygon([(1.23,10),(4.4, 10)...])

Body:
Simply, use, Series.transform:

df['NewPolygon'] = df['NewPolygon'].transform(Polygon)

To use methods on polygon objects stored inside NewPolygon column, Use:

df['NewPolygon'].apply(lambda p : p.contains(point))


问:
Xamarin.Android How to separate speech to text sentences into separate words
I have Android speech recognition set up in my Xamarin.Android. Currently the user can say a word which is then shown in a textview.

What I want to do is split a sentence into separate words using a separator word such as 'and'.

For example: if I say 'fish and chips' in one sentence, the words fish and chips should be split into separate strings and added to a list view.

Is this possible?

答:
You can separate strings by using String.Split:

For example:

```<code>public MainPage()
{
    InitializeComponent();

    string testStr = "fish and chips in one sentence";

    string[] separatedStrs = testStr.Split(new[] { "and" }, StringSplitOptions.None);

    foreach (var item in separatedStrs)
    {
        Console.WriteLine(item);
    }
}
</code>```

Body:
You can separate strings by using String.Split:

For example:

public MainPage()
{
    InitializeComponent();

    string testStr = "fish and chips in one sentence";

    string[] separatedStrs = testStr.Split(new[] { "and" }, StringSplitOptions.None);

    foreach (var item in separatedStrs)
    {
        Console.WriteLine(item);
    }
}


问:
Is Django middleware thread safe?
Are Django middleware thread safe? Can I do something like this,</p>

```<code>class ThreadsafeTestMiddleware(object):

    def process_request(self, request):
        self.thread_safe_variable = some_dynamic_value_from_request

    def process_response(self, request, response):
        # will self.thread_safe_variable always equal to some_dynamic_value_from_request?
</code>```

答:
Why not bind your variable to the request object, like so:</p>

```<code>class ThreadsafeTestMiddleware(object):

    def process_request(self, request):
        request.thread_safe_variable = some_dynamic_value_from_request

    def process_response(self, request, response):
        #... do something with request.thread_safe_variable here ...
</code>```

Title: Is Django middleware thread safe?

Body:
Are Django middleware thread safe? Can I do something like this,

class ThreadsafeTestMiddleware(object):

    def process_request(self, request):
        self.thread_safe_variable = some_dynamic_value_from_request

    def process_response(self, request, response):
        # will self.thread_safe_variable always equal to some_dynamic_value_from_request?

Body:
Why not bind your variable to the request object, like so:

class ThreadsafeTestMiddleware(object):

    def process_request(self, request):
        request.thread_safe_variable = some_dynamic_value_from_request

    def process_response(self, request, response):
        #... do something with request.thread_safe_variable here ...


问:
Default value for Text Field flutter?
How can I have a text as a place holder until onTap() happen? (onTap is on another page)

```<code>Align(
        alignment: Alignment.center,
        child: Text(//Default value goes here
          widget.categoryTitle,//this string comes from another page it changes on every onTap()
          style: TextStyle(
            color: Colors.black,
            fontSize: 17.0,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
</code>```

Right now if no onTap happens the Text is holding a white blank space, How to replace it with a default/initial value?

答:
Add Ternary operator and assign values as per text  </p>

```<code>       Align(
            alignment: Alignment.center,
            child: Text(//Default value goes here
              widget.categoryTitle.isEmpty? "Default Text": widget.categoryTitle,
              style: TextStyle(
                color: Colors.black,
                fontSize: 17.0,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
</code>```

Title: Default value for Text Field flutter?

Body:
How can I have a text as a place holder until onTap() happen? (onTap is on another page)

Align(
        alignment: Alignment.center,
        child: Text(//Default value goes here
          widget.categoryTitle,//this string comes from another page it changes on every onTap()
          style: TextStyle(
            color: Colors.black,
            fontSize: 17.0,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),

Right now if no onTap happens the Text is holding a white blank space, How to replace it with a default/initial value?

Body:
Add Ternary operator and assign values as per text

       Align(
            alignment: Alignment.center,
            child: Text(//Default value goes here
              widget.categoryTitle.isEmpty? "Default Text": widget.categoryTitle,
              style: TextStyle(
                color: Colors.black,
                fontSize: 17.0,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),


问:
region based environment based dynamic vars file loading in ansible
i want to load specific var files in ansible based on region and environment type.
I have a playbook which creates several ec2 instances in at a go with following kind of configuration -

```<code>---
- hosts: local
  gather_facts: true
  any_errors_fatal: true
  vars_files:
    - group_vars/ec2.yml

  roles:
    - role-for-instance-1-creation
    - role-for-instance-1-creation
</code>```

but the problem is.. depending on the user requirement, it may create the instances in EU region once, in US region some other time. ec2.yml contains ec2 role related vars which may vary depending on the region , also depending on the enviroment, is it prod or is it testing. but i could not find a way.

I need some kind of structure.. where suppose user provided extra vars while running the playbook like --extra-vars "environment=prod location=EU"
and the playbook will create the ec2 instnaces in the specfic region reading specific ec2.yml file like ec2_prod_EU.yml or like

```<code>ec2_testing_US.yml
</code>```

or in better way that vars files will be loaded from specific directory

```<code>group_vars/prod/ec2-EU.yml
group_vars/testing/ec2-US.yml
</code>```

how can i do that.. include_vars is an option but is there any better way to acheive it. Thanks in advance

答:
I have done it in the following way-
conditionally added vars file on the roles and the condition parameters i have passed while executing the playbook -

```<code>- name: dynamic ec2 yml load
  include_vars:
        file: group_vars/test/ec2_us_test_session_host_1.yml
  when: environment_use == 'test' and location == 'us'
  tags:
          - ec2-creation
</code>```

and while calling the playbook -

```<code>ansible-playbook my-playbook.yml --extra-vars "source_ami=${Source_AMI} Description_new_hosts=${description} environment_use=${environment_use} location=${location} availability_zone=${AZ} subnet=${subnet}"
</code>```

Body:
i want to load specific var files in ansible based on region and environment type.
I have a playbook which creates several ec2 instances in at a go with following kind of configuration -

---
- hosts: local
  gather_facts: true
  any_errors_fatal: true
  vars_files:
    - group_vars/ec2.yml

  roles:
    - role-for-instance-1-creation
    - role-for-instance-1-creation

but the problem is.. depending on the user requirement, it may create the instances in EU region once, in US region some other time. ec2.yml contains ec2 role related vars which may vary depending on the region , also depending on the enviroment, is it prod or is it testing. but i could not find a way.

I need some kind of structure.. where suppose user provided extra vars while running the playbook like --extra-vars "environment=prod location=EU"
and the playbook will create the ec2 instnaces in the specfic region reading specific ec2.yml file like ec2_prod_EU.yml or like

ec2_testing_US.yml

or in better way that vars files will be loaded from specific directory

group_vars/prod/ec2-EU.yml
group_vars/testing/ec2-US.yml

how can i do that.. include_vars is an option but is there any better way to acheive it. Thanks in advance

Body:
I have done it in the following way-
conditionally added vars file on the roles and the condition parameters i have passed while executing the playbook -

- name: dynamic ec2 yml load
  include_vars:
        file: group_vars/test/ec2_us_test_session_host_1.yml
  when: environment_use == 'test' and location == 'us'
  tags:
          - ec2-creation

and while calling the playbook -

ansible-playbook my-playbook.yml --extra-vars "source_ami=${Source_AMI} Description_new_hosts=${description} environment_use=${environment_use} location=${location} availability_zone=${AZ} subnet=${subnet}"


问:
What is the right way to extend AspnetUserRoles table in ASPNET.Core 3.1?
Situation

I'm using Identity ASP.NET Core 3.1 with Angular 8 Template. I want to extend the ASPNETUserRoles table and add another custom key column CompanyId in it.

By Default Identity provides:

```<code>public virtual TKey UserId { get; set; }
public virtual TKey RoleId { get; set; }
</code>```

As I modified my DbContext from UserId (string) to UserId (long), DbContext looks like:

```<code>public class CompanyDBContext : KeyApiAuthorizationDbContext<User, Role, UserRole, long>
{
    public CompanyDBContext(
        DbContextOptions options,
        IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions)
        {
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
    public DbSet<Company> Companies { get; set; }

}
</code>```

KeyApiAuthorizationDbContext

```<code>public class KeyApiAuthorizationDbContext<TUser, TRole, IdentityUserRole, TKey> : IdentityDbContext<TUser, TRole, TKey, IdentityUserClaim<TKey>, IdentityUserRole<TKey>, IdentityUserLogin<TKey>, IdentityRoleClaim<TKey>, IdentityUserToken<TKey>>, IPersistedGrantDbContext
    where TUser : IdentityUser<TKey>
    where TRole : IdentityRole<TKey>
    where IdentityUserRole : IdentityUserRole<TKey>
    where TKey : IEquatable<TKey>
{
    private readonly IOptions<OperationalStoreOptions> _operationalStoreOptions;

    /// <summary>
    /// Initializes a new instance of <see cref="ApiAuthorizationDbContext{TUser, TRole, TKey}"/>.
    /// </summary>
    /// <param name="options">The <see cref="DbContextOptions"/>.</param>
    /// <param name="operationalStoreOptions">The <see cref="IOptions{OperationalStoreOptions}"/>.</param>
    public KeyApiAuthorizationDbContext(
        DbContextOptions options,
        IOptions<OperationalStoreOptions> operationalStoreOptions)
        : base(options)
    {
        _operationalStoreOptions = operationalStoreOptions;
    }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{PersistedGrant}"/>.
    /// </summary>
    public DbSet<PersistedGrant> PersistedGrants { get; set; }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{DeviceFlowCodes}"/>.
    /// </summary>
    public DbSet<DeviceFlowCodes> DeviceFlowCodes { get; set; }

    Task<int> IPersistedGrantDbContext.SaveChangesAsync() => base.SaveChangesAsync();

    /// <inheritdoc />
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        builder.ConfigurePersistedGrantContext(_operationalStoreOptions.Value);
    }
}
</code>```

Entities

```<code>public class User : IdentityUser<long> {}
public class Role : IdentityRole<long> {}
public class UserRole : IdentityUserRole<long>
{
    public long CompanyId { get; set; }
}
</code>```

Problem Occur

When I registered my user and it returns true then I'll add a current user in UserRole table like below but when my debugger reached await _context.SaveChangesAsync(); method its shows me an exception

```<code>if (result.Succeeded)
{
    foreach (var role in model.Roles.Where(x => x.IsChecked = true))
    {
        var entity = new Core.Entities.Identity.UserRole()
        {
            UserId = model.User.Id,
            RoleId = role.Id,
            CompanyId = companycode
        };

            _context.UserRoles.Add(entity);
    }
    await _context.SaveChangesAsync();

}
</code>```

I don't know where I'm making my mistake? If above steps of overriding userrole are wrong then assist me on that.

I'm also sharing my migration details for your information may be something I'm doing wrong there.

Migrations

```<code>migrationBuilder.CreateTable(
name: "Companies",
columns: table => new
{
   Id = table.Column<long>(nullable: false)
       .Annotation("SqlServer:Identity", "1, 1"),
                Name = table.Column<string>(nullable: false),
                Code = table.Column<string>(nullable: false),
                Logo = table.Column<string>(nullable: true)
       },
       constraints: table =>
       {
                table.PrimaryKey("PK_Companies", x => x.Id);
});

migrationBuilder.CreateTable(
                name: "AspNetUserRoles",
                columns: table => new
                {
                    UserId = table.Column<long>(nullable: false),
                    RoleId = table.Column<long>(nullable: false),
                    CompanyId = table.Column<long>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId, x.CompanyId });
                    table.ForeignKey(
                        name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
                        column: x => x.RoleId,
                        principalTable: "AspNetRoles",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                    table.ForeignKey(
                        name: "FK_AspNetUserRoles_AspNetUsers_UserId",
                        column: x => x.UserId,
                        principalTable: "AspNetUsers",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                    table.ForeignKey(
                        name: "FK_AspNetUserRoles_Companies_CompanyId",
                        column: x => x.CompanyId,
                        principalTable: "Companies",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });
</code>```

Migration Snapshot

```<code>modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<long>", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int")
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.Property<string>("ClaimType")
                        .HasColumnType("nvarchar(max)");

                    b.Property<string>("ClaimValue")
                        .HasColumnType("nvarchar(max)");

                    b.Property<long>("RoleId")
                        .HasColumnType("bigint");

                    b.HasKey("Id");

                    b.HasIndex("RoleId");

                    b.ToTable("AspNetRoleClaims");
                });
</code>```

答:
Now I came up with an answer to my own question.

Recall Question

I want to extend the User Role (IdentityUserRole) and adding a few foreign keys, but faced two errors:

Error 1

Invalid column name 'discriminator'

Error 2

A key cannot be configured on ‘UserRole’ because it is a derived type. The key must be configured on the root type ‘IdentityUserRole’. If you did not intend for ‘IdentityUserRole’ to be included in the model, ensure that it is not included in a DbSet property on your context, referenced in a configuration call to ModelBuilder, or referenced from a navigation property on a type that is included in the model.

This is because if you look into the definition of IdentityUserRole, you’ll find out that it already has primary keys:

```<code>public virtual TKey UserId { get; set; }
public virtual TKey RoleId { get; set; }
</code>```

So, what's the solution?

To fix this, we have to override the user role implementation.

Now if you see the code:

```<code>public class CompanyDBContext : IdentityDbContext<User, Role, long, UserClaim, UserRole, UserLogin, RoleClaim, UserToken>, IPersistedGrantDbContext
    {
        private readonly IOptions<OperationalStoreOptions> _operationalStoreOptions;
        public CompanyDBContext(
            DbContextOptions options,
            IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options)
        {
            _operationalStoreOptions = operationalStoreOptions;
        }

        Task<int> IPersistedGrantDbContext.SaveChangesAsync() => base.SaveChangesAsync();

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.ConfigurePersistedGrantContext(_operationalStoreOptions.Value);
            modelBuilder.Entity<UserRole>(b =>
            {
                b.HasKey(ur => new { ur.UserId, ur.RoleId, ur.CompanyId });
            });
        public DbSet<DeviceFlowCodes> DeviceFlowCodes { get; set; }
        public DbSet<PersistedGrant> PersistedGrants { get; set; }

    }
</code>```

That's it. As @EduCielo suggested I re-consider my code and do the proper mapping and configuration and override the modelbuilder to map the proper relationship for user role.

For new developers, I'm sharing entity classes which I used above to make it fully worked with your code.

```<code>public class User : IdentityUser<long> { //Add new props to modify ASP.NETUsers Table }

public class Role : IdentityRole<long> { }

public class UserClaim: IdentityUserClaim<long> { }

public class UserRole : IdentityUserRole<long>
{

    [Key, Column(Order = 2)]
    public long CompanyId { get; set; }

    public Company Company { get; set; }
}

public class UserLogin: IdentityUserLogin<long> { }

public class RoleClaim : IdentityRoleClaim<long> { }

public class UserToken : IdentityUserToken<long> { }
</code>```

Conclusion

```<code>add-migration FirstMigration -context CompanyDbContext
update-database -context CompanyDbContext
</code>```

Happy Coding :)

Ref Link

Body:
Situation

I'm using Identity ASP.NET Core 3.1 with Angular 8 Template. I want to extend the ASPNETUserRoles table and add another custom key column CompanyId in it.

By Default Identity provides:

public virtual TKey UserId { get; set; }
public virtual TKey RoleId { get; set; }

As I modified my DbContext from UserId (string) to UserId (long), DbContext looks like:

public class CompanyDBContext : KeyApiAuthorizationDbContext<User, Role, UserRole, long>
{
    public CompanyDBContext(
        DbContextOptions options,
        IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions)
        {
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
    public DbSet<Company> Companies { get; set; }

}

KeyApiAuthorizationDbContext

public class KeyApiAuthorizationDbContext<TUser, TRole, IdentityUserRole, TKey> : IdentityDbContext<TUser, TRole, TKey, IdentityUserClaim<TKey>, IdentityUserRole<TKey>, IdentityUserLogin<TKey>, IdentityRoleClaim<TKey>, IdentityUserToken<TKey>>, IPersistedGrantDbContext
    where TUser : IdentityUser<TKey>
    where TRole : IdentityRole<TKey>
    where IdentityUserRole : IdentityUserRole<TKey>
    where TKey : IEquatable<TKey>
{
    private readonly IOptions<OperationalStoreOptions> _operationalStoreOptions;

    ///
    /// Initializes a new instance of <see cref="ApiAuthorizationDbContext{TUser, TRole, TKey}"/>.
    ///
    /// <param name="options">The <see cref="DbContextOptions"/>.</param>
    /// <param name="operationalStoreOptions">The <see cref="IOptions{OperationalStoreOptions}"/>.</param>
    public KeyApiAuthorizationDbContext(
        DbContextOptions options,
        IOptions<OperationalStoreOptions> operationalStoreOptions)
        : base(options)
    {
        _operationalStoreOptions = operationalStoreOptions;
    }

    ///
    /// Gets or sets the <see cref="DbSet{PersistedGrant}"/>.
    ///
    public DbSet<PersistedGrant> PersistedGrants { get; set; }

    ///
    /// Gets or sets the <see cref="DbSet{DeviceFlowCodes}"/>.
    ///
    public DbSet<DeviceFlowCodes> DeviceFlowCodes { get; set; }

    Task<int> IPersistedGrantDbContext.SaveChangesAsync() => base.SaveChangesAsync();

    /// <inheritdoc />
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        builder.ConfigurePersistedGrantContext(_operationalStoreOptions.Value);
    }
}

Entities

public class User : IdentityUser<long> {}
public class Role : IdentityRole<long> {}
public class UserRole : IdentityUserRole<long>
{
    public long CompanyId { get; set; }
}

Problem Occur

When I registered my user and it returns true then I'll add a current user in UserRole table like below but when my debugger reached await _context.SaveChangesAsync(); method its shows me an exception

if (result.Succeeded)
{
    foreach (var role in model.Roles.Where(x => x.IsChecked = true))
    {
        var entity = new Core.Entities.Identity.UserRole()
        {
            UserId = model.User.Id,
            RoleId = role.Id,
            CompanyId = companycode
        };

            _context.UserRoles.Add(entity);
    }
    await _context.SaveChangesAsync();

}

I don't know where I'm making my mistake? If above steps of overriding userrole are wrong then assist me on that.

I'm also sharing my migration details for your information may be something I'm doing wrong there.

Migrations

migrationBuilder.CreateTable(
name: "Companies",
columns: table => new
{
   Id = table.Column<long>(nullable: false)
       .Annotation("SqlServer:Identity", "1, 1"),
                Name = table.Column<string>(nullable: false),
                Code = table.Column<string>(nullable: false),
                Logo = table.Column<string>(nullable: true)
       },
       constraints: table =>
       {
                table.PrimaryKey("PK_Companies", x => x.Id);
});

migrationBuilder.CreateTable(
                name: "AspNetUserRoles",
                columns: table => new
                {
                    UserId = table.Column<long>(nullable: false),
                    RoleId = table.Column<long>(nullable: false),
                    CompanyId = table.Column<long>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId, x.CompanyId });
                    table.ForeignKey(
                        name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
                        column: x => x.RoleId,
                        principalTable: "AspNetRoles",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                    table.ForeignKey(
                        name: "FK_AspNetUserRoles_AspNetUsers_UserId",
                        column: x => x.UserId,
                        principalTable: "AspNetUsers",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                    table.ForeignKey(
                        name: "FK_AspNetUserRoles_Companies_CompanyId",
                        column: x => x.CompanyId,
                        principalTable: "Companies",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

Migration Snapshot

modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<long>", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int")
                        .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

                    b.Property<string>("ClaimType")
                        .HasColumnType("nvarchar(max)");

                    b.Property<string>("ClaimValue")
                        .HasColumnType("nvarchar(max)");

                    b.Property<long>("RoleId")
                        .HasColumnType("bigint");

                    b.HasKey("Id");

                    b.HasIndex("RoleId");

                    b.ToTable("AspNetRoleClaims");
                });

Body:
Now I came up with an answer to my own question.

Recall Question

I want to extend the User Role (IdentityUserRole) and adding a few foreign keys, but faced two errors:

Error 1

Invalid column name 'discriminator'

Error 2

A key cannot be configured on ‘UserRole’ because it is a derived type. The key must be configured on the root type ‘IdentityUserRole’. If you did not intend for ‘IdentityUserRole’ to be included in the model, ensure that it is not included in a DbSet property on your context, referenced in a configuration call to ModelBuilder, or referenced from a navigation property on a type that is included in the model.

This is because if you look into the definition of IdentityUserRole, you’ll find out that it already has primary keys:

public virtual TKey UserId { get; set; }
public virtual TKey RoleId { get; set; }

So, what's the solution?

To fix this, we have to override the user role implementation.

Now if you see the code:

public class CompanyDBContext : IdentityDbContext<User, Role, long, UserClaim, UserRole, UserLogin, RoleClaim, UserToken>, IPersistedGrantDbContext
    {
        private readonly IOptions<OperationalStoreOptions> _operationalStoreOptions;
        public CompanyDBContext(
            DbContextOptions options,
            IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options)
        {
            _operationalStoreOptions = operationalStoreOptions;
        }

        Task<int> IPersistedGrantDbContext.SaveChangesAsync() => base.SaveChangesAsync();

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.ConfigurePersistedGrantContext(_operationalStoreOptions.Value);
            modelBuilder.Entity<UserRole>(b =>
            {
                b.HasKey(ur => new { ur.UserId, ur.RoleId, ur.CompanyId });
            });
        public DbSet<DeviceFlowCodes> DeviceFlowCodes { get; set; }
        public DbSet<PersistedGrant> PersistedGrants { get; set; }

    }

That's it. As @EduCielo suggested I re-consider my code and do the proper mapping and configuration and override the modelbuilder to map the proper relationship for user role.

For new developers, I'm sharing entity classes which I used above to make it fully worked with your code.

public class User : IdentityUser<long> { //Add new props to modify ASP.NETUsers Table }

public class Role : IdentityRole<long> { }

public class UserClaim: IdentityUserClaim<long> { }

public class UserRole : IdentityUserRole<long>
{

    [Key, Column(Order = 2)]
    public long CompanyId { get; set; }

    public Company Company { get; set; }
}

public class UserLogin: IdentityUserLogin<long> { }

public class RoleClaim : IdentityRoleClaim<long> { }

public class UserToken : IdentityUserToken<long> { }

Conclusion

add-migration FirstMigration -context CompanyDbContext
update-database -context CompanyDbContext

Happy Coding :)

Ref Link


问:
Karma Chrome Headless not working on Jenkins
When I run the below setup with Docker locally on my mac everything works fine.

But same setup does not work on Jenkins running on Ubuntu 16.04

ChromiumHeadless have not captured in 60000 ms, killing.

Following error log is from Jenkins console:

```<code>25 05 2018 06:35:09.076:INFO [karma]: Karma v2.0.2 server started at http://0.0.0.0:9222/
25 05 2018 06:35:09.079:INFO [launcher]: Launching browser Chromium_no_sandbox with unlimited concurrency
25 05 2018 06:35:09.090:INFO [launcher]: Starting browser ChromiumHeadless
25 05 2018 06:36:09.128:WARN [launcher]: ChromiumHeadless have not captured in 60000 ms, killing.
25 05 2018 06:36:09.139:INFO [launcher]: Trying to start ChromiumHeadless again (1/2).
25 05 2018 06:37:09.140:WARN [launcher]: ChromiumHeadless have not captured in 60000 ms, killing.
25 05 2018 06:37:09.147:INFO [launcher]: Trying to start ChromiumHeadless again (2/2).
</code>```

Package.json ...
"testProd": "./node_modules/karma/bin/karma start karma.conf-prod.js --single-run",

Dockerfile

```<code>FROM zenika/alpine-node:latest
LABEL name="product-web"

# Update apk repositories
RUN echo "http://dl-2.alpinelinux.org/alpine/edge/main" > /etc/apk/repositories
RUN echo "http://dl-2.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories
RUN echo "http://dl-2.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories

# Install chromium
RUN apk -U --no-cache \
    --allow-untrusted add \
    zlib-dev \
    chromium \
    xvfb \
    wait4ports \
    xorg-server \
    dbus \
    ttf-freefont \
    mesa-dri-swrast \
    grep \
    udev \
    && apk del --purge --force linux-headers binutils-gold gnupg zlib-dev libc-utils \
    && rm -rf /var/lib/apt/lists/* \
    /var/cache/apk/* \
    /usr/share/man \
    /tmp/* \
    /usr/lib/node_modules/npm/man \
    /usr/lib/node_modules/npm/doc \
    /usr/lib/node_modules/npm/html \
    /usr/lib/node_modules/npm/scripts

WORKDIR /home/dev/code
COPY . .

#RUN rm -rf node_modules && npm cache clear --force

ENV CHROME_BIN=/usr/bin/chromium-browser
ENV CHROME_PATH=/usr/lib/chromium/

RUN npm install
RUN npm run testProd && npm run buildProd
</code>```

karma.conf-prod.js

```<code>const path = require('path');
module.exports = function(config) {
    config.set({
        basePath: '',
        browsers: ['ChromeHeadlessNoSandbox'],
    customLaunchers: {
        ChromeHeadlessNoSandbox: {
            base: 'ChromeHeadless',
            flags: [
                '--no-sandbox',
                '--user-data-dir=/tmp/chrome-test-profile',
                '--disable-web-security'
            ]
        }
    },
        frameworks: ['mocha', 'chai'],
        captureConsole: true,
        files: [
            'node_modules/babel-polyfill/dist/polyfill.js',
            'test/root.js'
        ],
        preprocessors: {
            'src/index.js': ['webpack', 'sourcemap'],
            'test/root.js': ['webpack']
        },
        webpack: {
            devtool: 'inline-source-map',
            module: {
                loaders: [
                    {
                        test: /\.js$/,
                        loader: 'babel-loader',
                        exclude: path.resolve(__dirname, 'node_modules'),
                        query: {
                            plugins: ['transform-decorators-legacy', 'transform-regenerator'],
                            presets: ['env', 'stage-1', 'react']
                        }
                    },
                    {
                        test: /\.json$/,
                        loader: 'json-loader',
                    },
                ]
            },
            externals: {
                'react/addons': true,
                'react/lib/ExecutionEnvironment': true,
                'react/lib/ReactContext': true
            }
        },
        webpackServer: {
            noInfo: true
        },
        reporters: ['spec'],
        port: 9222,
        logLevel: config.LOG_INFO
    });
};
</code>```

I even tried with logLevel: config.LOG_DEBUG but did not show anything missing or unusual.

答:
package.json

```<code>"karma": "~1.7.1",
"karma-chrome-launcher": "~2.2.0",
</code>```

karma.conf.js

```<code>browsers: ['ChromeHeadlessNoSandbox'],
customLaunchers: {
    ChromeHeadlessNoSandbox: {
        base: 'ChromeHeadless',
        flags: ['--no-sandbox']
    }
},
</code>```

and need to use the below command with --source-map=false

```<code>"qa-test": "ng test --watch=false --progress=false --browsers=ChromeHeadless --code-coverage --source-map=false"
</code>```

my build got succeeded after this change.

Body:
When I run the below setup with Docker locally on my mac everything works fine.

But same setup does not work on Jenkins running on Ubuntu 16.04

ChromiumHeadless have not captured in 60000 ms, killing.

Following error log is from Jenkins console:

25 05 2018 06:35:09.076:INFO [karma]: Karma v2.0.2 server started at http://0.0.0.0:9222/
25 05 2018 06:35:09.079:INFO [launcher]: Launching browser Chromium_no_sandbox with unlimited concurrency
25 05 2018 06:35:09.090:INFO [launcher]: Starting browser ChromiumHeadless
25 05 2018 06:36:09.128:WARN [launcher]: ChromiumHeadless have not captured in 60000 ms, killing.
25 05 2018 06:36:09.139:INFO [launcher]: Trying to start ChromiumHeadless again (1/2).
25 05 2018 06:37:09.140:WARN [launcher]: ChromiumHeadless have not captured in 60000 ms, killing.
25 05 2018 06:37:09.147:INFO [launcher]: Trying to start ChromiumHeadless again (2/2).

Package.json ...
"testProd": "./node_modules/karma/bin/karma start karma.conf-prod.js --single-run",

Dockerfile

FROM zenika/alpine-node:latest
LABEL name="product-web"

# Update apk repositories
RUN echo "http://dl-2.alpinelinux.org/alpine/edge/main" > /etc/apk/repositories
RUN echo "http://dl-2.alpinelinux.org/alpine/edge/community" >> /etc/apk/repositories
RUN echo "http://dl-2.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories

# Install chromium
RUN apk -U --no-cache \
    --allow-untrusted add \
    zlib-dev \
    chromium \
    xvfb \
    wait4ports \
    xorg-server \
    dbus \
    ttf-freefont \
    mesa-dri-swrast \
    grep \
    udev \
    && apk del --purge --force linux-headers binutils-gold gnupg zlib-dev libc-utils \
    && rm -rf /var/lib/apt/lists/* \
    /var/cache/apk/* \
    /usr/share/man \
    /tmp/* \
    /usr/lib/node_modules/npm/man \
    /usr/lib/node_modules/npm/doc \
    /usr/lib/node_modules/npm/html \
    /usr/lib/node_modules/npm/scripts

WORKDIR /home/dev/code
COPY . .

#RUN rm -rf node_modules && npm cache clear --force

ENV CHROME_BIN=/usr/bin/chromium-browser
ENV CHROME_PATH=/usr/lib/chromium/

RUN npm install
RUN npm run testProd && npm run buildProd

karma.conf-prod.js

const path = require('path');
module.exports = function(config) {
    config.set({
        basePath: '',
        browsers: ['ChromeHeadlessNoSandbox'],
    customLaunchers: {
        ChromeHeadlessNoSandbox: {
            base: 'ChromeHeadless',
            flags: [
                '--no-sandbox',
                '--user-data-dir=/tmp/chrome-test-profile',
                '--disable-web-security'
            ]
        }
    },
        frameworks: ['mocha', 'chai'],
        captureConsole: true,
        files: [
            'node_modules/babel-polyfill/dist/polyfill.js',
            'test/root.js'
        ],
        preprocessors: {
            'src/index.js': ['webpack', 'sourcemap'],
            'test/root.js': ['webpack']
        },
        webpack: {
            devtool: 'inline-source-map',
            module: {
                loaders: [
                    {
                        test: /\.js$/,
                        loader: 'babel-loader',
                        exclude: path.resolve(__dirname, 'node_modules'),
                        query: {
                            plugins: ['transform-decorators-legacy', 'transform-regenerator'],
                            presets: ['env', 'stage-1', 'react']
                        }
                    },
                    {
                        test: /\.json$/,
                        loader: 'json-loader',
                    },
                ]
            },
            externals: {
                'react/addons': true,
                'react/lib/ExecutionEnvironment': true,
                'react/lib/ReactContext': true
            }
        },
        webpackServer: {
            noInfo: true
        },
        reporters: ['spec'],
        port: 9222,
        logLevel: config.LOG_INFO
    });
};

I even tried with logLevel: config.LOG_DEBUG but did not show anything missing or unusual.

Body:
package.json

"karma": "~1.7.1",
"karma-chrome-launcher": "~2.2.0",

karma.conf.js

browsers: ['ChromeHeadlessNoSandbox'],
customLaunchers: {
    ChromeHeadlessNoSandbox: {
        base: 'ChromeHeadless',
        flags: ['--no-sandbox']
    }
},

and need to use the below command with --source-map=false

"qa-test": "ng test --watch=false --progress=false --browsers=ChromeHeadless --code-coverage --source-map=false"

my build got succeeded after this change.


问:
linker error when overriding operator<< in visual C++
I have a template class "LinkedList", and what I'd like to do is override the << operator, to print the contents of the list.

So I have a header file like so:

```<code>#pragma once
#include <cstdlib>
#include <iostream>
#include "Node.h"

using namespace std;

template <class T> class LinkedList
{
    public:
        LinkedList<T>() { this->head = nullptr; listSize = 0; };
        ~LinkedList();
        friend ostream& operator<< (ostream& outputStream, LinkedList<T>& list);

        //we don't check if you're putting in a duplicate to keep the insert at O(1)
        //you're on your own if you do that
        void insert(T* item);

        //O(n) worst case, O(1) best case, we move queried items to the front, to get more best cases
        T* find(T item); //returns nullptr if not found
        T* find(int key);

        T* first();

        //complexity same as find
        bool remove(int key);
        bool remove(T item);

        int length() { return listSize; }

    private:
        Node<T>* head;
        Node<T>* findItemNeighbors(int item, Node<T>* prev, Node<T>* next);
        unsigned int listSize;

};
</code>```

And I have a class file, with the various implementations, and this guy:

```<code>ostream& operator<<(ostream& outputStream, LinkedList<T>& list)
{
    Node<T>* current = list.head;
    while (current != nullptr)
    {
        outputStream << *(current->item) << " -> ";
        current = current->next;
    }
    return outputStream;
}
</code>```

Now, problem is, when I try to compile. I'm getting a linker error, but only when I try to use the operator in main, like so:

```<code>LinkedList<Employee>* list = new LinkedList<Employee>();
Employee* test4 = new Employee("Alex", "Herbert", 1101);
list->insert(test4);
cout << *list << "\n";
</code>```

And the linker error, in all its glorious clarity is:

What am I missing here? Everything otherwise compiles fine, until I try to use the << operator on that type.

答:
EDIT: Everything I had written here is wrong.

The trick is how to deal with template friend functions, and how the compiler interprets them.
https://isocpp.org/wiki/faq/templates#template-friends

TL;DR is that the compiler (okay I got some bones to pick with C++ compiler authors) assumes that the friend function is the regular type, not the template type.

So, for friend functions, this cute little guy goes in your function signature "<>"

Like so:

```<code>friend ostream& operator<< <> (std::ostream& outputStream, const LinkedList<T>& list);
</code>```

Now the compiler looks for the properly typed function and it doesn't complain it can't find anything.

Body:
I have a template class "LinkedList", and what I'd like to do is override the << operator, to print the contents of the list.

So I have a header file like so:

#pragma once
#include <cstdlib>
#include <iostream>
#include "Node.h"

using namespace std;

template <class T> class LinkedList
{
    public:
        LinkedList<T>() { this->head = nullptr; listSize = 0; };
        ~LinkedList();
        friend ostream& operator<< (ostream& outputStream, LinkedList<T>& list);

        //we don't check if you're putting in a duplicate to keep the insert at O(1)
        //you're on your own if you do that
        void insert(T* item);

        //O(n) worst case, O(1) best case, we move queried items to the front, to get more best cases
        T* find(T item); //returns nullptr if not found
        T* find(int key);

        T* first();

        //complexity same as find
        bool remove(int key);
        bool remove(T item);

        int length() { return listSize; }

    private:
        Node<T>* head;
        Node<T>* findItemNeighbors(int item, Node<T>* prev, Node<T>* next);
        unsigned int listSize;

};

And I have a class file, with the various implementations, and this guy:

ostream& operator<<(ostream& outputStream, LinkedList<T>& list)
{
    Node<T>* current = list.head;
    while (current != nullptr)
    {
        outputStream << *(current->item) << " -> ";
        current = current->next;
    }
    return outputStream;
}

Now, problem is, when I try to compile. I'm getting a linker error, but only when I try to use the operator in main, like so:

LinkedList<Employee>* list = new LinkedList<Employee>();
Employee* test4 = new Employee("Alex", "Herbert", 1101);
list->insert(test4);
cout << *list << "\n";

And the linker error, in all its glorious clarity is:

What am I missing here? Everything otherwise compiles fine, until I try to use the << operator on that type.

Body:
EDIT: Everything I had written here is wrong.

The trick is how to deal with template friend functions, and how the compiler interprets them.
https://isocpp.org/wiki/faq/templates#template-friends

TL;DR is that the compiler (okay I got some bones to pick with C++ compiler authors) assumes that the friend function is the regular type, not the template type.

So, for friend functions, this cute little guy goes in your function signature "<>"

Like so:

friend ostream& operator<< <> (std::ostream& outputStream, const LinkedList<T>& list);

Now the compiler looks for the properly typed function and it doesn't complain it can't find anything.


问:
Failed to start Neo4j service
I am using neo4j enterprise 3.0.3 version for windows. Following the operations manual 3.0, I have installed the neo4j service with bin\neo4j install-service. But I can't start it with bin\neo4j start. It said

Invoke-Neo4j : Failed to start service 'Neo4j Graph Database - neo4j (neo4j)'.

And I can't start the neo4j service in windows serice either. Maybe anyone have encountered this case before?

答:
```<code>neo4j console
</code>```

Posting for latest versions > 4.x

I had the same issue using neo4j start, Neo4j console is the right command I was looking for. It is a web-based graph that acts as an interactive tutorial.

Title: Failed to start Neo4j service

Body:
neo4j console

Posting for latest versions > 4.x

I had the same issue using neo4j start, Neo4j console is the right command I was looking for. It is a web-based graph that acts as an interactive tutorial.


答:
did you register an app registration in azure ad, create a secret, set the proper api permissions?
there are even quickstarts in the app registration portal that helps you configure the code and give you a pre set up project that you can experiment with.

Also your code seems to be missing scopes, you need to request the appropriate scopes for graph api token to access groups.

I think the documentation here is better: https://github.com/microsoftgraph/msgraph-sdk-dotnet-auth

and if you check the unit tests here for authorization code flow: https://github.com/microsoftgraph/msgraph-sdk-dotnet-auth/blob/dev/tests/Microsoft.Graph.Auth.Test/ConfidentialClient/AuthorizationCodeProviderTests.cs

gives you a good example of how to make it work.

Title: Using GraphServiceClient to retrieve group info of Azure Ad members

Body:
i want to retrieve all members of a Azure Ad group within my backend application. I followed the steps here and here and here is my code:

But I always get this error when using the method:
  Microsoft.Graph.ServiceException: Code: generalException Message: An
  error occurred sending the request.

---> Microsoft.Graph.Auth.AuthenticationException: Code:
  authenticationChallengeRequired Message: Authentication challange is
  required.

Can someone help me with that? I didn't find this specific error.


问:
slot filling triggers different intent in dialogflow
I have two intents pizzaSelected and burgerSelected in both intents I am asking for required parameters

I have below entities

```<code>@pizza [pepperoni, farmhouse, country special, cheese]
@pizzaSize [small, medium, large]
@burger [veg, beef, ham]
@burgerToppings [onion, tomato, lettuce, pepper]
</code>```

expected conversation

```<code>user: order 2 burgers
bot: which burger?
user: cheese
bot: sorry but we have veg, beef and ham burgers. please select one from this.
user: veg
bot: toppings?
user: tomato and lettuce
bot: you order for 2 veg burgers with tomato and lettuce toppings is placed.
</code>```

actual conversation

```<code>user: order 2 burgers
bot: which burger?
user: cheese
bot: what size of pizza you want
</code>```

as in actual conv when user says cheese which belongs to @pizza entity then it triggers the pizzaSelected intent instead of re-prompting the user for entering correct value.

Is there a way to handle this.

答:
If you are not using custom fulfilment based logic for slot filing then your burger_type entity (or whichever name you might have used for entity) must have cheese as a valid value.

I would recommend to go to entities and check the values of entity which you are using to store type of burger. Even if you have only the correct values there try reordering them and then save. This will force the bot to retrain as this is a machine learning model sometimes it might get optimized for the wrong output, if that is the case for you then try retraining it.

Body:
I have two intents pizzaSelected and burgerSelected in both intents I am asking for required parameters

I have below entities

@pizza [pepperoni, farmhouse, country special, cheese]
@pizzaSize [small, medium, large]
@burger [veg, beef, ham]
@burgerToppings [onion, tomato, lettuce, pepper]

expected conversation

user: order 2 burgers
bot: which burger?
user: cheese
bot: sorry but we have veg, beef and ham burgers. please select one from this.
user: veg
bot: toppings?
user: tomato and lettuce
bot: you order for 2 veg burgers with tomato and lettuce toppings is placed.

actual conversation

user: order 2 burgers
bot: which burger?
user: cheese
bot: what size of pizza you want

as in actual conv when user says cheese which belongs to @pizza entity then it triggers the pizzaSelected intent instead of re-prompting the user for entering correct value.

Is there a way to handle this.


问:
Raw Query In Vapor 4

In Vapor 3 I was able to get a newConnection to the database and call a raw sql query using this:

```<code>return request.withNewConnection(to: .mysql) { (con) -> EventLoopFuture<T> in
    return con.raw(sql)...
}
</code>```

Now that I'm migrating my code to Vapor 4 the function raw or withNewConnection is gone, what can I use to make a raw query.

Steps to reproduce

```<code>return request.withNewConnection(to: .mysql) { (con) -> EventLoopFuture<T> in
...
}
</code>```

Error:
Cannot infer contextual base in reference to member 'mysql'
Value of type 'Request' has no member 'withNewConnection'

Expected behavior

Have a function inside request.db that let me get a new connection or run a raw query.

Environment

Vapor Framework version: 4.7.1

Vapor Toolbox version: vapor-beta

OS version: macOS Catalina

答:
Try this:

    import SQLKit
    struct Row:Content
    {
        // fields go here
    }
    struct Context:Decodable
    {
        let rows:[Row]
    }
    func rawDemo(_ request:Request) throws -> EventLoopFuture<View>
    {
        return (request.db as! SQLDatabase).raw("SELECT * FROM MyTable").all(decoding:Row.self).flatMap
        {
            results in
            let context = Context(rows:results)
            return request.view.render("rawDemo", context)
        }
    }
```

You must import the SQLKit module and cast request.db to SQLDatabase as shown in order to execute raw queries. Once you've done that, it becomes much like the Vapor 3 method. However, with the new functionality available in Vapor 4, I have now managed to get rid of all my raw queries and replace with sleek Fluent ones!

Title: Raw Query In Vapor 4

Body:
In Vapor 3 I was able to get a newConnection to the database and call a raw sql query using this:

return request.withNewConnection(to: .mysql) { (con) -> EventLoopFuture<T> in
    return con.raw(sql)...
}

Now that I'm migrating my code to Vapor 4 the function raw or withNewConnection is gone, what can I use to make a raw query.

Steps to reproduce

return request.withNewConnection(to: .mysql) { (con) -> EventLoopFuture<T> in
...
}

Error:
Cannot infer contextual base in reference to member 'mysql'
Value of type 'Request' has no member 'withNewConnection'

Expected behavior

Have a function inside request.db that let me get a new connection or run a raw query.

Environment

Vapor Framework version: 4.7.1

Vapor Toolbox version: vapor-beta

OS version: macOS Catalina

Body:
Try this:

    import SQLKit
    struct Row:Content
    {
        // fields go here
    }
    struct Context:Decodable
    {
        let rows:[Row]
    }
    func rawDemo(_ request:Request) throws -> EventLoopFuture<View>
    {
        return (request.db as! SQLDatabase).raw("SELECT * FROM MyTable").all(decoding:Row.self).flatMap
        {
            results in
            let context = Context(rows:results)
            return request.view.render("rawDemo", context)
        }
    }

You must import the SQLKit module and cast request.db to SQLDatabase as shown in order to execute raw queries. Once you've done that, it becomes much like the Vapor 3 method. However, with the new functionality available in Vapor 4, I have now managed to get rid of all my raw queries and replace with sleek Fluent ones!


问:
Spark dataframe convert all the columns into json format and then modify json structure
Converted my dataframe into json using df.toJSON

After json conversion the schema looks like this :

```<code>root
 |-- value: string (nullable = true)
</code>```

Whats the best way to make the current schema(i.e., all root level attributes; in this case the 'value' column) nested into a new root level json key ( called 'data' ) and add new attributes at root level. How to achieve this in scala.

答:
Please check below code.</p>

```<code>scala> df.toJSON.select(struct($"value").as("data")).printSchema
root
 |-- data: struct (nullable = false)
 |    |-- value: string (nullable = true)

</code>```

Body:
Converted my dataframe into json using df.toJSON

After json conversion the schema looks like this :

root
 |-- value: string (nullable = true)

Whats the best way to make the current schema(i.e., all root level attributes; in this case the 'value' column) nested into a new root level json key ( called 'data' ) and add new attributes at root level. How to achieve this in scala.

Body:
Please check below code.

scala> df.toJSON.select(struct($"value").as("data")).printSchema
root
 |-- data: struct (nullable = false)
 |    |-- value: string (nullable = true)


问:
Find the Last Cell Value of the 2nd Column Set for each 1st Column Cell in EXCEL
I have the following structured table in excel where 1000s of rows included.

I want to return the Last Cell Value of Column B for Each value in Column A.

For example:

For Cell A1 -> I want to return the Cell B5.

For Cell A6 -> I want to return the Cell B9.

I have tried with VLOOKUP, HLOOKUP, INDEX likewise so many formulas where I ended with more conflict situations. Can anyone please write down a Formula to give my requirement a life?

答: if you don't mind using column C as a helper column you could use something like that:


问:
How to interpret TFLite output tensor
I am executing a TFLite model on python in order to make predictions based on input data. The model has been trained on AutoML-Google-API, then I downloaded its TFLite model. I used tf.lite.Interpreter to load the model and run an inference as follows

```<code>input_details = interpreter.get_input_details();print(input_details )
output_details = interpreter.get_output_details();print(output_details )
//...preparing input_data
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index']);print(output_data )
</code>```

The results are as follows:

```<code>input_details:
[{'name': 'image',
  'index': 0,
  'shape': array([  1, 224, 224,   3]),
  'dtype': numpy.uint8,
  'quantization': (0.007874015718698502, 128)}]
output_details:
[{'name': 'scores',
  'index': 173,
  'shape': array([ 1, 10]),
  'dtype': numpy.uint8,
  'quantization': (0.00390625, 0)}]
output_data :
array([[ 34, 100,  67,  14,  15,  24,  21,  18,  25,  37]], dtype=uint8)
</code>```

The output_data has some integer numbers, is it true to say that "the index of its largest number corresponds to the predicted label", and how can I convert those numbers to probability?

答:
You could use softmax to convert the numbers into probability distribution and argmax to get the index of the label with the largest probability.

So something like this:

```<code>output_probs = tf.math.softmax(output_data)
pred_label = tf.math.argmax(output_probs)
</code>```

Title: How to interpret TFLite output tensor

Body:
I am executing a TFLite model on python in order to make predictions based on input data. The model has been trained on AutoML-Google-API, then I downloaded its TFLite model. I used tf.lite.Interpreter to load the model and run an inference as follows

input_details = interpreter.get_input_details();print(input_details )
output_details = interpreter.get_output_details();print(output_details )
//...preparing input_data
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index']);print(output_data )

The results are as follows:

input_details:
[{'name': 'image',
  'index': 0,
  'shape': array([  1, 224, 224,   3]),
  'dtype': numpy.uint8,
  'quantization': (0.007874015718698502, 128)}]
output_details:
[{'name': 'scores',
  'index': 173,
  'shape': array([ 1, 10]),
  'dtype': numpy.uint8,
  'quantization': (0.00390625, 0)}]
output_data :
array([[ 34, 100,  67,  14,  15,  24,  21,  18,  25,  37]], dtype=uint8)

The output_data has some integer numbers, is it true to say that "the index of its largest number corresponds to the predicted label", and how can I convert those numbers to probability?

Body:
You could use softmax to convert the numbers into probability distribution and argmax to get the index of the label with the largest probability.

So something like this:

output_probs = tf.math.softmax(output_data)
pred_label = tf.math.argmax(output_probs)


问:
Embedding key as string in Paramiko application
I'm trying to create a single file executable in Python and using Paramiko for my SSH. I need to eliminate external files such as private key files and try to go for embedded strings.

I tried this solution but it's not working for me:

Paramiko: Creating a PKey from a public key string

How do I accomplish this? Thanks.

答:
To add a public key from a string on the ssh client you must set the keyword arg look_for_keys=False then use the MissingHostKeyPolicy classes missing_host_key() method to add the key from your string. </p>

```<code>my_pub_key = "xx.xx.xx.xx ecdsa-sha2-nistp256 mlzdHAyNT....."
my_host = my_pub_key.split(' ')[0]
password = 'myFavortitePassword'
username = 'myUsername'

ssh_client=paramiko.SSHClient()

host_key_policy = paramiko.MissingHostKeyPolicy()
host_key_policy.missing_host_key(ssh_client, my_host, my_pub_key)

ssh_client.connect(hostname= my_host
                            ,username=username
                            ,password=password
                            ,port=22
                            ,look_for_keys=False)
</code>```

Body:
To add a public key from a string on the ssh client you must set the keyword arg look_for_keys=False then use the MissingHostKeyPolicy classes missing_host_key() method to add the key from your string.

my_pub_key = "xx.xx.xx.xx ecdsa-sha2-nistp256 mlzdHAyNT....."
my_host = my_pub_key.split(' ')[0]
password = 'myFavortitePassword'
username = 'myUsername'

ssh_client=paramiko.SSHClient()

host_key_policy = paramiko.MissingHostKeyPolicy()
host_key_policy.missing_host_key(ssh_client, my_host, my_pub_key)

ssh_client.connect(hostname= my_host
                            ,username=username
                            ,password=password
                            ,port=22
                            ,look_for_keys=False)