问:
Swift: my destinationVC segue is showing nil
I'm having users fill out some profile information via texts fields (name, email, etc.), which is used to set my ProfileContoller.shared.profile values. When I get to my navigation segue to pass the data over, my destinationVC.profile will not set its value to the sending profile object and I get nil instead.

My sendingVC is embedded in a navigation controller, while my destinationVC is embedded in Tab Bar Controller.

Segue SendingVC

Attributes Inspector SendingVC

DestinationVC

```<code>// Sending View Controller:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard let profile = ProfileController.shared.profile else { return }
    if segue.identifier == "signUpMemicTBC" {
        let destinationVC = segue.destination as? ProfileViewController
        destinationVC?.profile = profile

// Receiving ProfileViewController:
class ProfileViewController: UIViewController {

    // MARK: - IBOutlets
    @IBOutlet weak var fullNameLabel: UILabel!
    @IBOutlet weak var usernameLabel: UILabel!
    @IBOutlet weak var emailLabel: UILabel!

    // MARK: - Landing Pad
    var profile : Profile? {
        didSet {
            updateViews()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        updateViews()
    }

    func updateViews () {
        guard let profile = profile else { return }
        fullNameLabel.text = profile.firstName + " " + profile.lastName
        usernameLabel.text = profile.username
        emailLabel.text = profile.email
    }
}

// ProfileController:
class ProfileController {

    // MARK: - Properties
    var profile : Profile?

    // MARK: - Singleton
    static let shared = ProfileController()

}
</code>```

My sending object has data:
    (lldb) po profile
    Profile: 0x600000c873c0

The destination object is unexpectedly nil:
    (lldb) po destinationVC?.profile
    nil

答:
didSet triggers while your vc in segue isn't loaded yet so all outlets are nil

you need to put  updateViews() inside viewDidLoad

Plus your destination is a tabBar

```<code>let tab = segue.destination as! UITabBarController
let destinationVC = tab.viewControllers![2] as! ProfileViewController
</code>```

Body:
I'm having users fill out some profile information via texts fields (name, email, etc.), which is used to set my ProfileContoller.shared.profile values. When I get to my navigation segue to pass the data over, my destinationVC.profile will not set its value to the sending profile object and I get nil instead.

My sendingVC is embedded in a navigation controller, while my destinationVC is embedded in Tab Bar Controller.

Segue SendingVC

Attributes Inspector SendingVC

DestinationVC

