问:
Authentication with firebase and angular. How to navigate to other component after the user log in?
I want to authenticate a site that is written in Angular, with the help of firebase.

I found a guide that describes in a detailed and clear way how to do it.

Website address: https://www.positronx.io/full-angular-7-firebase-authentication-system/

The github that the guide attached:https://github.com/SinghDigamber/angularfirebase-authentication

I followed the instructions but i didn't succeed to navigate to other component  after the user logs in (The user remains on the same page).
 when I ran the code from the github, I encountered the same problem.

Partial code from auth.service.ts:

```<code>  // Sign in with email/password
  SignIn(email, password) {
    alert(":)");
    return this.afAuth.signInWithEmailAndPassword(email, password)
      .then((result) => {
        this.ngZone.run(() => {
          this.router.navigate(['/dashboard']);
        });
        this.SetUserData(result.user);
      }).catch((error) => {
        window.alert(error.message)
      })
  }
</code>```

Why the user does not navigate to dashboard component after login?

What could be the cause of the problem? Thank you.

EDIT:
I'll add the code here that I think is relevant:

auth.service.ts:

```<code>import { Injectable, NgZone } from '@angular/core';
//import { User } from "../services/user";
//import { auth } from 'firebase/app';
import { AngularFireAuth } from "@angular/fire/auth";
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Router } from "@angular/router";

export interface User {
  email: string;
}

@Injectable({
  providedIn: 'root'
})

export class AuthService {
  userData: any; // Save logged in user data
  authStateSubs: any;
  //authStateSubs: any;

  constructor(
    public afs: AngularFirestore,   // Inject Firestore service
    public afAuth: AngularFireAuth, // Inject Firebase auth service
    public router: Router,
    public auth: AngularFireAuth,
    public ngZone: NgZone // NgZone service to remove outside scope warning
  ) {

    /* Saving user data in localstorage when
    logged in and setting up null when logged out */
    this.afAuth.authState.subscribe(user => {
      if (user) {
        this.userData = user;
        localStorage.setItem('user', JSON.stringify(this.userData));
        JSON.parse(localStorage.getItem('user'));

      } else {
        localStorage.setItem('user', null);
        JSON.parse(localStorage.getItem('user'));
      }
    })
  }

  // Sign in with email/password
  SignIn(email, password) {
    return this.afAuth.signInWithEmailAndPassword(email, password)
      .then((result) => {
        alert("after signInWithEmailAndPassword");
        this.ngZone.run(() => {
          alert("after ngZone.run");
          this.router.navigate(['/authorized-zone']);
        });
        this.SetUserData(result.user);
      }).catch((error) => {
        window.alert(error.message)
      })
  }

  // Returns true when user is looged in and email is verified
  get isLoggedIn(): boolean {
    const user = JSON.parse(localStorage.getItem('user'));
    return (user !== null && user.emailVerified !== false) ? true : false;
  }

  /* Setting up user data when sign in with username/password,
  sign up with username/password and sign in with social auth
  provider in Firestore database using AngularFirestore + AngularFirestoreDocument service */
  SetUserData(user) {
    const userRef: AngularFirestoreDocument<any> = this.afs.doc(`users/${user.email}`);
    const userData: User = {
      email: user.email,
    }
    return userRef.set(userData, {
      merge: true
    })
  }

  // Sign out
  SignOut() {
    return this.afAuth.signOut().then(() => {
      localStorage.removeItem('user');
      this.router.navigate(['login']);
    })
  }
}
</code>```

auth.guard.ts:

```<code>import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthService } from "../services/auth.service";
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class AuthGuard implements CanActivate {

  constructor(
    public authService: AuthService,
    public router: Router
  ){ }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if(this.authService.isLoggedIn !== true) {
      this.router.navigate(['login'])
    }
    return true;
  }

}
</code>```

答:
If you would like to do something based on sign-in and sign-out, a simple and good way is use a subscription to authState. Do it in your service's constrictor.
You do not do any thing inside signInWithEmailAndPassword's then.  </p>

```<code>constructor(
    public auth: AngularFireAuth,
    private router: Router,
    //...
    ){
        this.authStateSubs=this.auth.authState.subscribe(fbUser=>{
           //this is a Sign in.
           if( fbUser && fbUser.uid){
                this.router.navigate(['/wherever_you_want']);
           }else{
            //Sign out. Go to sign-in page.
           }
        });
    }
</code>```

Body:
I want to authenticate a site that is written in Angular, with the help of firebase.

I found a guide that describes in a detailed and clear way how to do it.

Website address: https://www.positronx.io/full-angular-7-firebase-authentication-system/

The github that the guide attached:https://github.com/SinghDigamber/angularfirebase-authentication

I followed the instructions but i didn't succeed to navigate to other component  after the user logs in (The user remains on the same page).
 when I ran the code from the github, I encountered the same problem.

Partial code from auth.service.ts:

  // Sign in with email/password
  SignIn(email, password) {
    alert(":)");
    return this.afAuth.signInWithEmailAndPassword(email, password)
      .then((result) => {
        this.ngZone.run(() => {
          this.router.navigate(['/dashboard']);
        });
        this.SetUserData(result.user);
      }).catch((error) => {
        window.alert(error.message)
      })
  }

Why the user does not navigate to dashboard component after login?

What could be the cause of the problem? Thank you.

EDIT:
I'll add the code here that I think is relevant:

auth.service.ts:

import { Injectable, NgZone } from '@angular/core';
//import { User } from "../services/user";
//import { auth } from 'firebase/app';
import { AngularFireAuth } from "@angular/fire/auth";
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Router } from "@angular/router";

export interface User {
  email: string;
}

@Injectable({
  providedIn: 'root'
})

export class AuthService {
  userData: any; // Save logged in user data
  authStateSubs: any;
  //authStateSubs: any;

  constructor(
    public afs: AngularFirestore,   // Inject Firestore service
    public afAuth: AngularFireAuth, // Inject Firebase auth service
    public router: Router,
    public auth: AngularFireAuth,
    public ngZone: NgZone // NgZone service to remove outside scope warning
  ) {

    /* Saving user data in localstorage when
    logged in and setting up null when logged out */
    this.afAuth.authState.subscribe(user => {
      if (user) {
        this.userData = user;
        localStorage.setItem('user', JSON.stringify(this.userData));
        JSON.parse(localStorage.getItem('user'));

      } else {
        localStorage.setItem('user', null);
        JSON.parse(localStorage.getItem('user'));
      }
    })
  }

  // Sign in with email/password
  SignIn(email, password) {
    return this.afAuth.signInWithEmailAndPassword(email, password)
      .then((result) => {
        alert("after signInWithEmailAndPassword");
        this.ngZone.run(() => {
          alert("after ngZone.run");
          this.router.navigate(['/authorized-zone']);
        });
        this.SetUserData(result.user);
      }).catch((error) => {
        window.alert(error.message)
      })
  }

  // Returns true when user is looged in and email is verified
  get isLoggedIn(): boolean {
    const user = JSON.parse(localStorage.getItem('user'));
    return (user !== null && user.emailVerified !== false) ? true : false;
  }

  /* Setting up user data when sign in with username/password,
  sign up with username/password and sign in with social auth
  provider in Firestore database using AngularFirestore + AngularFirestoreDocument service */
  SetUserData(user) {
    const userRef: AngularFirestoreDocument<any> = this.afs.doc(`users/${user.email}`);
    const userData: User = {
      email: user.email,
    }
    return userRef.set(userData, {
      merge: true
    })
  }

  // Sign out
  SignOut() {
    return this.afAuth.signOut().then(() => {
      localStorage.removeItem('user');
      this.router.navigate(['login']);
    })
  }
}

auth.guard.ts:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthService } from "../services/auth.service";
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class AuthGuard implements CanActivate {

  constructor(
    public authService: AuthService,
    public router: Router
  ){ }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if(this.authService.isLoggedIn !== true) {
      this.router.navigate(['login'])
    }
    return true;
  }

}

Body:
If you would like to do something based on sign-in and sign-out, a simple and good way is use a subscription to authState. Do it in your service's constrictor.
You do not do any thing inside signInWithEmailAndPassword's then.

constructor(
    public auth: AngularFireAuth,
    private router: Router,
    //...
    ){
        this.authStateSubs=this.auth.authState.subscribe(fbUser=>{
           //this is a Sign in.
           if( fbUser && fbUser.uid){
                this.router.navigate(['/wherever_you_want']);
           }else{
            //Sign out. Go to sign-in page.
           }
        });
    }


来源: stackexchange

问:
Best way to save SQL versions while working on Tableau?
I am working using Tableau and have to write down multiple different SQL each time, while making new data sources.
I have to save all changes on SQL for every data source.
Currently I would paste the SQL on notepad and save them on separate folder in my computer, along with description of the changes.
Is there any better way to do this?</p>

答:
I had similar problem as you.

We ended up writing the queries in SQL Editor SQL Work bench (https://www.sql-workbench.eu/), then managed the code history and performed code peer-review (logic, error check, etc) in team shared space (like confluence).

The reasons we did that is

1) SQL queries are much easy to write on Work Bench
2) Code review is a must! You will find through implementing a review process more mistakes than you could ever think about
3) The shared space is just really convenient as it is accessible by everyone, and all errors are documented. After sometimes you get a lot of visible knowledge accumulated.

I also totally agree with Nick as this is one step to a reporting solution. But developing a whole reporting server is heavy, costly and takes time. Unless management are really convinced of the importance of developing a reporting solution, you may have to get a workaround with queries and Tableau (at least that was the case for us)

ContentLicense: CC BY-SA 4.0


问:
Ansible inventory: aws_ec2 module -- Looking for an example of a working 'groups:' function
I have a dynamic ansible inventory which uses the aws_ec2 module. It works quite well, generally.  However, there is one issue.  I've tried several times to create groups using the 'groups:' keyword, and all attempts have failed.  The documentation is a little sparse -- in fact here it is, in its entirety:

```<code>groups: (dictionary)
Default:{}
Add hosts to group based on Jinja2 conditionals.
</code>```

I've tried a number of syntaxes, Jinja2, conditionals, declarations, and so far none have succeeded in creating a group named 'foo'.  For awhile I thought maybe I need to pass a small code snibbet that returns true or false, and thus include or exclude the targeted hosts.  This doesn't seem to be the case. I'm wondering if anyone here has used the 'groups:' keyword and gotten further than I have. I found very little while Googling. FWIW, I am using ansible 2.9.9 on Linux.

Some examples of things that don't work:

```<code>---
plugin: aws_ec2

### fails to create a group
groups:
  foo: >-
    tags.get('Name') if tags.get('Name') == 'foo-server'

### returns every host in the AWS account.
groups:
  bar:
    - "{{ tags.get('Name') == 'bar-server' }}"
</code>```

