问:
SwiftUI UISearchController searchResultsController navigation stack issue
I have UISearchController that's been made UIViewControllerRepresentable for SwiftUI, as follows:

```<code>struct SearchViewController<Content: View>: UIViewControllerRepresentable {
    var content: () -> Content
    let searchResultsView = SearchResultsView()

    init(@ViewBuilder content: @escaping () -> Content) {
        self.content = content
    }

    func makeUIViewController(context: Context) -> UINavigationController {

        let rootViewController = UIHostingController(rootView: content())
        let navigationController = UINavigationController(rootViewController: rootViewController)
        let searchResultsController = UIHostingController(rootView: searchResultsView)

        // Set nav properties
        navigationController.navigationBar.prefersLargeTitles = true
        navigationController.definesPresentationContext = true

        // Create search controller
        let searchController = UISearchController(searchResultsController: searchResultsController)
        searchController.searchBar.autocapitalizationType = .none
        searchController.delegate =  context.coordinator
        searchController.searchBar.delegate = context.coordinator // Monitor when the search button is tapped.

        // Create default view
        rootViewController.navigationItem.searchController = searchController
        rootViewController.title = "Search"

        return navigationController
    }

    func updateUIViewController(_ navigationController: UINavigationController, context: UIViewControllerRepresentableContext<SearchViewController>) {
        //
    }
}
</code>```

This works, and displays the searchResultsController when the user is searching. However, the searchResultsController doesn't seem to know it's navigational context/stack, so I can't navigate from that list view in the searchResultsController.

Can this be structured to allow navigation from searchResultsController, or is this currently a SwiftUI limitation.

Any advice is much appreciated!

答:
I recently also need to implement this feature(search bar like navigation bar) in my app. Looking you snippets really inspired m2! My Thanks First!

After learning from you, ula1990, Lorenzo Boaro and V8tr, I implemented my own.

I set the searchResultsController to nil (due to untappable navigation link in it, so i set it to nil).

Demo

Code:

```<code>struct SearchController<Result: View>: UIViewControllerRepresentable {
    @Binding var searchText: String
    private var content: (_ searchText:String)->Result

    private var searchBarPlaceholder: String

    init(_ searchBarPlaceholder: String = "", searchedText: Binding<String>,
         resultView: @escaping (_ searchText:String) -> Result) {
        self.content = resultView
        self._searchText = searchedText
        self.searchBarPlaceholder = searchBarPlaceholder
    }
    func makeUIViewController(context: Context) -> UINavigationController {
        let contentViewController = UIHostingController(rootView: SearchResultView(result: $searchText, content: content))
        let navigationController = UINavigationController(rootViewController: contentViewController)

        let searchController = UISearchController(searchResultsController: nil)
        searchController.searchResultsUpdater = context.coordinator
        searchController.obscuresBackgroundDuringPresentation = false // for results
        searchController.searchBar.placeholder = searchBarPlaceholder

        contentViewController.title = "\\(Title)" // for customization
        contentViewController.navigationItem.searchController = searchController
        contentViewController.navigationItem.hidesSearchBarWhenScrolling = true
        contentViewController.definesPresentationContext = true

        searchController.searchBar.delegate = context.coordinator

        return navigationController
    }

    func updateUIViewController(_ uiViewController: UINavigationController, context: UIViewControllerRepresentableContext<SearchController>) {
        //

    }
}
extension SearchController {
    func makeCoordinator() -> SearchController<Result>.Coordinator {
        Coordinator(self)
    }
    class Coordinator: NSObject, UISearchResultsUpdating, UISearchBarDelegate {
        var parent: SearchController
        init(_ parent: SearchController){self.parent = parent}

        // MARK: - UISearchResultsUpdating
        func updateSearchResults(for searchController: UISearchController) {
            self.parent.searchText = searchController.searchBar.text!
        }

        // MARK: - UISearchBarDelegate
        func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
            self.parent.searchText = ""
        }

        func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
            self.parent.searchText = ""
            return true
        }
    }
}

// "nofity" the result content about the searchText
struct SearchResultView<Content: View>: View {
    @Binding var searchText: String
    private var content: (_ searchText:String)->Content
    init(result searchText: Binding<String>, @ViewBuilder content: @escaping (_ searchText:String) -> Content) {
        self._searchText = searchText
        self.content = content
    }
    var body: some View {
        content(searchText)
    }
}

</code>```

I don't if this is what you want, but thanks again!.

Body:
I have UISearchController that's been made UIViewControllerRepresentable for SwiftUI, as follows:

struct SearchViewController<Content: View>: UIViewControllerRepresentable {
    var content: () -> Content
    let searchResultsView = SearchResultsView()

    init(@ViewBuilder content: @escaping () -> Content) {
        self.content = content
    }

    func makeUIViewController(context: Context) -> UINavigationController {

        let rootViewController = UIHostingController(rootView: content())
        let navigationController = UINavigationController(rootViewController: rootViewController)
        let searchResultsController = UIHostingController(rootView: searchResultsView)

        // Set nav properties
        navigationController.navigationBar.prefersLargeTitles = true
        navigationController.definesPresentationContext = true

        // Create search controller
        let searchController = UISearchController(searchResultsController: searchResultsController)
        searchController.searchBar.autocapitalizationType = .none
        searchController.delegate =  context.coordinator
        searchController.searchBar.delegate = context.coordinator // Monitor when the search button is tapped.

        // Create default view
        rootViewController.navigationItem.searchController = searchController
        rootViewController.title = "Search"

        return navigationController
    }

    func updateUIViewController(_ navigationController: UINavigationController, context: UIViewControllerRepresentableContext<SearchViewController>) {
        //
    }
}

This works, and displays the searchResultsController when the user is searching. However, the searchResultsController doesn't seem to know it's navigational context/stack, so I can't navigate from that list view in the searchResultsController.

Can this be structured to allow navigation from searchResultsController, or is this currently a SwiftUI limitation.

Any advice is much appreciated!

Body:
I recently also need to implement this feature(search bar like navigation bar) in my app. Looking you snippets really inspired m2! My Thanks First!

After learning from you, ula1990, Lorenzo Boaro and V8tr, I implemented my own.

I set the searchResultsController to nil (due to untappable navigation link in it, so i set it to nil).

Demo

Code:

struct SearchController<Result: View>: UIViewControllerRepresentable {
    @Binding var searchText: String
    private var content: (_ searchText:String)->Result

    private var searchBarPlaceholder: String

    init(_ searchBarPlaceholder: String = "", searchedText: Binding<String>,
         resultView: @escaping (_ searchText:String) -> Result) {
        self.content = resultView
        self._searchText = searchedText
        self.searchBarPlaceholder = searchBarPlaceholder
    }
    func makeUIViewController(context: Context) -> UINavigationController {
        let contentViewController = UIHostingController(rootView: SearchResultView(result: $searchText, content: content))
        let navigationController = UINavigationController(rootViewController: contentViewController)

        let searchController = UISearchController(searchResultsController: nil)
        searchController.searchResultsUpdater = context.coordinator
        searchController.obscuresBackgroundDuringPresentation = false // for results
        searchController.searchBar.placeholder = searchBarPlaceholder

        contentViewController.title = "\\(Title)" // for customization
        contentViewController.navigationItem.searchController = searchController
        contentViewController.navigationItem.hidesSearchBarWhenScrolling = true
        contentViewController.definesPresentationContext = true

        searchController.searchBar.delegate = context.coordinator

        return navigationController
    }

    func updateUIViewController(_ uiViewController: UINavigationController, context: UIViewControllerRepresentableContext<SearchController>) {
        //

    }
}
extension SearchController {
    func makeCoordinator() -> SearchController<Result>.Coordinator {
        Coordinator(self)
    }
    class Coordinator: NSObject, UISearchResultsUpdating, UISearchBarDelegate {
        var parent: SearchController
        init(_ parent: SearchController){self.parent = parent}

        // MARK: - UISearchResultsUpdating
        func updateSearchResults(for searchController: UISearchController) {
            self.parent.searchText = searchController.searchBar.text!
        }