// Sending View Controller:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard let profile = ProfileController.shared.profile else { return }
    if segue.identifier == "signUpMemicTBC" {
        let destinationVC = segue.destination as? ProfileViewController
        destinationVC?.profile = profile

// Receiving ProfileViewController:
class ProfileViewController: UIViewController {

    // MARK: - IBOutlets
    @IBOutlet weak var fullNameLabel: UILabel!
    @IBOutlet weak var usernameLabel: UILabel!
    @IBOutlet weak var emailLabel: UILabel!

    // MARK: - Landing Pad
    var profile : Profile? {
        didSet {
            updateViews()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        updateViews()
    }

    func updateViews () {
        guard let profile = profile else { return }
        fullNameLabel.text = profile.firstName + " " + profile.lastName
        usernameLabel.text = profile.username
        emailLabel.text = profile.email
    }
}

// ProfileController:
class ProfileController {

    // MARK: - Properties
    var profile : Profile?

    // MARK: - Singleton
    static let shared = ProfileController()

}

My sending object has data:
    (lldb) po profile
    Profile: 0x600000c873c0

The destination object is unexpectedly nil:
    (lldb) po destinationVC?.profile
    nil

Body:
didSet triggers while your vc in segue isn't loaded yet so all outlets are nil

you need to put  updateViews() inside viewDidLoad

Plus your destination is a tabBar

let tab = segue.destination as! UITabBarController
let destinationVC = tab.viewControllers![2] as! ProfileViewController


来源: stackexchange

问:
builder for HashMap
Guava provides us with great factory methods for Java types, such as Maps.newHashMap().

But are there also builders for java Maps?

```<code>HashMap<String,Integer> m = Maps.BuildHashMap.
    put("a",1).
    put("b",2).
    build();
</code>```

答:
Since Java 9 Map interface contains:

Map.of(k1,v1, k2,v2, ..)

Map.ofEntries(Map.entry(k1,v1), Map.entry(k2,v2), ..).

Limitations of those factory methods are that they:

can't hold nulls as keys and/or values (if you need to store nulls take a look at other answers)

produce immutable maps

If we need mutable map (like HashMap) we can use its copy-constructor and let it copy content of map created via Map.of(..)

```<code>Map<Integer, String> map = new HashMap<>( Map.of(1,"a", 2,"b", 3,"c") );
</code>```

ContentLicense: CC BY-SA 3.0

Title: builder for HashMap

Body:
Guava provides us with great factory methods for Java types, such as Maps.newHashMap().

But are there also builders for java Maps?

HashMap<String,Integer> m = Maps.BuildHashMap.
    put("a",1).
    put("b",2).
    build();

Body:
Since Java 9 Map interface contains:

Map.of(k1,v1, k2,v2, ..)

Map.ofEntries(Map.entry(k1,v1), Map.entry(k2,v2), ..).

Limitations of those factory methods are that they:

can't hold nulls as keys and/or values (if you need to store nulls take a look at other answers)

produce immutable maps

If we need mutable map (like HashMap) we can use its copy-constructor and let it copy content of map created via Map.of(..)

Map<Integer, String> map = new HashMap<>( Map.of(1,"a", 2,"b", 3,"c") );

ContentLicense: CC BY-SA 4.0


问:
how can i track which page i am on in asp.net-mvc
i have a link in a master page that says "Send feedback" which brings up a new web page:

When i go to that new page, i have a form and i want to populate a textbox with the URL that the person was on when they clicked the "Send Feedback" button.

How can i grab the current URL to pass that over?  should i do this on teh client side (jquery) or on the asp.net-mvc server side??

答:
There is no need to pass along the URL as you can check the UrlReferrer property on the Request object in the "Send feedback" action.

Use this as your controller action:

```<code>public ActionResult SendFeedback(string message) {
   var referrer = Request.UrlReferrer;
   feedbackService.Send(message, referrer);
}
</code>```

Body:
There is no need to pass along the URL as you can check the UrlReferrer property on the Request object in the "Send feedback" action.

Use this as your controller action:

public ActionResult SendFeedback(string message) {
   var referrer = Request.UrlReferrer;
   feedbackService.Send(message, referrer);
}


问:
Verify if a category already exist, if exists save() if doesn't exist add() PrestaShop
My project is with Webservices add categories and when I refresh the file of categories it creates the same categories I had before.

```<code>  foreach ($XMLRSString->Families->Family as $family)
        {
            $categories = $family->Code;

            $exists = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('select id_category from ps_category where id_category = "'.$categories['id_category'].'"');

                $category = new Category((int)$categories);

                $category->id=  (int)$categories;

                $category->id_category_default=(int)$family->Code;

                $category->force_id = true;

                $category->is_root_category = false;

                $category->name = array((int)Configuration::get('PS_LANG_DEFAULT') => $family->Designation);

                $category->link_rewrite = array((int)Configuration::get('PS_LANG_DEFAULT') =>  $family->Code);

                $category->id_parent = Configuration::get('PS_HOME_CATEGORY');

                if($exists){
                    $category->add();
                    echo "created ".$family->Code."<br>";
                }
                else{
                    $category->save();
                    echo "already exists ".$family->Code."<br>";
                }
        }
</code>```

It doesn't appear any error but it doesn't show up on PrestaShop categories

答:
No need to use if ($exists), as $category->save(); will already check if the category exists, if so it will update it, otherwise it will create it.

You can refer to your previous question on this topic:
How to test if a category already exists? PrestaShop

I think your issue comes from the fact your forgot to set the category as active:

$category->active = 1;

Also, you should check the return value of $category->save();.

I hope this helps!

Body:
My project is with Webservices add categories and when I refresh the file of categories it creates the same categories I had before.

  foreach ($XMLRSString->Families->Family as $family)
        {
            $categories = $family->Code;

            $exists = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('select id_category from ps_category where id_category = "'.$categories['id_category'].'"');

                $category = new Category((int)$categories);

                $category->id=  (int)$categories;

                $category->id_category_default=(int)$family->Code;

                $category->force_id = true;

                $category->is_root_category = false;

                $category->name = array((int)Configuration::get('PS_LANG_DEFAULT') => $family->Designation);

                $category->link_rewrite = array((int)Configuration::get('PS_LANG_DEFAULT') =>  $family->Code);

                $category->id_parent = Configuration::get('PS_HOME_CATEGORY');

                if($exists){
                    $category->add();
                    echo "created ".$family->Code."
";
                }
                else{
                    $category->save();
                    echo "already exists ".$family->Code."
";
                }
        }

It doesn't appear any error but it doesn't show up on PrestaShop categories


问:
ERROR in ./node_modules/@elastic/elasticsearch/lib/Connection.js Module not found: Error: Can't resolve 'http'
I am working on an angular 6 project and I updated the version of elasticsearch from 6 to 7 on the server, after changing the code of the old API to use the new one, these errors occurred, does anyone have any idea how to correct?

The angular application is made on visual studio code and elasticsearch is on a linux server.

```<code>import { Injectable } from '@angular/core';
// import { Clientex } from 'elasticsearch-browser';
import { Client } from '@elastic/elasticsearch';
// import * as elasticsearch from 'elasticsearch-browser';
// import { concatMapTo } from 'rxjs/operators';
// import { stringify } from '@angular/core/src/render3/util';

@Injectable({
  providedIn: 'root'
})

export class ElasticsearchService {

  private client: Client;
  // private clientex: Clientex;

  constructor() {
    if (!this.client) {
      this.connect();
    }
  }

  private connect() {
    /*this.client = new Client(
      {node: 'http://localhost:9200'}
    );*/
    this.client = new Client();
  }

  isAvailable(): Promise<any> {
    return this.client.ping({
    });
  }

  // tslint:disable-next-line:member-ordering
  private queryalldocs = {
    'query': {
      'match_all': {}
    }
  };

  getAllDocuments(_index, _type): any {
    this.client.search({
      index: _index,
      body: this.queryalldocs
    }, {
      ignore: [404]
    }, (err, { body, statusCode, headers, warnings }) => {
      if (err) { console.log(err); }
    });
}

  getAllDocumentsByKey(_index, _type, campo, valor) {
    const string = 'let match = {' + campo + ':' + valor + '}';
    return this.client.search({
      index: _index,
      type: _type,
      body: {
           // tslint:disable-next-line:no-shadowed-variable
           eval(string) {}
      }
    });
  }

  createDocument(value: any) {
    // return this.client.index(value);
    this.client.create(value);
  }

}
</code>```

ERRORS:

ERROR in ./node_modules/@elastic/elasticsearch/lib/Connection.js
Module not found: Error: Can't resolve 'http' in
'C:\Users\ICARO\Desktop\projetos\pastas\xtr-social\node_modules@elastic\elasticsearch\lib'

ERROR in ./node_modules/@elastic/elasticsearch/lib/Connection.js
Module not found: Error: Can't resolve 'https' in
'C:\Users\ICARO\Desktop\projetos\pastas\xtr-social\node_modules@elastic\elasticsearch\lib'

ERROR in ./node_modules/@elastic/elasticsearch/lib/Transport.js Module
not found: Error: Can't resolve 'os' in
'C:\Users\ICARO\Desktop\projetos\pastas\xtr-social\node_modules@elastic\elasticsearch\lib'

ERROR in ./node_modules/decompress-response/index.js Module not found:
Error: Can't resolve 'stream' in
'C:\Users\ICARO\Desktop\projetos\pastas\xtr-social\node_modules\decompress-response'

ERROR in ./node_modules/@elastic/elasticsearch/lib/Transport.js Module
not found: Error: Can't resolve 'zlib' in
'C:\Users\ICARO\Desktop\projetos\pastas\xtr-social\node_modules@elastic\elasticsearch\lib'

ERROR in ./node_modules/decompress-response/index.js Module not found:
Error: Can't resolve 'zlib' in
'C:\Users\ICARO\Desktop\projetos\pastas\xtr-social\node_modules\decompress-response'

答:
I believe you need to install elasticsearch-browser and then:</p>

```<code>import { Client } from 'elasticsearch-browser';
</code>```

Body:
I am working on an angular 6 project and I updated the version of elasticsearch from 6 to 7 on the server, after changing the code of the old API to use the new one, these errors occurred, does anyone have any idea how to correct?

The angular application is made on visual studio code and elasticsearch is on a linux server.

import { Injectable } from '@angular/core';
// import { Clientex } from 'elasticsearch-browser';
import { Client } from '@elastic/elasticsearch';
// import * as elasticsearch from 'elasticsearch-browser';
// import { concatMapTo } from 'rxjs/operators';
// import { stringify } from '@angular/core/src/render3/util';

@Injectable({
  providedIn: 'root'
})

export class ElasticsearchService {

  private client: Client;
  // private clientex: Clientex;

  constructor() {
    if (!this.client) {
      this.connect();
    }
  }

  private connect() {
    /*this.client = new Client(
      {node: 'http://localhost:9200'}
    );*/
    this.client = new Client();
  }

  isAvailable(): Promise<any> {
    return this.client.ping({
    });
  }

  // tslint:disable-next-line:member-ordering
  private queryalldocs = {
    'query': {
      'match_all': {}
    }
  };

  getAllDocuments(_index, _type): any {
    this.client.search({
      index: _index,
      body: this.queryalldocs
    }, {
      ignore: [404]
    }, (err, { body, statusCode, headers, warnings }) => {
      if (err) { console.log(err); }
    });
}

  getAllDocumentsByKey(_index, _type, campo, valor) {
    const string = 'let match = {' + campo + ':' + valor + '}';
    return this.client.search({
      index: _index,
      type: _type,
      body: {
           // tslint:disable-next-line:no-shadowed-variable
           eval(string) {}
      }
    });
  }

  createDocument(value: any) {
    // return this.client.index(value);
    this.client.create(value);
  }

}

ERRORS:

ERROR in ./node_modules/@elastic/elasticsearch/lib/Connection.js
Module not found: Error: Can't resolve 'http' in
'C:\Users\ICARO\Desktop\projetos\pastas\xtr-social\node_modules@elastic\elasticsearch\lib'

ERROR in ./node_modules/@elastic/elasticsearch/lib/Connection.js
Module not found: Error: Can't resolve 'https' in
'C:\Users\ICARO\Desktop\projetos\pastas\xtr-social\node_modules@elastic\elasticsearch\lib'

ERROR in ./node_modules/@elastic/elasticsearch/lib/Transport.js Module
not found: Error: Can't resolve 'os' in
'C:\Users\ICARO\Desktop\projetos\pastas\xtr-social\node_modules@elastic\elasticsearch\lib'

ERROR in ./node_modules/decompress-response/index.js Module not found:
Error: Can't resolve 'stream' in
'C:\Users\ICARO\Desktop\projetos\pastas\xtr-social\node_modules\decompress-response'

ERROR in ./node_modules/@elastic/elasticsearch/lib/Transport.js Module
not found: Error: Can't resolve 'zlib' in
'C:\Users\ICARO\Desktop\projetos\pastas\xtr-social\node_modules@elastic\elasticsearch\lib'

ERROR in ./node_modules/decompress-response/index.js Module not found:
Error: Can't resolve 'zlib' in
'C:\Users\ICARO\Desktop\projetos\pastas\xtr-social\node_modules\decompress-response'

Body:
I believe you need to install elasticsearch-browser and then:

import { Client } from 'elasticsearch-browser';


问:
how can I see data for last month in Fabric Answers? Or is it just for last 30 days overview
how can I see data for last month in Fabric Answers? Or is it just for last 30 days overview

I looked all documents on Fabric Answers website, blog and read almost every question here, but I have seen only data for 1 day, last 7 days or last 30 days.

答: Fabric/Firebase here - it depends what you're looking for. If you're talking about the active user categories, the dashboard will show you Daily Active Users (1 day), Weekly Active Users (7 days), or Monthly Active Users (30 days). If you just want Answers data that's more than 30 days old in general, you can actually export up to a year's worth of data directly from the Fabric dashboard for many different metrics. Check out this link for more information: https://docs.fabric.io/android/answers/export-data.html. Hope that answers your question.</p>


问:
Restart the while loop after the error message in the output
Problem: How can I restart the following codeblock? My idea is if you enter a character that will return an error message. What is the condition for the loop?

```<code>string r_operation;
Console.Write("\tBitte geben Sie ihre Rechenoperation ein: ");
r_operation = Console.ReadLine();
-------------

while (?r_operation = Console.ReadLine())
{
Console.WriteLine("\tUngültige Eingabe. Bitte geben Sie nur Zahlen ein!");
}
</code>```

答:
You can convert your existing code to use the int.TryParse method, which returns a bool indicating if the input string is a valid number (and sets an out parameter to the converted value):

```<code>Console.Write("\tBitte geben Sie ihre Rechenoperation ein: ");
string r_operation = Console.ReadLine();
int result = 0;

while (!int.TryParse(r_operation, out result))
{
    Console.WriteLine("\tUngültige Eingabe. Bitte geben Sie nur Zahlen ein!");
    Console.Write("\tBitte geben Sie ihre Rechenoperation ein: ");
    r_operation = Console.ReadLine();
}

// When we exit the while loop, we know that 'r_operation' is a number,
// and it's value is stored as an integer in 'result'
</code>```

Another way to do this is to encapsulate the process of getting a strongly-typed number from the user into a method. Here's one I use:

```<code>private static int GetIntFromUser(string prompt, Func<int, bool> validator = null)
{
    int result;
    var cursorTop = Console.CursorTop;

    do
    {
        ClearSpecificLineAndWrite(cursorTop, prompt);
    } while (!int.TryParse(Console.ReadLine(), out result) ||
             !(validator?.Invoke(result) ?? true));

    return result;
}

private static void ClearSpecificLineAndWrite(int cursorTop, string message)
{
    Console.SetCursorPosition(0, cursorTop);
    Console.Write(new string(' ', Console.WindowWidth));
    Console.SetCursorPosition(0, cursorTop);
    Console.Write(message);
}
</code>```

With these helper methods, your code can be reduced to:

```<code>int operation = GetIntFromUser("\tBitte geben Sie ihre Rechenoperation ein: ");
</code>```

And if you wanted to add some additional constraints, the helper method also takes in a validator function (which takes an int and returns a bool indicating whether or not the int is valid). So if you wanted to restrict the numbers to be from 1 to 5, you could do something like:

```<code>var result = GetIntFromUser("Enter a number from 1 to 5: ", i => i > 0 && i < 6);
</code>```

Body:
Problem: How can I restart the following codeblock? My idea is if you enter a character that will return an error message. What is the condition for the loop?

string r_operation;
Console.Write("\tBitte geben Sie ihre Rechenoperation ein: ");
r_operation = Console.ReadLine();
-------------

while (?r_operation = Console.ReadLine())
{
Console.WriteLine("\tUngültige Eingabe. Bitte geben Sie nur Zahlen ein!");
}

Body:
You can convert your existing code to use the int.TryParse method, which returns a bool indicating if the input string is a valid number (and sets an out parameter to the converted value):

Console.Write("\tBitte geben Sie ihre Rechenoperation ein: ");
string r_operation = Console.ReadLine();
int result = 0;

while (!int.TryParse(r_operation, out result))
{
    Console.WriteLine("\tUngültige Eingabe. Bitte geben Sie nur Zahlen ein!");
    Console.Write("\tBitte geben Sie ihre Rechenoperation ein: ");
    r_operation = Console.ReadLine();
}

// When we exit the while loop, we know that 'r_operation' is a number,
// and it's value is stored as an integer in 'result'

Another way to do this is to encapsulate the process of getting a strongly-typed number from the user into a method. Here's one I use:

private static int GetIntFromUser(string prompt, Func<int, bool> validator = null)
{
    int result;
    var cursorTop = Console.CursorTop;

    do
    {
        ClearSpecificLineAndWrite(cursorTop, prompt);
    } while (!int.TryParse(Console.ReadLine(), out result) ||
             !(validator?.Invoke(result) ?? true));

    return result;
}

private static void ClearSpecificLineAndWrite(int cursorTop, string message)
{
    Console.SetCursorPosition(0, cursorTop);
    Console.Write(new string(' ', Console.WindowWidth));
    Console.SetCursorPosition(0, cursorTop);
    Console.Write(message);
}

With these helper methods, your code can be reduced to:

int operation = GetIntFromUser("\tBitte geben Sie ihre Rechenoperation ein: ");

And if you wanted to add some additional constraints, the helper method also takes in a validator function (which takes an int and returns a bool indicating whether or not the int is valid). So if you wanted to restrict the numbers to be from 1 to 5, you could do something like:

var result = GetIntFromUser("Enter a number from 1 to 5: ", i => i > 0 && i < 6);


问:
Parsing JSON effectively in Flutter/Dart
How to extract a pair of values out of a JSON using dart

This is the function I have so far:

This is the JSON:

```<code>{
    "displayNames": [
        "John Doe",
        "Chloé Kamgang",
        "Lady Testing of Tarth"
    ],
    "users": [
        {
            "uid": "1tcPRqNZ7wexX2DWa11V9Ay1zES2",
            "displayName": "John Doe"
        },
        {
            "uid": "aZg7Emp8H9W42irnM73NBdTe6YM2",
            "displayName": "Chloé Kamgang",
            "photoURL": "https://firebasestorage.googleapis.com/v0/b/atalaku-fcf9e.appspot.com/o/Profilescaled_1e189635-0bc0-4791-ba20-6aded7ad3e8f7210544.jpg621jpg?alt=media&token=f5cffac3-a20c-4a83-8241-4fab16a9bd66"
        },
        {
            "uid": "hXzyTuDE8eafnSxITmz7ZdMQDnw1",
            "displayName": "Lady Testing of Tarth",
            "photoURL": "https://firebasestorage.googleapis.com/v0/b/atalaku-fcf9e.appspot.com/o/Profilescaled_image_picker8162975920.jpg645jpg?alt=media&token=269007d1-09ee-4fe4-b7ad-72aa7cea756a"
        }
    ]
}

</code>```

And this is the function:

Future<List<Map<String, dynamic>>> getProfilesBySuggestion(
      String sSuggestion) async {
    try {
      List<Map<String, dynamic>> listToReturn = [];
      if (sSuggestion == null ||
          sSuggestion.isEmpty ||
          !sSuggestion.startsWith('@')) return listToReturn;

      //Getting all the names
      Map<String, dynamic> listUsers = await getAllUsers();
      if (listUsers == null) return listToReturn;

      //Returning only the names corresponding
      List<dynamic> listNames = listUsers['displayNames'];
      for (String name in listNames)
        if (name
            .toLowerCase()
            .startsWith(sSuggestion.substring(1).toLowerCase())) {
          List<Map<String, dynamic>> listOfusers = listUsers['users'] as List<Map<String, dynamic>>;
          Map<String, dynamic> rightOne = listOfusers.firstWhere((user) => user['displayName'] == name);
          String sPhotoURL = rightOne['photoURL'];
          print('** name = $name, photoURL = $sPhotoURL');
          listToReturn.add({'name': name, 'photoURL': sPhotoURL});
        }
      return listToReturn;
    } catch (error) {
      print('*** Error During getProfilesBySuggestion: ${error.toString()}');
      return [
        {'errorMessage': error.toString()}
      ];
    }
  }
```

What I want is a list of pair (name, photoURL). I am using the flutter_typeahead plugin, I want to display a list of names and their respective avatars. As you can see, I am using Firebase. Please let me know if there is a better option as well, as this will get pretty heavy with scale. Thank you!

答:
A good starting point when working with data that's not organised the way you want it, is to re-organize it.

And if that's not an option, you can still mitigate the impact. It's always easier to work with plain old dart classes than json, so I'd encourage you to map the json to classes.

I usually use package:built_value for that. There is a tool that helps map json:
https://charafau.github.io/json2builtvalue/ Careful, it's not 100%. Eg. it will not include photoUrl field if you just copy-paste your json.

Basically, I'd take the json.users, and map it to objects. Make sure to make photoUrl optional.

Once that's done, you can create any lookup table you want. You could just have a List<User> to iterate over names and photoUrls, or you could create a Map<String, User> to look up users by their name.

Tip: class Map has got a number of constructors that you can work with.

Body:
How to extract a pair of values out of a JSON using dart

This is the function I have so far:

This is the JSON:

{
    "displayNames": [
        "John Doe",
        "Chloé Kamgang",
        "Lady Testing of Tarth"
    ],
    "users": [
        {
            "uid": "1tcPRqNZ7wexX2DWa11V9Ay1zES2",
            "displayName": "John Doe"
        },
        {
            "uid": "aZg7Emp8H9W42irnM73NBdTe6YM2",
            "displayName": "Chloé Kamgang",
            "photoURL": "https://firebasestorage.googleapis.com/v0/b/atalaku-fcf9e.appspot.com/o/Profilescaled_1e189635-0bc0-4791-ba20-6aded7ad3e8f7210544.jpg621jpg?alt=media&token=f5cffac3-a20c-4a83-8241-4fab16a9bd66"
        },
        {
            "uid": "hXzyTuDE8eafnSxITmz7ZdMQDnw1",
            "displayName": "Lady Testing of Tarth",
            "photoURL": "https://firebasestorage.googleapis.com/v0/b/atalaku-fcf9e.appspot.com/o/Profilescaled_image_picker8162975920.jpg645jpg?alt=media&token=269007d1-09ee-4fe4-b7ad-72aa7cea756a"
        }
    ]
}

And this is the function:

Future<List<Map<String, dynamic>>> getProfilesBySuggestion(
      String sSuggestion) async {
    try {
      List<Map<String, dynamic>> listToReturn = [];
      if (sSuggestion == null ||
          sSuggestion.isEmpty ||
          !sSuggestion.startsWith('@')) return listToReturn;

      //Getting all the names
      Map<String, dynamic> listUsers = await getAllUsers();
      if (listUsers == null) return listToReturn;

      //Returning only the names corresponding
      List<dynamic> listNames = listUsers['displayNames'];
      for (String name in listNames)
        if (name
            .toLowerCase()
            .startsWith(sSuggestion.substring(1).toLowerCase())) {
          List<Map<String, dynamic>> listOfusers = listUsers['users'] as List<Map<String, dynamic>>;
          Map<String, dynamic> rightOne = listOfusers.firstWhere((user) => user['displayName'] == name);
          String sPhotoURL = rightOne['photoURL'];
          print('** name = $name, photoURL = $sPhotoURL');
          listToReturn.add({'name': name, 'photoURL': sPhotoURL});
        }
      return listToReturn;
    } catch (error) {
      print('*** Error During getProfilesBySuggestion: ${error.toString()}');
      return [
        {'errorMessage': error.toString()}
      ];
    }
  }

What I want is a list of pair (name, photoURL). I am using the flutter_typeahead plugin, I want to display a list of names and their respective avatars. As you can see, I am using Firebase. Please let me know if there is a better option as well, as this will get pretty heavy with scale. Thank you!


问:
Modifying a data structure while iterating over it
What happens when you add elements to a data structure such as a vector while
iterating over it. Can I not do this?

I tried this and it breaks:

```<code>int main() {
    vector<int> x = { 1, 2, 3 };

    int j = 0;
    for (auto it = x.begin(); it != x.end(); ++it) {
        x.push_back(j);
        j++;
        cout << j << " .. ";
    }
}
</code>```

答:
What happens when you add elements to a data structure such as a vector while iterating over it. Can I not to this?

The iterator would become invalid IF the vector resizes itself. So you're safe as long as the vector doesn't resize itself.

I would suggest you to avoid this.

The short explanation why resizing invalidates iterator:

Initially the vector has some capacity (which you can know by calling vector::capacity().), and you add elements to it, and when it becomes full, it allocates larger size of memory, copying the elements from the old memory to the newly allocated memory, and then deletes the old memory, and the problem is that iterator still points to the old memory, which has been deallocated. That is how resizing invalidates iterator.

Here is simple demonstration. Just see when the capacity changes:

```<code>std::vector<int> v;
for(int i = 0 ; i < 100 ; i++ )
{
  std::cout <<"size = "<<v.size()<<", capacity = "<<v.capacity()<<std::endl;
  v.push_back(i);
}
</code>```

Partial Output:

```<code>size = 0, capacity = 0
size = 1, capacity = 1
size = 2, capacity = 2
size = 3, capacity = 4
size = 4, capacity = 4
size = 5, capacity = 8
size = 6, capacity = 8
size = 7, capacity = 8
size = 8, capacity = 8
size = 9, capacity = 16
size = 10, capacity = 16
</code>```

See the complete output here : http://ideone.com/rQfWe

Note: capacity() tells the maximum number of elements the vector can contain without allocating new memory, and size() tells the number of elements the vector currently containing.

Body:
What happens when you add elements to a data structure such as a vector while
iterating over it. Can I not do this?

I tried this and it breaks:

int main() {
    vector<int> x = { 1, 2, 3 };

    int j = 0;
    for (auto it = x.begin(); it != x.end(); ++it) {
        x.push_back(j);
        j++;
        cout << j << " .. ";
    }
}

Body:
What happens when you add elements to a data structure such as a vector while iterating over it. Can I not to this?

The iterator would become invalid IF the vector resizes itself. So you're safe as long as the vector doesn't resize itself.

I would suggest you to avoid this.

The short explanation why resizing invalidates iterator:

Initially the vector has some capacity (which you can know by calling vector::capacity().), and you add elements to it, and when it becomes full, it allocates larger size of memory, copying the elements from the old memory to the newly allocated memory, and then deletes the old memory, and the problem is that iterator still points to the old memory, which has been deallocated. That is how resizing invalidates iterator.

Here is simple demonstration. Just see when the capacity changes:

std::vector<int> v;
for(int i = 0 ; i < 100 ; i++ )
{
  std::cout <<"size = "<<v.size()<<", capacity = "<<v.capacity()<<std::endl;
  v.push_back(i);
}

Partial Output:

size = 0, capacity = 0
size = 1, capacity = 1
size = 2, capacity = 2
size = 3, capacity = 4
size = 4, capacity = 4
size = 5, capacity = 8
size = 6, capacity = 8
size = 7, capacity = 8
size = 8, capacity = 8
size = 9, capacity = 16
size = 10, capacity = 16

See the complete output here : http://ideone.com/rQfWe

Note: capacity() tells the maximum number of elements the vector can contain without allocating new memory, and size() tells the number of elements the vector currently containing.


问:
Objective-c app crash only when exported (ad-hoc or on AppStore) in correspondence of dispatch_async
I'm experiencing a crash on an iOS app, but only when it is archived and exported (ad-hoc or on AppStore). The develop version does not have any problem.

The crash is in correspondence of a dispatch_async on the main queue. In particular:

    dispatch_async(dispatch_get_main_queue(), ^{
    ...
            [self.view hideToastActivity];
            self.view.userInteractionEnabled = YES;
            if (self.delegate != nil) {
            [self.delegate postFooObject:foo];
        }
    ...
    });
```

<p>As you can see, the code block calls a delegate method, whose code is:</p>

<pre class="lang-c prettyprint-override"><code>
- (void)postFooObject:(Foo *)foo {
        [self.view makeToastActivity:CSToastPositionCenter];
        self.view.userInteractionEnabled = NO;

        [[FooManager sharedManager] postFoo:&foo completition:^(BOOL success) {

            if (success) {
                [self.view hideToastActivity];
                self.view.userInteractionEnabled = YES;

                [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
            }
}
</code>```

The postFooObject delegate method contains a call to a REST endpoint, which returns successfully.

Since it is a production app, I  managed to print the log when the app is killed by means of iSO Console application. The following screenshot shows the device log at the moment of the crash:

The app process is identified by "indemni".

Executing all the instructions contained in the dispatch block outside the dispatch_async itself instead was fine.

Can you help me?
Thanks

答:
The main queue should be used only for UI tasks, if u are making rest calls try to use a global queue and use the main just to update the UI components with the new data.

Are you testing the develop version on simulator or an iPhone? This could generate different responses to this code, but i think that change the queue should solve your problem! :)

Good luck!

Body:
I'm experiencing a crash on an iOS app, but only when it is archived and exported (ad-hoc or on AppStore). The develop version does not have any problem.

The crash is in correspondence of a dispatch_async on the main queue. In particular:

    dispatch_async(dispatch_get_main_queue(), ^{
    ...
            [self.view hideToastActivity];
            self.view.userInteractionEnabled = YES;
            if (self.delegate != nil) {
            [self.delegate postFooObject:foo];
        }
    ...
    });

As you can see, the code block calls a delegate method, whose code is:

- (void)postFooObject:(Foo *)foo {
        [self.view makeToastActivity:CSToastPositionCenter];
        self.view.userInteractionEnabled = NO;

        [[FooManager sharedManager] postFoo:&foo completition:^(BOOL success) {

            if (success) {
                [self.view hideToastActivity];
                self.view.userInteractionEnabled = YES;

                [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
            }
}

The postFooObject delegate method contains a call to a REST endpoint, which returns successfully.

Since it is a production app, I  managed to print the log when the app is killed by means of iSO Console application. The following screenshot shows the device log at the moment of the crash:

The app process is identified by "indemni".

Executing all the instructions contained in the dispatch block outside the dispatch_async itself instead was fine.

Can you help me?
Thanks


问:
How to delete files in the app's sandbox?
I have a UITableView set up and its data source is the app's sandbox, so all the rows are filled with the files that were imported using UIDocumentPicker, but I also need to be able to delete those files.

The delete function works, I am able to slide and delete a row and everything, but the file stays in the app's sandbox, so every time I import a new file, the rows are refilled (the TableView reloads every time something is imported) with the previously "deleted" stuff.

```<code>    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == UITableViewCell.EditingStyle.delete {
            self.deleteFile()
            importedfiles.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic)
        }

 }
</code>```

Plus everything that is in the code already, I need the function to delete the file from the app's sandbox (importedfiles).

Here's what I've got so far, I am able to delete files, but only the entire directory, which is not what I want. Code:

```<code>   func deleteFile() {
        let dirPaths = FM.urls(for: .documentDirectory, in: .userDomainMask)
        let docsDir = dirPaths[0].path

        if FM.fileExists(atPath: docsDir) {
            do {
                try FM.removeItem(atPath: docsDir)
            } catch {
                print("Could not delete file: \(error)")
            }
        }
    }
</code>```

Edit: "importedfiles" are files that were imported in the app's directory (documents) using UIDocumentPickerViewController. And the TableView uses this data to create cells.

答:
Change your delete method to

```<code>func deleteFile(_ url: URL) {
    let fm = FileManager.default
    do {
        try fm.removeItem(at: url)
    } catch {
        print(error)
    }
}
</code>```

and call it

```<code>if editingStyle == UITableViewCell.EditingStyle.delete {
    self.deleteFile(importedfiles[indexPath.row])
    importedfiles.remove(at: indexPath.row)
    tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic)
}
</code>```

This should work but there is no error handling and if you want that you can define your method to return Result

```<code>func deleteFile(_ url: URL) -> Result<Void,Error> {
    let fm = FileManager.default
    do {
        try fm.removeItem(at: url)
        return .success(())
    } catch {
        return .failure(error)
    }
}
</code>```

and handle the result in a switch

```<code>let result = deleteFile(importedfiles[indexPath.row])
switch result {
case .success:
    //Maybe update array and table view here
case .failure(let error):
     //dislplay error?
}
</code>```

Body:
I have a UITableView set up and its data source is the app's sandbox, so all the rows are filled with the files that were imported using UIDocumentPicker, but I also need to be able to delete those files.

The delete function works, I am able to slide and delete a row and everything, but the file stays in the app's sandbox, so every time I import a new file, the rows are refilled (the TableView reloads every time something is imported) with the previously "deleted" stuff.

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == UITableViewCell.EditingStyle.delete {
            self.deleteFile()
            importedfiles.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic)
        }

 }

Plus everything that is in the code already, I need the function to delete the file from the app's sandbox (importedfiles).

Here's what I've got so far, I am able to delete files, but only the entire directory, which is not what I want. Code:

   func deleteFile() {
        let dirPaths = FM.urls(for: .documentDirectory, in: .userDomainMask)
        let docsDir = dirPaths[0].path

        if FM.fileExists(atPath: docsDir) {
            do {
                try FM.removeItem(atPath: docsDir)
            } catch {
                print("Could not delete file: \(error)")
            }
        }
    }

Edit: "importedfiles" are files that were imported in the app's directory (documents) using UIDocumentPickerViewController. And the TableView uses this data to create cells.

Body:
Change your delete method to

func deleteFile(_ url: URL) {
    let fm = FileManager.default
    do {
        try fm.removeItem(at: url)
    } catch {
        print(error)
    }
}

and call it

if editingStyle == UITableViewCell.EditingStyle.delete {
    self.deleteFile(importedfiles[indexPath.row])
    importedfiles.remove(at: indexPath.row)
    tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic)
}

This should work but there is no error handling and if you want that you can define your method to return Result

func deleteFile(_ url: URL) -> Result<Void,Error> {
    let fm = FileManager.default
    do {
        try fm.removeItem(at: url)
        return .success(())
    } catch {
        return .failure(error)
    }
}

and handle the result in a switch

let result = deleteFile(importedfiles[indexPath.row])
switch result {
case .success:
    //Maybe update array and table view here
case .failure(let error):
     //dislplay error?
}


问:
How to access data from one function in another function
I have a web scraping program and in my spider I need to access to information in my process_csv function but I need to access it from my start_requests function.  in my process_csv function I have a variable "ip" which takes ips from a CSV file and adds http:// to the beginning and the port number to the end and the function goes on to pair them with a user agent and URL that needs to be scraped.  Anyways I need access to those ips in my start_requests function therefore I need to call the variable "ip" from my start_requests function.  How would I do that?

SplashSpider.py

```<code>import csv
from scrapy.spiders import Spider
from scrapy_splash import SplashRequest
from ..items import GameItem

# process the csv file so the url + ip address + useragent pairs are the same as defined in the file # returns a list of dictionaries, example:
# [ {'url': 'http://www.starcitygames.com/catalog/category/Rivals%20of%20Ixalan',
#    'ip': 'http://204.152.114.244:8050',
#    'ua': "Mozilla/5.0 (BlackBerry; U; BlackBerry 9320; en-GB) AppleWebKit/534.11"},
#    ...
# ]
def process_csv(csv_file):
    data = []
    reader = csv.reader(csv_file)
    next(reader)
    for fields in reader:
        if fields[0] != "":
            url = fields[0]
        else:
            continue # skip the whole row if the url column is empty
        if fields[1] != "":
            ip = "http://" + fields[1] + ":8050" # adding http and port because this is the needed scheme
        if fields[2] != "":
            useragent = fields[2]
        data.append({"url": url, "ip": ip, "ua": useragent})
    return data

class MySpider(Spider):
    name = 'splash_spider'  # Name of Spider

    # notice that we don't need to define start_urls
    # just make sure to get all the urls you want to scrape inside start_requests function

    # getting all the url + ip address + useragent pairs then request them
    def start_requests(self):

        # get the file path of the csv file that contains the pairs from the settings.py
        with open(self.settings["PROXY_CSV_FILE"], mode="r") as csv_file:
            # requests is a list of dictionaries like this -> {url: str, ua: str, ip: str}
            requests = process_csv(csv_file)

        for req in requests:
            # no need to create custom middlewares
            # just pass useragent using the headers param, and pass proxy using the meta param
            yield SplashRequest(url=req["url"], callback=self.parse, args={"wait": 3},
                                splash_url = ip,
                                headers={"User-Agent": req["ua"]},
                                meta={
                                    "proxy": (req["ip"]),
                                  })

    # Scraping
#    def parse(self, response):
#        item = GameItem()
#        for game in response.css("tr"):
#            # Card Name
#            item["card_name"] = game.css("a.card_popup::text").extract_first()
#            yield item
</code>```

答:
In your process_csv function, you are appending a list called data with {"url": url, "ip": ip, "ua": useragent}. So you can call each of those records from the function, which will return a dict and then you can call the ip. Example:

request_ip = process_csv(csv_file)[0]["ip"] - will return the ip in the first record in the list. You can run a loop to get all the ip's and store them in a list.

Hope this helps.

Body:
I have a web scraping program and in my spider I need to access to information in my process_csv function but I need to access it from my start_requests function.  in my process_csv function I have a variable "ip" which takes ips from a CSV file and adds http:// to the beginning and the port number to the end and the function goes on to pair them with a user agent and URL that needs to be scraped.  Anyways I need access to those ips in my start_requests function therefore I need to call the variable "ip" from my start_requests function.  How would I do that?

SplashSpider.py

import csv
from scrapy.spiders import Spider
from scrapy_splash import SplashRequest
from ..items import GameItem

# process the csv file so the url + ip address + useragent pairs are the same as defined in the file # returns a list of dictionaries, example:
# [ {'url': 'http://www.starcitygames.com/catalog/category/Rivals%20of%20Ixalan',
#    'ip': 'http://204.152.114.244:8050',
#    'ua': "Mozilla/5.0 (BlackBerry; U; BlackBerry 9320; en-GB) AppleWebKit/534.11"},
#    ...
# ]
def process_csv(csv_file):
    data = []
    reader = csv.reader(csv_file)
    next(reader)
    for fields in reader:
        if fields[0] != "":
            url = fields[0]
        else:
            continue # skip the whole row if the url column is empty
        if fields[1] != "":
            ip = "http://" + fields[1] + ":8050" # adding http and port because this is the needed scheme
        if fields[2] != "":
            useragent = fields[2]
        data.append({"url": url, "ip": ip, "ua": useragent})
    return data

class MySpider(Spider):
    name = 'splash_spider'  # Name of Spider

    # notice that we don't need to define start_urls
    # just make sure to get all the urls you want to scrape inside start_requests function

    # getting all the url + ip address + useragent pairs then request them
    def start_requests(self):

        # get the file path of the csv file that contains the pairs from the settings.py
        with open(self.settings["PROXY_CSV_FILE"], mode="r") as csv_file:
            # requests is a list of dictionaries like this -> {url: str, ua: str, ip: str}
            requests = process_csv(csv_file)

        for req in requests:
            # no need to create custom middlewares
            # just pass useragent using the headers param, and pass proxy using the meta param
            yield SplashRequest(url=req["url"], callback=self.parse, args={"wait": 3},
                                splash_url = ip,
                                headers={"User-Agent": req["ua"]},
                                meta={
                                    "proxy": (req["ip"]),
                                  })

    # Scraping
#    def parse(self, response):
#        item = GameItem()
#        for game in response.css("tr"):
#            # Card Name
#            item["card_name"] = game.css("a.card_popup::text").extract_first()
#            yield item


问:
ImproperlyConfigured: The included URLconf 'buttonpython.urls' does not appear to have any patterns in it
The error im getting is

django.core.exceptions.ImproperlyConfigured: The included URLconf
  'buttonpython.urls' does not appear to have any patterns in it. If you
  see valid patterns in the file then the issue is probably caused by a
  circular import.

I am following an older django tutorial because those are literally all i can find and got his error.
Here is the urls.py:

```<code>from . import views
from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.button)
]
</code>```

Settings.py (i included this because i found the buttonpython.urls variable in it):

```<code>INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'buttonpython.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'buttonpython.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'
</code>```

Views.py:

```<code>from django.shortcuts import render
from . import urls.py
import requests
from bs4 import BeautifulSoup