Also, it is difficult to use ansible's debugging tools with this module.
Many, like the playbook debugger, seem not to work properly, though I find
them quite useful in other contexts. Any tips you might have for debugging
in this context would be warmly appreciated.

答:
It looks like you were very close

As with many things ansible, the authoritative "documentation" is the source code. Specifically their use of the 'groups' option which calls _add_host_to_composed_groups wherein they feed the groups: dict into a Jinja2 evaluation context containing all the hostvars. The expression is plugged into {% if ... %} so you wouldn't want to include the {{ markers in your expression, just the "raw" jinja2 expression

groups:
  foo: tags.get('Name') == 'foo-server'
```

Be forewarned that I don't have an environment handy to test that inventory script, but that's the theory

Body:
I have a dynamic ansible inventory which uses the aws_ec2 module. It works quite well, generally.  However, there is one issue.  I've tried several times to create groups using the 'groups:' keyword, and all attempts have failed.  The documentation is a little sparse -- in fact here it is, in its entirety:

groups: (dictionary)
Default:{}
Add hosts to group based on Jinja2 conditionals.

I've tried a number of syntaxes, Jinja2, conditionals, declarations, and so far none have succeeded in creating a group named 'foo'.  For awhile I thought maybe I need to pass a small code snibbet that returns true or false, and thus include or exclude the targeted hosts.  This doesn't seem to be the case. I'm wondering if anyone here has used the 'groups:' keyword and gotten further than I have. I found very little while Googling. FWIW, I am using ansible 2.9.9 on Linux.

Some examples of things that don't work:

---
plugin: aws_ec2

### fails to create a group
groups:
  foo: >-
    tags.get('Name') if tags.get('Name') == 'foo-server'

### returns every host in the AWS account.
groups:
  bar:
    - "{{ tags.get('Name') == 'bar-server' }}"

Also, it is difficult to use ansible's debugging tools with this module.
Many, like the playbook debugger, seem not to work properly, though I find
them quite useful in other contexts. Any tips you might have for debugging
in this context would be warmly appreciated.

Body:
It looks like you were very close

As with many things ansible, the authoritative "documentation" is the source code. Specifically their use of the 'groups' option which calls _add_host_to_composed_groups wherein they feed the groups: dict into a Jinja2 evaluation context containing all the hostvars. The expression is plugged into {% if ... %} so you wouldn't want to include the {{ markers in your expression, just the "raw" jinja2 expression

groups:
  foo: tags.get('Name') == 'foo-server'

Be forewarned that I don't have an environment handy to test that inventory script, but that's the theory


问:
Visualize the files generated by the tensor-board after training
I activated the tensor-board option during training to view the metrics and learning during training. It created a directory called “runs (default)” and placed the files there. The files look like this:

```<code>events.out.tfevents.1590963894.moissan.17321.0
</code>```

I have tried viewing the content of the file, but it’s a binary file…

Please can anyone help me with how to view the files generated when you activate the tensor-board option?

答:
To view these files, you need to install tensorboard: https://www.tensorflow.org/tensorboard/get_started

Once tensorboard is installed, open a terminal window and run via

```<code>tensorboard --logdir=runs\ (default)
</code>```

If using standard options, you will then be able to view by opening http://127.0.0.1:6006/ in your web browser.

Body:
I activated the tensor-board option during training to view the metrics and learning during training. It created a directory called “runs (default)” and placed the files there. The files look like this:

events.out.tfevents.1590963894.moissan.17321.0

I have tried viewing the content of the file, but it’s a binary file…

Please can anyone help me with how to view the files generated when you activate the tensor-board option?

Body:
To view these files, you need to install tensorboard: https://www.tensorflow.org/tensorboard/get_started

Once tensorboard is installed, open a terminal window and run via

tensorboard --logdir=runs\ (default)

If using standard options, you will then be able to view by opening http://127.0.0.1:6006/ in your web browser.


问:
Model-building function in Keras Tuner did not return a valid Keras Model instance
I am trying to learn CNN following Krish naik Youtube tutorial in one program i am getting this error:

```<code>RuntimeError: Model-building function did not return a valid Keras Model instance, found <keras.engine.sequential.Sequential object at 0x7fd882393b38>
</code>```

my code is given below

```<code>import keras.datasets
fashion=keras.datasets.fashion_mnist
(x_train,y_train),(x_test,y_test)=fashion.load_data()

x_train=x_train/255.00
x_test=x_test/255.00
x_train=x_train.reshape(x_train.shape[0],x_train.shape[1],x_train.shape[2],1)
x_test=x_test.reshape(x_test.shape[0],x_test.shape[1],x_test.shape[2],1)
from keras.models import Sequential
from keras.layers import Conv2D,Flatten,Dropout,Dense
from keras.optimizers import Adam
def build_knn(hp):
    models=Sequential()
    models.add(Conv2D(filters=hp.Int('conv2d_1',min_value=32,max_value=128,step=16),
                      kernel_size=hp.Choice('conv1_kernal',values=[3,5]),
                      activation='relu',
                      input_shape=(28,28,1)
                                    ))
    models.add(Conv2D(filters=hp.Int('conv2d_1',min_value=32,max_value=128,step=16),
                      kernel_size=hp.Choice('conv1_kernal',values=[3,5]),
                      activation='relu'
                                    ))
    models.add(Flatten())
    models.add(Dense(hp.Int('neural1',min_value=32,max_value=128,step=16),activation='relu'))
    models.add(Dense(10,activation='softmax'))
    models.compile(optimizer=Adam(hp.Choice('learning_rate',values=[1e-2,1e-3])),
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy']
                 )
    return models
from kerastuner import RandomSearch
from kerastuner.engine.hyperparameters import HyperParameters
tuner_search=RandomSearch(build_knn,objective='val_accuracy',max_trials=5,directory='jupyterfiles',project_name='krish_naik_fashion_mnist')
</code>```

答:
It is not very clear in the project site, but is indeed mentioned that Keras Tuner is (emphasis added):

A hyperparameter tuner for Keras, specifically for tf.keras with TensorFlow 2.0.

In other words, it works for tf.keras, but not for the stand-alone version of Keras, which you seem to be using here.

Indeed, adapting the basic example from the project site linked above, but changing the imports to use stand-alone Keras, replicates the error you report:

```<code>!pip install -U keras-tuner

import keras
from keras import layers
from kerastuner.tuners import RandomSearch

def build_model(hp):
    model = keras.Sequential()
    model.add(layers.Dense(units=hp.Int('units',
                                        min_value=32,
                                        max_value=512,
                                        step=32),
                           activation='relu'))
    model.add(layers.Dense(10, activation='softmax'))
    model.compile(
        optimizer=keras.optimizers.Adam(
            hp.Choice('learning_rate',
                      values=[1e-2, 1e-3, 1e-4])),
        loss='sparse_categorical_crossentropy',
        metrics=['accuracy'])
    return model

tuner = RandomSearch(
    build_model,
    objective='val_accuracy',
    max_trials=5,
    executions_per_trial=3,
    directory='my_dir',
    project_name='helloworld')