        // MARK: - UISearchBarDelegate
        func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
            self.parent.searchText = ""
        }

        func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
            self.parent.searchText = ""
            return true
        }
    }
}

// "nofity" the result content about the searchText
struct SearchResultView<Content: View>: View {
    @Binding var searchText: String
    private var content: (_ searchText:String)->Content
    init(result searchText: Binding<String>, @ViewBuilder content: @escaping (_ searchText:String) -> Content) {
        self._searchText = searchText
        self.content = content
    }
    var body: some View {
        content(searchText)
    }
}

I don't if this is what you want, but thanks again!.


来源: stackexchange

问:
NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference

java.lang.NullPointerException:Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference

Logcat

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
        at com.marsad.earningapp.activity.RegisterActivity$4.onComplete(RegisterActivity.java:138)
        at com.google.android.gms.tasks.zzj.run(Unknown Source:4)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:192)
        at android.app.ActivityThread.main(ActivityThread.java:6711)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)
</code>```

Error

reference.child(currentUser.getUid()).setValue(userInformation).addOnSuccessListener(new OnSuccessListener() {...

Here is the RegisterActivity.java

```<code>public class RegisterActivity extends AppCompatActivity {

    private EditText nameEdit, emailEdit, phoneEdit, passwordEdit;
    private Button loginBtn, signupBtn;

    private static final String TAG = "SignUpActivity";
    String defaultImage = "https://firebasestorage.googleapis.com/v0/b/earning-app-27780.appspot.com/o/woman.png?alt=media&token=4d66f140-4bd9-4a25-9838-cca28ebf48bb";

    private FirebaseDatabase userinfoDatabase;
    private DatabaseReference reference;
    private FirebaseAuth mAuth;
    private FirebaseUser currentUser;
    private SweetAlertDialog sweetAlertDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        nameEdit = findViewById(R.id.nameEditSignup);
        emailEdit = findViewById(R.id.emailEditSignup);
        phoneEdit = findViewById(R.id.phoneEditSignup);
        passwordEdit = findViewById(R.id.passwordEditSignup);
        loginBtn = findViewById(R.id.loginBtnSignup);
        signupBtn = findViewById(R.id.registerBTn);

        userinfoDatabase = FirebaseDatabase.getInstance();
        reference = userinfoDatabase.getReference("Users");
        mAuth = FirebaseAuth.getInstance();
        currentUser = mAuth.getCurrentUser();

        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                finish();
            }
        });

        signupBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = nameEdit.getText().toString();
                String phone = phoneEdit.getText().toString();

                if (TextUtils.isEmpty(name) && TextUtils.isEmpty(phone)){

                    if (TextUtils.isEmpty(name)){
                        nameEdit.setError("Enter Your Name");
                        nameEdit.requestFocus();
                    }

                    if (TextUtils.isEmpty(phone)){
                        phoneEdit.setError("Enter Your Phone Number");
                        phoneEdit.requestFocus();
                    }

                } else {

                    showRegisterDialog();
                    authenticationListener();

                }
            }
        });

    }

    private void authenticationListener(){

        final String email = emailEdit.getText().toString();
        final String password = passwordEdit.getText().toString();

        if(TextUtils.isEmpty(email) && TextUtils.isEmpty(password)){

            if (TextUtils.isEmpty(email)){
                emailEdit.setError("Enter Your Email");
                emailEdit.requestFocus();
            }
            if (TextUtils.isEmpty(password)){
                passwordEdit.setError("Enter Your Password");
                passwordEdit.requestFocus();
            }

        } else
            mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                    RegisterModel userInformation = new RegisterModel();

                    userInformation.setEmail(email);
                    userInformation.setName(nameEdit.getText().toString());
                    userInformation.setPassword(password);
                    userInformation.setPhone(phoneEdit.getText().toString());
                    userInformation.setRupees(0);
                    userInformation.setPoints(0);
                    userInformation.setImage(defaultImage);

                    reference.child(currentUser.getUid()).setValue(userInformation).addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            //user registered successfully
                            sweetAlertDialog.dismissWithAnimation();
                            startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                            finish();

                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            //user failed to register
                            sweetAlertDialog.dismissWithAnimation();
                            showRegisterErrorDialog();
                        }
                    });

                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    //Error
                    sweetAlertDialog.dismissWithAnimation();
                    showRegisterErrorDialog();
                }
            });

    }
}
</code>```

答: currentUser is null, which means no user is signed in.  You need to check for this case before calling getUid() on it.

ContentLicense: CC BY-SA 4.0

Body:
java.lang.NullPointerException:Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference

Logcat

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
        at com.marsad.earningapp.activity.RegisterActivity$4.onComplete(RegisterActivity.java:138)
        at com.google.android.gms.tasks.zzj.run(Unknown Source:4)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:192)
        at android.app.ActivityThread.main(ActivityThread.java:6711)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)

Error

reference.child(currentUser.getUid()).setValue(userInformation).addOnSuccessListener(new OnSuccessListener() {...

Here is the RegisterActivity.java

public class RegisterActivity extends AppCompatActivity {

    private EditText nameEdit, emailEdit, phoneEdit, passwordEdit;
    private Button loginBtn, signupBtn;

    private static final String TAG = "SignUpActivity";
    String defaultImage = "https://firebasestorage.googleapis.com/v0/b/earning-app-27780.appspot.com/o/woman.png?alt=media&token=4d66f140-4bd9-4a25-9838-cca28ebf48bb";

    private FirebaseDatabase userinfoDatabase;
    private DatabaseReference reference;
    private FirebaseAuth mAuth;
    private FirebaseUser currentUser;
    private SweetAlertDialog sweetAlertDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        nameEdit = findViewById(R.id.nameEditSignup);
        emailEdit = findViewById(R.id.emailEditSignup);
        phoneEdit = findViewById(R.id.phoneEditSignup);
        passwordEdit = findViewById(R.id.passwordEditSignup);
        loginBtn = findViewById(R.id.loginBtnSignup);
        signupBtn = findViewById(R.id.registerBTn);

        userinfoDatabase = FirebaseDatabase.getInstance();
        reference = userinfoDatabase.getReference("Users");
        mAuth = FirebaseAuth.getInstance();
        currentUser = mAuth.getCurrentUser();

        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                finish();
            }
        });

        signupBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = nameEdit.getText().toString();
                String phone = phoneEdit.getText().toString();

                if (TextUtils.isEmpty(name) && TextUtils.isEmpty(phone)){

                    if (TextUtils.isEmpty(name)){
                        nameEdit.setError("Enter Your Name");
                        nameEdit.requestFocus();
                    }

                    if (TextUtils.isEmpty(phone)){
                        phoneEdit.setError("Enter Your Phone Number");
                        phoneEdit.requestFocus();
                    }

                } else {

                    showRegisterDialog();
                    authenticationListener();

                }
            }
        });

    }

    private void authenticationListener(){

        final String email = emailEdit.getText().toString();
        final String password = passwordEdit.getText().toString();

        if(TextUtils.isEmpty(email) && TextUtils.isEmpty(password)){

            if (TextUtils.isEmpty(email)){
                emailEdit.setError("Enter Your Email");
                emailEdit.requestFocus();
            }
            if (TextUtils.isEmpty(password)){
                passwordEdit.setError("Enter Your Password");
                passwordEdit.requestFocus();
            }

        } else
            mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                    RegisterModel userInformation = new RegisterModel();

                    userInformation.setEmail(email);
                    userInformation.setName(nameEdit.getText().toString());
                    userInformation.setPassword(password);
                    userInformation.setPhone(phoneEdit.getText().toString());
                    userInformation.setRupees(0);
                    userInformation.setPoints(0);
                    userInformation.setImage(defaultImage);

                    reference.child(currentUser.getUid()).setValue(userInformation).addOnSuccessListener(new OnSuccessListener<Void>() {
                        @Override
                        public void onSuccess(Void aVoid) {
                            //user registered successfully
                            sweetAlertDialog.dismissWithAnimation();
                            startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                            finish();

                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            //user failed to register
                            sweetAlertDialog.dismissWithAnimation();
                            showRegisterErrorDialog();
                        }
                    });

                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    //Error
                    sweetAlertDialog.dismissWithAnimation();
                    showRegisterErrorDialog();
                }
            });

    }
}


问:
Hangfire function couldn't invoke in appService layer using asp boilerplate
I've created a webhook(IAppservice) which triggers a hangfire job, Job is adding in Hangfire.Job record as scheduled. but not executing.</p>

答: Implement your background job in an interface which is being inherited by IDomainService.</p>


问:
Filter an array of repeated objects and get the sum of them
So I have the next information, what I want to achieve is filter the array of objects and sum the qty of the objects repeated

```<code>//Original Data
var data = {
    sublists = [
    { item: 1, qty: 2},
    { item: 2, qty: 2},
    { item: 3, qty: 2},
    { item: 1, qty: 5}
    { item: 3, qty: 3}
    ],
    ...
};
//This is what I want to achieve
var result = {
    sublists = [
    { item: 1, qty: 7},
    { item: 2, qty: 2},
    { item: 3, qty: 5}

    ],
    ...
};
</code>```

So far what I got is the items name that repeat and an object that has the data of this variables

```<code>var repeatedObjects = {
  1: [{ item: 1, qty: 2}, { item: 1, qty: 5}],
  3: [{ item: 3, qty: 2}, { item: 3, qty: 3}]
}
var repeatedItems = [1, 3];
</code>```

But Im stuck at reducing the object so I can get the original data, with just one of the repeated objects and the sum of all of them. Any ideas?

答:
Create an itemByFreq json object like below

var data = {
    sublists : [
    { item: 1, qty: 2},
    { item: 2, qty: 2},
    { item: 3, qty: 2},
    { item: 1, qty: 5},
    { item: 3, qty: 3}
    ]
};

var itemByFreq = {};
for(var i=0;i<data.sublists.length;i++){
var ji = data.sublists[i];
itemByFreq[ji.item] = (itemByFreq[ji.item] || 0) + ji.qty;
}

console.log(itemByFreq);

var duplicateItems = [];
for(var key in itemByFreq)
 duplicateItems.push({item: key,qty: itemByFreq[key]});

console.log(duplicateItems);```