def button(request):
    return render(request, 'home.html')

def output(request):
    def trade_spider(max_pages):
        page = 1
        data = ''
        while(page <= max_pages):
                search = 'Ipad'
                url = 'https://www.ebay.com/sch/i.html?_from=R40&_nkw=' + search + '&_sacat=0&_pgn=' + str(page)
                src = requests.get(url)
                text = src.text
                soup = BeautifulSoup(text, features="html.parser")
                for link in soup.findAll('a', {'class': 's-item__link'}):
                        href = link.get('href')
                        title = link.string
                        if(title == None):
                            title = "Sorry the title was unavailable however you can check the price."
                        price = get_item_price(href)
                        data += href + '\n' + title + '\n' + price + '\n'

                page+=1
        return data

    def get_item_price(item_url):
        src = requests.get(item_url)
        text = src.text
        soup = BeautifulSoup(text, features="html.parser")
        for item_price in soup.findAll('span', {'class': 'notranslate'}):
                price = item_price.string
                return price

    data = trade_spider(1)
    return render(request, 'home.html', {'data':data})
</code>```

I am stumped any help would be appreciated.

答:
start project:

```<code>django-admin.py startproject buttonpython

cd buttonpython
</code>```

start app:

```<code>django-admin.py startapp app_name
</code>```

settings.py:

```<code>INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',

        'app_name',
    ]