</code>```

Result:

```<code>RuntimeError: Model-building function did not return a valid Keras Model instance, found <keras.engine.sequential.Sequential object at 0x7fd882393b38>
</code>```

But just by changing the imports to use tf.keras instead, i.e.:

```<code>from tensorflow import keras
from tensorflow.keras import layers
from kerastuner.tuners import RandomSearch
</code>```

the same code above runs OK without error.

So, you should change the imports shown here to:

```<code>from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D,Flatten,Dropout,Dense
from tensorflow.keras.optimizers import Adam
</code>```

and you should be fine (provided of course that you use Tensorflow 2.0 indeed).

I have just opened a relevant Github issue, advising that they include this clarification explicitly in a visible position.

Body:
I am trying to learn CNN following Krish naik Youtube tutorial in one program i am getting this error:

RuntimeError: Model-building function did not return a valid Keras Model instance, found <keras.engine.sequential.Sequential object at 0x7fd882393b38>

my code is given below

import keras.datasets
fashion=keras.datasets.fashion_mnist
(x_train,y_train),(x_test,y_test)=fashion.load_data()

x_train=x_train/255.00
x_test=x_test/255.00
x_train=x_train.reshape(x_train.shape[0],x_train.shape[1],x_train.shape[2],1)
x_test=x_test.reshape(x_test.shape[0],x_test.shape[1],x_test.shape[2],1)
from keras.models import Sequential
from keras.layers import Conv2D,Flatten,Dropout,Dense
from keras.optimizers import Adam
def build_knn(hp):
    models=Sequential()
    models.add(Conv2D(filters=hp.Int('conv2d_1',min_value=32,max_value=128,step=16),
                      kernel_size=hp.Choice('conv1_kernal',values=[3,5]),
                      activation='relu',
                      input_shape=(28,28,1)
                                    ))
    models.add(Conv2D(filters=hp.Int('conv2d_1',min_value=32,max_value=128,step=16),
                      kernel_size=hp.Choice('conv1_kernal',values=[3,5]),
                      activation='relu'
                                    ))
    models.add(Flatten())
    models.add(Dense(hp.Int('neural1',min_value=32,max_value=128,step=16),activation='relu'))
    models.add(Dense(10,activation='softmax'))
    models.compile(optimizer=Adam(hp.Choice('learning_rate',values=[1e-2,1e-3])),
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy']
                 )
    return models
from kerastuner import RandomSearch
from kerastuner.engine.hyperparameters import HyperParameters
tuner_search=RandomSearch(build_knn,objective='val_accuracy',max_trials=5,directory='jupyterfiles',project_name='krish_naik_fashion_mnist')

Body:
It is not very clear in the project site, but is indeed mentioned that Keras Tuner is (emphasis added):

A hyperparameter tuner for Keras, specifically for tf.keras with TensorFlow 2.0.

In other words, it works for tf.keras, but not for the stand-alone version of Keras, which you seem to be using here.

Indeed, adapting the basic example from the project site linked above, but changing the imports to use stand-alone Keras, replicates the error you report:

!pip install -U keras-tuner

import keras
from keras import layers
from kerastuner.tuners import RandomSearch

def build_model(hp):
    model = keras.Sequential()
    model.add(layers.Dense(units=hp.Int('units',
                                        min_value=32,
                                        max_value=512,
                                        step=32),
                           activation='relu'))
    model.add(layers.Dense(10, activation='softmax'))
    model.compile(
        optimizer=keras.optimizers.Adam(
            hp.Choice('learning_rate',
                      values=[1e-2, 1e-3, 1e-4])),
        loss='sparse_categorical_crossentropy',
        metrics=['accuracy'])
    return model

tuner = RandomSearch(
    build_model,
    objective='val_accuracy',
    max_trials=5,
    executions_per_trial=3,
    directory='my_dir',
    project_name='helloworld')

Result:

RuntimeError: Model-building function did not return a valid Keras Model instance, found <keras.engine.sequential.Sequential object at 0x7fd882393b38>

But just by changing the imports to use tf.keras instead, i.e.:

from tensorflow import keras
from tensorflow.keras import layers
from kerastuner.tuners import RandomSearch

the same code above runs OK without error.

So, you should change the imports shown here to:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D,Flatten,Dropout,Dense
from tensorflow.keras.optimizers import Adam

and you should be fine (provided of course that you use Tensorflow 2.0 indeed).

I have just opened a relevant Github issue, advising that they include this clarification explicitly in a visible position.


问:
How to write WIC XMP people tags to jpg?
I have images with people tagging information in xml format. I wish to edit this information and also add it to pictures that do not yet have it. By looking at the xml I assume it is based on the people tagging used in the microsoft imaging component.

I haven't quite understood the format, but I understood it sof far, that I can alter or gemerate the xml, I just do not know where to write it in the image. I am probably just doing some stupid mistake, because I am not experienced with these image metadatas. So if you think I'm just on the wrong track and that can be done much simpler, please tell me.

In those images that already contain this xml, I can use search and replace to update the xml. However I have a lot of pictures that do not yet contain that information and I do not know where I should write it to inside the image.

Images that already contain this information can be read with exiftool as follows:

```<code>exiftool -xmp -b existingTags.JPG
</code>```

The result is the following xml:

```<code><?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?> <x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="XMP
Core 4.4.0-Exiv2"> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <rdf:Description rdf:about=""
xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:MP="http://ns.microsoft.com/photo/1.2/" xmlns:MPRI="http://ns.microsoft.com/photo/1.2/t/RegionInfo#"
xmlns:MPReg="http://ns.microsoft.com/photo/1.2/t/Region#" xmp:Rating="0"> <dc:subject> <rdf:Bag> <rdf:li>Valeriya
</rdf:li> </rdf:Bag> </dc:subject> <MP:RegionInfo rdf:parseType="Resource"> <MPRI:Regions> <rdf:Bag> <rdf:li
MPReg:Rectangle="0.48, 0.418, 0.059333, 0.089" MPReg:PersonDisplayName="findus_l"/> </rdf:Bag> </MPRI:Regions>
</MP:RegionInfo> </rdf:Description> </rdf:RDF> </x:xmpmeta> <?xpacket end="w"?>
</code>```

However I cannot write the information using exiftool. When I ran this command, it simply reads the information again, instead of writing the contents of the file to the image:

```<code>exiftool -xmp<=alteredXMP.txt existingTags.JPG
</code>```

A bit of research has shown me, that exiftool can only write specific xmp tags, and the people tagging tags from windows imaging component do not seem to be part of this.

Where in the image file should I write the information? Can I somehow find this spot programmatically and then just insert the xml there?

I am using Kotlin as programming language but I don't mind having to call command line functions or other programs.

Background: I have a Synology Diskstation and use the included software called photo station. The photo station supports tagging of people on the images and uses this given format. I like the photo station in many ways, but the face recognition is bad, so I want to use my own but have photo station be able to read it.

答:
The data you are trying to write is part of the Microsoft Region Structure.  XMP Structured data is a complex subject but you should be able to add the data with exiftool by writing region names to the RegionPersonDisplayName tag and the region dimensions to the RegionRectangle.  Using the data in your example, the command would be:

exiftool -RegionPersonDisplayName=findus_l -RegionRectangle="0.48, 0.418, 0.059333, 0.089" /path/to/files

If you have to write multiple regions, you can just add them on, but you must keep names and the matching dimensions in the same order.  For example

exiftool -RegionPersonDisplayName=findus_l -RegionRectangle="0.48, 0.418, 0.059333, 0.089" -RegionPersonDisplayName="John Smith" -RegionRectangle="0.37645533, 0.04499886, 0.35111009, 0.26633097" /path/to/files

These commands would overwrite any existing region data.  If you are adding new names without overwriting, you would change the equal signs to PlusEqual +=.

Body:
I have images with people tagging information in xml format. I wish to edit this information and also add it to pictures that do not yet have it. By looking at the xml I assume it is based on the people tagging used in the microsoft imaging component.

I haven't quite understood the format, but I understood it sof far, that I can alter or gemerate the xml, I just do not know where to write it in the image. I am probably just doing some stupid mistake, because I am not experienced with these image metadatas. So if you think I'm just on the wrong track and that can be done much simpler, please tell me.

In those images that already contain this xml, I can use search and replace to update the xml. However I have a lot of pictures that do not yet contain that information and I do not know where I should write it to inside the image.

Images that already contain this information can be read with exiftool as follows:

exiftool -xmp -b existingTags.JPG

The result is the following xml:

<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?> <x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="XMP
Core 4.4.0-Exiv2"> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <rdf:Description rdf:about=""
xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:MP="http://ns.microsoft.com/photo/1.2/" xmlns:MPRI="http://ns.microsoft.com/photo/1.2/t/RegionInfo#"
xmlns:MPReg="http://ns.microsoft.com/photo/1.2/t/Region#" xmp:Rating="0"> <dc:subject> <rdf:Bag> <rdf:li>Valeriya
</rdf:li> </rdf:Bag> </dc:subject> <MP:RegionInfo rdf:parseType="Resource"> <MPRI:Regions> <rdf:Bag> <rdf:li
MPReg:Rectangle="0.48, 0.418, 0.059333, 0.089" MPReg:PersonDisplayName="findus_l"/> </rdf:Bag> </MPRI:Regions>
</MP:RegionInfo> </rdf:Description> </rdf:RDF> </x:xmpmeta> <?xpacket end="w"?>

However I cannot write the information using exiftool. When I ran this command, it simply reads the information again, instead of writing the contents of the file to the image:

exiftool -xmp<=alteredXMP.txt existingTags.JPG

A bit of research has shown me, that exiftool can only write specific xmp tags, and the people tagging tags from windows imaging component do not seem to be part of this.

Where in the image file should I write the information? Can I somehow find this spot programmatically and then just insert the xml there?

I am using Kotlin as programming language but I don't mind having to call command line functions or other programs.

Background: I have a Synology Diskstation and use the included software called photo station. The photo station supports tagging of people on the images and uses this given format. I like the photo station in many ways, but the face recognition is bad, so I want to use my own but have photo station be able to read it.


问:
Count values in a dict of lists and join keys and values names for the output using pandas
I need help getting some outputs from a dictionary (python3):

```<code>{'horse': ['brown', 'black'], 'duck': ['brown', 'black', 'brown', 'grey', 'brown']}
</code>```

Outputs required:

```<code>black horse: 1
brown horse: 1
grey horse: 0
black duck: 1
brown duck: 3
grey duck: 1
</code>```

Can someone offer a solution please?

答:
You can use defaultdict, with default factory set to integer - this acts as a counter on all the entries in the dictionary :</p>
```<code>from collections import defaultdict
d = defaultdict(int)
for k,v in data.items():
    for val in v:
        #combine the key with the individual values in the list
        #and get the tally/count
        d[" ".join((val,k))] += 1

d

defaultdict(int,
            {'brown horse': 1,
             'black horse': 1,
             'brown duck': 3,
             'black duck': 1,
             'grey duck': 1})
</code>```

Body:
I need help getting some outputs from a dictionary (python3):

{'horse': ['brown', 'black'], 'duck': ['brown', 'black', 'brown', 'grey', 'brown']}

Outputs required:

black horse: 1
brown horse: 1
grey horse: 0
black duck: 1
brown duck: 3
grey duck: 1

Can someone offer a solution please?

Body:
You can use defaultdict, with default factory set to integer - this acts as a counter on all the entries in the dictionary :

from collections import defaultdict
d = defaultdict(int)
for k,v in data.items():
    for val in v:
        #combine the key with the individual values in the list
        #and get the tally/count
        d[" ".join((val,k))] += 1

d

defaultdict(int,
            {'brown horse': 1,
             'black horse': 1,
             'brown duck': 3,
             'black duck': 1,
             'grey duck': 1})


问:
Best and shortest way to evaluate mathematical expressions
There are many algorithms to evaluate expressions, for example:

By Recursive Descent

Shunting-yard algorithm

Reverse Polish notation

Is there any way to evaluate any mathematical expression using C# .net reflection or other modern .net technology?

答:
To dynamically compile code using the new Roslyn API's, and load the assembly in a .net core project;

    string finalSource = ...;
    IEnumerable<Assembly> references = ...;

    var compilation = CSharpCompilation.Create("Dynamic",
        new[] {
            SyntaxFactory.ParseSyntaxTree(
                finalSource,
                CSharpParseOptions.Default
                    .WithLanguageVersion(LanguageVersion.Latest)
            ) },
        references.Select(a => MetadataReference.CreateFromFile(a.Location)),

        new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
            .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)
    );

    using var ms = new MemoryStream();
    var e = compilation.Emit(ms);
    if (!e.Success)
        throw new Exception("Compilation failed");
    ms.Seek(0, SeekOrigin.Begin);

    var context = new AssemblyLoadContext(null, true);
    var assembly = context.LoadFromStream(ms);
```

<p>Note that along with any other types required by the source you are compiling. In order to load the compiled assembly within the same process, references will need to include;</p>

<pre class="lang-cs prettyprint-override"><code>    AppDomain.CurrentDomain.GetAssemblies().Where(a => a.GetName().Name == "netstandard").Single(),
    typeof(object).Assembly
</code>```

ContentLicense: CC BY-SA 3.0

Body:
To dynamically compile code using the new Roslyn API's, and load the assembly in a .net core project;

    string finalSource = ...;
    IEnumerable<Assembly> references = ...;

    var compilation = CSharpCompilation.Create("Dynamic",
        new[] {
            SyntaxFactory.ParseSyntaxTree(
                finalSource,
                CSharpParseOptions.Default
                    .WithLanguageVersion(LanguageVersion.Latest)
            ) },
        references.Select(a => MetadataReference.CreateFromFile(a.Location)),

        new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
            .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)
    );

    using var ms = new MemoryStream();
    var e = compilation.Emit(ms);
    if (!e.Success)
        throw new Exception("Compilation failed");
    ms.Seek(0, SeekOrigin.Begin);

    var context = new AssemblyLoadContext(null, true);
    var assembly = context.LoadFromStream(ms);

Note that along with any other types required by the source you are compiling. In order to load the compiled assembly within the same process, references will need to include;

    AppDomain.CurrentDomain.GetAssemblies().Where(a => a.GetName().Name == "netstandard").Single(),
    typeof(object).Assembly


问:
Using polymorphic function as a parameter
I have a function exec which accepts 3 parameters and applies a function f passed as first argument to the other two - p1 and p2.

```<code>  def exec[T](f: (T, T) => Boolean, p1: T, p2: T) = f(p1, p2)
</code>```

Everything works fine if I declare in advance a function which will be passed as an argument.

Somehow compiler can infer types for arguments of eq or in other words it can figure out that whatever in this case is Int

```<code>  // declaring a function with type parameter (polymorphic method)
  def eq[whatever](p1: whatever, p2: whatever) = p1 == p2
  // using a declared function
  println(exec(eq, 10, 10))