Body:
So I have the next information, what I want to achieve is filter the array of objects and sum the qty of the objects repeated

//Original Data
var data = {
    sublists = [
    { item: 1, qty: 2},
    { item: 2, qty: 2},
    { item: 3, qty: 2},
    { item: 1, qty: 5}
    { item: 3, qty: 3}
    ],
    ...
};
//This is what I want to achieve
var result = {
    sublists = [
    { item: 1, qty: 7},
    { item: 2, qty: 2},
    { item: 3, qty: 5}

    ],
    ...
};

So far what I got is the items name that repeat and an object that has the data of this variables

var repeatedObjects = {
  1: [{ item: 1, qty: 2}, { item: 1, qty: 5}],
  3: [{ item: 3, qty: 2}, { item: 3, qty: 3}]
}
var repeatedItems = [1, 3];

But Im stuck at reducing the object so I can get the original data, with just one of the repeated objects and the sum of all of them. Any ideas?


问:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource [Twitter API]
I'm aware that this is one of the most common problem. But unfortunately after doing a lot of study about CORS from the internet and questions on stackoverflow I'm not able to solve it. I'm trying to create a simple Angular project with twitter API. I want to fetch all my timeline status on the webpage with the twitter-api. Here's my code:

server.js

```<code>const express = require('express');
const Twitter = require('twit');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');

app.listen(3000, () => console.log('Server running'));
app.use(bodyParser.json());
app.use(cors());

const api_client = new Twitter({
    consumer_key: 'mykey',
    consumer_secret: 'mykey',
    access_token: 'mykey',
    access_token_secret: 'mykey'
})

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/home_timeline', (req, res) => {
    const params = { tweet_mode: 'extended', count: 10 };

    api_client
      .get('statuses/home_timeline', params)
      .then(timeline => {
        res.send(timeline);
      })
      .catch(error => {
      res.send(error);
    });
});
</code>```

This is my service twitterservice.service.ts

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class TwitterserviceService {

  api_url = 'https:/localhost:3000';

  constructor(private http: HttpClient) { }

  getTimeline() {
    return this.http
      .get<any[]>(this.api_url+'/home_timeline')
      .pipe(map(data => data));
  }
}
</code>```

and this is the component which is using the service twitter-timeline.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { TwitterserviceService } from '../twitterservice.service';

@Component({
  selector: 'app-twitter-timeline',
  templateUrl: './twitter-timeline.component.html',
  styleUrls: ['./twitter-timeline.component.scss']
})

export class TwitterTimelineComponent implements OnInit {

  myTimeline: any;

  constructor(private api: TwitterserviceService) { }

  ngOnInit() {
   this.getTwitterTimeline();
  }

  getTwitterTimeline(): void {
    this.api.getTimeline()
      .subscribe(
        myTimeline => {
          this.myTimeline = myTimeline;
          console.log(this.myTimeline);
        }
      )
   }
}
</code>```

On Postman I'm getting exactly what I want:

But the browser is telling a different story:

I tried disabling the security settings and I also added an extension CORS everywhere but I think that's not a good idea. I'm getting this for both Chrome and Firefox. Please correct me.

Please correct me where I'm wrong.

答: I think the problem is that you're making a https request in your angular app. Try using http://url in your service component instead.</p>

Body:
I'm aware that this is one of the most common problem. But unfortunately after doing a lot of study about CORS from the internet and questions on stackoverflow I'm not able to solve it. I'm trying to create a simple Angular project with twitter API. I want to fetch all my timeline status on the webpage with the twitter-api. Here's my code:

server.js

const express = require('express');
const Twitter = require('twit');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');

app.listen(3000, () => console.log('Server running'));
app.use(bodyParser.json());
app.use(cors());

const api_client = new Twitter({
    consumer_key: 'mykey',
    consumer_secret: 'mykey',
    access_token: 'mykey',
    access_token_secret: 'mykey'
})

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/home_timeline', (req, res) => {
    const params = { tweet_mode: 'extended', count: 10 };

    api_client
      .get('statuses/home_timeline', params)
      .then(timeline => {
        res.send(timeline);
      })
      .catch(error => {
      res.send(error);
    });
});

This is my service twitterservice.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class TwitterserviceService {

  api_url = 'https:/localhost:3000';

  constructor(private http: HttpClient) { }

  getTimeline() {
    return this.http
      .get<any[]>(this.api_url+'/home_timeline')
      .pipe(map(data => data));
  }
}

and this is the component which is using the service twitter-timeline.component.ts

import { Component, OnInit } from '@angular/core';
import { TwitterserviceService } from '../twitterservice.service';

@Component({
  selector: 'app-twitter-timeline',
  templateUrl: './twitter-timeline.component.html',
  styleUrls: ['./twitter-timeline.component.scss']
})

export class TwitterTimelineComponent implements OnInit {

  myTimeline: any;

  constructor(private api: TwitterserviceService) { }

  ngOnInit() {
   this.getTwitterTimeline();
  }

  getTwitterTimeline(): void {
    this.api.getTimeline()
      .subscribe(
        myTimeline => {
          this.myTimeline = myTimeline;
          console.log(this.myTimeline);
        }
      )
   }
}

On Postman I'm getting exactly what I want:

But the browser is telling a different story:

I tried disabling the security settings and I also added an extension CORS everywhere but I think that's not a good idea. I'm getting this for both Chrome and Firefox. Please correct me.

Please correct me where I'm wrong.


问:
I am trying to create a cal_average function however I keep getting the syntax error that python cannot assign to function call
Image of code

I am trying to create a cal_average function, please see block of code below:

```<code>def cal_average(numbers):
       sum(list_name) = sum(numbers)
       len(list_name) = len(numbers)
       ave(list_name) = sum(list_name)/len(list_names)
       return ave(list_name)
</code>```