</code>```

app_name/views.py same as your views.py in your question. without import urls.py.

urls.py:

```<code>from app_name import views
from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.button, name="home")
]
</code>```

Body:
The error im getting is

django.core.exceptions.ImproperlyConfigured: The included URLconf
  'buttonpython.urls' does not appear to have any patterns in it. If you
  see valid patterns in the file then the issue is probably caused by a
  circular import.

I am following an older django tutorial because those are literally all i can find and got his error.
Here is the urls.py:

from . import views
from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.button)
]

Settings.py (i included this because i found the buttonpython.urls variable in it):

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'buttonpython.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'buttonpython.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'

Views.py:

from django.shortcuts import render
from . import urls.py
import requests
from bs4 import BeautifulSoup

def button(request):
    return render(request, 'home.html')

def output(request):
    def trade_spider(max_pages):
        page = 1
        data = ''
        while(page <= max_pages):
                search = 'Ipad'
                url = 'https://www.ebay.com/sch/i.html?_from=R40&_nkw=' + search + '&_sacat=0&_pgn=' + str(page)
                src = requests.get(url)
                text = src.text
                soup = BeautifulSoup(text, features="html.parser")
                for link in soup.findAll('a', {'class': 's-item__link'}):
                        href = link.get('href')
                        title = link.string
                        if(title == None):
                            title = "Sorry the title was unavailable however you can check the price."
                        price = get_item_price(href)
                        data += href + '\n' + title + '\n' + price + '\n'

                page+=1
        return data

    def get_item_price(item_url):
        src = requests.get(item_url)
        text = src.text
        soup = BeautifulSoup(text, features="html.parser")
        for item_price in soup.findAll('span', {'class': 'notranslate'}):
                price = item_price.string
                return price

    data = trade_spider(1)
    return render(request, 'home.html', {'data':data})

I am stumped any help would be appreciated.

Body:
start project:

django-admin.py startproject buttonpython

cd buttonpython

start app:

django-admin.py startapp app_name

settings.py:

INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',

        'app_name',
    ]

app_name/views.py same as your views.py in your question. without import urls.py.

urls.py:

from app_name import views
from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.button, name="home")
]


问:
Spring with Quartz worker initialize a member only once?
I have a QuartzJob with multiple methods that call the same rest API

The class holds a member (configuration ) with the  rest api configuration.

The  rest api configuration is initialize once using getConfiguration method.

```<code>public QuartzJob implements Job{
     @Value("${API_URL}")private String apiUrl;

     ApiCallConfiguration configuration = getConfiguration();

     method1(){call api using configuration  }
     method2(){call api using configuration  }
     method3(){call api using configuration  }
}
</code>```

When I try to create a constructor, it fails probably because  the API values are not constructed yet...  @Value("${API_URL}")private String apiUrl;

Exception below.

what is the correct way to initialize the configuration property only once in the QuartzJob after everything is set up?

```<code>Caused by: java.lang.NullPointerException: Configuration key     Caused by: java.lang.NullPointerException: Configuration key API_URL has no value
 at org.apache.commons.lang3.Validate.notBlank(Validate.java:451)
 at com.xerox.printerTech.quartz.jobs.PrinterVerificationJob.getPrinterRestApiConfig(PrinterVerificationJob.java:722)
 at com.xerox.printerTech.quartz.jobs.PrinterVerificationJob.<init>(PrinterVerificationJob.java:164)
 ... 10 more  has no value
 at org.apache.commons.lang3.Validate.notBlank(Validate.java:451)
 at com.xerox.printerTech.quartz.jobs.PrinterVerificationJob.getPrinterRestApiConfig(PrinterVerificationJob.java:722)
 at com.xerox.printerTech.quartz.jobs.PrinterVerificationJob.<init>(PrinterVerificationJob.java:164)
 ... 10 more