</code>```

It also works fine if I explicitly specify Int as shown below

```<code>  // specifying type explicitly in function literal
  println(exec((p1: Int, p2: Int) => p1 == p2, 10, 10))
  // specifying type parameter
  println(exec[Int]((p1, p2) => p1 == p2, 10, 10))
</code>```

Question 1

Is it possible to get below working?

```<code>println(exec((p1, p2) => p1 == p2, 10, 10))
</code>```

For example, by using implicits, defining exec differently or using some other way making it possible for compiler to infer types of p1 and p2 so that it does not fail with missing parameter type.

So no explicit type hints or declared methods are used.

Question 2

How does compiler infer types for eq and why it works for expressions like p1 == p2 or p1 != p2 but fails for p1 >= p2 (error is value >= is not a member of type parameter whatever)?

答:
Scala 3 (dotty) will be able to infer the types in exec without having to rely on multiple parameter lists to help inference

```<code>scala> def exec[T](f: (T, T) => Boolean, p1: T, p2: T) = f(p1, p2)
     | exec((p1, p2) => p1 == p2, 10, 10)
def exec[T](f: (T, T) => Boolean, p1: T, p2: T): Boolean
val res0: Boolean = true
</code>```

Body:
I have a function exec which accepts 3 parameters and applies a function f passed as first argument to the other two - p1 and p2.

  def exec[T](f: (T, T) => Boolean, p1: T, p2: T) = f(p1, p2)

Everything works fine if I declare in advance a function which will be passed as an argument.

Somehow compiler can infer types for arguments of eq or in other words it can figure out that whatever in this case is Int

  // declaring a function with type parameter (polymorphic method)
  def eq[whatever](p1: whatever, p2: whatever) = p1 == p2
  // using a declared function
  println(exec(eq, 10, 10))

It also works fine if I explicitly specify Int as shown below

  // specifying type explicitly in function literal
  println(exec((p1: Int, p2: Int) => p1 == p2, 10, 10))
  // specifying type parameter
  println(exec[Int]((p1, p2) => p1 == p2, 10, 10))

Question 1

Is it possible to get below working?

println(exec((p1, p2) => p1 == p2, 10, 10))

For example, by using implicits, defining exec differently or using some other way making it possible for compiler to infer types of p1 and p2 so that it does not fail with missing parameter type.

So no explicit type hints or declared methods are used.

Question 2

How does compiler infer types for eq and why it works for expressions like p1 == p2 or p1 != p2 but fails for p1 >= p2 (error is value >= is not a member of type parameter whatever)?

Body:
Scala 3 (dotty) will be able to infer the types in exec without having to rely on multiple parameter lists to help inference

scala> def exec[T](f: (T, T) => Boolean, p1: T, p2: T) = f(p1, p2)
     | exec((p1, p2) => p1 == p2, 10, 10)
def exec[T](f: (T, T) => Boolean, p1: T, p2: T): Boolean
val res0: Boolean = true


问:
Data file only saves 12 rows when loc is used to sort database
I am trying to iteratively select the 500 rows and all columns using .loc in pandas. However, the final written file only shows data up to 12 rows of data. First 5 rows and last 5 rows. Middle data is not displayed on the written file. What needs to be done to display all 500 rows ???

Following is code

```<code>"""
Program to
1. load data from a file. Skip the first 52 rows of data from a tab-separated file.
2. Select 500 rows and all columns from the dataset. Write this file.
3. Use the next name for saving the next set of 500 rows and iterate this process for 20 times

"""

import pandas as pd
import numpy as np
import os
import datetime
import shutil
import math
import datetime

b='b'
b=pd.read_csv('Oct4_3.dat',delimiter='\t',skiprows=52)
c=0
d=500

for i in range (1,20):
    a='a'
    filename = 'a'+str(i)+'.dat'

    a=a+str(i)
    print(a)

    a=b.loc[c:d,'# V UG']

    f = open(filename,'a+')
    f.write(" %s \n"%(a))
    c=d+1
    d=d+500
    f.close()

print('done')
</code>```

output of code generates 20 files. One specific file looks like following

答:
What you get in your file seem like the result of the print(a).
To save a pandas dataframe as a csv, use to_csv() method

```<code>a.to_csv('your_csv_filename.csv',index=False)
</code>```

Also, you are saving 501 rows for the first iteration and not 500 (index start at 0 not 1)

Body:
I am trying to iteratively select the 500 rows and all columns using .loc in pandas. However, the final written file only shows data up to 12 rows of data. First 5 rows and last 5 rows. Middle data is not displayed on the written file. What needs to be done to display all 500 rows ???

Following is code

"""
Program to
1. load data from a file. Skip the first 52 rows of data from a tab-separated file.
2. Select 500 rows and all columns from the dataset. Write this file.
3. Use the next name for saving the next set of 500 rows and iterate this process for 20 times

"""

import pandas as pd
import numpy as np
import os
import datetime
import shutil
import math
import datetime

b='b'
b=pd.read_csv('Oct4_3.dat',delimiter='\t',skiprows=52)
c=0
d=500

for i in range (1,20):
    a='a'
    filename = 'a'+str(i)+'.dat'

    a=a+str(i)
    print(a)

    a=b.loc[c:d,'# V UG']

    f = open(filename,'a+')
    f.write(" %s \n"%(a))
    c=d+1
    d=d+500
    f.close()

print('done')

output of code generates 20 files. One specific file looks like following

Body:
What you get in your file seem like the result of the print(a).
To save a pandas dataframe as a csv, use to_csv() method

a.to_csv('your_csv_filename.csv',index=False)

Also, you are saving 501 rows for the first iteration and not 500 (index start at 0 not 1)


问:
Mongock (Mongobee) and Spring Boot in unit test
I have the following dummy class:

```<code>@Document("items")
static class Item {
    int i;

    public Item() {
    }

    public Item(int i) {
        this.i = i;
    }

    public int getI() {
        return i;
    }
}
</code>```

And here's a simple @Changeset:

```<code>//@Autowired
@ChangeSet(order = "001", id = "add_items", author = "tester")
public void changeset1(MongoTemplate mongoTemplate) {
    for (int i = 0; i < NUM_OF_DB_ITEMS; i++) {
        mongoTemplate.insert(new Item(i));
    }
}
</code>```

After @Changeset is called, the unit test is running (Notice that mongoTemplate is @Autowired)

```<code>@Test
public void test() {
    List<Item> items = mongoTemplate.findAll(Item.class);
    System.out.println(items);
}
</code>```

Problem: I'm getting zero items from findAll()

I found that when I'm adding @Autowired to changeset1() it does work (commented above) - I'm getting all items.

Can you explain why? In the examples, I don't see they need to @Autowired

Should I even do that? I mean, can it damage the locking mechanism of Mongock?

答:
I had the same issue and in my case the bean creator/runner had a mispelled package name for the builder atribute "changeLogScanPackage"

```<code>@Bean
public SpringMongock springMongock(MongoTemplate mongoTemplate, Environment springEnvironment) {
  return new SpringMongockBuilder(mongoTemplate, "changeLogScanPackage")
        .setSpringEnvironment(springEnvironment)
      .setLockQuickConfig() OR .setLockConfig(3, 4, 3)
       ...other setters
      .build();
}
</code>```

Body:
I have the following dummy class:

@Document("items")
static class Item {
    int i;

    public Item() {
    }

    public Item(int i) {
        this.i = i;
    }

    public int getI() {
        return i;
    }
}

And here's a simple @Changeset:

//@Autowired
@ChangeSet(order = "001", id = "add_items", author = "tester")
public void changeset1(MongoTemplate mongoTemplate) {
    for (int i = 0; i < NUM_OF_DB_ITEMS; i++) {
        mongoTemplate.insert(new Item(i));
    }
}

After @Changeset is called, the unit test is running (Notice that mongoTemplate is @Autowired)

@Test
public void test() {
    List<Item> items = mongoTemplate.findAll(Item.class);
    System.out.println(items);
}

Problem: I'm getting zero items from findAll()

I found that when I'm adding @Autowired to changeset1() it does work (commented above) - I'm getting all items.

Can you explain why? In the examples, I don't see they need to @Autowired

Should I even do that? I mean, can it damage the locking mechanism of Mongock?

Body:
I had the same issue and in my case the bean creator/runner had a mispelled package name for the builder atribute "changeLogScanPackage"

@Bean
public SpringMongock springMongock(MongoTemplate mongoTemplate, Environment springEnvironment) {
  return new SpringMongockBuilder(mongoTemplate, "changeLogScanPackage")
        .setSpringEnvironment(springEnvironment)
      .setLockQuickConfig() OR .setLockConfig(3, 4, 3)
       ...other setters
      .build();
}


问:
Java HTTP getResponseCode returns 200 for non-existent URL
I was expecting this code to return a 404, however it produces the output :

"Response code is 200"

Would it be possible to learn how to differentiate between existent and non-existent web pages . . . thanks so much,

```<code>    try
    {
    // create the HttpURLConnection
    URL url = new URL("http://www.thisurldoesnotexist");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    System.out.println("Response code is " + connection.getResponseCode());
    }
</code>```

答:
Ideally you should be getting this error:

```<code>java.net.UnknownHostException: www.thisurldoesnotexist
</code>```

But it looks like your URL is resolved by you DNS provider.

For instance on my company's network running your code with URI "http://profile/" displays
the employee profile.

Please also check etc.home file if you are on windows to check if any settings have been changed.

Body:
I was expecting this code to return a 404, however it produces the output :

"Response code is 200"

Would it be possible to learn how to differentiate between existent and non-existent web pages . . . thanks so much,

    try
    {
    // create the HttpURLConnection
    URL url = new URL("http://www.thisurldoesnotexist");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    System.out.println("Response code is " + connection.getResponseCode());
    }

Body:
Ideally you should be getting this error:

java.net.UnknownHostException: www.thisurldoesnotexist

But it looks like your URL is resolved by you DNS provider.

For instance on my company's network running your code with URI "http://profile/" displays
the employee profile.

Please also check etc.home file if you are on windows to check if any settings have been changed.


问:
How to continue using gdb to debug c++ code after reconnecting to remote Ubuntu machine using ssh?
My local machine is of Windows 10 and I have a bad network condition.

So when I ssh to log in remote Ubuntu machine, and try to debug using gdb, which costs perhaps 30 minutes to the breakpoint, I often get connection close error.

And when I ssh again, I have to start over.

Is there a recoverable function of gdb so that I can continue using it after reconnecting?

答:
Is there a recoverable function of gdb so that I can continue using it after reconnecting?

No.

You need to use a program designed to keep your session alive: tmux or screen. Spending time learning to use them well now will pay for itself many times over.


问:
How to make work a function inside a for statement?
I'm having a problem with this exercise. They first asked me to write a code to detect if a number is a prime number. This worked pretty well with this piece of code down here:

```<code>def primo(n):
  resultado = False
  div = 2
  while div**2 <= n:

    if n == 1:
        resultado = False
        div+=1
    if n%div == 0:
      resultado = False
      return resultado
      div**2 > n
    else:
      resultado = True

    div+=1

  return(resultado)