enter code here    result = cal_average([3,4,5])

答:
the error is clear, you cannot assign to function call, in python sum is a build-in function also len is a built-in function, you can use statistics.mean:

```<code>import statistics

statistics.mean([3, 4, 5])
</code>```

output:

```<code>4
</code>```

or, if you want to keep your function:

```<code>def cal_average(numbers):
       return sum(numbers) / len(numbers)
</code>```

Body:
Image of code

I am trying to create a cal_average function, please see block of code below:

def cal_average(numbers):
       sum(list_name) = sum(numbers)
       len(list_name) = len(numbers)
       ave(list_name) = sum(list_name)/len(list_names)
       return ave(list_name)

enter code here    result = cal_average([3,4,5])

Body:
the error is clear, you cannot assign to function call, in python sum is a build-in function also len is a built-in function, you can use statistics.mean:

import statistics

statistics.mean([3, 4, 5])

output:

4

or, if you want to keep your function:

def cal_average(numbers):
       return sum(numbers) / len(numbers)


问:
Jenkins DSL - mask password
I need to know how to perform mask password with DSL plugin - i do not want to see the password at all (not with echo  and not in Jenkins )

this is what i did in Jenkins UI]1

Please help!

答:
i found the way to do so :

add the user and password as a global credentials in Jenkins

use:
credentialsBinding {
            usernamePassword('the name of the user', 'the name of the password ', 'user's id according to Jenkins global credentials')
        }

Title: Jenkins DSL - mask password


问:
Jenkins Pipeline Send email with an attachment
I am trying to send an email with attachment using the emailextension. I am not seeing the attachment in the mail.

How to resolve this?

```<code>emailext attachmentsPattern: '/scratch/testuser/output.html', body: "Test", mimeType: 'text/html',  subject: 's1', to: "${EMAIL_LIST}"
</code>```

答:
```<code>     emailext attachmentsPattern: 'attachment.html',
     body: "test",
     recipientProviders: [developers(), requestor()],
     subject: "testattachment: Job test"
</code>```

Body:
I am trying to send an email with attachment using the emailextension. I am not seeing the attachment in the mail.

How to resolve this?

emailext attachmentsPattern: '/scratch/testuser/output.html', body: "Test", mimeType: 'text/html',  subject: 's1', to: "${EMAIL_LIST}"


问:
matplotlib figures disappearing between show() and savefig()
I've kept a set of references to figures in a dictionary so that I could save them later if desired.  I am troubled that the saved figures are blank if invoke a show() command and look at them first.  Since the show() command blocks and I am not using a spyder-like interpreter, I have to close the figures before I get to savefig()

```<code>figures['myfig_1'] = figure()
...
figures['myfig_n'] = figure()
...

#show() #disabling this makes the problem go away
print "Saving:"
for fig in figures:
   figure(figures[fig].number)
   savefig(fig)
   print "Figure " + str(figures[fig].number) + ": " + fig
</code>```

The print statement here has given me the indication that the dictionary is still intact, which I think means that I have not lost the figure references (they are still returning meaningful numbers in their .number attribute.)

Another twist I have noticed is that when I have done a similar thing in a class, storing the dictionary as a member and dividing the store and save functions into their own methods, this does not happen.  Is there something about the way I am closing the figures or storing the data which is making the figures loose their data?

答: From the documentation, whether or not the drawing elements are destroyed from show() depends on the backend, and the version of matplotlib.  Not having the figures destroyed seems to be available with version 1.1.0.   To figure out which backend is in use, use the get_backend() function.  In my case, I was using the Qt4Agg backend.  By invoking the TkAgg backend, with the call matplotlib.use('TkAgg') the figures were not destroyed before the save.  Now to find out how to change the behavior of the Qt4Agg...

ContentLicense: CC BY-SA 3.0

Body:
I've kept a set of references to figures in a dictionary so that I could save them later if desired.  I am troubled that the saved figures are blank if invoke a show() command and look at them first.  Since the show() command blocks and I am not using a spyder-like interpreter, I have to close the figures before I get to savefig()

figures['myfig_1'] = figure()
...
figures['myfig_n'] = figure()
...

#show() #disabling this makes the problem go away
print "Saving:"
for fig in figures:
   figure(figures[fig].number)
   savefig(fig)
   print "Figure " + str(figures[fig].number) + ": " + fig

The print statement here has given me the indication that the dictionary is still intact, which I think means that I have not lost the figure references (they are still returning meaningful numbers in their .number attribute.)

Another twist I have noticed is that when I have done a similar thing in a class, storing the dictionary as a member and dividing the store and save functions into their own methods, this does not happen.  Is there something about the way I am closing the figures or storing the data which is making the figures loose their data?


问:
Web API not adding Controller, Sqlite error?
I have a .Net Core 2.2 application, I made migrations and updated the database successfully, I want to add an API Controller with actions using Entity Framework Core, but it won't scaffold successfully. I made a similar application before this and it generated controllers fine, I'm not sure what the issue is and I tried solving it myself, but couldn't find a solution.

In the package console I get this info:

unrecognized option '--useSqlite'
   at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.HandleUnexpectedArg(CommandLineApplication command, String[] args, Int32 index, String argTypeName)
   at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
   at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.Execute(String[] args)
   at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args)

I have tried uninstalling sqlite NuGetpackage but I still get the error, I tried rebuilding the app and restarting Visual Code, but it still doesn't work.

Here are my files

Startup.cs

```<code>    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddDbContext<LoanContext>(options =>
            options.UseSqlite(Configuration.GetConnectionString("DevConnection")));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}
</code>```

appsetting.json

```<code>{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "connectionStrings": {
    "DevConnection": "server=(local)\\sqlite;Database=TestDB;User Id=sa;Password=LovelyWorld1;"
  }
}

</code>```

Loan.cs

```<code> public class Loan
    {
        [Key]

        public int Details { get; set; }
        [Column(TypeName = "nvarchar(250)")]
        [Required]

        public string LoanID { get; set; }
        [Column(TypeName = "nvarchar(10)")]

        public string BorrowerName { get; set; }
        [Column(TypeName = "nvarchar(100)")]

        public string FundingAmount { get; set; }
        [Column(TypeName = "nvarchar(100)")]

        public string RepaymentAmount { get; set; }

    }
}
</code>```