</code>```

答:
I was able to resolve this issue using  @Component and  @Autowired

here is a sample code:

```<code>public QuartzJob implements Job{

    @Autowired
    ApiCallConfiguration configuration;

     method1(){configuration.getApiUrl();  }
     method2(){configuration.apiUseSSL();  }
     method3(){configuration.getApiUserName();  }
}

@Component
public class ApiCallConfiguration {

    public ApiCallConfiguration(
                @Value("${API_URL}")      String apiUrl,
                @Value("${API_URL_SSL}")  String apiUseSSL
                @Value("${API_USER_NAME}")  String apiUserName
               ){
                this.apiUrl = apiUrl;
                this.apiUseSSL = apiUseSSL;
                this.apiUserName = apiUserName;
                }

    }
</code>```

Body:
I have a QuartzJob with multiple methods that call the same rest API

The class holds a member (configuration ) with the  rest api configuration.

The  rest api configuration is initialize once using getConfiguration method.

public QuartzJob implements Job{
     @Value("${API_URL}")private String apiUrl;

     ApiCallConfiguration configuration = getConfiguration();

     method1(){call api using configuration  }
     method2(){call api using configuration  }
     method3(){call api using configuration  }
}

When I try to create a constructor, it fails probably because  the API values are not constructed yet...  @Value("${API_URL}")private String apiUrl;

Exception below.

what is the correct way to initialize the configuration property only once in the QuartzJob after everything is set up?

Caused by: java.lang.NullPointerException: Configuration key     Caused by: java.lang.NullPointerException: Configuration key API_URL has no value
 at org.apache.commons.lang3.Validate.notBlank(Validate.java:451)
 at com.xerox.printerTech.quartz.jobs.PrinterVerificationJob.getPrinterRestApiConfig(PrinterVerificationJob.java:722)
 at com.xerox.printerTech.quartz.jobs.PrinterVerificationJob.<init>(PrinterVerificationJob.java:164)
 ... 10 more  has no value
 at org.apache.commons.lang3.Validate.notBlank(Validate.java:451)
 at com.xerox.printerTech.quartz.jobs.PrinterVerificationJob.getPrinterRestApiConfig(PrinterVerificationJob.java:722)
 at com.xerox.printerTech.quartz.jobs.PrinterVerificationJob.<init>(PrinterVerificationJob.java:164)
 ... 10 more

Body:
I was able to resolve this issue using  @Component and  @Autowired

here is a sample code:

public QuartzJob implements Job{

    @Autowired
    ApiCallConfiguration configuration;

     method1(){configuration.getApiUrl();  }
     method2(){configuration.apiUseSSL();  }
     method3(){configuration.getApiUserName();  }
}

@Component
public class ApiCallConfiguration {

    public ApiCallConfiguration(
                @Value("${API_URL}")      String apiUrl,
                @Value("${API_URL_SSL}")  String apiUseSSL
                @Value("${API_USER_NAME}")  String apiUserName
               ){
                this.apiUrl = apiUrl;
                this.apiUseSSL = apiUseSSL;
                this.apiUserName = apiUserName;
                }

    }


问:
nHibernate ProxyFactory issues
I am setting up my first nHibernate project.  I have created a simple web form that accepts a name and an id however, I keep on getting the following error:

The ProxyFactoryFactory was not configured.
Initialize 'proxyfactory.factory_class' property of the session-factory configuration section with one of the available NHibernate.ByteCode providers.
Example:
NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu
Example:
NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle

I have already added the references to both Castle and LinFu to my project.  I have also configured the web.config to the following:

```<code><section name="nhibernate" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" allowDefinition="Everywhere"/>
</code>```

Can you tell me what is going on?  I have tried everything.  Is it that I imported a lot of my mappings etc, from visualNHibernate?  Appreciate the help.

答:
You need to add the proper ProxyFactoryFactory and let NHibernate know what implementation should be used to create proxy objects. Fabio posted how to do it a while ago over at nhibernate.info: http://nhibernate.info/blog/2008/11/09/nh2-1-0-bytecode-providers.html
I also strongly suggest to read the documentation about configuration of NHibernate.</p>

```<code><hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
    <session-factory name="YourAppName">
        <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
        <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
        <property name="connection.connection_string">
            Server=(local);initial catalog=nhibernate;Integrated Security=SSPI
        </property>
        <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
    </session-factory>