</code>```

After this, the exercise is asking me to write a for loop to check if any number between 1 and 20 is a prime, so i wrote:

```<code>for n in range(1,21):
    primo(n)
</code>```

and nothing happens, why is this?

答:
primo return a boolean indicating if the number is prime, but you don't do anything with that value so you never see the result. You probably want something like:

```<code>for n in range(1, 21):
    is_prime = primo(n)
    print('{} is prime? {}'.format(n, is_prime))
</code>```

Body:
I'm having a problem with this exercise. They first asked me to write a code to detect if a number is a prime number. This worked pretty well with this piece of code down here:

def primo(n):
  resultado = False
  div = 2
  while div**2 <= n:

    if n == 1:
        resultado = False
        div+=1
    if n%div == 0:
      resultado = False
      return resultado
      div**2 > n
    else:
      resultado = True

    div+=1

  return(resultado)

After this, the exercise is asking me to write a for loop to check if any number between 1 and 20 is a prime, so i wrote:

for n in range(1,21):
    primo(n)

and nothing happens, why is this?

Body:
primo return a boolean indicating if the number is prime, but you don't do anything with that value so you never see the result. You probably want something like:

for n in range(1, 21):
    is_prime = primo(n)
    print('{} is prime? {}'.format(n, is_prime))


问:
Quicksort not sorting the lower half
I am new to programming and trying to do Udacity's quicksort practice. But my code doesn't quite do it.

Something might be wrong with how I assign low and high in the quicksort function, but I don't know how to fix it.

```<code># this returns a sorted array
def quicksort(array):
    low = 0
    high = len(array) - 1
    if low >= high:
        return array
    pi = partition(array, low, high)
    array[:pi-1] = quicksort(array[:pi-1])
    array[pi+1:] = quicksort(array[pi+1:])
    return array

# this places the pivot in the right position in the array.
# all elements smaller than the pivot are moved to the left of it.
def partition(array, low, high):
    border = low
    pivot = array[high]
    for i in range(low, high):
        if array[i] <= pivot:
            array[border], array[i] = array[i], array[border]
            border += 1
    array[border], array[high] = array[high], array[border]
    return border

test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
print quicksort(test)
</code>```

Expected answer: [1, 3, 4, 6, 9, 14, 20, 21, 21, 25]

What I got: [1, 4, 3, 9, 6, 14, 20, 21, 21, 25]

答:
To get the lower half of the array you need to do array[:pi] not array[:pi-1]. The end index is exclusive. If you change the line to:

```<code>array[:pi] = quicksort(array[:pi])
</code>```

your algorithm works: repl.it link

Title: Quicksort not sorting the lower half

Body:
I am new to programming and trying to do Udacity's quicksort practice. But my code doesn't quite do it.

Something might be wrong with how I assign low and high in the quicksort function, but I don't know how to fix it.

# this returns a sorted array
def quicksort(array):
    low = 0
    high = len(array) - 1
    if low >= high:
        return array
    pi = partition(array, low, high)
    array[:pi-1] = quicksort(array[:pi-1])
    array[pi+1:] = quicksort(array[pi+1:])
    return array

# this places the pivot in the right position in the array.
# all elements smaller than the pivot are moved to the left of it.
def partition(array, low, high):
    border = low
    pivot = array[high]
    for i in range(low, high):
        if array[i] <= pivot:
            array[border], array[i] = array[i], array[border]
            border += 1
    array[border], array[high] = array[high], array[border]
    return border

test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
print quicksort(test)

Expected answer: [1, 3, 4, 6, 9, 14, 20, 21, 21, 25]

What I got: [1, 4, 3, 9, 6, 14, 20, 21, 21, 25]

Body:
To get the lower half of the array you need to do array[:pi] not array[:pi-1]. The end index is exclusive. If you change the line to:

array[:pi] = quicksort(array[:pi])

your algorithm works: repl.it link


问:
Flux to List<Objects> without blocking
Looking for converting Flux to List<Object>. Getting error if I use block(). So, need to conver without blocking calls.

```<code>Flux.from(Collection.find())
</code>```

Using reactive programming, but graphql expects List<objects> and erroring with returning Flux.

Code with Block()

```<code>public List<Test> findAll() {
        return Flux.from(testCollection.find()).collectList().block();

}
</code>```

Error :-

```<code>block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-kqueue-7
</code>```

Here, I need to return List<Test> as I can not send Flux<Test> for some reason.

答:
As stated in the comments, You can't. The reactive pattern is to stay in a flow.

So,

```<code>Mono<GraphqlResponse> = Flux.just("A", "B" "C")
  .collectList()
  .map(this::someMethod);

GraphqlResponse someMethod(List<String> abcs) {
    return graphQl.doSomething(abcs);
}
</code>```

Title: Flux to List<Objects> without blocking

Body:
Looking for converting Flux to List<Object>. Getting error if I use block(). So, need to conver without blocking calls.

Flux.from(Collection.find())

Using reactive programming, but graphql expects List<objects> and erroring with returning Flux.

Code with Block()

public List<Test> findAll() {
        return Flux.from(testCollection.find()).collectList().block();

}

Error :-

block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-kqueue-7

Here, I need to return List<Test> as I can not send Flux<Test> for some reason.

Body:
As stated in the comments, You can't. The reactive pattern is to stay in a flow.

So,

Mono<GraphqlResponse> = Flux.just("A", "B" "C")
  .collectList()
  .map(this::someMethod);

GraphqlResponse someMethod(List<String> abcs) {
    return graphQl.doSomething(abcs);
}


问:
BeautifulSoup find_all('href') returns only part of the value
I'm attempting to scrape actor/actress IDs from an IMDB movie page. I only want actors and actresses (I don't want to get any of the crew), and this question is specifically about getting the person's internal ID. I already have peoples' names, so I don't need help getting those. I'm starting with this webpage (https://www.imdb.com/title/tt0084726/fullcredits?ref_=tt_cl_sm#cast) as a hard-coded url to get the code right.

On examination of the links I was able to find that the links for the actors look like this.

```<code><a href="/name/nm0000638/?ref_=ttfc_fc_cl_t1"> William Shatner</a>
<a href="/name/nm0000559/?ref_=ttfc_fc_cl_t2"> Leonard Nimoy</a>
<a href="/name/nm0346415/?ref_=ttfc_fc_cl_t17"> Nicholas Guest</a>
</code>```

while the ones for other contributors look like this

```<code><a href="/name/nm0583292/?ref_=ttfc_fc_dr1"> Nicholas Meyer </a>
<a href="/name/nm0734472/?ref_=ttfc_fc_wr1"> Gene Roddenberry</a>
</code>```

This should allow me to differentiate actors/actresses from crew like the director or writer by checking for the end of the href being "t[0-9]+$" rather than the same but with "dr" or "wr".

Here's the code I'm running.

```<code>import urllib.request
from bs4 import BeautifulSoup
import re

movieNumber = 'tt0084726'
url = 'https://www.imdb.com/title/' + movieNumber + '/fullcredits?ref_=tt_cl_sm#cast'

def clearLists(n):
    return [[] for _ in range(n)]

def getSoupObject(urlInput):
    page = urllib.request.urlopen(urlInput).read()
    soup = BeautifulSoup(page, features="html.parser")
    return(soup)

def getPeopleForMovie(soupObject):
    listOfPeopleNames, listOfPeopleIDs, listOfMovieIDs = clearLists(3)

    #get all the tags with links in them
    link_tags = soupObject.find_all('a')

    #get the ids of people
    for linkTag in link_tags:
        link = str(linkTag.get('href'))
        #print(link)
        p = re.compile('t[0-9]+$')
        q = p.search(link)
        if link.startswith('/name/') and q != None:
            id = link[6:15]
            #print(id)
            listOfPeopleIDs.append(id)

    #return the names and IDs
    return listOfPeopleNames, listOfPeopleIDs

newSoupObject = getSoupObject(url)
pNames, pIds = getPeopleForMovie(newSoupObject)
</code>```

The above code returns an empty list for the IDs, and if you uncomment the print statement you can see that it's because the value that gets put in the "link" variable ends up being what's below (with variations for the specific people)

```<code>/name/nm0583292/
/name/nm0000638/
</code>```

That won't do. I want the IDs only for the actors and actresses so that I can use those IDs later.
I've tried to find other answers on stackoverflow; I haven't been able to find this particular issue.

This question (Beautifulsoup: parsing html – get part of href) is close to what I want to do, but it gets the info from the text part between tags rather than from the href part in the tag attribute.

How can I make sure I get only the name IDs that I want (just the actor ones) from the page?
(Also, feel free to offer suggestions to tighten up the code)

答:
It appears that the links you are trying to match have either been modified by JavaScript after loading, or perhaps get loaded differently based on other variables than the URL alone (like cookies or headers).

However, since you're only after links of people in the cast, an easier way would be to simply match the ids of people in the cast section. This is actually fairly straightforward, since they are all in a single element,

So:

```<code>import urllib.request
from bs4 import BeautifulSoup
import re

# it's Python, so use Python conventions, no uppercase in function or variable names
movie_number = 'tt0084726'
# The f-string is often more readable than a + concatenation
url = f'https://www.imdb.com/title/{movieNumber}/fullcredits?ref_=tt_cl_sm#cast'

# this is overly fancy for something as simple as initialising some variables
# how about:
# a, b, c = [], [], []
# def clearLists(n):
#     return [[] for _ in range(n)]

# in an object-oriented program, assuming something is an object is the norm
def get_soup(url_input):
    page = urllib.request.urlopen(url_input).read()
    soup = BeautifulSoup(page, features="html.parser")
    # removed needless parentheses - arguably, even `soup` is superfluous:
    # return BeautifulSoup(page, features="html.parser")
    return soup

