问:
mat-chip not rendering according to initial FormControl value
I need to render mat-chips using formControl's value, and also render multi-select option. I used material modules for the same. It doesn't display the initial value of the formControl

HTML:

```<code><mat-form-field>
  <mat-label>Toppings</mat-label>
  <mat-select [formControl]="toppingsControl" multiple>

    <mat-select-trigger>
      <mat-chip-list>
        <mat-chip *ngFor="let topping of toppingsControl?.value"
          [removable]="true" (removed)="onToppingRemoved(topping)">
          {{ topping?.name }}
          <mat-icon matChipRemove>cancel</mat-icon>
        </mat-chip>
      </mat-chip-list>
    </mat-select-trigger>

    <mat-option *ngFor="let topping of toppingList$ | async" [value]="topping">{{topping.name}}</mat-option>

  </mat-select>
</mat-form-field>

<br/>
{{ toppingsControl?.value | json }}
</code>```

Ts file:

```<code>export class SelectMultipleExample {
  private test = new Subject<{ id: number; name: string }[]>();
  toppingList$ = this.test.asObservable();

  // Initialize formCOntrol value
  toppingsControl = new FormControl([{ id: 1, name: "Extra cheese" }]);

  constructor() {
    setTimeout(() => {
      this.test.next([
        { id: 1, name: "Extra cheese" },
        { id: 2, name: "Mushroom" }
      ]);
    }, 5000);
  }

  onToppingRemoved(topping: string) {
    const toppings = this.toppingsControl.value as string[];
    this.removeFirst(toppings, topping);
    this.toppingsControl.setValue(toppings); // To trigger change detection
  }

  private removeFirst<T>(array: T[], toRemove: T): void {
    const index = array.indexOf(toRemove);
    if (index !== -1) {
      array.splice(index, 1);
    }
  }
}

</code>```

Click to see what is rendered on screen:

答:
I think it's because you are using 2 instances of { id: 1, name: "Extra cheese" }.

So you have to way to do what you want :

you use the same instance of your object, something like this :

myExtraCheeseObject = { id: 1, name: "Extra cheese" };

 // Initialize formControl value
  toppingsControl = new FormControl([myExtraCheeseObject]);

  constructor() {
    setTimeout(() => {
      this.test.next([
        myExtraCheeseObject,
        { id: 2, name: "Mushroom" }
      ]);
    }, 5000);
  }```
</div>
</div>
</p>

<ul>
<li>you use <code>compareWith</code> (https://material.angular.io/components/select/api) </li>
</ul>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// just compare ids
compareObjects(o1: any, o2: any) {
  return o1.id == o2.id
}

// compare id and name
compareObjects(o1: any, o2: any) {
  return o1.id == o2.id && o1.name == o2.name
}</code>```

 <mat-select [formControl]="toppingsControl"
     [compareWith]="compareObjects"
     multiple>
 </mat-select>```

(another tip : you should avoid use setTimeout and code in the constructor, use ngOnInit instead)

Body:
I need to render mat-chips using formControl's value, and also render multi-select option. I used material modules for the same. It doesn't display the initial value of the formControl

HTML:

<mat-form-field>
  <mat-label>Toppings</mat-label>
  <mat-select [formControl]="toppingsControl" multiple>

    <mat-select-trigger>
      <mat-chip-list>
        <mat-chip *ngFor="let topping of toppingsControl?.value"
          [removable]="true" (removed)="onToppingRemoved(topping)">
          {{ topping?.name }}
          <mat-icon matChipRemove>cancel</mat-icon>
        </mat-chip>
      </mat-chip-list>
    </mat-select-trigger>

    <mat-option *ngFor="let topping of toppingList$ | async" [value]="topping">{{topping.name}}</mat-option>

  </mat-select>
</mat-form-field>

{{ toppingsControl?.value | json }}

Ts file:

export class SelectMultipleExample {
  private test = new Subject<{ id: number; name: string }[]>();
  toppingList$ = this.test.asObservable();

  // Initialize formCOntrol value
  toppingsControl = new FormControl([{ id: 1, name: "Extra cheese" }]);

  constructor() {
    setTimeout(() => {
      this.test.next([
        { id: 1, name: "Extra cheese" },
        { id: 2, name: "Mushroom" }
      ]);
    }, 5000);
  }

  onToppingRemoved(topping: string) {
    const toppings = this.toppingsControl.value as string[];
    this.removeFirst(toppings, topping);
    this.toppingsControl.setValue(toppings); // To trigger change detection
  }

  private removeFirst<T>(array: T[], toRemove: T): void {
    const index = array.indexOf(toRemove);
    if (index !== -1) {
      array.splice(index, 1);
    }
  }
}

Click to see what is rendered on screen:

Body:
I think it's because you are using 2 instances of { id: 1, name: "Extra cheese" }.

So you have to way to do what you want :

you use the same instance of your object, something like this :

myExtraCheeseObject = { id: 1, name: "Extra cheese" };

 // Initialize formControl value
  toppingsControl = new FormControl([myExtraCheeseObject]);

  constructor() {
    setTimeout(() => {
      this.test.next([
        myExtraCheeseObject,
        { id: 2, name: "Mushroom" }
      ]);
    }, 5000);
  }

you use compareWith (https://material.angular.io/components/select/api)

// just compare ids
compareObjects(o1: any, o2: any) {
  return o1.id == o2.id
}

// compare id and name
compareObjects(o1: any, o2: any) {
  return o1.id == o2.id && o1.name == o2.name
}

 <mat-select [formControl]="toppingsControl"
     [compareWith]="compareObjects"
     multiple>
 </mat-select>

(another tip : you should avoid use setTimeout and code in the constructor, use ngOnInit instead)


来源: stackexchange

问:
Achieving simple tasks with vue (Laravel)
Ive recently started learning vue.js (Coming from angular 2+), Ive watched a few tutorials and it all seemed to go swimmingly.

As always after ive finished doing the tutorials, I create a little app for myself just to ensure I know what im doing. But I seem to be really stuggling with Vue.

So far the app is very simple. A user posts a story, The story has comments.... simple as that

I got to the point where I wanted the user to be able to edit there comment, But It seems I cannot work out how to do this. I would like it so that when the user clicks the edit button the comment changes to a textarea or an input of some kind.

At this point I have not used to vue in the project at all. All the pages are rendered with blade.

Im trying to get my head round how you are meant to use it? So I have the following questions

Are you meant to use multiple vue components, Loop in blade and create a  on each iteration?

```<code><div id="app">
    @foreach($comments as $comment)
        <comment {Stuff passed in}></comment>
    @endforeach