</hibernate-configuration>
</code>```

Title: nHibernate ProxyFactory issues

Body:
I am setting up my first nHibernate project.  I have created a simple web form that accepts a name and an id however, I keep on getting the following error:

The ProxyFactoryFactory was not configured.
Initialize 'proxyfactory.factory_class' property of the session-factory configuration section with one of the available NHibernate.ByteCode providers.
Example:
NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu
Example:
NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle

I have already added the references to both Castle and LinFu to my project.  I have also configured the web.config to the following:

Can you tell me what is going on?  I have tried everything.  Is it that I imported a lot of my mappings etc, from visualNHibernate?  Appreciate the help.

Body:
You need to add the proper ProxyFactoryFactory and let NHibernate know what implementation should be used to create proxy objects. Fabio posted how to do it a while ago over at nhibernate.info: http://nhibernate.info/blog/2008/11/09/nh2-1-0-bytecode-providers.html
I also strongly suggest to read the documentation about configuration of NHibernate.

<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
    <session-factory name="YourAppName">
        <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
        <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
        <property name="connection.connection_string">
            Server=(local);initial catalog=nhibernate;Integrated Security=SSPI
        </property>
        <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
    </session-factory>
</hibernate-configuration>


问:
Enable Rsyslog with TLS to Graylog2
My problem is that I cannot get logs from my remote app to log to a Graylog2 input using TLS. The remote app was logging just fine before I attempted to enable TLS with self-signed certs so I am pretty sure I just have a config problem

Here is some background. First, I created some self-signed certs following these steps:

```<code>$ openssl genrsa -out CA.key 2048
$ openssl req -x509 -new -nodes -key CA.key -sha256 -days 3650 -out rootCA.crt
$ openssl genrsa -out graylog-server.key 2048
$ openssl req -new -key graylog-server.key -out graylog-server.csr
$ openssl x509 -req -in graylog-server.csr -CA rootCA.crt -CAkey CA.key -CAcreateserial -out graylog-server.crt -days 3640 -sha256

</code>```

source: https://gist.github.com/fntlnz/cf14feb5a46b2eda428e000157447309

Where I filled in the DNS name for the graylog server in the graylog-server.crt

I then imported the rootCA.crt to the keystore on the graylog server:

```<code>$ keytool -importcert -keystore ./graylog-cacerts -alias graylogRootCaCert -file rootCa.crt
</code>```

Then, I log into the Graylog web interface and I reconfigure the input fields to this:

```<code>port: 51xx
TLS Cert File: /path/to/certs/graylog-server.csr
TLS Private Key File: /path/to/certs/graylog-server.key
Enable TLS: True
TLS Client authentication: Optional
TLS Client Auth Trusted Certs: /path/to/certs*

</code>```

all the created certs are in the /path/to/certs/ directory which is owned by the graylog. All keys are read only.

The remote app running on Ubuntu 16.04 has an rsyslog config that looks like this:

```<code>$ cat 60-remote-rsyslog.conf

$DefaultNetstreamDriver gtls

$DefaultNetstreamDriverCAFile /etc/ssl/graylog/rootCA.pem
$ActionSendStreamDriverAuthMode anon
$ActionSendStreamDriverMode 1 # run driver in TLS-only mode
#$ActionSendStreamDriverPermittedPeer graylog.name.com

. @@graylog.name.com:51XX;RSYSLOG_SyslogProtocol23Format
</code>```

As for the rsyslog.conf on the server, it is using all the defaults. I have seen a solution where the TLS is set up through rsyslog directly and then Graylog picks up the logs from there, but this is not ideal for my application. We need to use the inputs. That solution is here:
https://serverfault.com/questions/807651/forwarding-logs-from-rsyslog-to-graylog-over-tls

I have tried following the steps in these links, but it is still not working:
https://community.graylog.org/t/rsyslog-over-tls/263/4
https://community.graylog.org/t/encrypt-traffic-from-rsyslog/5649

I expect that the logs will come from the client TLS secured into the configured input. What happens is the logs do not arrive in the input, and the graylog-server logs do not have any errors to speak of.

Any help or suggestions are appreciated. Thanks.

答:
I was having the exact same issue.
 The lack of detailed connection error logs for graylog configured TLS inputs is annoying when things don't work...

Remember that Graylog needs PKCS8 configured key's so you may be looking at a PKCS8 key compatibility issue.  Start with plain.key's for initial setup and troubleshooting...

Convert existing key to pkcs8

```<code>sudo openssl pkcs8 -in my.key -topk8 -nocrypt -out my.key.plain.pem
sudo openssl pkcs8 -in my.key.plain.pem -topk8 -out my.key.encrypted.pem -passout pass:secret
</code>```

My Centos Box has rsyslog and /etc/rsyslog.d/rsyslog-tls.conf is configured like so:

```<code># certificate files
$DefaultNetstreamDriverCAFile /etc/pki/tls/certs/my-CA.pem
$DefaultNetstreamDriverCertFile /etc/pki/tls/certs/server-01.domain.com.crt.pem
$DefaultNetstreamDriverKeyFile /etc/pki/tls/certs/server-01.domain.com.key.plain.pem
# set up the action
$DefaultNetstreamDriver gtls
$ActionSendStreamDriverMode 1
$ActionSendStreamDriverAuthMode x509/name
$ActionSendStreamDriverPermittedPeer *.domain.com
*.* @@(o)graylog.domain.com:6514
</code>```

My Graylog SyslogTCP(TLS) Input

```<code>tls_cert_file: /etc/graylog/ssl/shadowCA/graylog.domain.com/graylog.domain.com.crt.pem
tls_client_auth: optional
tls_client_auth_cert_file: <empty>
tls_enable: true
tls_key_file: /etc/graylog/ssl/shadowCA/graylog.domain.com/graylog.domain.com.key.plain.pem
</code>```

Troubleshooting TLS with OpenSSL S_CLIENT

PS. A helpful troubleshooting step is to ensure the input is properly configured for TLS, LISTENING, ANSWERING, and ACCEPTING MESSAGES

```<code>openssl s_client -connect localhost:1514 -tls1_2 -tlsextdebug
</code>```

-tlsextdebug  allows you to type test messages to graylog over TLS.

Title: Enable Rsyslog with TLS to Graylog2

Body:
My problem is that I cannot get logs from my remote app to log to a Graylog2 input using TLS. The remote app was logging just fine before I attempted to enable TLS with self-signed certs so I am pretty sure I just have a config problem

Here is some background. First, I created some self-signed certs following these steps:

$ openssl genrsa -out CA.key 2048
$ openssl req -x509 -new -nodes -key CA.key -sha256 -days 3650 -out rootCA.crt
$ openssl genrsa -out graylog-server.key 2048
$ openssl req -new -key graylog-server.key -out graylog-server.csr
$ openssl x509 -req -in graylog-server.csr -CA rootCA.crt -CAkey CA.key -CAcreateserial -out graylog-server.crt -days 3640 -sha256

source: https://gist.github.com/fntlnz/cf14feb5a46b2eda428e000157447309

Where I filled in the DNS name for the graylog server in the graylog-server.crt

I then imported the rootCA.crt to the keystore on the graylog server:

$ keytool -importcert -keystore ./graylog-cacerts -alias graylogRootCaCert -file rootCa.crt

Then, I log into the Graylog web interface and I reconfigure the input fields to this:

port: 51xx
TLS Cert File: /path/to/certs/graylog-server.csr
TLS Private Key File: /path/to/certs/graylog-server.key
Enable TLS: True
TLS Client authentication: Optional
TLS Client Auth Trusted Certs: /path/to/certs*

all the created certs are in the /path/to/certs/ directory which is owned by the graylog. All keys are read only.

The remote app running on Ubuntu 16.04 has an rsyslog config that looks like this:

$ cat 60-remote-rsyslog.conf

$DefaultNetstreamDriver gtls

$DefaultNetstreamDriverCAFile /etc/ssl/graylog/rootCA.pem
$ActionSendStreamDriverAuthMode anon
$ActionSendStreamDriverMode 1 # run driver in TLS-only mode
#$ActionSendStreamDriverPermittedPeer graylog.name.com

. @@graylog.name.com:51XX;RSYSLOG_SyslogProtocol23Format

As for the rsyslog.conf on the server, it is using all the defaults. I have seen a solution where the TLS is set up through rsyslog directly and then Graylog picks up the logs from there, but this is not ideal for my application. We need to use the inputs. That solution is here:
https://serverfault.com/questions/807651/forwarding-logs-from-rsyslog-to-graylog-over-tls

I have tried following the steps in these links, but it is still not working:
https://community.graylog.org/t/rsyslog-over-tls/263/4
https://community.graylog.org/t/encrypt-traffic-from-rsyslog/5649

I expect that the logs will come from the client TLS secured into the configured input. What happens is the logs do not arrive in the input, and the graylog-server logs do not have any errors to speak of.

Any help or suggestions are appreciated. Thanks.

Body:
I was having the exact same issue.
 The lack of detailed connection error logs for graylog configured TLS inputs is annoying when things don't work...

Remember that Graylog needs PKCS8 configured key's so you may be looking at a PKCS8 key compatibility issue.  Start with plain.key's for initial setup and troubleshooting...

Convert existing key to pkcs8

sudo openssl pkcs8 -in my.key -topk8 -nocrypt -out my.key.plain.pem
sudo openssl pkcs8 -in my.key.plain.pem -topk8 -out my.key.encrypted.pem -passout pass:secret

My Centos Box has rsyslog and /etc/rsyslog.d/rsyslog-tls.conf is configured like so:

# certificate files
$DefaultNetstreamDriverCAFile /etc/pki/tls/certs/my-CA.pem
$DefaultNetstreamDriverCertFile /etc/pki/tls/certs/server-01.domain.com.crt.pem
$DefaultNetstreamDriverKeyFile /etc/pki/tls/certs/server-01.domain.com.key.plain.pem
# set up the action
$DefaultNetstreamDriver gtls
$ActionSendStreamDriverMode 1
$ActionSendStreamDriverAuthMode x509/name
$ActionSendStreamDriverPermittedPeer *.domain.com
*.* @@(o)graylog.domain.com:6514

My Graylog SyslogTCP(TLS) Input

tls_cert_file: /etc/graylog/ssl/shadowCA/graylog.domain.com/graylog.domain.com.crt.pem
tls_client_auth: optional
tls_client_auth_cert_file: <empty>
tls_enable: true
tls_key_file: /etc/graylog/ssl/shadowCA/graylog.domain.com/graylog.domain.com.key.plain.pem

Troubleshooting TLS with OpenSSL S_CLIENT

PS. A helpful troubleshooting step is to ensure the input is properly configured for TLS, LISTENING, ANSWERING, and ACCEPTING MESSAGES

openssl s_client -connect localhost:1514 -tls1_2 -tlsextdebug

-tlsextdebug  allows you to type test messages to graylog over TLS.


答:
Valgrind will by itself not change (much at least) the stack size used by the guest program.

What you see is very probably just the stack size used by the startup code: before main started to run, a whole lot of other things can happen.

Title: Is Valgrind Massif profiling itself with 7 KB of stack?

Body:
I need to profile and trace used of stack of some program for my study, but I found that Valgrind Massif seems to profile itself with 7 KB of stack usage, how can I ignore it or is there any other profiler suitable for me?

it shows 7 KB of stack usage even execute nothing...

int main()
{
    return 0;
}

and the massif result:

--------------------------------------------------------------------------------
Command:            ./a.out
Massif arguments:   --stacks=yes --heap=yes
ms_print arguments: massif.out.29255
--------------------------------------------------------------------------------

    KB
7.008^                 #
     |                 #:
     |                 #:
     |                :#:
     |                :#:
     |                :#:
     |                :#:
     |                :#:
     |                :#:
     |                :#:
     |                :#:
     |                :#:  :
     |                :#:::::
     |                :#::@::
     |                :#::@::
     |                :#::@::
     |                :#::@::            ::  :::@:: : :::::  ::  :   ::::@  :
     |                :#::@:::::::::::::::::::::@::@::::::::@:::@:::@::::@: :
     |              :::#::@::::       ::::::::::@::@::::::::@:::@:::@::::@: :
     |::::::::::::::@::#::@::::       ::::::::::@::@::::::::@:::@:::@::::@: :@
   0 +----------------------------------------------------------------------->ki
     0                                                                   135.7

Number of snapshots: 96
 Detailed snapshots: [2, 6 (peak), 11, 33, 38, 53, 63, 73, 83, 93]


问:
How to copy a nodelist?
I am trying to set up a search feature for a large table that has about 1000 rows. The problem with this is that the rendering eats up performance by a lot. This is because I am iterating through all the rows in the table and setting the style of the ones that do not contain the search query to 'none'.

For some reason, the browser renders all the elements again each time I make a change. I am getting the table data as a nodelist via document.quesrtySelectorAll('tbody tr'). My solution is to copy this to a new object, do the search and style changes on the new object, and then copy it back, causing the browser to only have to re-render the table once.

```<code>let items = document.querySelectorAll('tbody tr');
let itemsArr = [...items];