答:
I think the main problem is in your loan model attributes.
They are not in the correct place. for example, I think the key attribute should be on top of the LoadID. Also, the loadID is a string and I think it should be int instead. I changed the model like this:

 public class Loan
    {
        [Key]
        public int LoanID { get; set; }

        [Column(TypeName = "nvarchar(250)"), Required]
        public string Details { get; set; }

        [Column(TypeName = "nvarchar(10)")]
        public string BorrowerName { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        public string FundingAmount { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        public string RepaymentAmount { get; set; }
    }
```

And then I deleted your init migration and added a new one. I tested that migration with SQL server and SQLite and it was fine.
Just be sure when you are using slite you should set the connection string like this

"Data Source=loanDb.db"

note: It is better to use decimal for "FundingAmount" and "RepaymentAmount" fields instead of string.

Body:
I have a .Net Core 2.2 application, I made migrations and updated the database successfully, I want to add an API Controller with actions using Entity Framework Core, but it won't scaffold successfully. I made a similar application before this and it generated controllers fine, I'm not sure what the issue is and I tried solving it myself, but couldn't find a solution.

In the package console I get this info:

unrecognized option '--useSqlite'
   at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.HandleUnexpectedArg(CommandLineApplication command, String[] args, Int32 index, String argTypeName)
   at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
   at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.Execute(String[] args)
   at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args)

I have tried uninstalling sqlite NuGetpackage but I still get the error, I tried rebuilding the app and restarting Visual Code, but it still doesn't work.

Here are my files

Startup.cs

    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddDbContext<LoanContext>(options =>
            options.UseSqlite(Configuration.GetConnectionString("DevConnection")));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}

appsetting.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "connectionStrings": {
    "DevConnection": "server=(local)\\sqlite;Database=TestDB;User Id=sa;Password=LovelyWorld1;"
  }
}

Loan.cs

 public class Loan
    {
        [Key]

        public int Details { get; set; }
        [Column(TypeName = "nvarchar(250)")]
        [Required]

        public string LoanID { get; set; }
        [Column(TypeName = "nvarchar(10)")]

        public string BorrowerName { get; set; }
        [Column(TypeName = "nvarchar(100)")]

        public string FundingAmount { get; set; }
        [Column(TypeName = "nvarchar(100)")]

        public string RepaymentAmount { get; set; }

    }
}

Body:
I think the main problem is in your loan model attributes.
They are not in the correct place. for example, I think the key attribute should be on top of the LoadID. Also, the loadID is a string and I think it should be int instead. I changed the model like this:

 public class Loan
    {
        [Key]
        public int LoanID { get; set; }

        [Column(TypeName = "nvarchar(250)"), Required]
        public string Details { get; set; }

        [Column(TypeName = "nvarchar(10)")]
        public string BorrowerName { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        public string FundingAmount { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        public string RepaymentAmount { get; set; }
    }

And then I deleted your init migration and added a new one. I tested that migration with SQL server and SQLite and it was fine.
Just be sure when you are using slite you should set the connection string like this

"Data Source=loanDb.db"

note: It is better to use decimal for "FundingAmount" and "RepaymentAmount" fields instead of string.


问:
Trying to show the product of two EditTexts as a TextView in another activity
I am having a ton of trouble passing the product of two EditTexts to a TextView in another activity. Here is my code for MainActivity.

```<code>class MainActivity : AppCompatActivity() {

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

        val button1: Button = findViewById(R.id.button1)
        val editText1: EditText = findViewById(R.id.editText1)
        val editText2: EditText = findViewById(R.id.editText2)
        val firstNumber = editText1.toString().toInt()
        val secondNumber = editText2.toString().toInt()
        val product = firstNumber * secondNumber

        button1.setOnClickListener{

            val intent = Intent(this, Activity2::class.java)
            intent.putExtra("RESULT_PRODUCT", product)
            startActivity(intent)
        }
    }
}
</code>```

Here is my code for Activity2:

```<code>class Activity2 : AppCompatActivity() {

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

        val product = intent.getIntExtra("RESULT_SUM", 0)
        textView1.text = product.toString()
    }
}
</code>```

I am relatively new to Kotlin and Android Studio but this has caused crashes left and right.

答: You are passing "RESULT_PRODUCT" from MainActivity but getting "RESULT_SUM" in your Activity2. You should use intent.getIntExtra("RESULT_PRODUCT", 0) in you second activity.

Body:
I am having a ton of trouble passing the product of two EditTexts to a TextView in another activity. Here is my code for MainActivity.

class MainActivity : AppCompatActivity() {

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

        val button1: Button = findViewById(R.id.button1)
        val editText1: EditText = findViewById(R.id.editText1)
        val editText2: EditText = findViewById(R.id.editText2)
        val firstNumber = editText1.toString().toInt()
        val secondNumber = editText2.toString().toInt()
        val product = firstNumber * secondNumber

        button1.setOnClickListener{

            val intent = Intent(this, Activity2::class.java)
            intent.putExtra("RESULT_PRODUCT", product)
            startActivity(intent)
        }
    }
}

Here is my code for Activity2:

class Activity2 : AppCompatActivity() {

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

        val product = intent.getIntExtra("RESULT_SUM", 0)
        textView1.text = product.toString()
    }
}

I am relatively new to Kotlin and Android Studio but this has caused crashes left and right.


问:
React-native IOS app goes blank on startup when i change from main.m to appdegelegate.swift
i am trying to convert the appdelegate.h .m and main.m (objective c files) to swift by creating appdelegate.swift (and of course deleting those files) but when i do this the app brings a black screen on startup

here is the main.m code

```<code>#import <UIKit/UIKit.h>

#import "AppDelegate.m"

int main(int argc, char * argv[]) {
@autoreleasepool {
 return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
 }
}
</code>```

and appdelegate.m

```<code>#import "AppDelegate.h"

#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
@import Firebase;

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary
*)launchOptions
  {
 RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
 RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                               moduleName:@"doctor_react_app"
                                        initialProperties:nil];

 rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
 rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
 [self.window makeKeyAndVisible];
 [FIRApp configure];
 return YES;
 }

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
 return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"
 fallbackResource:nil];
#else
 return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

@end
</code>```

and here is the code am trying to using in the appdelegate.swift

```<code>import UIKit
import PushKit
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?

 private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        //Enable all notification type. VoIP Notifications don't present a UI but we will use this to show local nofications later
        let notificationSettings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)

        //register the notification settings
        application.registerUserNotificationSettings(notificationSettings)

        //output what state the app is in. This will be used to see when the app is started in the background
        NSLog("app launched with state \(application.applicationState)")
        FirebaseApp.configure()
        return true
}

func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {

  //register for voip notifications
let voipRegistry = PKPushRegistry(queue: DispatchQueue.main)
voipRegistry.desiredPushTypes = Set([PKPushType.voIP])
  voipRegistry.delegate = self;

 }

  }
 extension AppDelegate: PKPushRegistryDelegate {

  func pushRegistry(_ registry: PKPushRegistry,
                    didUpdate pushCredentials: PKPushCredentials,
                    for type: PKPushType) {
    //print out the VoIP token. We will use this to test the notification.
    NSLog("voip token: \(pushCredentials.token)")
  }

  func pushRegistry(_ registry: PKPushRegistry,
                             didReceiveIncomingPushWith payload: PKPushPayload,
                             for type: PKPushType,
                             completion: @escaping () -> Void){
    let payloadDict = payload.dictionaryPayload["aps"] as? Dictionary<String, String>
    let message = payloadDict?["alert"]

    //present a local notifcation to visually see when we are recieving a VoIP Notification
    if UIApplication.shared.applicationState == UIApplication.State.background {

      let localNotification = UILocalNotification();
      localNotification.alertBody = message
      localNotification.applicationIconBadgeNumber = 1;
      localNotification.soundName = UILocalNotificationDefaultSoundName;

      UIApplication.shared.presentLocalNotificationNow(localNotification);
    }

    else {

      DispatchQueue.main.async(execute: { () -> Void in

        let alert = UIAlertController(title: "My Alert", message: "This is an alert.", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .default, handler: { _ in
        NSLog("The \"OK\" alert occured.")
        }))

 //            alert.show()
      })
    }

    NSLog("incoming voip notfication: \(payload.dictionaryPayload)")
  }
  func pushRegistry(_ registry: PKPushRegistry,
                             didInvalidatePushTokenFor type: PKPushType) {

    NSLog("token invalidated")
  }
 }