</div>
</code>```

Are you meant to have that one vue "app" that gets the data from the api and loop them within the vue component?

```<code>    const comments = new Vue({
        el: '#comments#'
    })
</code>```

As all the site is a multipage application (Dont want to go down the SPA route) and lets say I now have a products page, The product has a list of attributes (Pretty much the same as comments). Do I create another vue app?

```<code>const comments = new Vue({
    el: '#comments',
});

const productThings = new Vue({
    el: '#productThings'
})
</code>```

If I want to sections on a page controlled by vue (Lets say the comment section and another interactive section) Would this have to be 2 vue "apps" like in the above code example, One that is "comments" and one that is "somethingelse" or would the whole page have to be one big vue component.

```<code>// Comment loop, How ever this gets handled with vue
// Some other content
// Another place I need it to be interactive````
```

This seems very complicated just to acheive simple tasks, Also seems as if it would get out of control very quickly (I could only imagine coming back to this after 6 months and trying to work out what was going on).

You can see how confused I am with it all, The more I read the more confused I seem to get.

答:
No, typically you'd use a Vue component to iterate and render out each comment (possibly as sub-components).

You can fetch the data from an API, or render it into your blade template for Vue to use (saves on an API call and having to set up an API endpoint if you don't already have one).

If you're using the Vue scaffolding that Laravel provides, then a Vue instance is initialised on any page where the app.js bundle is loaded and attached to an element with the ID app, if there is one. Inside this element Vue will parse any template directives and render any components that have been registered. So you could register additional components (e.g. ProductThings) to put into different blade templates.

As I mentioned above, Laravel creates a single Vue instance. There's nothing that stops you rendering out static content via blade into the app container, which Vue will leave as-is, between components which contain independant functionality.

ContentLicense: CC BY-SA 4.0

Body:
Ive recently started learning vue.js (Coming from angular 2+), Ive watched a few tutorials and it all seemed to go swimmingly.

As always after ive finished doing the tutorials, I create a little app for myself just to ensure I know what im doing. But I seem to be really stuggling with Vue.

So far the app is very simple. A user posts a story, The story has comments.... simple as that

I got to the point where I wanted the user to be able to edit there comment, But It seems I cannot work out how to do this. I would like it so that when the user clicks the edit button the comment changes to a textarea or an input of some kind.

At this point I have not used to vue in the project at all. All the pages are rendered with blade.

Im trying to get my head round how you are meant to use it? So I have the following questions

Are you meant to use multiple vue components, Loop in blade and create a  on each iteration?

    @foreach($comments as $comment)
        <comment {Stuff passed in}></comment>
    @endforeach

Are you meant to have that one vue "app" that gets the data from the api and loop them within the vue component?

    const comments = new Vue({
        el: '#comments#'
    })

As all the site is a multipage application (Dont want to go down the SPA route) and lets say I now have a products page, The product has a list of attributes (Pretty much the same as comments). Do I create another vue app?

const comments = new Vue({
    el: '#comments',
});

const productThings = new Vue({
    el: '#productThings'
})

If I want to sections on a page controlled by vue (Lets say the comment section and another interactive section) Would this have to be 2 vue "apps" like in the above code example, One that is "comments" and one that is "somethingelse" or would the whole page have to be one big vue component.

// Comment loop, How ever this gets handled with vue
// Some other content
// Another place I need it to be interactive````

This seems very complicated just to acheive simple tasks, Also seems as if it would get out of control very quickly (I could only imagine coming back to this after 6 months and trying to work out what was going on).

You can see how confused I am with it all, The more I read the more confused I seem to get.


问:
FileNotFoundException but File present at right path
I'm new to programming, every time I try to read a file. I get FileNOtFoundException.

Where could I be going wrong?

```<code>import java.io.*;
import java.util.Scanner;

public class ReadFile
{
    public ReadFile()
    {
        readFile();
    }
    public void readFile()
    {
        String filename = "trees.txt";
        System.out.println(new File(".").getAbsolutePath()); //file is at this path.
        String name = "";
        try
        {
            FileReader inputFile = new FileReader(filename);
            Scanner parser = new Scanner(inputFile);
            while (parser.hasNextLine())
            {
                name = parser.nextLine();
                System.out.println(name);
            }
            inputFile.close();
        }
        catch (FileNotFoundException exception)
        {
            System.out.println(filename + " not found");
        }
    }
}
</code>```

Is there any other way I could read the file?

答:
this code

FileReader inputFile = new FileReader(filename);
```

<p>You must define full path to file with name <code>filename</code> if not it will open file not at current working directory
you should try</p>

<pre class="lang-java prettyprint-override"><code>FileReader inputFile = new FileReader(new File(new File("."), filename));
// defind new File(".") it mean you will you open file in current working directory
</code>```

you can read more at: Java, reading a file from current directory?

Body:
I'm new to programming, every time I try to read a file. I get FileNOtFoundException.

Where could I be going wrong?

import java.io.*;
import java.util.Scanner;

public class ReadFile
{
    public ReadFile()
    {
        readFile();
    }
    public void readFile()
    {
        String filename = "trees.txt";
        System.out.println(new File(".").getAbsolutePath()); //file is at this path.
        String name = "";
        try
        {
            FileReader inputFile = new FileReader(filename);
            Scanner parser = new Scanner(inputFile);
            while (parser.hasNextLine())
            {
                name = parser.nextLine();
                System.out.println(name);
            }
            inputFile.close();
        }
        catch (FileNotFoundException exception)
        {
            System.out.println(filename + " not found");
        }
    }
}

Is there any other way I could read the file?

Body:
this code

FileReader inputFile = new FileReader(filename);

You must define full path to file with name filename if not it will open file not at current working directory
you should try

FileReader inputFile = new FileReader(new File(new File("."), filename));
// defind new File(".") it mean you will you open file in current working directory

you can read more at: Java, reading a file from current directory?


问:
Using a second passport strategy using the same User model?
I started a node project some time ago using Node, Express, MongoDB and Passport using passport-local-mongoose for user auth using sessions, and my user model looks like this:

```<code>const mongoose = require("mongoose");
const passportLocalMongoose = require("passport-local-mongoose");

var UserSchema = new mongoose.Schema({
  username: String,
  email: String,
  password: String,
  //etc

});

UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
</code>```

Now i want to create a react native app for the same webapp, so I want to use the same DB of users.

My questions is: can I use something like passport-jwt alongside the current user model and auth strategy that I have on the website? Or do you guys recommend me to re-create the complete project using jsonwebtokens for auth only and then trying to import the current users DB?

Thanks!

答:
You can implement a new strategy using same db. create a passport.js file and initiate the strategy type you want to use for that user. From there you can call the same model and check the auth of that user from the same db. You also need to write a comparePassowrd function in model. So you can compare your password for login and session will be maintain for web frontend

```<code>    passport.use('user',new LocalStrategy({
        usernameField: 'email',
        passwordField: 'password'

    }, function (username, password, done) {

        Collection.findOne({username: username}, (err, user) => {

            if (err) {
                return done(err);
            }
            if (!user) {
                return done(null, false, {"user not found"});
            }
            user.comparePassword(password, (err, isMatch) => {
                if (err) {
                    return done(err);
                }
                if (!isMatch) {
                    return done(null, false,  {"wrong password"});
                }
                return done(null, user);
            });
        });
    }
));
</code>```

Add isAuthenticated and isAuthorized Functions in passport.js

```<code>passport.isAuthenticated = (req, res, next) => {
if (req.isAuthenticated()) {
    return next();
}
res.status(401);
return next({"user not authenticated"});
};
passport.isAuthorized = (userType) => {
    return (req, res, next) => {
        if (req.user.userType == userType) {
            return next();
        }
        res.status(403);
        return next({"user not authorized"});
    };
};
</code>```

Here userType is for different level of users for example: admin/ moderator etc

Now in route just call the auth function before moving to the actual function

```<code>app.post('/apiRoute',passport.isAuthenticated, passport.isAuthorized('ADMIN'),controllerFile.actualFunction;
</code>```

Body:
I started a node project some time ago using Node, Express, MongoDB and Passport using passport-local-mongoose for user auth using sessions, and my user model looks like this:

const mongoose = require("mongoose");
const passportLocalMongoose = require("passport-local-mongoose");

var UserSchema = new mongoose.Schema({
  username: String,
  email: String,
  password: String,
  //etc

});

UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);

Now i want to create a react native app for the same webapp, so I want to use the same DB of users.

My questions is: can I use something like passport-jwt alongside the current user model and auth strategy that I have on the website? Or do you guys recommend me to re-create the complete project using jsonwebtokens for auth only and then trying to import the current users DB?

Thanks!

Body:
You can implement a new strategy using same db. create a passport.js file and initiate the strategy type you want to use for that user. From there you can call the same model and check the auth of that user from the same db. You also need to write a comparePassowrd function in model. So you can compare your password for login and session will be maintain for web frontend

    passport.use('user',new LocalStrategy({
        usernameField: 'email',
        passwordField: 'password'

    }, function (username, password, done) {

        Collection.findOne({username: username}, (err, user) => {

            if (err) {
                return done(err);
            }
            if (!user) {
                return done(null, false, {"user not found"});
            }
            user.comparePassword(password, (err, isMatch) => {
                if (err) {
                    return done(err);
                }
                if (!isMatch) {
                    return done(null, false,  {"wrong password"});
                }
                return done(null, user);
            });
        });
    }
));

Add isAuthenticated and isAuthorized Functions in passport.js

passport.isAuthenticated = (req, res, next) => {
if (req.isAuthenticated()) {
    return next();
}
res.status(401);
return next({"user not authenticated"});
};
passport.isAuthorized = (userType) => {
    return (req, res, next) => {
        if (req.user.userType == userType) {
            return next();
        }
        res.status(403);
        return next({"user not authorized"});
    };
};

Here userType is for different level of users for example: admin/ moderator etc

Now in route just call the auth function before moving to the actual function

app.post('/apiRoute',passport.isAuthenticated, passport.isAuthorized('ADMIN'),controllerFile.actualFunction;


问:
Optimize row access and transformation in pyspark
I have a large dataset(5GB) in the form of jason in S3 bucket.
I need to transform the schema of the data, and write back the transformed data to S3 using an ETL script.

So I use a crawler to detect the schema and load the data in pyspark dataframe, and change the schema. Now I iterate over every row in the dataframe and convert it to dictionary. Remove null columns, and then convert the dictionary to string and write back to S3. Following is the code:

```<code>#df is the pyspark dataframe
columns = df.columns
print(columns)
s3 = boto3.resource('s3')
cnt = 1

for row in df.rdd.toLocalIterator():
    data = row.asDict(True)

    for col_name in columns:
        if data[col_name] is None:
            del data[col_name]

    content = json.dumps(data)
    object = s3.Object('write-test-transaction-transformed', str(cnt)).put(Body=content)
    cnt = cnt+1
print(cnt)
</code>```

I have used toLocalIterator.
Is the execution of above code performes serially? if yes then how to optimize it? Is there any better approach for execution of above logic?

答:
assuming, each row in the dataset as json string format

```<code>import pyspark.sql.functions as F

def drop_null_cols(data):
    import json
    content = json.loads(data)
    for key, value in list(content.items()):
        if value is None:
            del content[key]

    return json.dumps(content)

drop_null_cols_udf = F.udf(drop_null_cols, F.StringType())

df = spark.createDataFrame(
    ["{\"name\":\"Ranga\", \"age\":25, \"city\":\"Hyderabad\"}",
     "{\"name\":\"John\", \"age\":null, \"city\":\"New York\"}",
     "{\"name\":null, \"age\":31, \"city\":\"London\"}"],
    "string"
).toDF("data")

df.select(
    drop_null_cols_udf("data").alias("data")
).show(10,False)
</code>```

If the input dataframe is having the cols and output only needs to be not null cols json

```<code>df = spark.createDataFrame(
        [('Ranga', 25, 'Hyderabad'),
         ('John', None, 'New York'),
         (None, 31, 'London'),
        ],
        ['name', 'age', 'city']
    )

df.withColumn(
    "data", F.to_json(F.struct([x for x in df.columns]))
).select(
    drop_null_cols_udf("data").alias("data")
).show(10, False)

#df.write.format("csv").save("s3://path/to/file/) -- save to s3
</code>```

which results

```<code>+-------------------------------------------------+
|data                                             |
+-------------------------------------------------+
|{"name": "Ranga", "age": 25, "city": "Hyderabad"}|
|{"name": "John", "city": "New York"}             |
|{"age": 31, "city": "London"}                    |
+-------------------------------------------------+
</code>```

Body:
I have a large dataset(5GB) in the form of jason in S3 bucket.
I need to transform the schema of the data, and write back the transformed data to S3 using an ETL script.

So I use a crawler to detect the schema and load the data in pyspark dataframe, and change the schema. Now I iterate over every row in the dataframe and convert it to dictionary. Remove null columns, and then convert the dictionary to string and write back to S3. Following is the code:

#df is the pyspark dataframe
columns = df.columns
print(columns)
s3 = boto3.resource('s3')
cnt = 1

for row in df.rdd.toLocalIterator():
    data = row.asDict(True)

    for col_name in columns:
        if data[col_name] is None:
            del data[col_name]

    content = json.dumps(data)
    object = s3.Object('write-test-transaction-transformed', str(cnt)).put(Body=content)
    cnt = cnt+1
print(cnt)

I have used toLocalIterator.
Is the execution of above code performes serially? if yes then how to optimize it? Is there any better approach for execution of above logic?

Body:
assuming, each row in the dataset as json string format

import pyspark.sql.functions as F

def drop_null_cols(data):
    import json
    content = json.loads(data)
    for key, value in list(content.items()):
        if value is None:
            del content[key]

    return json.dumps(content)

drop_null_cols_udf = F.udf(drop_null_cols, F.StringType())

df = spark.createDataFrame(
    ["{\"name\":\"Ranga\", \"age\":25, \"city\":\"Hyderabad\"}",
     "{\"name\":\"John\", \"age\":null, \"city\":\"New York\"}",
     "{\"name\":null, \"age\":31, \"city\":\"London\"}"],
    "string"
).toDF("data")

df.select(
    drop_null_cols_udf("data").alias("data")
).show(10,False)

If the input dataframe is having the cols and output only needs to be not null cols json

df = spark.createDataFrame(
        [('Ranga', 25, 'Hyderabad'),
         ('John', None, 'New York'),
         (None, 31, 'London'),
        ],
        ['name', 'age', 'city']
    )

df.withColumn(
    "data", F.to_json(F.struct([x for x in df.columns]))
).select(
    drop_null_cols_udf("data").alias("data")
).show(10, False)

#df.write.format("csv").save("s3://path/to/file/) -- save to s3

which results

+-------------------------------------------------+
|data                                             |
+-------------------------------------------------+
|{"name": "Ranga", "age": 25, "city": "Hyderabad"}|
|{"name": "John", "city": "New York"}             |
|{"age": 31, "city": "London"}                    |
+-------------------------------------------------+


问:
ReactNative Firestore multiple wheres and comparing result
I am trying to create a function in my app that allows the user to choose two medicaments and in a third screen get the result whether these two have interactions.

For this I have a database with the interactions the chosen medicamentations pass an "ATC" number, called GRP1D or GRP2D in the interaction database. The two ATC numbers passed should be compared with the GRPD numbers in the database in order to return the interaction, or if there is none, "No interaction" should be returned. Idealy I would use multiple where clauses combined with an OR clause to make the sequence of the passed ATC numbers irrelevant.

I have tried a lot of things but in the end I am not even sure this is possible with firestore. Here is the relevant part of the database

Below is the code that I would like for it to work, obviously it doesn't because there doesn't seem to be an OR or even multiple where clauses in firestore. Any Idea how this could be solved? Thanks a lot in advance!

```<code>render() {
   console.log(this.state.atc1);
    console.log(this.state.atc2);
    var atc1 = this.state.atc1
    var atc2 = this.state.atc2
    var interactiondescription
    dbh.collection('IX')
      .where('GRP1D', '==', atc1)
      .where('GRP2D', '==', atc2)
      or
      .where('GRP1D', '==', atc2)
      .where('GRP2D', '==', atc1)
      .get()
      .then(querySnapshot => {
        querySnapshot.forEach(doc => {

         interactiondescription = doc.data().MEASD
        console.log('this', interactiondesctription)
        })
      });

    //console.log('Desc:', this.interactiondescription)

</code>```

答:
As you've already found, Cloud Firestore doesn't support OR type conditions. That means that you'll need to run a separate query for each of these ORs, which luckily isn't too bad in your case:

```<code>let query1 = dbh.collection('IX')
  .where('GRP1D', '==', atc1)
  .where('GRP2D', '==', atc2);
let query2 = dbh.collection('IX')
  .where('GRP1D', '==', atc2)
  .where('GRP2D', '==', atc1);
Promise.all([query1.get(), query2.get()])
  .then((querySnapshots) => {
    console.log('Queries executed: ', querySnapshots);
    let querySnapshot = !querySnapshots[0].empty() ? querySnapshots[0] : querySnapshots[1];
    querySnapshot.forEach(doc => {
      interactiondescription = doc.data().MEASD
      console.log(interactiondesctription)
    })
  });
</code>```

This executes two queries and when both are done, it takes the one that has results and loops over that.

If the ordering of your GRP1D and GRP2D doesn't matter, you could also consider having an single array field GRPDs in your documents with both/all GRPD values:

```<code>GRPDs: ["atc2", "atc1"]
</code>```

With such a field you could use a single array-contains-any query to get the documents for up to 10 values:

```<code>dbh.collection('IX').where('GRPDs', 'array-contains-any', [atc1, atc2]);
</code>```

Body:
I am trying to create a function in my app that allows the user to choose two medicaments and in a third screen get the result whether these two have interactions.

For this I have a database with the interactions the chosen medicamentations pass an "ATC" number, called GRP1D or GRP2D in the interaction database. The two ATC numbers passed should be compared with the GRPD numbers in the database in order to return the interaction, or if there is none, "No interaction" should be returned. Idealy I would use multiple where clauses combined with an OR clause to make the sequence of the passed ATC numbers irrelevant.

I have tried a lot of things but in the end I am not even sure this is possible with firestore. Here is the relevant part of the database

Below is the code that I would like for it to work, obviously it doesn't because there doesn't seem to be an OR or even multiple where clauses in firestore. Any Idea how this could be solved? Thanks a lot in advance!

render() {
   console.log(this.state.atc1);
    console.log(this.state.atc2);
    var atc1 = this.state.atc1
    var atc2 = this.state.atc2
    var interactiondescription
    dbh.collection('IX')
      .where('GRP1D', '==', atc1)
      .where('GRP2D', '==', atc2)
      or
      .where('GRP1D', '==', atc2)
      .where('GRP2D', '==', atc1)
      .get()
      .then(querySnapshot => {
        querySnapshot.forEach(doc => {

         interactiondescription = doc.data().MEASD
        console.log('this', interactiondesctription)
        })
      });

    //console.log('Desc:', this.interactiondescription)

Body:
As you've already found, Cloud Firestore doesn't support OR type conditions. That means that you'll need to run a separate query for each of these ORs, which luckily isn't too bad in your case:

let query1 = dbh.collection('IX')
  .where('GRP1D', '==', atc1)
  .where('GRP2D', '==', atc2);
let query2 = dbh.collection('IX')
  .where('GRP1D', '==', atc2)
  .where('GRP2D', '==', atc1);
Promise.all([query1.get(), query2.get()])
  .then((querySnapshots) => {
    console.log('Queries executed: ', querySnapshots);
    let querySnapshot = !querySnapshots[0].empty() ? querySnapshots[0] : querySnapshots[1];
    querySnapshot.forEach(doc => {
      interactiondescription = doc.data().MEASD
      console.log(interactiondesctription)
    })
  });

This executes two queries and when both are done, it takes the one that has results and loops over that.

If the ordering of your GRP1D and GRP2D doesn't matter, you could also consider having an single array field GRPDs in your documents with both/all GRPD values:

GRPDs: ["atc2", "atc1"]

With such a field you could use a single array-contains-any query to get the documents for up to 10 values:

dbh.collection('IX').where('GRPDs', 'array-contains-any', [atc1, atc2]);


问:
Test case for Action ngrx 4
i am new in ngrx, we have angular proj which is usig ngrx storing/state the data. and now i have to write a test case for the all action, reducer and other code. but i am stuck in writing test cases for the actions. looked in google but no help found.

```<code>export enum ProjAction {
   INSERT_RECORD = "[ProjAction] Insert a record."
}

export class ProjActionCreator(private store: Store<ProjState>) {
   insertRecord(data: any) {
        this.store.dispatch(<Action>{
           type: ProjAction.INSERT_RECORD,
           payload: data
        })
   }
</code>```

}

i tried to make a spy object and dispatch but it won't help for me.
any help will appreciated.

答:
For this you need simply to assert that this.store.dispatch has been called with desired arguments.

it('test', () => {
  // preparation
  const store = TestBed.get(Store);
  spyOn(store, 'dispatch');

  // action
  component.insertRecord({test: '123'});

  // assertion
  expect(store.dispatch).toHaveBeenCalledWith({
    type: ProjAction.INSERT_RECORD,
    payload: {
      test: '123',
    },
  });
});
```

Title: Test case for Action ngrx 4

Body:
i am new in ngrx, we have angular proj which is usig ngrx storing/state the data. and now i have to write a test case for the all action, reducer and other code. but i am stuck in writing test cases for the actions. looked in google but no help found.

export enum ProjAction {
   INSERT_RECORD = "[ProjAction] Insert a record."
}

export class ProjActionCreator(private store: Store<ProjState>) {
   insertRecord(data: any) {
        this.store.dispatch(<Action>{
           type: ProjAction.INSERT_RECORD,
           payload: data
        })
   }

}

i tried to make a spy object and dispatch but it won't help for me.
any help will appreciated.


问:
Pattern matching on Class[_] type?
I'm trying to use Scala pattern matching on Java Class[_] (in context of using Java reflection from Scala) but I'm getting some unexpected error. The following gives "unreachable code" on the line with case jLong

```<code>def foo[T](paramType: Class[_]): Unit = {
  val jInteger = classOf[java.lang.Integer]
  val jLong = classOf[java.lang.Long]
  paramType match {
    case jInteger => println("int")
    case jLong => println("long")
  }
}
</code>```

Any ideas why this is happening ?

答:
JMPL is simple java library, which could emulate some of the features pattern matching, using Java 8 features.</p>

```<code>    matches(data).as(
      Integer.class, i  -> { System.out.println(i * i); },
      Byte.class,    b  -> { System.out.println(b * b); },
      Long.class,    l  -> { System.out.println(l * l); },
      String.class,  s  -> { System.out.println(s * s); },
      Null.class,    () -> { System.out.println("Null value "); },
      Else.class,    () -> { System.out.println("Default value: " + data); }
   );
</code>```

ContentLicense: CC BY-SA 3.0

Title: Pattern matching on Class[_] type?

Body:
I'm trying to use Scala pattern matching on Java Class[_] (in context of using Java reflection from Scala) but I'm getting some unexpected error. The following gives "unreachable code" on the line with case jLong

def foo[T](paramType: Class[_]): Unit = {
  val jInteger = classOf[java.lang.Integer]
  val jLong = classOf[java.lang.Long]
  paramType match {
    case jInteger => println("int")
    case jLong => println("long")
  }
}

Any ideas why this is happening ?

Body:
JMPL is simple java library, which could emulate some of the features pattern matching, using Java 8 features.

    matches(data).as(
      Integer.class, i  -> { System.out.println(i * i); },
      Byte.class,    b  -> { System.out.println(b * b); },
      Long.class,    l  -> { System.out.println(l * l); },
      String.class,  s  -> { System.out.println(s * s); },
      Null.class,    () -> { System.out.println("Null value "); },
      Else.class,    () -> { System.out.println("Default value: " + data); }
   );


问:
DrawerLayout with Navigation component: Hamburger menu on non-home top level destinations doesn't load the drawer
I'm setting up a DrawerLayout in my one-activity Navigation component setup, pretty much as outlined on the guide here.

Here is my main activity's code:

```<code>class MainActivity : AppCompatActivity(), SubjectFragment.OnListFragmentInteractionListener {
    lateinit var drawerLayout: DrawerLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        drawerLayout = findViewById<DrawerLayout>(R.id.main_drawer_layout)
        val navView = findViewById<NavigationView>(R.id.main_navigation_view)
        val sroToolbar = findViewById<Toolbar>(R.id.main_toolbar)
        val navController = findNavController(R.id.nav_host_fragment)

        navView.setupWithNavController(navController)
        setSupportActionBar(sroToolbar)

        val appBarConfiguration = AppBarConfiguration(
            setOf(R.id.subjectFragment, R.id.aboutFragment, R.id.settingsFragment),
            drawerLayout
        )
        setupActionBarWithNavController(navController, appBarConfiguration)

    }

    override fun onSupportNavigateUp(): Boolean {
        return findNavController(R.id.nav_host_fragment).navigateUp(drawerLayout)
    }
</code>```

Above, I'm using AppBarConfiguration to set up the three top level destinations (subjectFragment, aboutFragment, settingsFragment), with the subjectFragment being the home destination in the navigation graph. Here's my nav graph:

```<code><?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/sro_nav_graph"
    app:startDestination="@id/subjectFragment">

    <fragment
        android:id="@+id/subjectFragment"
        android:name="black.old.spacedrepetitionowl.SubjectFragment"
        android:label="Spaced Repetition Owl: Subjects"
        tools:layout="@layout/fragment_subject_list" >
        <action
            android:id="@+id/action_subjectFragment_to_aboutFragment"
            app:destination="@id/aboutFragment" />
        <action
            android:id="@+id/action_subjectFragment_to_settingsFragment"
            app:destination="@id/settingsFragment" />
    </fragment>
    <fragment
        android:id="@+id/aboutFragment"
        android:name="black.old.spacedrepetitionowl.AboutFragment"
        android:label="Spaced Repetition Owl: About"
        tools:layout="@layout/fragment_about" />
    <fragment
        android:id="@+id/settingsFragment"
        android:name="black.old.spacedrepetitionowl.settingsFragment"
        android:label="fragment_settings"
        tools:layout="@layout/fragment_settings" />
</navigation>
</code>```

When I start the app, it shows the subjectFragment and the hamburger menu opens the drawer when tapped. This so far is the correct behavior. My drawer then shows three items: Subjects, Settings, and About.

When I select Settings/About from the menu, this then opens the Settings/About fragment correctly.

My problem is, when I'm on those two screens, tapping the hamburger icon will then load the SubjectFragment, instead of making the drawer show up. Here's a GIF of what happened:

The behavior I want is so that the drawer loads each time the hamburger menu is tapped on each of those destinations. What might be the issue here?

答:
Aha! I figured this out by comparing it to a new project made using the 'Navigation Drawer Activity' as project template.

As it turns out, the appBarConfiguration needs to be used as the parameter for navigateUp so that the top-level destinations setup are obeyed:

```<code>    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment)
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }
</code>```

Body:
I'm setting up a DrawerLayout in my one-activity Navigation component setup, pretty much as outlined on the guide here.

Here is my main activity's code:

class MainActivity : AppCompatActivity(), SubjectFragment.OnListFragmentInteractionListener {
    lateinit var drawerLayout: DrawerLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        drawerLayout = findViewById<DrawerLayout>(R.id.main_drawer_layout)
        val navView = findViewById<NavigationView>(R.id.main_navigation_view)
        val sroToolbar = findViewById<Toolbar>(R.id.main_toolbar)
        val navController = findNavController(R.id.nav_host_fragment)

        navView.setupWithNavController(navController)
        setSupportActionBar(sroToolbar)

        val appBarConfiguration = AppBarConfiguration(
            setOf(R.id.subjectFragment, R.id.aboutFragment, R.id.settingsFragment),
            drawerLayout
        )
        setupActionBarWithNavController(navController, appBarConfiguration)

    }

    override fun onSupportNavigateUp(): Boolean {
        return findNavController(R.id.nav_host_fragment).navigateUp(drawerLayout)
    }

Above, I'm using AppBarConfiguration to set up the three top level destinations (subjectFragment, aboutFragment, settingsFragment), with the subjectFragment being the home destination in the navigation graph. Here's my nav graph:

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/sro_nav_graph"
    app:startDestination="@id/subjectFragment">

    <fragment
        android:id="@+id/subjectFragment"
        android:name="black.old.spacedrepetitionowl.SubjectFragment"
        android:label="Spaced Repetition Owl: Subjects"
        tools:layout="@layout/fragment_subject_list" >
        <action
            android:id="@+id/action_subjectFragment_to_aboutFragment"
            app:destination="@id/aboutFragment" />
        <action
            android:id="@+id/action_subjectFragment_to_settingsFragment"
            app:destination="@id/settingsFragment" />
    </fragment>
    <fragment
        android:id="@+id/aboutFragment"
        android:name="black.old.spacedrepetitionowl.AboutFragment"
        android:label="Spaced Repetition Owl: About"
        tools:layout="@layout/fragment_about" />
    <fragment
        android:id="@+id/settingsFragment"
        android:name="black.old.spacedrepetitionowl.settingsFragment"
        android:label="fragment_settings"
        tools:layout="@layout/fragment_settings" />
</navigation>

When I start the app, it shows the subjectFragment and the hamburger menu opens the drawer when tapped. This so far is the correct behavior. My drawer then shows three items: Subjects, Settings, and About.

When I select Settings/About from the menu, this then opens the Settings/About fragment correctly.

My problem is, when I'm on those two screens, tapping the hamburger icon will then load the SubjectFragment, instead of making the drawer show up. Here's a GIF of what happened:

The behavior I want is so that the drawer loads each time the hamburger menu is tapped on each of those destinations. What might be the issue here?

Body:
Aha! I figured this out by comparing it to a new project made using the 'Navigation Drawer Activity' as project template.

As it turns out, the appBarConfiguration needs to be used as the parameter for navigateUp so that the top-level destinations setup are obeyed:

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment)
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }


问:
Dynamically generate tabs and subtabs on a webpage based on count from parent page
I have an index page that records the number of Usecases(1-4), records no. of scenes(1-x) for each Usecase and every scene has set of same input fields.

Considering that I have the above numbers in javascript variables how do I dynamically load the second page based on the values given in the index page.

Index page where we define use cases and no. of scenes.

Second page which has loaded the page according to the number of use cases and scenes from index page

Use case tab :

```<code>    <ul role="tablist" class="ibm-tabs" aria-label="Tab navigation">
          <li role="presentation"><a role="tab" href="#">Usecase 1</a></li>
          <li role="presentation"><a role="tab" href="#">Usecase 2</a></li>
          <li role="presentation"><a role="tab" href="#">Usecase 3</a></li>
          <li role="presentation"><a role="tab" href="#">Usecase 4</a></li>
        </ul>
</code>```

Scenes :

```<code>            <li><a aria-selected="true" role="tab" href="#example2b-tab1">Intro Page</a></li>
            <li><a role="tab" href="#example2b-tab2">Scene 1</a></li>
            <li><a role="tab" href="#example2b-tab3">Scene 2</a></li>
            <li><a role="tab" href="#example2b-tab4">Scene 3</a></li>
            <li><a role="tab" href="#example2b-tab5">Scene 4</a></li>
        </ul>
    </div>
</div>
<!-- Tabs content body with tab contents divs inside a 4-3: -->
<div class="ibm-col-4-3 ibm-col-medium-5-3">
    <div id="example2b-tab1" class="ibm-tabs-content">
      <label for="__REPLACE_ME_1__" class="ibm-textcolor-green-60">Use case description<span class="ibm-required">*</span></label>
      <span>
        <input type="text" value="" size="70" id="first_name" name="first_name" required>
      </span>
</code>```

答:
If you are working just for a demo and want to use only frontend then you have to use javascript variables to store the values in the index page and then generate the page with a loop all on front-end.

see this example

But for real functionality...
It can be easily done from the server-side.

In the index page where one can actually set values.
One can fetch those values using POST requests.

With the values, received generate the next page at the server using a for loop or something and then return the page.

You might also want to store these values as session variables for a particular client at the server-side.

see this example for doing the loop thing on server side using jinja and flask

Body:
I have an index page that records the number of Usecases(1-4), records no. of scenes(1-x) for each Usecase and every scene has set of same input fields.

Considering that I have the above numbers in javascript variables how do I dynamically load the second page based on the values given in the index page.

Index page where we define use cases and no. of scenes.

Second page which has loaded the page according to the number of use cases and scenes from index page

Use case tab :

Usecase 1

Usecase 2

Usecase 3

Usecase 4

Scenes :

Intro Page

Scene 1

Scene 2

Scene 3

Scene 4

      Use case description*

        <input type="text" value="" size="70" id="first_name" name="first_name" required>


问:
How to process inner observables?
In my Angular app is an array recordlist. This array contains other arrays of objects. What I'm trying to do now is to process a http.post (via a function) on every nested element in the recordlist array.

The this.recordlist is an Observable which works and is shown as a table in my app.

```<code>/**
 *
 */
save() {
    this.recordlist
        .pipe(
            mergeMap((response: any) => response.flat()),
            map((response: any) => {
                console.log('---', response);
                return this.skaterService.setSkaterSeasonBestTimes(response);
            })
        )
        .subscribe(
            response => {},
            error => {},
            () => {
                console.log('.....done');
            }
        );
    }

/**
 *
 */
setSkaterSeasonBestTimes(value: SkaterBesttime): Observable<any> {
    return this.restService.post('/skater/besttimes', value).pipe(
        map((response: any) => {
            console.log('+++', response);
            return new SkaterBesttime(response, true);
        })
    );
}
</code>```

The problem is now that the inner setSkaterSeasonBestTimes(...) is not processed. I hope that somebody can give me a useful hint and solution.

答:
Changed save method :- </p>

```<code>save() {
    this.recordlist
        .pipe(
            mergeMap((response: any) => {
                let res = response.flat().map((item) => this.setSkaterSeasonBestTimes(item));
                return forkJoin(res);
            })
        )
        .subscribe(
            response => {},
            error => {},
            () => {
                console.log('.....done');
            }
        );
    }
</code>```

Title: How to process inner observables?

Body:
In my Angular app is an array recordlist. This array contains other arrays of objects. What I'm trying to do now is to process a http.post (via a function) on every nested element in the recordlist array.

The this.recordlist is an Observable which works and is shown as a table in my app.

/**
 *
 */
save() {
    this.recordlist
        .pipe(
            mergeMap((response: any) => response.flat()),
            map((response: any) => {
                console.log('---', response);
                return this.skaterService.setSkaterSeasonBestTimes(response);
            })
        )
        .subscribe(
            response => {},
            error => {},
            () => {
                console.log('.....done');
            }
        );
    }

/**
 *
 */
setSkaterSeasonBestTimes(value: SkaterBesttime): Observable<any> {
    return this.restService.post('/skater/besttimes', value).pipe(
        map((response: any) => {
            console.log('+++', response);
            return new SkaterBesttime(response, true);
        })
    );
}

The problem is now that the inner setSkaterSeasonBestTimes(...) is not processed. I hope that somebody can give me a useful hint and solution.

Body:
Changed save method :-

save() {
    this.recordlist
        .pipe(
            mergeMap((response: any) => {
                let res = response.flat().map((item) => this.setSkaterSeasonBestTimes(item));
                return forkJoin(res);
            })
        )
        .subscribe(
            response => {},
            error => {},
            () => {
                console.log('.....done');
            }
        );
    }


问:
Conditionally set viewport for iPhone4?
I was hoping to just use,

```<code>    <meta name="viewport" content="width=device-width,maximum-scale=1.0,user-scalable=false" />
</code>```

and then call different style sheets based on the width. The only problem is that the iPhone4 reports a width of 320px even tho its 640px. How would I conditionally set the content width to 640px for iPhone4s?

答:
I would look into Media Queries to achieve what you are asking.

Here are some really good articles related to building responsive, fluid, multi-device websites:

Smashing Magazine's 'How to use Media Queries':
http://www.smashingmagazine.com/2010/07/19/how-to-use-css3-media-queries-to-create-a-mobile-version-of-your-website/

A-List Apart article on Fluid Grids:
http://www.alistapart.com/articles/fluidgrids/

And, Smashing Magazine article on Responsive web Design (references A-List Apart's article on same subject):
http://www.smashingmagazine.com/2011/01/12/guidelines-for-responsive-web-design/

Title: Conditionally set viewport for iPhone4?

Body:
I was hoping to just use,

    <meta name="viewport" content="width=device-width,maximum-scale=1.0,user-scalable=false" />

and then call different style sheets based on the width. The only problem is that the iPhone4 reports a width of 320px even tho its 640px. How would I conditionally set the content width to 640px for iPhone4s?


问:
R: how to round weights digits in plot.nn()?
I am trying to plot my neural network and I am wondering how can I round the weights to 3 digits.

```<code>library(neuralnet)
set.seed(0)

x = matrix(rnorm(100, 0, 5), ncol=4)
y = rnorm(25, 100, 20)
data = data.frame(y, x)
nn.model = neuralnet(y~., data, linear.output=T, stepmax = 1e+06)

plot(nn.model)
</code>```

I've tried mapply(round) but it didn't work out on lists as neuralnet model generates. Any suggestion is appreciated!

答:
Like this:

```<code>nn.model$weights[[1]] <- lapply(nn.model$weights[[1]], function(x) round(x, 3))
plot(nn.model)
</code>```

Body:
I am trying to plot my neural network and I am wondering how can I round the weights to 3 digits.

library(neuralnet)
set.seed(0)

x = matrix(rnorm(100, 0, 5), ncol=4)
y = rnorm(25, 100, 20)
data = data.frame(y, x)
nn.model = neuralnet(y~., data, linear.output=T, stepmax = 1e+06)

plot(nn.model)

I've tried mapply(round) but it didn't work out on lists as neuralnet model generates. Any suggestion is appreciated!

Body:
Like this:

nn.model$weights[[1]] <- lapply(nn.model$weights[[1]], function(x) round(x, 3))
plot(nn.model)


问:
In Java, how to print divisor numbers?
I want to print the divisors of a user input value between 1 and 10000.

```<code>import java.util.Scanner;

public class Divisors {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int Range;
        int Divisor;

        while(true) {

            System.out.print("Please insert a number between 1 and 10000: ");
            Range = scan.nextInt();

            if (Range < 1 || Range > 10000)
            System.out.println("Wrong choice");

            else
                break;
        }

        Divisor = 0;    // Start counting Divisor from Zero

        for (int loop = 1; loop <= Range; loop++) {
            if (Range % loop == 0)
                Divisor++;
                System.out.println("loop);
            }

        System.out.println("Total number of divisors of " + Range + " is " + Divisor);

    }
}
</code>```

I have problem here with command System.out.println("loop);.
  I want to print all the divisors, like if a user inserted 10, then the
  output should show something like:

!

```<code>Please insert a number between 1 and 10000: 10
1
2
5
10
Total number of divisors of 10 is 4
</code>```

!
!

But the current output is:

!

```<code>Please insert a number between 1 and 10000: 10
1
2
3
4
5
6
7
8
9
10
Total number of divisors of 10 is 4
</code>```

!
!

so how to print loop only when the (Range % loop == 0) is true??

答:
You're missed the {} in the loop :

```<code>for (int loop = 1; loop <= Range; loop++) {
    if (Range % loop == 0) {
       System.out.println("loop);
       Divisor++;
    }

}
</code>```

When you write if condition and you have one line of code after it will be executed : (Witout {} )

```<code> if (Range % loop == 0)
           System.out.println("loop); //WORK !
           Divisor++; /// NOT WORK !!
</code>```

But with {} the two line executed  :

```<code>if (Range % loop == 0) {
           System.out.println("loop); //WORK !
           Divisor++; /// WORK !!
        }
</code>```

Title: In Java, how to print divisor numbers?

Body:
I want to print the divisors of a user input value between 1 and 10000.

import java.util.Scanner;

public class Divisors {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int Range;
        int Divisor;

        while(true) {

            System.out.print("Please insert a number between 1 and 10000: ");
            Range = scan.nextInt();

            if (Range < 1 || Range > 10000)
            System.out.println("Wrong choice");

            else
                break;
        }

        Divisor = 0;    // Start counting Divisor from Zero

        for (int loop = 1; loop <= Range; loop++) {
            if (Range % loop == 0)
                Divisor++;
                System.out.println("loop);
            }

        System.out.println("Total number of divisors of " + Range + " is " + Divisor);

    }
}

I have problem here with command System.out.println("loop);.
  I want to print all the divisors, like if a user inserted 10, then the
  output should show something like:

!

Please insert a number between 1 and 10000: 10
1
2
5
10
Total number of divisors of 10 is 4

!
!

But the current output is:

!

Please insert a number between 1 and 10000: 10
1
2
3
4
5
6
7
8
9
10
Total number of divisors of 10 is 4

!
!

so how to print loop only when the (Range % loop == 0) is true??

Body:
You're missed the {} in the loop :

for (int loop = 1; loop <= Range; loop++) {
    if (Range % loop == 0) {
       System.out.println("loop);
       Divisor++;
    }

}

When you write if condition and you have one line of code after it will be executed : (Witout {} )

 if (Range % loop == 0)
           System.out.println("loop); //WORK !
           Divisor++; /// NOT WORK !!

But with {} the two line executed  :

if (Range % loop == 0) {
           System.out.println("loop); //WORK !
           Divisor++; /// WORK !!
        }


问:
SQL Connection class won't connect when run from a Blazor App
I am trying to use the following code to query a database from a Blazor web page, the exception is as follows

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 44 - Could not compose Service Principal Name (SPN) for Windows Integrated Authentication. Possible causes are server(s) incorrectly specified to connection API calls, Domain Name System (DNS) lookup failure or memory shortage)

System.PlatformNotSupportedException: System.Net.Dns:GetHostByName is not supported on this platform.

at System.Net.Dns.GetHostByName (System.String hostName) <0x38c58e8 + 0x0001c> in :0
  ...

When I run the same code in a traditional web or console app the connection opens/closes instantly.

```<code>public class MySQLHelper
{
    public static SqlConnection GetConnection()
    {
        string m_connectionString = "connection string here";
        SqlConnection sqlConn = new SqlConnection(m_connectionString);
        sqlConn.Open(); // fails to open when called from a regular registered 'service' in Blazor

        return sqlConn;
    }
}
</code>```

Thoughts?

答:
You can use Entity framework

Visit https://www.c-sharpcorner.com/article/create-a-single-page-app-with-blazor-server-and-entity-framework-core-3-0/

Body:
I am trying to use the following code to query a database from a Blazor web page, the exception is as follows

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 44 - Could not compose Service Principal Name (SPN) for Windows Integrated Authentication. Possible causes are server(s) incorrectly specified to connection API calls, Domain Name System (DNS) lookup failure or memory shortage)

System.PlatformNotSupportedException: System.Net.Dns:GetHostByName is not supported on this platform.

at System.Net.Dns.GetHostByName (System.String hostName) <0x38c58e8 + 0x0001c> in :0
  ...

When I run the same code in a traditional web or console app the connection opens/closes instantly.

public class MySQLHelper
{
    public static SqlConnection GetConnection()
    {
        string m_connectionString = "connection string here";
        SqlConnection sqlConn = new SqlConnection(m_connectionString);
        sqlConn.Open(); // fails to open when called from a regular registered 'service' in Blazor

        return sqlConn;
    }
}

Thoughts?