for (let ele of itemsArr) {
    . . .

    if (!lower_case_table_value.match(lower_case_search_value)) {
        ele.style.display = 'none';
    }
    else {
        ele.style.display = 'table-row';
    }
}

let list = document.querySelector('tbody');
for (let i = 0; i < items.length; i++) {
    list.appendChild(itemsArr[i]);
}
</code>```

No matter what I do, though, any changes I make on the new object also makes the changes to the old. I removed the second for loop and it behaves like nothing happened. It is like it is not a copy, but a pointer.

Does anybody know who to copy a nodelist to a new object and make sure they are separate and not pointers to one another?

答:
if you want to get a new Array instead of a chilNode
use Array.from(nodeToCopy)
this returns a new Array instead of a child node

Title: How to copy a nodelist?

Body:
I am trying to set up a search feature for a large table that has about 1000 rows. The problem with this is that the rendering eats up performance by a lot. This is because I am iterating through all the rows in the table and setting the style of the ones that do not contain the search query to 'none'.

For some reason, the browser renders all the elements again each time I make a change. I am getting the table data as a nodelist via document.quesrtySelectorAll('tbody tr'). My solution is to copy this to a new object, do the search and style changes on the new object, and then copy it back, causing the browser to only have to re-render the table once.

let items = document.querySelectorAll('tbody tr');
let itemsArr = [...items];

for (let ele of itemsArr) {
    . . .

    if (!lower_case_table_value.match(lower_case_search_value)) {
        ele.style.display = 'none';
    }
    else {
        ele.style.display = 'table-row';
    }
}

let list = document.querySelector('tbody');
for (let i = 0; i < items.length; i++) {
    list.appendChild(itemsArr[i]);
}

No matter what I do, though, any changes I make on the new object also makes the changes to the old. I removed the second for loop and it behaves like nothing happened. It is like it is not a copy, but a pointer.

Does anybody know who to copy a nodelist to a new object and make sure they are separate and not pointers to one another?


问:
This asp.net password recovery code has an error. Can anyone spot it?
We use email address instead of user id.  But when the user enters his email address into the password recovery form and submits it, the site returns "We were unable to access your information. Please try again." and replaces the email value in the text box with a long string of characters and numbers (e.g. e61686cb-93a5-4737-8c40-52g8eb01bb67).

Here's the relevant aspx page code...

```<code><asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"
    runat="server">

<div class="login_page">
    <div class="login_header">Password Reset</div>
    <div class="login_body">
        <asp:PasswordRecovery ID="PasswordRecovery1" runat="server"
            onverifyinguser="PasswordRecovery1_VerifyingUser"
            onsendingmail="PasswordRecovery1_SendingMail">
        </asp:PasswordRecovery>
    </div>
</div>
</asp:Content>
</code>```

And the code behind...

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Text.RegularExpressions;
using System.Net.Mail;
using System.Configuration;
using System.Web.Profile;
using System.Text;

namespace Sample.Web
{
    public partial class PasswordReset : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

    }

    bool IsValidEmail(string strIn)
    {
        // Return true if strIn is in valid e-mail format.
        return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
    }

    protected void PasswordRecovery1_VerifyingUser(object sender, LoginCancelEventArgs e)
    {
        if (IsValidEmail(PasswordRecovery1.UserName))
        {
            string username = Membership.GetUserNameByEmail(PasswordRecovery1.UserName);
            if (username != null)
            {
                PasswordRecovery1.UserName = username;
            }
            else
            {
                PasswordRecovery1.UserNameInstructionText = "We were unable to access your information. Check your user name and try again.";
                e.Cancel = true;
            }
        }
        else
        {
            PasswordRecovery1.UserNameInstructionText = "You must enter a valid e-mail address.";
            e.Cancel = true;
        }
    }

    protected void PasswordRecovery1_SendingMail(object sender, MailMessageEventArgs e)
    {
        string pwd = Membership.GetUser(PasswordRecovery1.UserName).ResetPassword(PasswordRecovery1.Answer);
        string email = StorageByMail.BLL.SBMUser.SelectUser(
            StorageByMail.Data.User.GetIDFromUserName(PasswordRecovery1.UserName)).Email;

        MailMessage m = new MailMessage(ConfigurationManager.AppSettings["AdminEmail"].Trim(), email);
        m.ReplyTo = new MailAddress(ConfigurationSettings.AppSettings["AdminEmailReply"].Trim());
        StringBuilder sb = new StringBuilder();
        sb.Append("Please return to the site and log in using the following information.\n");
        sb.Append("User Name: " + email + "\n");
        sb.Append("Password: " + pwd);
        m.Body = sb.ToString();
        m.Subject = "Password reset from StorageByMail.com";

        SmtpClient o = new SmtpClient(ConfigurationManager.AppSettings["SMTPHost"].Trim());
        string smtpUser = ConfigurationSettings.AppSettings["SMTPUser"].Trim();
        string smtpPass = ConfigurationSettings.AppSettings["SMTPPassword"].Trim();

        if (smtpUser.Length > 0 && smtpPass.Length > 0)
        {
            o.Credentials = new System.Net.NetworkCredential(smtpUser, smtpPass);
        }

        o.Send(m);
        e.Cancel = true;
    }
}
</code>```

}

答:
Without knowing a lot about ASP.NET membership, my guess would be that the line:

```<code>PasswordRecovery1.UserName = username;
// where username = Membership.GetUserNameByEmail(PasswordRecovery1.UserName);
</code>```

is causing your problem.  Even though you say you're not using username in your model, I'd bet that ASP.NET populates the username column in your database with a GUID. Take a look at your database, and see if that GUID matches up with the username column in your table for this user.

Body:
We use email address instead of user id.  But when the user enters his email address into the password recovery form and submits it, the site returns "We were unable to access your information. Please try again." and replaces the email value in the text box with a long string of characters and numbers (e.g. e61686cb-93a5-4737-8c40-52g8eb01bb67).

Here's the relevant aspx page code...

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"
    runat="server">

Password Reset

        <asp:PasswordRecovery ID="PasswordRecovery1" runat="server"
            onverifyinguser="PasswordRecovery1_VerifyingUser"
            onsendingmail="PasswordRecovery1_SendingMail">
        </asp:PasswordRecovery>

</asp:Content>

And the code behind...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Text.RegularExpressions;
using System.Net.Mail;
using System.Configuration;
using System.Web.Profile;
using System.Text;