</code>```

答:
You can try 2 things here:-

1: Set Root-View-Controller in the didFinishLaunchingWithOptions

2: In iOS 13, Apple introduced a new class called SceneDelegate, so all things related to window, you have to implement here and now SceneDelegate class is extending UIResponder, so just set root view controller in this function of SceneDelegate class:-

```<code>func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    //set root vc here
}
</code>```

Body:
i am trying to convert the appdelegate.h .m and main.m (objective c files) to swift by creating appdelegate.swift (and of course deleting those files) but when i do this the app brings a black screen on startup

here is the main.m code

#import <UIKit/UIKit.h>

#import "AppDelegate.m"

int main(int argc, char * argv[]) {
@autoreleasepool {
 return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
 }
}

and appdelegate.m

#import "AppDelegate.h"

#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
@import Firebase;

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary
*)launchOptions
  {
 RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
 RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                               moduleName:@"doctor_react_app"
                                        initialProperties:nil];

 rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
 rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
 [self.window makeKeyAndVisible];
 [FIRApp configure];
 return YES;
 }

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
 return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"
 fallbackResource:nil];
#else
 return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

@end

and here is the code am trying to using in the appdelegate.swift

import UIKit
import PushKit
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?

 private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        //Enable all notification type. VoIP Notifications don't present a UI but we will use this to show local nofications later
        let notificationSettings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)

        //register the notification settings
        application.registerUserNotificationSettings(notificationSettings)

        //output what state the app is in. This will be used to see when the app is started in the background
        NSLog("app launched with state \(application.applicationState)")
        FirebaseApp.configure()
        return true
}

func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {

  //register for voip notifications
let voipRegistry = PKPushRegistry(queue: DispatchQueue.main)
voipRegistry.desiredPushTypes = Set([PKPushType.voIP])
  voipRegistry.delegate = self;

 }

  }
 extension AppDelegate: PKPushRegistryDelegate {

  func pushRegistry(_ registry: PKPushRegistry,
                    didUpdate pushCredentials: PKPushCredentials,
                    for type: PKPushType) {
    //print out the VoIP token. We will use this to test the notification.
    NSLog("voip token: \(pushCredentials.token)")
  }

  func pushRegistry(_ registry: PKPushRegistry,
                             didReceiveIncomingPushWith payload: PKPushPayload,
                             for type: PKPushType,
                             completion: @escaping () -> Void){
    let payloadDict = payload.dictionaryPayload["aps"] as? Dictionary<String, String>
    let message = payloadDict?["alert"]

    //present a local notifcation to visually see when we are recieving a VoIP Notification
    if UIApplication.shared.applicationState == UIApplication.State.background {

      let localNotification = UILocalNotification();
      localNotification.alertBody = message
      localNotification.applicationIconBadgeNumber = 1;
      localNotification.soundName = UILocalNotificationDefaultSoundName;

      UIApplication.shared.presentLocalNotificationNow(localNotification);
    }

    else {

      DispatchQueue.main.async(execute: { () -> Void in

        let alert = UIAlertController(title: "My Alert", message: "This is an alert.", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: .default, handler: { _ in
        NSLog("The \"OK\" alert occured.")
        }))

 //            alert.show()
      })
    }

    NSLog("incoming voip notfication: \(payload.dictionaryPayload)")
  }
  func pushRegistry(_ registry: PKPushRegistry,
                             didInvalidatePushTokenFor type: PKPushType) {

    NSLog("token invalidated")
  }
 }

Body:
You can try 2 things here:-

1: Set Root-View-Controller in the didFinishLaunchingWithOptions

2: In iOS 13, Apple introduced a new class called SceneDelegate, so all things related to window, you have to implement here and now SceneDelegate class is extending UIResponder, so just set root view controller in this function of SceneDelegate class:-

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    //set root vc here
}


问:
How to convert an array of map in Firestore to a List of map Dart
I am trying to build an app with Flutter and Firestore, but I am confused by the way I have to implement my data from Firestore  to Dart language, so the problem is that I have an array of the map in my Firestore, each element in the array represent a map like this

And in my app, I want to represent the data from Firestore to something readable, I declare a class like this:

```<code>class rest_model{
String rest_name;
GeoPoint rest_lat_long;
GeoPoint city_lat_long;
var rest_address = new Map();
var rest_food_list = new List<Map>();
</code>```

I know how to convert the other into variables or readable, I use this approach:

```<code>rest_model.map(dynamic obj){

this.rest_name = obj['rest_name'];
this.rest_lat_long = obj['rest_lat_long'];
this.city_lat_long = obj['city_lat_long'];
this.rest_address['rest_email'] = obj['rest_address']['rest_email'];
this.rest_address['rest_phone']=obj['rest_address']['rest_phone'];
this.rest_address['rest_website'] = obj['rest_address']['rest_website'];
}

rest_model.fromMap(Map<String, dynamic> map){

this.rest_name = map['rest_name'];
this.rest_lat_long = map['rest_lat_long'];
this.city_lat_long = map['city_lat_long'];
this.rest_address['rest_email'] = map['rest_address']['rest_email'];
this.rest_address['rest_phone']=map['rest_address']['rest_phone'];
this.rest_address['rest_website'] = map['rest_address']['rest_website'];
}

Map<String, dynamic> toMap(){
var map = new Map<String, dynamic>();
map['rest_name'] = rest_name ;
map['rest_lat_long'] = rest_lat_long;
map['city_lat_long'] = city_lat_long;
map['rest_address'] = rest_address.values;
}
</code>```

But I don't know how to convert the array of the map rest_food_list.

Please anyone can help me?

答:
Create a class in dart similar to that in firestore1. Create a class in dart similar to that in firestore. I have a Post class in Dart and an array of posts in firestore.
Firestore Array of Map

My class in Dart is like below

```<code>class Main{
  final String userName;
  final List<Post> post;

  Main({this.userName, this.post});
}

class Post {
  final String postImg;
  final int likes;
  final String description;

  Post({this.postImg, this.description, this.likes});
}
</code>```

When I am fetching the data from firestore, since firestore has array so you can convert that array of Map like this in dart.

```<code>//fetch firestore documents by getDocuments()
data.documents.forEach((doc) {
      Main main = new Main(
          userImg: doc.data["user_image"],
          post: List<Post>.from(doc.data["posts"].map((item) {
            return new Post(
                likes: item["likes"],
                postImg: item["image"],
                description: item["description"]);
          })));
      //add the main data object to List;
    }
</code>```

Hope this helps!!

Body:
I am trying to build an app with Flutter and Firestore, but I am confused by the way I have to implement my data from Firestore  to Dart language, so the problem is that I have an array of the map in my Firestore, each element in the array represent a map like this

And in my app, I want to represent the data from Firestore to something readable, I declare a class like this:

class rest_model{
String rest_name;
GeoPoint rest_lat_long;
GeoPoint city_lat_long;
var rest_address = new Map();
var rest_food_list = new List<Map>();

I know how to convert the other into variables or readable, I use this approach:

rest_model.map(dynamic obj){

this.rest_name = obj['rest_name'];
this.rest_lat_long = obj['rest_lat_long'];
this.city_lat_long = obj['city_lat_long'];
this.rest_address['rest_email'] = obj['rest_address']['rest_email'];
this.rest_address['rest_phone']=obj['rest_address']['rest_phone'];
this.rest_address['rest_website'] = obj['rest_address']['rest_website'];
}

rest_model.fromMap(Map<String, dynamic> map){

this.rest_name = map['rest_name'];
this.rest_lat_long = map['rest_lat_long'];
this.city_lat_long = map['city_lat_long'];
this.rest_address['rest_email'] = map['rest_address']['rest_email'];
this.rest_address['rest_phone']=map['rest_address']['rest_phone'];
this.rest_address['rest_website'] = map['rest_address']['rest_website'];
}

Map<String, dynamic> toMap(){
var map = new Map<String, dynamic>();
map['rest_name'] = rest_name ;
map['rest_lat_long'] = rest_lat_long;
map['city_lat_long'] = city_lat_long;
map['rest_address'] = rest_address.values;
}

But I don't know how to convert the array of the map rest_food_list.

Please anyone can help me?

Body:
Create a class in dart similar to that in firestore1. Create a class in dart similar to that in firestore. I have a Post class in Dart and an array of posts in firestore.
Firestore Array of Map

My class in Dart is like below

class Main{
  final String userName;
  final List<Post> post;

  Main({this.userName, this.post});
}

class Post {
  final String postImg;
  final int likes;
  final String description;

  Post({this.postImg, this.description, this.likes});
}

When I am fetching the data from firestore, since firestore has array so you can convert that array of Map like this in dart.

//fetch firestore documents by getDocuments()
data.documents.forEach((doc) {
      Main main = new Main(
          userImg: doc.data["user_image"],
          post: List<Post>.from(doc.data["posts"].map((item) {
            return new Post(
                likes: item["likes"],
                postImg: item["image"],
                description: item["description"]);
          })));
      //add the main data object to List;
    }

Hope this helps!!


问:
make the first tab the active tab when open a bootstrap modal
i have a button that will show a bootstrap modal when clicks on it
the modal contains sidebar tabs.

my problem is when i close the modal and open it again by clicking on the button it will open with the last activated tab
i want the activated tab to be the first tab once i close the modal and open the modal again without reloading the page.

my html

```<code> // the button that will open the bootstrap modal
            <div>
            <a href="#"  class="popupLink" data-toggle="modal" data-target="#yDetailsModal">
            </a>
            </div>

// bootstrap modal

<div class="modal" id="MyDetailsModal" tabindex="-1" role="dialog" arialabelledby="myDetailsModal" aria-hidden="true" >

 <div class="modal-dialog modal-details" role="document">

  <div class="modal-content modal-details">

   <div class="modal-header">

 <button type="button" class="close close-button"  data-dismiss="modal" aria-label="Close" id="btnId"> </button>

  </div>

 <div class="modal-body">
  <div class=" tabs-left" id= "modal-tabs">
   <ul class="nav nav-tabs">

   <li class="active">
   <a href="#personal"  data-toggle="tab"></a></li>

  <li>
   <a  href="#promotion" data-toggle="tab"> </a> </li>
    <li>
    <a  href="#vacation" data-toggle="tab"> </a> </li>

</ul>
 </div>

<div class="tab-content" id="tab-content">
 <div class="tab-pane active" id="personalInformation">
  <div>
   <ul>
     <li>

      <span> this is a personal information</span>
      </li>
</ul>
</div>
</div>

</code>```

答:
Calling a function ActiveFirstTab() before the model pop up

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

    <button type="button" onclick="ActiveFirstTab();" class="btn btn-info btn-lg" data-toggle="modal" data-target="#MyDetailsModal">Open Modal</button>

       <button type="button" class="close close-button"  data-dismiss="modal" aria-label="Close" id="btnId"> </button>

          One

           Two

            Three

personal

Some content.

 promotion Menu 1

Some content in menu 1.

vacation Menu 2

Some content in menu 2.

     </script>
     ```

Body:
i have a button that will show a bootstrap modal when clicks on it
the modal contains sidebar tabs.

my problem is when i close the modal and open it again by clicking on the button it will open with the last activated tab
i want the activated tab to be the first tab once i close the modal and open the modal again without reloading the page.

my html

 // the button that will open the bootstrap modal

// bootstrap modal

 <button type="button" class="close close-button"  data-dismiss="modal" aria-label="Close" id="btnId"> </button>

       this is a personal information

Body:
Calling a function ActiveFirstTab() before the model pop up

<!DOCTYPE html>
<html>
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>

  <div>

    <button type="button" onclick="ActiveFirstTab();" class="btn btn-info btn-lg" data-toggle="modal" data-target="#MyDetailsModal">Open Modal</button>
  </div>

  <div class="modal" id="MyDetailsModal" tabindex="-1" role="dialog" arialabelledby="myDetailsModal" aria-hidden="true" >

   <div class="modal-dialog modal-details" role="document">

    <div class="modal-content modal-details">

     <div class="modal-header">

       <button type="button" class="close close-button"  data-dismiss="modal" aria-label="Close" id="btnId"> </button>

     </div>

     <div class="modal-body">
      <div class=" tabs-left" id= "modal-tabs">
       <ul class="nav nav-tabs">

         <li class="active">
          <a href="#personal"  data-toggle="tab">One</a></li>

          <li>
           <a  href="#promotion" data-toggle="tab">Two </a> </li>
           <li>
            <a  href="#vacation" data-toggle="tab">Three </a> </li>

          </ul>
          <div class="tab-content">
  <div id="personal" class="tab-pane fade in active">
    <h3>personal</h3>
    <p>Some content.</p>
  </div>
  <div id="promotion" class="tab-pane fade">
    <h3> promotion Menu 1</h3>
    <p>Some content in menu 1.</p>
  </div>
  <div id="vacation" class="tab-pane fade">
    <h3>vacation Menu 2</h3>
    <p>Some content in menu 2.</p>
  </div>
</div>
        </body>
        <script type="text/javascript">
          function ActiveFirstTab() {

           $('a[href="#personal"]').tab('show');

         }
       </script>

     </script>
     </html>


问:
Can you search and return results from an XML asset list in the Android SDK?
If so, is there a tutorial that I have missed somewhere that might help me get started with this? If not, can someone point me towards a place to get started setting up a database where I would preload the information instead of actually having the user do it?</p>

答:
Here's a simple example of loading values from a values xml file into a string array, searching through the values, and selecting one for display.

values/strings.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <string
        name="hello">Hello World, Main!</string>
    <string
        name="app_name">Q6024120_Load_And_Search_Array</string>
    <string-array
        name="planets_array">
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
        <item>Jupiter</item>
        <item>Saturn</item>
        <item>Uranus</item>
        <item>Neptune</item>
    </string-array>
</resources></code>```

```<code>public class Main extends Activity
{
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    String[] planets = getResources().getStringArray(R.array.planets_array);
    int foundIndex = -1;
    for (int i = 0; i < planets.length; i++)
    {
      String planet = planets[i];
      if (planet.equals("Mars"))
      {
        foundIndex = i;
        break;
      }
    }
    String foundPlanet = foundIndex >= 0 ? planets[foundIndex] : "nothing";
    ((TextView)findViewById(R.id.found_planet)).setText("found: " + foundPlanet);
  }
}</code>```

If you'd rather load the data from an xml file in the assets folder, note that it's a bit involved.  Take a look at android: how to load xml file from assets directory?.

If the values are just a simple list of strings, then xml structure probably isn't necessary.  Here's a simple example of loading the values from a text file in the assets folder.

assets/planets.txt

```<code>Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune</code>```

```<code>public class Main extends Activity
{
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // String[] planets = getResources().getStringArray(R.array.planets_array);
    String[] planets = readFromAssetsTxt();
    int foundIndex = -1;
    for (int i = 0; i < planets.length; i++)
    {
      String planet = planets[i];
      if (planet.equals("Mars"))
      {
        foundIndex = i;
        break;
      }
    }
    String foundPlanet = foundIndex >= 0 ? planets[foundIndex] : "nothing";
    ((TextView) findViewById(R.id.found_planet)).setText("found: " + foundPlanet);
  }

  String[] readFromAssetsTxt()
  {
    try
    {
      AssetManager assetManager = getAssets();
      List<String> planets = new ArrayList<String>();
      BufferedReader in = new BufferedReader(new InputStreamReader(assetManager.open("planets.txt")));
      String planet = null;
      while ((planet = in.readLine()) != null)
      {
        planets.add(planet);
      }
      in.close();
      String[] planetsArray = new String[planets.size()];
      planets.toArray(planetsArray);
      return planetsArray;
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    return new String[] {};
  }
}</code>```

Body:
Here's a simple example of loading values from a values xml file into a string array, searching through the values, and selecting one for display.

values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string
        name="hello">Hello World, Main!</string>
    <string
        name="app_name">Q6024120_Load_And_Search_Array</string>
    <string-array
        name="planets_array">
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
        <item>Jupiter</item>
        <item>Saturn</item>
        <item>Uranus</item>
        <item>Neptune</item>
    </string-array>
</resources>

public class Main extends Activity
{
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    String[] planets = getResources().getStringArray(R.array.planets_array);
    int foundIndex = -1;
    for (int i = 0; i < planets.length; i++)
    {
      String planet = planets[i];
      if (planet.equals("Mars"))
      {
        foundIndex = i;
        break;
      }
    }
    String foundPlanet = foundIndex >= 0 ? planets[foundIndex] : "nothing";
    ((TextView)findViewById(R.id.found_planet)).setText("found: " + foundPlanet);
  }
}

If you'd rather load the data from an xml file in the assets folder, note that it's a bit involved.  Take a look at android: how to load xml file from assets directory?.

If the values are just a simple list of strings, then xml structure probably isn't necessary.  Here's a simple example of loading the values from a text file in the assets folder.

assets/planets.txt

Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune

public class Main extends Activity
{
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // String[] planets = getResources().getStringArray(R.array.planets_array);
    String[] planets = readFromAssetsTxt();
    int foundIndex = -1;
    for (int i = 0; i < planets.length; i++)
    {
      String planet = planets[i];
      if (planet.equals("Mars"))
      {
        foundIndex = i;
        break;
      }
    }
    String foundPlanet = foundIndex >= 0 ? planets[foundIndex] : "nothing";
    ((TextView) findViewById(R.id.found_planet)).setText("found: " + foundPlanet);
  }

  String[] readFromAssetsTxt()
  {
    try
    {
      AssetManager assetManager = getAssets();
      List<String> planets = new ArrayList<String>();
      BufferedReader in = new BufferedReader(new InputStreamReader(assetManager.open("planets.txt")));
      String planet = null;
      while ((planet = in.readLine()) != null)
      {
        planets.add(planet);
      }
      in.close();
      String[] planetsArray = new String[planets.size()];
      planets.toArray(planetsArray);
      return planetsArray;
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    return new String[] {};
  }
}


问:
How to display django success message in every template from one view?
Here I have one function for newsletter which will be used in every template in the project.The issue here is the success message is  displaying only in the contact page template.I have placed django message tag {{message}} in the base.html only.It is working fine in the contact.html page.The corresponding message  for contact and newsletter displays correctly in the contact_page template but not in other templates .Other templates also extends base.html like the contact.html.

How  can i display newsletter success message in every template.I don't want to write {{message}} in every template. Is there any solution  for this ?

views.py

```<code>def contact(request):
    form = ContactForm()
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, 'Your message has been sent successfully.')
            return redirect('contact:contact_page')
    return render(request, 'contact/contact_page.html', {'form': form})