# keep two empty lines between functions, it's standard and for good reason
# it's easier to spot where a function starts and stops
# try using an editor or IDE that highlights your PEP8 mistakes, like PyCharm
# (that's just my opinion there, other IDEs than PyCharm will do as well)
def get_people_for_movie(soup_object):
    # removed unused variables, also 'list_of_people_ids' is needlessly verbose
    # since they go together, why not return people as a list of tuples, or a dictionary?
    # I'd prefer a dictionary as it automatically gets rid of duplicates as well
    people = {}

    # (put a space at the start of your comment blocks!)
    # get all the anchors tags inside the `cast_list` table
    link_tags = soup_object.find('table', class_='cast_list').find_all('a')

    # the whole point of compiling the regex is to only have to do it once,
    # so outside the loop
    id_regex = re.compile(r'/name/nm(\d+)/')

    # get the ids and names of people
    for link_tag in link_tags:
        # the href attributes is a strings, so casting with str() serves no purpose
        href = link_tag.get('href')
        # matching and extracting part of the match can all be done in one step:
        match = id_regex.search(href)
        if match:
            # don't shadow Python keywords like `id` with variable names!
            identifier = match.group(1)
            name = link_tag.text.strip()
            # just ignore the ones with no text, they're the thumbs
            if name:
                people[identifier] = name

    # return the names and IDs
    return people

def main():
    # don't do stuff globally, it'll just cause problems when reusing names in functions
    soup = get_soup(url)
    people = get_people_for_movie(soup)
    print(people)

# not needed here, but a good habit, allows you to import stuff without running the main
if __name__ == '__main__':
    main()