namespace Sample.Web
{
    public partial class PasswordReset : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

    }

    bool IsValidEmail(string strIn)
    {
        // Return true if strIn is in valid e-mail format.
        return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
    }

    protected void PasswordRecovery1_VerifyingUser(object sender, LoginCancelEventArgs e)
    {
        if (IsValidEmail(PasswordRecovery1.UserName))
        {
            string username = Membership.GetUserNameByEmail(PasswordRecovery1.UserName);
            if (username != null)
            {
                PasswordRecovery1.UserName = username;
            }
            else
            {
                PasswordRecovery1.UserNameInstructionText = "We were unable to access your information. Check your user name and try again.";
                e.Cancel = true;
            }
        }
        else
        {
            PasswordRecovery1.UserNameInstructionText = "You must enter a valid e-mail address.";
            e.Cancel = true;
        }
    }

    protected void PasswordRecovery1_SendingMail(object sender, MailMessageEventArgs e)
    {
        string pwd = Membership.GetUser(PasswordRecovery1.UserName).ResetPassword(PasswordRecovery1.Answer);
        string email = StorageByMail.BLL.SBMUser.SelectUser(
            StorageByMail.Data.User.GetIDFromUserName(PasswordRecovery1.UserName)).Email;

        MailMessage m = new MailMessage(ConfigurationManager.AppSettings["AdminEmail"].Trim(), email);
        m.ReplyTo = new MailAddress(ConfigurationSettings.AppSettings["AdminEmailReply"].Trim());
        StringBuilder sb = new StringBuilder();
        sb.Append("Please return to the site and log in using the following information.\n");
        sb.Append("User Name: " + email + "\n");
        sb.Append("Password: " + pwd);
        m.Body = sb.ToString();
        m.Subject = "Password reset from StorageByMail.com";

        SmtpClient o = new SmtpClient(ConfigurationManager.AppSettings["SMTPHost"].Trim());
        string smtpUser = ConfigurationSettings.AppSettings["SMTPUser"].Trim();
        string smtpPass = ConfigurationSettings.AppSettings["SMTPPassword"].Trim();

        if (smtpUser.Length > 0 && smtpPass.Length > 0)
        {
            o.Credentials = new System.Net.NetworkCredential(smtpUser, smtpPass);
        }

        o.Send(m);
        e.Cancel = true;
    }
}

}

Body:
Without knowing a lot about ASP.NET membership, my guess would be that the line:

PasswordRecovery1.UserName = username;
// where username = Membership.GetUserNameByEmail(PasswordRecovery1.UserName);

is causing your problem.  Even though you say you're not using username in your model, I'd bet that ASP.NET populates the username column in your database with a GUID. Take a look at your database, and see if that GUID matches up with the username column in your table for this user.


问:
I want to create multiple (i.e approx 4) On/Off toggle button
I am new to Flask and want to create multiple(approx 4 buttons) On/Off toggle button on my website. I was wondering if and how this is possible also including a dynamic label.

index.html

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">

    <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">

    <input type="checkbox"  class='toggle' checked data-toggle="toggle">

Toggled

    <input type="checkbox"  class="toggle1" checked data-toggle="toggle1">

Toggled2

```

<p>app.py(for routes)</p>

<pre class="lang-py prettyprint-override"><code>from flask import Flask, render_template, Response, request, redirect, url_for

app = Flask(__name__)

@app.route("/")
def index():
    return render_template('index.html')

@app.route('/switch_led', methods=['POST'])
def move_forward():
    if request.form['demo1']=='ON':
        table.put_item(
            Item={
                'ID':'APPLIANCE1',
                'sequence':1
                }
            )
        ar="PRESS TO UPDATE"
        templateData ={
        'ar':ar
        }
    if request.form['demo1']=='OFF':
        table.put_item(
            Item={
                'ID':'APPLIANCE1',
                'sequence':0
                }
            )
        ar="CHECK DATABASE"
        templateData ={
        'ar':ar
        }
    if request.form['demo2']=='ON':
        table.put_item(
            Item={
                'ID':'APPLIANCE2',
                'sequence':1
                }
            )
        ar="PRESS TO UPDATE"
        templateData ={
        'ar':ar
        }
    if request.form['demo2']=='OFF':
        table.put_item(
            Item={
                'ID':'APPLIANCE2',
                'sequence':0
                }
            )
        ar="CHECK DATABASE"
        templateData ={
        'ar':ar
        }
    if request.form['demo3']=='ON':
        table.put_item(
            Item={
                'ID':'APPLIANCE3',
                'sequence':1
                }
            )
        ar="PRESS TO UPDATE"
        templateData ={
        'ar':ar
        }
    if request.form['demo3']=='OFF':
        table.put_item(
            Item={
                'ID':'APPLIANCE3',
                'sequence':0
                }
            )
        ar="CHECK DATABASE"
        templateData ={
        'ar':ar
        }
    if request.form['demo4']=='ON':
        table.put_item(
            Item={
                'ID':'LOCK',
                'sequence':1
                }
            )
        ar="PRESS TO UPDATE"
        templateData ={
        'ar':ar
        }
    if request.form['demo4']=='OFF':
        table.put_item(
            Item={
                'ID':'LOCK',
                'sequence':0
                }
            )
        ar="CHECK DATABASE"
        templateData ={
        'ar':ar
        }

    return render_template('index.html', **templateData);

@app.route('/get_toggled_status')
def get_toggled_status():
  current_status = request.args.get('status')
  return 'Toggled' if current_status == 'Untoggled' else 'Untoggled'

@app.route('/get_toggled_status1')
def get_toggled_status1():
  current_status1 = request.args.get('status1')
  return 'Toggled' if current_status1 == 'Untoggled' else 'Untoggled'

if __name__ == '__main__':
    app.run(debug='true')
</code>```

My result is that it shows 2 toggle button named toggle and toggle1. But on clicking the button named toggle...it shows output as a toggle when ON and untoggle when OFF. Up to this point, everything gor=es fine. But when I click on 2nd button named toggled1, it performs the action on 1st toggle button not on the 2nd one.

答:
You need to change your html code like below:

```<code><body>
    <input type="checkbox"  class='toggle' checked
    data-toggle="toggle" onclick="change_status('.status')">
    <div class='status'>Toggled</div>

    <input type="checkbox"  class="toggle1" checked
    data-toggle="toggle1" onclick="change_status('.status2')">
    <div class="status1">Toggled2</div>
  </body>
</code>```

The js code will be similar to this:

```<code>function change_status(status_class) {
     var current_status = $(status_class).text();
     $.ajax({
      url: "/get_toggled_status",
      type: "get",
      data: {status: current_status},
      success: function(response) {
        $(status_class).html(response);
      },
      error: function(xhr) {

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

Body:
I am new to Flask and want to create multiple(approx 4 buttons) On/Off toggle button on my website. I was wondering if and how this is possible also including a dynamic label.

index.html

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">

    <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">

    <input type="checkbox"  class='toggle' checked data-toggle="toggle">

Toggled

    <input type="checkbox"  class="toggle1" checked data-toggle="toggle1">

Toggled2

app.py(for routes)

from flask import Flask, render_template, Response, request, redirect, url_for

app = Flask(__name__)

@app.route("/")
def index():
    return render_template('index.html')

@app.route('/switch_led', methods=['POST'])
def move_forward():
    if request.form['demo1']=='ON':
        table.put_item(
            Item={
                'ID':'APPLIANCE1',
                'sequence':1
                }
            )
        ar="PRESS TO UPDATE"
        templateData ={
        'ar':ar
        }
    if request.form['demo1']=='OFF':
        table.put_item(
            Item={
                'ID':'APPLIANCE1',
                'sequence':0
                }
            )
        ar="CHECK DATABASE"
        templateData ={
        'ar':ar
        }
    if request.form['demo2']=='ON':
        table.put_item(
            Item={
                'ID':'APPLIANCE2',
                'sequence':1
                }
            )
        ar="PRESS TO UPDATE"
        templateData ={
        'ar':ar
        }
    if request.form['demo2']=='OFF':
        table.put_item(
            Item={
                'ID':'APPLIANCE2',
                'sequence':0
                }
            )
        ar="CHECK DATABASE"
        templateData ={
        'ar':ar
        }
    if request.form['demo3']=='ON':
        table.put_item(
            Item={
                'ID':'APPLIANCE3',
                'sequence':1
                }
            )
        ar="PRESS TO UPDATE"
        templateData ={
        'ar':ar
        }
    if request.form['demo3']=='OFF':
        table.put_item(
            Item={
                'ID':'APPLIANCE3',
                'sequence':0
                }
            )
        ar="CHECK DATABASE"
        templateData ={
        'ar':ar
        }
    if request.form['demo4']=='ON':
        table.put_item(
            Item={
                'ID':'LOCK',
                'sequence':1
                }
            )
        ar="PRESS TO UPDATE"
        templateData ={
        'ar':ar
        }
    if request.form['demo4']=='OFF':
        table.put_item(
            Item={
                'ID':'LOCK',
                'sequence':0
                }
            )
        ar="CHECK DATABASE"
        templateData ={
        'ar':ar
        }

    return render_template('index.html', **templateData);

@app.route('/get_toggled_status')
def get_toggled_status():
  current_status = request.args.get('status')
  return 'Toggled' if current_status == 'Untoggled' else 'Untoggled'

@app.route('/get_toggled_status1')
def get_toggled_status1():
  current_status1 = request.args.get('status1')
  return 'Toggled' if current_status1 == 'Untoggled' else 'Untoggled'

if __name__ == '__main__':
    app.run(debug='true')

My result is that it shows 2 toggle button named toggle and toggle1. But on clicking the button named toggle...it shows output as a toggle when ON and untoggle when OFF. Up to this point, everything gor=es fine. But when I click on 2nd button named toggled1, it performs the action on 1st toggle button not on the 2nd one.

Body:
You need to change your html code like below:

<body>
    <input type="checkbox"  class='toggle' checked
    data-toggle="toggle" onclick="change_status('.status')">
    <div class='status'>Toggled</div>

    <input type="checkbox"  class="toggle1" checked
    data-toggle="toggle1" onclick="change_status('.status2')">
    <div class="status1">Toggled2</div>
  </body>

The js code will be similar to this:

function change_status(status_class) {
     var current_status = $(status_class).text();
     $.ajax({
      url: "/get_toggled_status",
      type: "get",
      data: {status: current_status},
      success: function(response) {
        $(status_class).html(response);
      },
      error: function(xhr) {

      }
    });
   }