def newsletter(request):
    form = NewsletterForm()
    if request.method == "POST":
        form = NewsletterForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, 'Thank you for your subscription.')
            return redirect(request.META['HTTP_REFERER'])
    return render(request, 'base.html', {'news_form': form})
</code>```

答:
create base.html with links to stylesheet and js files only. There you can place

```<code>{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}
{% block content %}{% endblock %}
</code>```

just above the block content, and extend all other templates from it. So it will be better to make a home.html file and render the news letter to there, and extend it from base.html. Refer doc

Body:
Here I have one function for newsletter which will be used in every template in the project.The issue here is the success message is  displaying only in the contact page template.I have placed django message tag {{message}} in the base.html only.It is working fine in the contact.html page.The corresponding message  for contact and newsletter displays correctly in the contact_page template but not in other templates .Other templates also extends base.html like the contact.html.

How  can i display newsletter success message in every template.I don't want to write {{message}} in every template. Is there any solution  for this ?

views.py

def contact(request):
    form = ContactForm()
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, 'Your message has been sent successfully.')
            return redirect('contact:contact_page')
    return render(request, 'contact/contact_page.html', {'form': form})

def newsletter(request):
    form = NewsletterForm()
    if request.method == "POST":
        form = NewsletterForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, 'Thank you for your subscription.')
            return redirect(request.META['HTTP_REFERER'])
    return render(request, 'base.html', {'news_form': form})

Body:
create base.html with links to stylesheet and js files only. There you can place

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}
{% block content %}{% endblock %}

just above the block content, and extend all other templates from it. So it will be better to make a home.html file and render the news letter to there, and extend it from base.html. Refer doc


问:
IN vs ANY operator in PostgreSQL
What is the difference between IN and ANY operator in PostgreSQL?

The working mechanism of both seems to be the same. Can anyone explain this with an example?

答:
There are two obvious points, as well as the points in the other answer:

They are exactly equivalent when using sub queries:

```<code>SELECT * FROM table
WHERE column IN(subquery);