</code>```

Result:

```<code>{'0000638': 'William Shatner', '0000559': 'Leonard Nimoy', '0001420': 'DeForest Kelley', etc.
</code>```

And the code with a few more tweaks and without the commentary on your code:

```<code>import urllib.request
from bs4 import BeautifulSoup
import re

def get_soup(url_input):
    page = urllib.request.urlopen(url_input).read()
    return BeautifulSoup(page, features="html.parser")

def get_people_for_movie(soup_object):
    people = {}

    link_tags = soup_object.find('table', class_='cast_list').find_all('a')

    id_regex = re.compile(r'/name/nm(\d+)/')

    # get the ids and names of the cast
    for link_tag in link_tags:
        match = id_regex.search(link_tag.get('href'))
        if match:
            name = link_tag.text.strip()
            if name:
                people[match.group(1)] = name

    return people

def main():
    movie_number = 'tt0084726'
    url = f'https://www.imdb.com/title/{movie_number}/fullcredits?ref_=tt_cl_sm#cast'

    people = get_people_for_movie(get_soup(url))
    print(people)

if __name__ == '__main__':
    main()
</code>```

Body:
I'm attempting to scrape actor/actress IDs from an IMDB movie page. I only want actors and actresses (I don't want to get any of the crew), and this question is specifically about getting the person's internal ID. I already have peoples' names, so I don't need help getting those. I'm starting with this webpage (https://www.imdb.com/title/tt0084726/fullcredits?ref_=tt_cl_sm#cast) as a hard-coded url to get the code right.

On examination of the links I was able to find that the links for the actors look like this.

 William Shatner
 Leonard Nimoy
 Nicholas Guest

while the ones for other contributors look like this

 Nicholas Meyer
 Gene Roddenberry

This should allow me to differentiate actors/actresses from crew like the director or writer by checking for the end of the href being "t[0-9]+$" rather than the same but with "dr" or "wr".

Here's the code I'm running.

import urllib.request
from bs4 import BeautifulSoup
import re

movieNumber = 'tt0084726'
url = 'https://www.imdb.com/title/' + movieNumber + '/fullcredits?ref_=tt_cl_sm#cast'

def clearLists(n):
    return [[] for _ in range(n)]

def getSoupObject(urlInput):
    page = urllib.request.urlopen(urlInput).read()
    soup = BeautifulSoup(page, features="html.parser")
    return(soup)

def getPeopleForMovie(soupObject):
    listOfPeopleNames, listOfPeopleIDs, listOfMovieIDs = clearLists(3)

    #get all the tags with links in them
    link_tags = soupObject.find_all('a')

    #get the ids of people
    for linkTag in link_tags:
        link = str(linkTag.get('href'))
        #print(link)
        p = re.compile('t[0-9]+$')
        q = p.search(link)
        if link.startswith('/name/') and q != None:
            id = link[6:15]
            #print(id)
            listOfPeopleIDs.append(id)

    #return the names and IDs
    return listOfPeopleNames, listOfPeopleIDs

newSoupObject = getSoupObject(url)
pNames, pIds = getPeopleForMovie(newSoupObject)

The above code returns an empty list for the IDs, and if you uncomment the print statement you can see that it's because the value that gets put in the "link" variable ends up being what's below (with variations for the specific people)

/name/nm0583292/
/name/nm0000638/

That won't do. I want the IDs only for the actors and actresses so that I can use those IDs later.
I've tried to find other answers on stackoverflow; I haven't been able to find this particular issue.

This question (Beautifulsoup: parsing html – get part of href) is close to what I want to do, but it gets the info from the text part between tags rather than from the href part in the tag attribute.

How can I make sure I get only the name IDs that I want (just the actor ones) from the page?
(Also, feel free to offer suggestions to tighten up the code)

Body:
It appears that the links you are trying to match have either been modified by JavaScript after loading, or perhaps get loaded differently based on other variables than the URL alone (like cookies or headers).

However, since you're only after links of people in the cast, an easier way would be to simply match the ids of people in the cast section. This is actually fairly straightforward, since they are all in a single element, <table class="cast_list">

So:

import urllib.request
from bs4 import BeautifulSoup
import re

# it's Python, so use Python conventions, no uppercase in function or variable names
movie_number = 'tt0084726'
# The f-string is often more readable than a + concatenation
url = f'https://www.imdb.com/title/{movieNumber}/fullcredits?ref_=tt_cl_sm#cast'

# this is overly fancy for something as simple as initialising some variables
# how about:
# a, b, c = [], [], []
# def clearLists(n):
#     return [[] for _ in range(n)]

# in an object-oriented program, assuming something is an object is the norm
def get_soup(url_input):
    page = urllib.request.urlopen(url_input).read()
    soup = BeautifulSoup(page, features="html.parser")
    # removed needless parentheses - arguably, even `soup` is superfluous:
    # return BeautifulSoup(page, features="html.parser")
    return soup

# keep two empty lines between functions, it's standard and for good reason
# it's easier to spot where a function starts and stops
# try using an editor or IDE that highlights your PEP8 mistakes, like PyCharm
# (that's just my opinion there, other IDEs than PyCharm will do as well)
def get_people_for_movie(soup_object):
    # removed unused variables, also 'list_of_people_ids' is needlessly verbose
    # since they go together, why not return people as a list of tuples, or a dictionary?
    # I'd prefer a dictionary as it automatically gets rid of duplicates as well
    people = {}

    # (put a space at the start of your comment blocks!)
    # get all the anchors tags inside the `cast_list` table
    link_tags = soup_object.find('table', class_='cast_list').find_all('a')

    # the whole point of compiling the regex is to only have to do it once,
    # so outside the loop
    id_regex = re.compile(r'/name/nm(\d+)/')

    # get the ids and names of people
    for link_tag in link_tags:
        # the href attributes is a strings, so casting with str() serves no purpose
        href = link_tag.get('href')
        # matching and extracting part of the match can all be done in one step:
        match = id_regex.search(href)
        if match:
            # don't shadow Python keywords like `id` with variable names!
            identifier = match.group(1)
            name = link_tag.text.strip()
            # just ignore the ones with no text, they're the thumbs
            if name:
                people[identifier] = name

    # return the names and IDs
    return people

def main():
    # don't do stuff globally, it'll just cause problems when reusing names in functions
    soup = get_soup(url)
    people = get_people_for_movie(soup)
    print(people)

# not needed here, but a good habit, allows you to import stuff without running the main
if __name__ == '__main__':
    main()

Result:

{'0000638': 'William Shatner', '0000559': 'Leonard Nimoy', '0001420': 'DeForest Kelley', etc.

And the code with a few more tweaks and without the commentary on your code:

import urllib.request
from bs4 import BeautifulSoup
import re

def get_soup(url_input):
    page = urllib.request.urlopen(url_input).read()
    return BeautifulSoup(page, features="html.parser")

def get_people_for_movie(soup_object):
    people = {}

    link_tags = soup_object.find('table', class_='cast_list').find_all('a')

    id_regex = re.compile(r'/name/nm(\d+)/')

    # get the ids and names of the cast
    for link_tag in link_tags:
        match = id_regex.search(link_tag.get('href'))
        if match:
            name = link_tag.text.strip()
            if name:
                people[match.group(1)] = name

    return people

def main():
    movie_number = 'tt0084726'
    url = f'https://www.imdb.com/title/{movie_number}/fullcredits?ref_=tt_cl_sm#cast'

    people = get_people_for_movie(get_soup(url))
    print(people)

if __name__ == '__main__':
    main()


答:
Your function primo() is returning a boolean which is either True or False. You are not doing anything with that return value. You can do something like that

```<code>for n in range(1,21):
    out=primo(n)
    print(out) #or whatever you want
</code>```

There is a problem in you primo function as well. For n=2 & n=3 it will not enter the loop and 3 will show as a non-prime number. I have modified that a little bit.

```<code>def primo(n):
  resultado = False
  div = 2
  if n == 1:
    resultado = False
    return(resultado)

  while div**2 <= n:
    if n%div == 0:
      resultado = False
      return resultado
    div+=1
</code>```

Title: How to make work a function inside a for statement?

Body:
Your function primo() is returning a boolean which is either True or False. You are not doing anything with that return value. You can do something like that

for n in range(1,21):
    out=primo(n)
    print(out) #or whatever you want

There is a problem in you primo function as well. For n=2 & n=3 it will not enter the loop and 3 will show as a non-prime number. I have modified that a little bit.

def primo(n):
  resultado = False
  div = 2
  if n == 1:
    resultado = False
    return(resultado)

  while div**2 <= n:
    if n%div == 0:
      resultado = False
      return resultado
    div+=1


问:
Get form name from iframe using AutoIt
I am using AutoIt to automate filling in forms on a website.

But I am having a problem getting the form name from a website. I look at the source of the HTML and find form and its name, but I still get a IEStatus_noMatch error.

Is there an easier way to get the form name or how to find it out?

I might face this same problem for objects.

```<code>$sUrl = "https://www.acgme.org/residentdatacollection/login.asp"
$oIE = _IEAttach($sUrl, "url")
If not isObj($oIE) Then
    $oIE = _IECreate()
    _IENavigate($oIE, $sUrl)
EndIf

; Get pointers to the login form and username and password fields
$o_form = _IEFormGetObjByName($oIE, "loginentry")
$o_login = _IEFormElementGetObjByName($o_form, "USERID")
$o_password = _IEFormElementGetObjByName($o_form, "PASSW")
</code>```

答: You are using the wrong function to get the form object... _IEForm*Element*GetObjByName is for form sub-elements. You should use the _IEFormGetObjByName function instead.

Title: Get form name from iframe using AutoIt

Body:
I am using AutoIt to automate filling in forms on a website.

But I am having a problem getting the form name from a website. I look at the source of the HTML and find form and its name, but I still get a IEStatus_noMatch error.

Is there an easier way to get the form name or how to find it out?

I might face this same problem for objects.

$sUrl = "https://www.acgme.org/residentdatacollection/login.asp"
$oIE = _IEAttach($sUrl, "url")
If not isObj($oIE) Then
    $oIE = _IECreate()
    _IENavigate($oIE, $sUrl)
EndIf

; Get pointers to the login form and username and password fields
$o_form = _IEFormGetObjByName($oIE, "loginentry")
$o_login = _IEFormElementGetObjByName($o_form, "USERID")
$o_password = _IEFormElementGetObjByName($o_form, "PASSW")


问:
How to pass different input to a class function
I have two different classes in Django rest framework who do exact same thing but with different data. Access to that data variable is only inside a specific function.
Currently I have explicitly writing two separate classes. How can I consolidate it into one class and inherit from it by just passing a separate argument.

```<code>from rest_framework import permissions
class CreateOrUpdateInSameSchool1(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in ('POST', 'PUT','PATCH'):
            return self.request.user.school.id == obj.xyz.school.id  # Different !!
        else:
            return True

class CreateOrUpdateInSameSchool2(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in ('POST', 'PUT','PATCH'):
            return self.request.user.school.id == obj.mno.school.id  # Different !!
        else:
            return True
</code>```

obj variable is only available inside function has_object_permission

答:
Are you trying to do something like this? I know it's ugly but may improve:

```<code>from rest_framework import permissions
class CreateOrUpdateInSameSchool(permissions.BasePermission):
    def __init__(self, school_id_type):
        self.school_id_type = school_id_type
    def has_object_permission(self, request, view, obj):
        if request.method in ('POST', 'PUT','PATCH'):
            if self.school_id_type == "xyz":
                return self.request.user.school.id == obj.xyz.school.id  # Different !!
            elif self.school_id_type == "mno":
                return self.request.user.school.id == obj.mno.school.id  # Different !!
            else:
                return None
        else:
            return True
</code>```

Or you can use operator.attrgetter():

```<code>from rest_framework import permissions
from operator import attrgetter

class CreateOrUpdateInSameSchool(permissions.BasePermission):
    def __init__(self, school_id_type: str):
        self.school_id_type = school_id_type
    def has_object_permission(self, request, view, obj):
        s_id_type = attrgetter(self.school_id_type, 'school', 'id')(obj)
        if request.method in ('POST', 'PUT','PATCH'):
            return self.request.user.school.id == s_id_type  # Different !!
        else:
            return True
</code>```

Both ways, you need to specify what kind of return object would you like when you're calling the class like this:

```<code>foo = CreateOrUpdateInSameSchool(school_id_type='xyz')
# or
bar = CreateOrUpdateInSameSchool(school_id_type='mno')
</code>```

Body:
I have two different classes in Django rest framework who do exact same thing but with different data. Access to that data variable is only inside a specific function.
Currently I have explicitly writing two separate classes. How can I consolidate it into one class and inherit from it by just passing a separate argument.

from rest_framework import permissions
class CreateOrUpdateInSameSchool1(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in ('POST', 'PUT','PATCH'):
            return self.request.user.school.id == obj.xyz.school.id  # Different !!
        else:
            return True

class CreateOrUpdateInSameSchool2(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in ('POST', 'PUT','PATCH'):
            return self.request.user.school.id == obj.mno.school.id  # Different !!
        else:
            return True

obj variable is only available inside function has_object_permission

Body:
Are you trying to do something like this? I know it's ugly but may improve:

from rest_framework import permissions
class CreateOrUpdateInSameSchool(permissions.BasePermission):
    def __init__(self, school_id_type):
        self.school_id_type = school_id_type
    def has_object_permission(self, request, view, obj):
        if request.method in ('POST', 'PUT','PATCH'):
            if self.school_id_type == "xyz":
                return self.request.user.school.id == obj.xyz.school.id  # Different !!
            elif self.school_id_type == "mno":
                return self.request.user.school.id == obj.mno.school.id  # Different !!
            else:
                return None
        else:
            return True

Or you can use operator.attrgetter():

from rest_framework import permissions
from operator import attrgetter

class CreateOrUpdateInSameSchool(permissions.BasePermission):
    def __init__(self, school_id_type: str):
        self.school_id_type = school_id_type
    def has_object_permission(self, request, view, obj):
        s_id_type = attrgetter(self.school_id_type, 'school', 'id')(obj)
        if request.method in ('POST', 'PUT','PATCH'):
            return self.request.user.school.id == s_id_type  # Different !!
        else:
            return True

Both ways, you need to specify what kind of return object would you like when you're calling the class like this:

foo = CreateOrUpdateInSameSchool(school_id_type='xyz')
# or
bar = CreateOrUpdateInSameSchool(school_id_type='mno')


问:
How to add an assembly reference in unit test project?
I want to add a reference to an assembly in my unit test project, because it has to be referenced in order to call the method to be tested, but... I can't. I don't have the option to do so in the "Add reference" window in Visual Studio. I can only add Project references or Browse for dll references (see image below, left is unit test project and right is the app project's "Add reference" window)

I have the error "The type is defined in an assembly that is not referenced. You must add a reference to the assembly.", but when I go ahead and use the quick action to do so, nothing happens.

Why can't I add a reference to the assembly and is there another way around the missing assembly issue?

Note: Using Visual Studio 2017

答:
Following the discussion with @Dai, the assembly references weren't available because an NUnit Test Project created in Visual Studio is created using .NET Core rather than .NET Framework.

To have access to .NET Framework assemblies, you need to create a .NET Framework Unit Test Project and then replace the MS Test Framework with the NUnit Test Framework.


问:
applying user defined function without for loop
I am trying to use a custom function to solve for multiple permutations of the arguments.

The function (yield.n) works fine when I call it one time such as:
yield.n(naa, F, M, S, Y)
naa is a large data frame (750000 x 17), F, M, and Y are numeric objects and S is a vector.

I would like to solve with this function for various values of Y. I tried multiple permutations of the apply family, but I cannot come up with functional code.
If I run a for loop for values of Y (code blow) it solves correctly but is very slow.

```<code>yn.out <- NULL
    for(yr in 50:150){
           yr.out <- yield.n(naa, ssf, M, S, yr)
           yr.out <- cbind(yr.out, yr)
           yn.out <- rbind(yn.out, yr.out)
        }

yn.out <- as.data.frame(yn.out)
</code>```

How do I get an apply function to work on this to solve for multiple values of Y?

The code for the function is as follows (but I am not sure that is relevant to the problem at hand).

```<code>function(naa, F, M, S, Y){
    yr <- Y
    naa.lci <- aggregate(naa[, 1:16], list(naa$year),
                         "quantile", probs = .05)
    naa.m   <-  aggregate(naa[, 1:16], list(naa$year),
                          "quantile", probs = .5)
    naa.uci <- aggregate(naa[, 1:16], list(naa$year),
                         "quantile", probs = .9)
    yield.n.lci <- round(sum(((F*S)/(M + (F*S))) * (1- exp(-M-(F*S))) *
                             naa.lci[yr, 2:17]))
    yield.n.m   <- round(sum(((F*S)/(M + (F*S))) * (1- exp(-M-(F*S))) *
                             naa.m[yr, 2:17]))
    yield.n.uci <- round(sum(((F*S)/(M + (F*S))) * (1- exp(-M-(F*S))) *
                             naa.uci[yr, 2:17]))
    yield.out <- cbind(yield.n.lci, yield.n.m, yield.n.uci)
    return(yield.out)
}
</code>```

答:
Try the following :

```<code>yn.out <- do.call(rbind, lapply(50:150, function(y)
                  cbind(yield.n(naa, F, M, S, y), yr = y)))
</code>```

Or using purrr::map_df

```<code>yn.out <- purrr::map_df(50:150, ~cbind(yield.n(naa, F, M, S, .x), yr = .x))
</code>```

Body:
I am trying to use a custom function to solve for multiple permutations of the arguments.

The function (yield.n) works fine when I call it one time such as:
yield.n(naa, F, M, S, Y)
naa is a large data frame (750000 x 17), F, M, and Y are numeric objects and S is a vector.

I would like to solve with this function for various values of Y. I tried multiple permutations of the apply family, but I cannot come up with functional code.
If I run a for loop for values of Y (code blow) it solves correctly but is very slow.

yn.out <- NULL
    for(yr in 50:150){
           yr.out <- yield.n(naa, ssf, M, S, yr)
           yr.out <- cbind(yr.out, yr)
           yn.out <- rbind(yn.out, yr.out)
        }

yn.out <- as.data.frame(yn.out)

How do I get an apply function to work on this to solve for multiple values of Y?

The code for the function is as follows (but I am not sure that is relevant to the problem at hand).

function(naa, F, M, S, Y){
    yr <- Y
    naa.lci <- aggregate(naa[, 1:16], list(naa$year),
                         "quantile", probs = .05)
    naa.m   <-  aggregate(naa[, 1:16], list(naa$year),
                          "quantile", probs = .5)
    naa.uci <- aggregate(naa[, 1:16], list(naa$year),
                         "quantile", probs = .9)
    yield.n.lci <- round(sum(((F*S)/(M + (F*S))) * (1- exp(-M-(F*S))) *
                             naa.lci[yr, 2:17]))
    yield.n.m   <- round(sum(((F*S)/(M + (F*S))) * (1- exp(-M-(F*S))) *
                             naa.m[yr, 2:17]))
    yield.n.uci <- round(sum(((F*S)/(M + (F*S))) * (1- exp(-M-(F*S))) *
                             naa.uci[yr, 2:17]))
    yield.out <- cbind(yield.n.lci, yield.n.m, yield.n.uci)
    return(yield.out)
}

Body:
Try the following :

yn.out <- do.call(rbind, lapply(50:150, function(y)
                  cbind(yield.n(naa, F, M, S, y), yr = y)))

Or using purrr::map_df

yn.out <- purrr::map_df(50:150, ~cbind(yield.n(naa, F, M, S, .x), yr = .x))


问:
xbee ansi C library endpoint example
Wondering if anyone has a full working example of how to make a ZCL endpoint using Digi's Xbee ANSI C Library ?
The samples directory in that repo has some things, the commission server sample is helpful but I'd love to see an example of the library actually being used for something real.

What I'm trying to make here is a simple sensor to interface with an existing Zigbee network (the coordinator being zigbee2mqtt with a cc2531 in my case) to report readings to home assistant.

I've seen mentions of a "xbee custom endpoint" example on the Digi forum, but I couldn't find that example, it sounds like that'd be exactly what I need.

Thanks

答:
The Commissioning Client and Server samples are overkill for just getting started, but they are used for "something real".  The Commissioning Cluster is a part of the Zigbee spec.

You might want to look at zcl_comm_startup_attributes and zcl_comm_startup_attribute_tree in src/zigbee/zcl_commissioning.c to see how you can set up an attribute tree for your cluster.

Perhaps look at include/zigbee/zcl_basic_attributes.h and samples/common/_zigbee_walker.c on how to set up the endpoint table with a Basic cluster and its attributes.  The Zigbee Walker sample shows how to use ZDO/ZDP queries to enumerate endpoints, and then ZCL queries to enumerate clusters and attributes.  You can use that sample to validate the endpoint/cluster/attribute table that you've set up in a particular program.

You might want to spend some time reading through the Zigbee Cluster Library specification to understand the concept of endpoints, clusters and attributes, which may help you to understand the tables you need to set up in your program to implement them.

Title: xbee ansi C library endpoint example


问:
Api key authentication for coinbase
I'm trying to write a request for API coinbase.com, but I can not correctly generate a signature. I've been trying to find my mistake for 2 days, but I can not. I analyzed the code for other languages on the page: https://developers.coinbase.com/docs/wallet/api-key-autumnicathion but I do not see any differences in implementation.

Help me please.

```<code><?php
$g_coinbase_key = 'KcxisxqmWRVgtwsj';
$g_coinbase_secret = 'isOLGBLaEkCy3ROQMvmjonGmXK0KRmUS';

$time = time();
$method = "GET";
$path = '/v2/accounts/';
$sign = base64_encode(hash_hmac("sha256", $time.$method.$path, $g_coinbase_secret));
$ch = curl_init('https://api.coinbase.com'.$path);
$headers = array(
    "CB-VERSION: 2017-10-26",
    "CB-ACCESS-SIGN: ".$sign,
    "CB-ACCESS-TIMESTAMP: ".$time,
    "CB-ACCESS-KEY: ".$g_coinbase_key,
    "Content-Type: application/json"
);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
var_dump($result);
?>
</code>```

Result:

```<code>{"errors":[{"id":"authentication_error","message":"invalid signature"}]}
</code>```

答:
Replace

```<code>$sign = base64_encode(hash_hmac("sha256", $time.$method.$path, $g_coinbase_secret));
</code>```

with

```<code>$sign = hash_hmac("sha256", $time.$method.$path, $g_coinbase_secret);
</code>```

Coibase Api uses hash_mac

Title: Api key authentication for coinbase

Body:
I'm trying to write a request for API coinbase.com, but I can not correctly generate a signature. I've been trying to find my mistake for 2 days, but I can not. I analyzed the code for other languages on the page: https://developers.coinbase.com/docs/wallet/api-key-autumnicathion but I do not see any differences in implementation.

Help me please.

<?php
$g_coinbase_key = 'KcxisxqmWRVgtwsj';
$g_coinbase_secret = 'isOLGBLaEkCy3ROQMvmjonGmXK0KRmUS';

$time = time();
$method = "GET";
$path = '/v2/accounts/';
$sign = base64_encode(hash_hmac("sha256", $time.$method.$path, $g_coinbase_secret));
$ch = curl_init('https://api.coinbase.com'.$path);
$headers = array(
    "CB-VERSION: 2017-10-26",
    "CB-ACCESS-SIGN: ".$sign,
    "CB-ACCESS-TIMESTAMP: ".$time,
    "CB-ACCESS-KEY: ".$g_coinbase_key,
    "Content-Type: application/json"
);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
var_dump($result);
?>

Result:

{"errors":[{"id":"authentication_error","message":"invalid signature"}]}

Body:
Replace

$sign = base64_encode(hash_hmac("sha256", $time.$method.$path, $g_coinbase_secret));

with

$sign = hash_hmac("sha256", $time.$method.$path, $g_coinbase_secret);

Coibase Api uses hash_mac


问:
How to attain such UI in Flutter?
I want to have a card like Container on a plain background as shown in the picture.

This is what I have tried using Stack, but I am having trouble positioning it in the right place.

I am new to flutter, sorry to ask such a dumb question.

```<code>  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          Container(
            color: Colors.grey,
          ),
          Positioned(
              child: Container(
            color: Colors.white,
            height: 400,
          ))
        ],
      ),
    );
  }