SELECT * FROM table
WHERE column = ANY(subquery);
</code>```

On the other hand:

Only the IN operator allows a simple list:

```<code>SELECT * FROM table
WHERE column IN(… , … , …);
</code>```

Presuming they are exactly the same has caught me out several times when forgetting that ANY doesn’t work with lists.

Title: IN vs ANY operator in PostgreSQL

Body:
There are two obvious points, as well as the points in the other answer:

They are exactly equivalent when using sub queries:

SELECT * FROM table
WHERE column IN(subquery);

SELECT * FROM table
WHERE column = ANY(subquery);

On the other hand:

Only the IN operator allows a simple list:

SELECT * FROM table
WHERE column IN(… , … , …);

Presuming they are exactly the same has caught me out several times when forgetting that ANY doesn’t work with lists.


问:
npm: import from outside the src folder
So I have this NodeJS project with the following folder tree

```<code>+ node-folder
   + react-app-folder
   + (other folders...)
   + config
       + default.json
</code>```

What I am trying to do is import that default.json file to any file in that react-app-folder.

The node-folder and react-app-folder have their own package.json file.

Is there any way of doing this?

Thank you all very much.

EDIT:
For more details about the node-folder . It is a NodeJS app server whose package.json has a script using concurrently to run both the nodejs-app on port 3000 and react-app on port 3001

答: If I understood your question correctly, I believe that you are using create-react-app. The ModuleScopePlugin enforces a restriction that prevents you from importing files outside src folder. Removing this from your webpack configuration will allow you to import files out of react app scope. Please check this similar question.

Title: npm: import from outside the src folder

Body:
So I have this NodeJS project with the following folder tree

+ node-folder
   + react-app-folder
   + (other folders...)
   + config
       + default.json

What I am trying to do is import that default.json file to any file in that react-app-folder.

The node-folder and react-app-folder have their own package.json file.

Is there any way of doing this?

Thank you all very much.

EDIT:
For more details about the node-folder . It is a NodeJS app server whose package.json has a script using concurrently to run both the nodejs-app on port 3000 and react-app on port 3001


问:
Looping through API results for pagination
I'm trying to access some data via an API.  Here's my current code:

```<code>$ch = curl_init("https://api.example.com/rest/1.3/analytics/affiliate/vendor/?account=xxxxx&select=EARNINGS_PER_HOP");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Page: 1', 'Accept: application/json', 'Authorization: XXXXX'));
$response = curl_exec($ch);
curl_close($ch);

if ($response) {
    $array = json_decode($response, TRUE);

    foreach ($array['rows']['row'] as $data) {
        $value = $data['data']['value']['$'];
        $dimension = $data['dimensionValue'];
        /// insert $value and $dimension into database
    }
}
</code>```

I'm just trying to get some data from it an insert it into a MySQL database.  My current code is technically working, but the API only displays the first 100 results.

If there's more than 100 results, it'll provide the data and give a header response of 206 Partial Content to let me know there's more results.  To get the next page, I have to send Page: n in the header.

As you can see from the code above, I am sending Page: 1 in the header.

How can I check to see if a 206 response code is given and if it is, keep looping through until it reaches a 200 response code (the page number in the header would need to be increased for each loop)?

答: You can put that code inside a function and then call that function with 'n' as parameter based on the response code you get. Did you try that ? you can get the response code using curl_getinfo option CURLINFO_RESPONSE_CODE or CURLINFO_HTTP_CODE.</p>

Body:
I'm trying to access some data via an API.  Here's my current code:

$ch = curl_init("https://api.example.com/rest/1.3/analytics/affiliate/vendor/?account=xxxxx&select=EARNINGS_PER_HOP");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Page: 1', 'Accept: application/json', 'Authorization: XXXXX'));
$response = curl_exec($ch);
curl_close($ch);

if ($response) {
    $array = json_decode($response, TRUE);

    foreach ($array['rows']['row'] as $data) {
        $value = $data['data']['value']['$'];
        $dimension = $data['dimensionValue'];
        /// insert $value and $dimension into database
    }
}

I'm just trying to get some data from it an insert it into a MySQL database.  My current code is technically working, but the API only displays the first 100 results.

If there's more than 100 results, it'll provide the data and give a header response of 206 Partial Content to let me know there's more results.  To get the next page, I have to send Page: n in the header.

As you can see from the code above, I am sending Page: 1 in the header.

How can I check to see if a 206 response code is given and if it is, keep looping through until it reaches a 200 response code (the page number in the header would need to be increased for each loop)?