</code>```

答:
Use Positioned.fill with Align as its child and give alignment as Alignment.bottomCenter.
Then, You can decorate the stacked Container for the border radius.

```<code>Widget build(BuildContext context) {
  return Scaffold(
    body: Stack(
      children: <Widget>[
        Container(
          color: Colors.grey,
        ),
        Positioned.fill(
          child: Align(
            alignment: Alignment.bottomCenter,
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                  topRight: Radius.circular(30),
                  topLeft: Radius.circular(30),
                ),
                color: Colors.white,
              ),
              height: 400,
            ),
          ),
        )
      ],
    ),
  );
}
</code>```

Title: How to attain such UI in Flutter?

Body:
I want to have a card like Container on a plain background as shown in the picture.

This is what I have tried using Stack, but I am having trouble positioning it in the right place.

I am new to flutter, sorry to ask such a dumb question.

  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          Container(
            color: Colors.grey,
          ),
          Positioned(
              child: Container(
            color: Colors.white,
            height: 400,
          ))
        ],
      ),
    );
  }

Body:
Use Positioned.fill with Align as its child and give alignment as Alignment.bottomCenter.
Then, You can decorate the stacked Container for the border radius.

Widget build(BuildContext context) {
  return Scaffold(
    body: Stack(
      children: <Widget>[
        Container(
          color: Colors.grey,
        ),
        Positioned.fill(
          child: Align(
            alignment: Alignment.bottomCenter,
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                  topRight: Radius.circular(30),
                  topLeft: Radius.circular(30),
                ),
                color: Colors.white,
              ),
              height: 400,
            ),
          ),
        )
      ],
    ),
  );
}


问:
What is the best way to parse a tuple from a string in Python?
I tried this:

```<code>def string_to_value(self, old_value, distribution_type, new_value_str):
    parameter_names = distribution_type.parameters  # a list of string
    try:
        parameter_values = ast.literal_eval(new_value_str)  # a tuple or basic type hopefully
    except SyntaxError:
        raise ValueError('Syntax error during parse')
    retval = copy.copy(old_value)
    try:
        if len(parameter_names) == 1:
            setattr(retval, parameter_names[0], parameter_values)
        else:
            if len(parameter_names) != len(parameter_values):
                raise BoostPythonArgumentError
            for parm_name, parm_value in zip(parameter_names,
                                             parameter_values):
                setattr(retval, parm_name, parm_value)
    except BoostPythonArgumentError:
        raise ValueError('Lots of helpful text here')
    return retval
</code>```

This works for a lot of cases.  Boost.Python automatically checks the type of parm_value at set time.  Unfortunately, it doesn't work on strings containing 'inf'.  ast.literal_eval raises ValueError('malformed string') when I would like it to return a float.  I don't understand how Python can parse 'inf', but literal_eval can't.

Body:
I tried this:

def string_to_value(self, old_value, distribution_type, new_value_str):
    parameter_names = distribution_type.parameters  # a list of string
    try:
        parameter_values = ast.literal_eval(new_value_str)  # a tuple or basic type hopefully
    except SyntaxError:
        raise ValueError('Syntax error during parse')
    retval = copy.copy(old_value)
    try:
        if len(parameter_names) == 1:
            setattr(retval, parameter_names[0], parameter_values)
        else:
            if len(parameter_names) != len(parameter_values):
                raise BoostPythonArgumentError
            for parm_name, parm_value in zip(parameter_names,
                                             parameter_values):
                setattr(retval, parm_name, parm_value)
    except BoostPythonArgumentError:
        raise ValueError('Lots of helpful text here')
    return retval

This works for a lot of cases.  Boost.Python automatically checks the type of parm_value at set time.  Unfortunately, it doesn't work on strings containing 'inf'.  ast.literal_eval raises ValueError('malformed string') when I would like it to return a float.  I don't understand how Python can parse 'inf', but literal_eval can't.

Body:
Do you need to evaluate? e.g.

a = "(1,2,3,4)"
b = tuple(a.strip('( )').split(','))
assert ('1','2','3','4') == b


问:
Updating a number from a for loop
```<code>var currentmix = document.getElementById('custommix').value.split(",");
        var additionalprice = 0;

        for (i = 0; i < currentmix.length; i++) {
            if (currentmix[i] != "") {
                var mixinpriceid = "mixinprice"+currentmix[i];
                additionalprice += parseFloat(document.getElementById(mixinpriceid).value));
            }
        }
</code>```

This code is not working :(

I know the expression
parseFloat(document.getElementById(mixinpriceid).value)
is giving me the right number on each iteration of the loop

But it is not affecting the variable "additionalprice" outside the for loop.  Any ways to do this???????

答:
Sathish is correct, you have an extra parenthesis. This snippet will show the code will work without it.

var currentmix = "12345";
var additionalprice = 0;

for (i = 0; i < currentmix.length; i++) {
  if (currentmix[i] != "") {
    var mixinpriceid = "mixinprice" + currentmix[i];
    additionalprice += parseFloat(document.getElementById(mixinpriceid).value);

    console.log(additionalprice);
  }
}

console.log("Final Value: " + additionalprice);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="mixinprice1" value="100">mixinprice1</input>
<input id="mixinprice2" value="200">mixinprice2</input>
<input id="mixinprice3" value="300">mixinprice3</input>
<input id="mixinprice4" value="400">mixinprice4</input>
<input id="mixinprice5" value="500">mixinprice5</input></code>```

Title: Updating a number from a for loop

Body:
var currentmix = document.getElementById('custommix').value.split(",");
        var additionalprice = 0;

        for (i = 0; i < currentmix.length; i++) {
            if (currentmix[i] != "") {
                var mixinpriceid = "mixinprice"+currentmix[i];
                additionalprice += parseFloat(document.getElementById(mixinpriceid).value));
            }
        }

This code is not working :(

I know the expression
parseFloat(document.getElementById(mixinpriceid).value)
is giving me the right number on each iteration of the loop

But it is not affecting the variable "additionalprice" outside the for loop.  Any ways to do this???????

Body:
Sathish is correct, you have an extra parenthesis. This snippet will show the code will work without it.

var currentmix = "12345";
var additionalprice = 0;

for (i = 0; i < currentmix.length; i++) {
  if (currentmix[i] != "") {
    var mixinpriceid = "mixinprice" + currentmix[i];
    additionalprice += parseFloat(document.getElementById(mixinpriceid).value);

    console.log(additionalprice);
  }
}

console.log("Final Value: " + additionalprice);

<input id="mixinprice1" value="100">mixinprice1</input>
<input id="mixinprice2" value="200">mixinprice2</input>
<input id="mixinprice3" value="300">mixinprice3</input>
<input id="mixinprice4" value="400">mixinprice4</input>
<input id="mixinprice5" value="500">mixinprice5</input>