问:
Body content in HTML not full screen although set width 100% in CSS? when responsive
In normal (not responsive yet) my website running good, but after I set responsive to (width: 1336px) for my web it's display screen like this although I've set width for this is 100%

/* Here is my CSS *style.css* */

* {
  box-sizing: border-box;
}

body {
  font-family: 'Montserrat', sans-serif;
  margin: 0;
  width: 100%;
}

/* style for header section */

h1 {
  line-height: 65px;
  font-size: 48px;
}

.header-container {
  background-image: linear-gradient( 0deg, rgba(35, 39, 49, -0.18), rgba(35, 39, 49, 1.82)), url("images/bg-image.jpeg");
  background-repeat: no-repeat;
  background-size: cover;
  box-sizing: border-box;
  position: absolute;
  width: 100%;
  height: 743px;
  left: -1px;
  top: 0px;
}

.nav-bar {
  position: absolute;
  width: 1700px;
  height: 135px;
  left: 69px;
  top: 17px;
  filter: brightness(100%);
}

.header-logo {
  float: left;
}

.nav-content {
  list-style-type: none;
}

.menu-section {
  width: 50%;
  float: right;
  margin-top: 34px;
}

.menu-item {
  float: left;
  display: block;
  margin-right: 70px;
}

/* nav menu */

.nav-content li a {
  text-decoration: none;
  color: #fff;
  font-size: 20px;
}

.nav-content li a:hover {
  color: #00B9F7;
}

/* header title */

.header-title {
  color: #fff;
  text-align: center;
  margin: auto;
  width: 30%;
  padding: 10px;
  margin-top: 10%;
}

/* header video */

.header-video {
  margin-left: 30%;
  width: fit-content;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- here is my HTML code *index.html* -->

<header class="header-container">
  <div class="header-content">
    <div class="nav-bar">
      <div class="header-logo">

          <img id="image-logo-header" class="bottom img-logo" src="images/logo.png">

      </div>

      <div class="menu-section">
        <div class="menu-btn-group">
          <div class="menu-toggle"></div>
          <div class="menu-close"></div>
        </div>
        <div class="navigation navbar-collapse ">
          <nav role="navigation">
            <ul class="nav-content">
              <li class="menu-item">Home</li>
              <li class="menu-item">Blog</li>
              <li class="menu-item">About</li>
              <li class="menu-item">Contact</li>
              <li class="menu-item">Login</li>
              <li class="menu-item">Sign up</li>
            </ul>
          </nav>
        </div>
      </div>
    </div>

    <div class="header-title">
      <h1>SHARE YOUR HOLIDDAY DREAM</h1>
    </div>

    <div class="header-video">
      <img class="video-img" src="images/video-img.png">
    </div>
  </div>
</header></code>```

Can anyone help me, please? your answer is my happiness, thank you so much

答:
This is happening because in your code you have set background width to 100% that is working fine but when you are using resposive design the background image not filling the screen.

Because the background image is filling the 100% width of your responsive container but the blank space that you are seeing in right side is because of nav-bar, you have set its width fixed to 1700px.

To resolve this make your nav-bar responsive so that it can also set its width according to container.

You can use

```<code>.nav-bar {
         position: absolute;
         width: 100%;
         height: 135px;
         left: 69px;
         top: 17px;
         filter: brightness(100%);
     }
</code>```

width: 100% make your nav-bar responsive too.

Body:
In normal (not responsive yet) my website running good, but after I set responsive to (width: 1336px) for my web it's display screen like this although I've set width for this is 100%

/* Here is my CSS *style.css* */

* {
  box-sizing: border-box;
}

body {
  font-family: 'Montserrat', sans-serif;
  margin: 0;
  width: 100%;
}

/* style for header section */

h1 {
  line-height: 65px;
  font-size: 48px;
}

.header-container {
  background-image: linear-gradient( 0deg, rgba(35, 39, 49, -0.18), rgba(35, 39, 49, 1.82)), url("images/bg-image.jpeg");
  background-repeat: no-repeat;
  background-size: cover;
  box-sizing: border-box;
  position: absolute;
  width: 100%;
  height: 743px;
  left: -1px;
  top: 0px;
}

.nav-bar {
  position: absolute;
  width: 1700px;
  height: 135px;
  left: 69px;
  top: 17px;
  filter: brightness(100%);
}

.header-logo {
  float: left;
}

.nav-content {
  list-style-type: none;
}

.menu-section {
  width: 50%;
  float: right;
  margin-top: 34px;
}

.menu-item {
  float: left;
  display: block;
  margin-right: 70px;
}

/* nav menu */

.nav-content li a {
  text-decoration: none;
  color: #fff;
  font-size: 20px;
}

.nav-content li a:hover {
  color: #00B9F7;
}

/* header title */

.header-title {
  color: #fff;
  text-align: center;
  margin: auto;
  width: 30%;
  padding: 10px;
  margin-top: 10%;
}

/* header video */

.header-video {
  margin-left: 30%;
  width: fit-content;
}

Home

Blog

About

Contact

Login

Sign up

SHARE YOUR HOLIDDAY DREAM

Can anyone help me, please? your answer is my happiness, thank you so much

Body:
This is happening because in your code you have set background width to 100% that is working fine but when you are using resposive design the background image not filling the screen.

Because the background image is filling the 100% width of your responsive container but the blank space that you are seeing in right side is because of nav-bar, you have set its width fixed to 1700px.

To resolve this make your nav-bar responsive so that it can also set its width according to container.

You can use

.nav-bar {
         position: absolute;
         width: 100%;
         height: 135px;
         left: 69px;
         top: 17px;
         filter: brightness(100%);
     }

width: 100% make your nav-bar responsive too.


来源: stackexchange

问:
Django: OperationalError at /admin/
So I ran my program based on from here and It worked without any error. I go to to /admin. I login. So far everything is good. Then when it loads I get this:

I checked the traceback (which is really long) and none of includes my code. It doesn't tell me what part of the code this error is occurring in so I don't know how to approach this. Please explain what this is, why this is happening, and how I can fix it.

If you need any part of my code, just ask in comments because I don't know where this is happening.

答:
Use pip install django==2.1.5

If the problem persists,

Use python manage.py migrate --run-syncdb

ContentLicense: CC BY-SA 3.0

Title: Django: OperationalError at /admin/

ContentLicense: CC BY-SA 4.0


问:
access to array elements from different function but same class
I have class that contains some functions with an array. One of them called pick, this function does not has an array but i want to display array element  from other function, once i write code to display array element i can not get the element, although the code work and if i add normal text it will display but can not display array elements, i will attach the code below:

Note i did not attache full code only important parts

```<code>#include <iostream>
#include<stdlib.h>

#include <string>

using namespace std;

// global variable
string  plantType;
int temperatures ;
string water;
string sunExposure;
bool pet;
string plant1,plant2,plant3;

class inside{
public:

void low(){
    string plant1 [3]={"Snake plant","Spider plant","Aloe Vera plant"};
    for(int i =0; i<3; i++){
        cout << "* "<< plant1[i]<<endl;
    }

}
void medium(){
    string plant2 [5]={"Pothos plant","Dracaena plant","ZZ plant","Rubber plant","Philodendron Green plant"};
  for(int i =0; i<5; i++){
        cout << "* "<< plant2[i]<<endl;

}
}
void high(){
    string plant3 [2]={"Bird’s Nest Fern plant","Peace Lily plant"};
     for(int i =0; i<2; i++){
        cout << "* "<< plant3[i]<<endl;

}
}

void pick(){
    cout <<"Best choice for you is: ";

    if (temperatures >= 13 && temperatures <=29 ){

        if(water=="low"){

            if(sunExposure=="fully"){
             cout<<"test"<<endl;
                if(pet==true){
                    cout<<plant1[1]<<endl; //this line cannot be executed

                }
            }
        }}}

int main(){
cout <<"Where do you want to grow the plant (inside), or (outside)"<<endl;
        cin>>grow;

        if (grow == "inside"){
                //inside home

     cout<<endl<<"inside"<<endl;
     cout<<"Enter the Temperature in (Celsius scale 13-29)"<<endl;
     cin>>temperatures;
     cout<<"Enter water level (low - medium - high)"<<endl;
     cin>>water;
     cout<<"Enter Sun Exposure (fully - partly - shady)"<<endl;
     cin>>sunExposure;
     cout<<"Do you have pet (true or false)? "<<endl;
     cin>>pet;

        inside inside;
        inside.pick();
        }
}
</code>```

答:
The string variables plant1[3], plant2[3] & plant3[3] are only visible to low(), medium(), high() but they're not for each other. For example, you're something trying to access a locally declared variable of foo() function in bar() function, which is impossible.

Secondly, you're trying to access plant1[3] data member in pick() but compiler doesn't know where you've actually defined those three plants' name outside of that function, just it knows plant1 variable with no arrays which is declared in the private section of the class. Hence, there's a good chance your code will get fail.

Rather you could just declare the same thing in this way:

```<code>class inside {
    std::string plants1[3] = {"...", ...}; // these variables are
    std::string plants2[3] = {"...", ...}; // only visible inside the
    std::string plants3[3] = {"...", ...}; // class member functions
    .
    .
}
</code>```

And after that, you'll get the line executed successfully.

Body:
I have class that contains some functions with an array. One of them called pick, this function does not has an array but i want to display array element  from other function, once i write code to display array element i can not get the element, although the code work and if i add normal text it will display but can not display array elements, i will attach the code below:

Note i did not attache full code only important parts

#include <iostream>
#include<stdlib.h>

#include <string>

using namespace std;

// global variable
string  plantType;
int temperatures ;
string water;
string sunExposure;
bool pet;
string plant1,plant2,plant3;

class inside{
public:

void low(){
    string plant1 [3]={"Snake plant","Spider plant","Aloe Vera plant"};
    for(int i =0; i<3; i++){
        cout << "* "<< plant1[i]<<endl;
    }

}
void medium(){
    string plant2 [5]={"Pothos plant","Dracaena plant","ZZ plant","Rubber plant","Philodendron Green plant"};
  for(int i =0; i<5; i++){
        cout << "* "<< plant2[i]<<endl;

}
}
void high(){
    string plant3 [2]={"Bird’s Nest Fern plant","Peace Lily plant"};
     for(int i =0; i<2; i++){
        cout << "* "<< plant3[i]<<endl;

}
}

void pick(){
    cout <<"Best choice for you is: ";

    if (temperatures >= 13 && temperatures <=29 ){

        if(water=="low"){

            if(sunExposure=="fully"){
             cout<<"test"<<endl;
                if(pet==true){
                    cout<<plant1[1]<<endl; //this line cannot be executed

                }
            }
        }}}

int main(){
cout <<"Where do you want to grow the plant (inside), or (outside)"<<endl;
        cin>>grow;

        if (grow == "inside"){
                //inside home

     cout<<endl<<"inside"<<endl;
     cout<<"Enter the Temperature in (Celsius scale 13-29)"<<endl;
     cin>>temperatures;
     cout<<"Enter water level (low - medium - high)"<<endl;
     cin>>water;
     cout<<"Enter Sun Exposure (fully - partly - shady)"<<endl;
     cin>>sunExposure;
     cout<<"Do you have pet (true or false)? "<<endl;
     cin>>pet;

        inside inside;
        inside.pick();
        }
}

Body:
The string variables plant1[3], plant2[3] & plant3[3] are only visible to low(), medium(), high() but they're not for each other. For example, you're something trying to access a locally declared variable of foo() function in bar() function, which is impossible.

Secondly, you're trying to access plant1[3] data member in pick() but compiler doesn't know where you've actually defined those three plants' name outside of that function, just it knows plant1 variable with no arrays which is declared in the private section of the class. Hence, there's a good chance your code will get fail.

Rather you could just declare the same thing in this way:

class inside {
    std::string plants1[3] = {"...", ...}; // these variables are
    std::string plants2[3] = {"...", ...}; // only visible inside the
    std::string plants3[3] = {"...", ...}; // class member functions
    .
    .
}

And after that, you'll get the line executed successfully.


问:
Xcode 11.4 - Archiving project - Segmentation Fault 11
I Just updated Xcode to 11.4 and when archiving a project it shows me 'Segmentation Fault 11'

This project would archive with Xcode 11.3.1 but now it doesn't..

Anyone else ran into the same issue?

Edit: April 15th 2020

Apple just released Xcode 11.4.1

答:
I was having the error with Eureka

The only thing that fixed the error was the temporary solution of WilsonGramer

The solution is the next:

"I found a workaround for this by replacing [unowned self] in RowType.swift with [weak self] and force-unwrapping the self. This prevents the compiler from crashing in Xcode 11.4 — if you'd like to take a look you can use my fork: https://github.com/Wilsonator5000/Eureka/tree/fix/xcode11.4-unowned-self

Project maintainers, if this is a suitable fix please let me know and I'll open a pull request!" WilsonGramer

I hope it works for you


问:
viewpager is hidden on some huawei&honor mobiles
I have a problem with viewpager widget on some huawei&honor mobiles. The widget doesn't show on these mobiles, it is clickable and works, but it just doesn't show and is hidden. Those mobiles have a different android version.</p>

答:
Viewpager is hidden in Huawei and glory mobile phones.
Viewpager, a view page flipping tool, provides the effect of multi page switching. A UI control introduced after Android 3.0 is located in the V4 package. It is necessary to import the V4 package for the use of the lower version, but now the app we developed is generally no longer compatible with the system version of 3.0 or below. In addition, most of the apps are developed using Android studio. The V7 package is imported by default, and V7 contains V4, so it is more and more convenient without package import.
Basic usage of viewpager: you can load an ImageView or a fragment in viewpager</p>


问:
AddSingleton<>() vs AddSingleton()
I'm implementing dependency injection in my project. I've come across two ways to add a singleton service -

services.AddSingleton(new MyCustomService())
```

<p>and </p>

<pre class="lang-csh prettyprint-override"><code>services.AddSingleton<MyCustomService>()
</code>```

Both methods seem to work. What's the difference between these two methods, and which one should I be using?

答:
According to the docs in first sample, you are using AddSingleton<TService>(IServiceCollection, TService) extension method, and in second one - AddSingleton<TService>(IServiceCollection).

The difference between this 2 is the time when the instance of TService is created. In first one - you create it upon registration. In second one - it will be created be container on first request.

It's up to you which one you should use. But if your MyCustomService may have additional dependencies - I guess AddSingleton<TService>(IServiceCollection) maybe more handy.

Title: AddSingleton<>() vs AddSingleton()

Body:
I'm implementing dependency injection in my project. I've come across two ways to add a singleton service -

services.AddSingleton(new MyCustomService())

and

services.AddSingleton<MyCustomService>()

Both methods seem to work. What's the difference between these two methods, and which one should I be using?


问:
Fetch all record including particular fields
I am working with Elasticcsearch 7.3. I want to fetch only two records of all the documents using JAVA Api from my index. I am using the following code but it returning the null object.

```<code>        RestHighLevelClient client;

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.fetchSource("recipe_ID,recipe_url", null);
        sourceBuilder.from(0);
        SearchRequest searchRequest = new SearchRequest("recipes");
        searchRequest.source(sourceBuilder);

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        SearchHit searchHit = searchResponse.getHits().getAt(0);

        String resultString = searchHit.getSourceAsString();

        return resultString;
</code>```

I need to include only two fields recipe_ID and recipe_url in my result.

答:
You're on the right path, although source filtering requires you to specify your fields in an array like this:</p>

```<code>    String[] includeFields = new String[] {"recipe_ID", "recipe_url"};
    sourceBuilder.fetchSource(includeFields, null);
</code>```

Body:
I am working with Elasticcsearch 7.3. I want to fetch only two records of all the documents using JAVA Api from my index. I am using the following code but it returning the null object.

        RestHighLevelClient client;

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.fetchSource("recipe_ID,recipe_url", null);
        sourceBuilder.from(0);
        SearchRequest searchRequest = new SearchRequest("recipes");
        searchRequest.source(sourceBuilder);

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        SearchHit searchHit = searchResponse.getHits().getAt(0);

        String resultString = searchHit.getSourceAsString();

        return resultString;

I need to include only two fields recipe_ID and recipe_url in my result.

Body:
You're on the right path, although source filtering requires you to specify your fields in an array like this:

    String[] includeFields = new String[] {"recipe_ID", "recipe_url"};
    sourceBuilder.fetchSource(includeFields, null);


问:
Objective-C Blocks: Incompatible block pointer types
I'm trying to implement a block call. Here is my method:

```<code>- (void) runTest; {
    void (^MyBlock)(id, NSUInteger, BOOL) = ^(id obj, NSUInteger idx, BOOL stop) {
        NSLog(@"Video game %@", (NSString *)obj);
    };

    BOOL stop;
    MyBlock(@"Path of exile", 0, &stop);

    NSArray *videoGames = @[@"fallout", @"Deus ex",@"final fintasy"];

    [videoGames enumerateObjectsUsingBlock:MyBlock];
}
</code>```

But on this line:

[videoGames enumerateObjectsUsingBlock:MyBlock];

I'm getting this error:

Incompatible block pointer types sending 'void (^__strong)(__strong id, NSUInteger, BOOL)' to parameter of type 'void (^ _Nonnull)(id  _Nonnull __strong, NSUInteger, BOOL * _Nonnull)'

Any of you knows what I'm doing wrong or how can I fix this?

I'll really appreciate your help.

答:
the Bool parameter of the Block should be a pointer hence you need to add *

```<code>- (void) runTest; {
    void (^MyBlock)(id, NSUInteger, BOOL *) = ^(id obj, NSUInteger idx, BOOL *stop) {
        NSLog(@"Video game %@", (NSString *)obj);
    };

    BOOL stop;
    MyBlock(@"Path of exile", 0, &stop);

    NSArray *videoGames = @[@"fallout", @"Deus ex",@"final fintasy"];
   [videoGames enumerateObjectsUsingBlock:MyBlock];
}
</code>```

Body:
I'm trying to implement a block call. Here is my method:

- (void) runTest; {
    void (^MyBlock)(id, NSUInteger, BOOL) = ^(id obj, NSUInteger idx, BOOL stop) {
        NSLog(@"Video game %@", (NSString *)obj);
    };

    BOOL stop;
    MyBlock(@"Path of exile", 0, &stop);

    NSArray *videoGames = @[@"fallout", @"Deus ex",@"final fintasy"];

    [videoGames enumerateObjectsUsingBlock:MyBlock];
}

But on this line:

[videoGames enumerateObjectsUsingBlock:MyBlock];

I'm getting this error:

Incompatible block pointer types sending 'void (^__strong)(__strong id, NSUInteger, BOOL)' to parameter of type 'void (^ _Nonnull)(id  _Nonnull __strong, NSUInteger, BOOL * _Nonnull)'

Any of you knows what I'm doing wrong or how can I fix this?

I'll really appreciate your help.

Body:
the Bool parameter of the Block should be a pointer hence you need to add *

- (void) runTest; {
    void (^MyBlock)(id, NSUInteger, BOOL *) = ^(id obj, NSUInteger idx, BOOL *stop) {
        NSLog(@"Video game %@", (NSString *)obj);
    };

    BOOL stop;
    MyBlock(@"Path of exile", 0, &stop);

    NSArray *videoGames = @[@"fallout", @"Deus ex",@"final fintasy"];
   [videoGames enumerateObjectsUsingBlock:MyBlock];
}


问:
How to delete sorted/filtered items when using UISearchController
The following code successfully creates, displays a list of Cars in a UITableView where you can later delete carts too. It also presents a UISearchController where you can successfully perform searches.

My issue is trying to delete cars after a search/filter, for instance, if the user makes a search for a car which is located in the middle of the array, it will display the right car on the top row of the table but if he/she decides to delete it, it will delete the first item in the cars array since the filtered item is always positioned at the top in the filteredCars array. Here I get no error, but it does not delete the right item from the cars array, it always deletes the first item from the cars array.

Here is the code:

Model

```<code>class Car{
    var make = ""
    var model = ""
}
</code>```

ViewController

```<code>class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating{

    var cars =  Array<Car>()
    var filteredCars =  Array<Car>()
    let searchController = UISearchController(searchResultsController: nil)
    @IBOutlet weak var myTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        createCars()

        filteredCars = cars

        searchController.searchResultsUpdater = self
        searchController.obscuresBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Search by model"
        navigationItem.searchController = searchController
        definesPresentationContext = true
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return filteredCars.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell")! as UITableViewCell
        cell.textLabel?.text = filteredCars[indexPath.row].model
        cell.detailTextLabel?.text = filteredCars[indexPath.row].make
        return cell
    }
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

        let delete = UITableViewRowAction(style: .destructive, title: "Delete") { action, index in
            let alert = UIAlertController(title: "Delete selected car?", message: "This will permanently delete the selected car, do you want to continue?", preferredStyle: UIAlertController.Style.alert)

            alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil))
            alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.destructive, handler: { action in
                self.filteredCars.remove(at: indexPath.row)
                self.cars.remove(at: indexPath.row)
                self.myTable.deleteRows(at: [indexPath], with: UITableView.RowAnimation.left)
            }
            ))
            self.present(alert, animated: true, completion: nil)
        }
        return [delete]
    }

    func updateSearchResults(for searchController: UISearchController) {
        if let searchText = searchController.searchBar.text {
            filteredCars = searchText.isEmpty ? cars : cars.filter({(dataString: Car) -> Bool in
                return dataString.model.lowercased().contains(searchText.lowercased())
            })
            myTable.reloadData()
        }
    }
    // create cars manually for demonstration only
    func createCars(){
        let car1 = Car()
        car1.make = "Ford"
        car1.model = "Explorer"

        //... more cars here

        cars.append(contentsOf: [car1, car2, car3, car4])
    }
}
</code>```

I tried the following but I keep getting an Index out of range error.

```<code>func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let delete = UITableViewRowAction(style: .destructive, title: "Delete") { action, index in
        let alert = UIAlertController(title: "Delete selected car?", message: "This will permanently delete the selected car, do you want to continue?", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.destructive, handler: { action in

            self.filteredCars.remove(at: indexPath.row)
            self.myTable.deleteRows(at: [indexPath], with: UITableView.RowAnimation.left)

            for i in 0..<self.cars.count {
                if self.cars[i].model == modelToDelete{
                    self.cars.remove(at:i)
                }
            }
        }
        ))
        self.present(alert, animated: true, completion: nil)
    }
    return [delete]
}
</code>```

What would be the right logic for deleting items after a search?

答:
You have to get the index in the main array for the given car

```<code>alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.destructive, handler: { action in
     let carToDelete = self.filteredCars.remove(at: indexPath.row)
     self.cars.remove(at: self.cars.index(of: carToDelete)!)
     tableView.deleteRows(at: [indexPath], with: .left)
}
</code>```

This requires that Car adopts Equatable which is pretty easy to implement. If you change class to struct you get Equatable for free.

```<code>class Car : Equatable {
    var make = ""
    var model = ""

    static func == (lhs: Car, rhs: Car) -> Bool {
        return lhs.make == rhs.make && lhs.model == rhs.model
    }
}
</code>```

And use always the table view instance passed as parameter.

Body:
The following code successfully creates, displays a list of Cars in a UITableView where you can later delete carts too. It also presents a UISearchController where you can successfully perform searches.

My issue is trying to delete cars after a search/filter, for instance, if the user makes a search for a car which is located in the middle of the array, it will display the right car on the top row of the table but if he/she decides to delete it, it will delete the first item in the cars array since the filtered item is always positioned at the top in the filteredCars array. Here I get no error, but it does not delete the right item from the cars array, it always deletes the first item from the cars array.

Here is the code:

Model

class Car{
    var make = ""
    var model = ""
}

ViewController

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating{

    var cars =  Array<Car>()
    var filteredCars =  Array<Car>()
    let searchController = UISearchController(searchResultsController: nil)
    @IBOutlet weak var myTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        createCars()

        filteredCars = cars

        searchController.searchResultsUpdater = self
        searchController.obscuresBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Search by model"
        navigationItem.searchController = searchController
        definesPresentationContext = true
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return filteredCars.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell")! as UITableViewCell
        cell.textLabel?.text = filteredCars[indexPath.row].model
        cell.detailTextLabel?.text = filteredCars[indexPath.row].make
        return cell
    }
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

        let delete = UITableViewRowAction(style: .destructive, title: "Delete") { action, index in
            let alert = UIAlertController(title: "Delete selected car?", message: "This will permanently delete the selected car, do you want to continue?", preferredStyle: UIAlertController.Style.alert)

            alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil))
            alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.destructive, handler: { action in
                self.filteredCars.remove(at: indexPath.row)
                self.cars.remove(at: indexPath.row)
                self.myTable.deleteRows(at: [indexPath], with: UITableView.RowAnimation.left)
            }
            ))
            self.present(alert, animated: true, completion: nil)
        }
        return [delete]
    }

    func updateSearchResults(for searchController: UISearchController) {
        if let searchText = searchController.searchBar.text {
            filteredCars = searchText.isEmpty ? cars : cars.filter({(dataString: Car) -> Bool in
                return dataString.model.lowercased().contains(searchText.lowercased())
            })
            myTable.reloadData()
        }
    }
    // create cars manually for demonstration only
    func createCars(){
        let car1 = Car()
        car1.make = "Ford"
        car1.model = "Explorer"

        //... more cars here

        cars.append(contentsOf: [car1, car2, car3, car4])
    }
}

I tried the following but I keep getting an Index out of range error.

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let delete = UITableViewRowAction(style: .destructive, title: "Delete") { action, index in
        let alert = UIAlertController(title: "Delete selected car?", message: "This will permanently delete the selected car, do you want to continue?", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.destructive, handler: { action in

            self.filteredCars.remove(at: indexPath.row)
            self.myTable.deleteRows(at: [indexPath], with: UITableView.RowAnimation.left)

            for i in 0..<self.cars.count {
                if self.cars[i].model == modelToDelete{
                    self.cars.remove(at:i)
                }
            }
        }
        ))
        self.present(alert, animated: true, completion: nil)
    }
    return [delete]
}

What would be the right logic for deleting items after a search?

Body:
You have to get the index in the main array for the given car

alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.destructive, handler: { action in
     let carToDelete = self.filteredCars.remove(at: indexPath.row)
     self.cars.remove(at: self.cars.index(of: carToDelete)!)
     tableView.deleteRows(at: [indexPath], with: .left)
}

This requires that Car adopts Equatable which is pretty easy to implement. If you change class to struct you get Equatable for free.

class Car : Equatable {
    var make = ""
    var model = ""

    static func == (lhs: Car, rhs: Car) -> Bool {
        return lhs.make == rhs.make && lhs.model == rhs.model
    }
}

And use always the table view instance passed as parameter.


问:
Conversion failed when converting date and/or time from character string - insert datetimepicker.value in database
```<code>String insertUser = "Insert into
Users(FirstName,LastName,EmailAddress,Password,BirthDate,PhoneNumber)"
+ "values('@first','@last','@ema','@pass','@bid','@num');";
 SqlCommand addUser = new SqlCommand(insertUser,scn);
addUser.Parameters.Clear();
addUser.Parameters.AddWithValue("@first", FirstNameTextbox.Text);
addUser.Parameters.AddWithValue("@last", LastNameTextbox.Text);
addUser.Parameters.AddWithValue("@ema", EmailTextbox.Text);
addUser.Parameters.AddWithValue("@pass", PasswordTextbox.Text);
addUser.Parameters.AddWithValue("@bid", BirthDateDateTimePicker.Value);
addUser.Parameters.AddWithValue("@num", PhoneNumberTextbox.Text);
addUser.ExecuteNonQuery();
</code>```

When i execute this i get the exception in the title . How can it be fixed ?

答:
Based on your description, you want to insert datetimepicker.value into database.

I recommend that you remove single quotes for insertion parameters.

Besides, you need to set the BirthDate column to date type.

Code:

```<code>string insertUser = "Insert into Users(FirstName, LastName, EmailAddress, Password, BirthDate, PhoneNumber)"
     + "values(@first,@last,@ema,@pass,@bid,@num);";
            SqlCommand addUser = new SqlCommand(insertUser, scn);
            addUser.Parameters.Clear();
            addUser.Parameters.AddWithValue("@first", FirstNameTextbox.Text);
            addUser.Parameters.AddWithValue("@last", LastNameTextbox.Text);
            addUser.Parameters.AddWithValue("@ema", EmailTextbox.Text);
            addUser.Parameters.AddWithValue("@pass", PasswordTextbox.Text);
            addUser.Parameters.AddWithValue("@bid", BirthDateDateTimePicker.Value.ToString("yyyy-MM-dd"));
            addUser.Parameters.AddWithValue("@num", PhoneNumberTextbox.Text);
            addUser.ExecuteNonQuery();
            MessageBox.Show("Data inserted successfully");
</code>```

Result:

Body:
String insertUser = "Insert into
Users(FirstName,LastName,EmailAddress,Password,BirthDate,PhoneNumber)"
+ "values('@first','@last','@ema','@pass','@bid','@num');";
 SqlCommand addUser = new SqlCommand(insertUser,scn);
addUser.Parameters.Clear();
addUser.Parameters.AddWithValue("@first", FirstNameTextbox.Text);
addUser.Parameters.AddWithValue("@last", LastNameTextbox.Text);
addUser.Parameters.AddWithValue("@ema", EmailTextbox.Text);
addUser.Parameters.AddWithValue("@pass", PasswordTextbox.Text);
addUser.Parameters.AddWithValue("@bid", BirthDateDateTimePicker.Value);
addUser.Parameters.AddWithValue("@num", PhoneNumberTextbox.Text);
addUser.ExecuteNonQuery();

When i execute this i get the exception in the title . How can it be fixed ?

Body:
Based on your description, you want to insert datetimepicker.value into database.

I recommend that you remove single quotes for insertion parameters.

Besides, you need to set the BirthDate column to date type.

Code:

string insertUser = "Insert into Users(FirstName, LastName, EmailAddress, Password, BirthDate, PhoneNumber)"
     + "values(@first,@last,@ema,@pass,@bid,@num);";
            SqlCommand addUser = new SqlCommand(insertUser, scn);
            addUser.Parameters.Clear();
            addUser.Parameters.AddWithValue("@first", FirstNameTextbox.Text);
            addUser.Parameters.AddWithValue("@last", LastNameTextbox.Text);
            addUser.Parameters.AddWithValue("@ema", EmailTextbox.Text);
            addUser.Parameters.AddWithValue("@pass", PasswordTextbox.Text);
            addUser.Parameters.AddWithValue("@bid", BirthDateDateTimePicker.Value.ToString("yyyy-MM-dd"));
            addUser.Parameters.AddWithValue("@num", PhoneNumberTextbox.Text);
            addUser.ExecuteNonQuery();
            MessageBox.Show("Data inserted successfully");

Result:


问:
Android Device not recognized by adb
My Android device isn't recognized by eclipse nor adb anymore.
My OS is Windows 7 64-bit, and I'm using a Nexus 4 with Stock Android 4.4.2.

Here are some details on the problem:

Yesterday I could run Android Projects from eclipse on my device with no problems. The only thing that I did on eclipse, which could have caused this problem, was installing the v7 appcompat support library from a resource to eclipse using this guide on developers.android (https://developer.android.com/tools/support-library/setup.html).

The device is still recognized as a normal multimedia drive in Windows when it's not in debug mode.

The device is in Developers mode and in Debug mode when I try to run an Android Project in eclipse or try to see if it's recognized by adb using adb devices in the console.

The Google USB drivers have been installed through the ADK Manager

The USB OEM drivers for Windows have already been installed according to the tutorial on the android-developers site  (see: https://developer.android.com/tools/extras/oem-usb.html)

I tried to restart adb by using the commands adb kill-server and adb start-server, and again checked if the devices was recognized by using adb devices. The device was still not listed on the console.

Restarting windows & eclipse did not fix this problem.

What's the solution to this problem?

UPDATE: Thanks for the replies, the problem is solved (for now).
I tried the following suggestions in this order:

I restarted my device - this did not fix the problem

I set my device to PTP mode - this fixed the problem.

So I reset my device to MTP mode & debug mode again to check if it still would be recognised by adb for some reason. It definitly doesn't get recognised by adb when it's in MTP-mode. I don't know how it got recognised some days ago, because I never setmy device to PTP-mode. Anyway, the solution to my problem is that my Nexus 4 must be in PTP-Mode and of course in debug-mode to get recognised by adb.

I didn't try any other suggestions since my problem got solved with my current drivers.

答: For those facing problem after upgrading their android device to android 10, same PTP Mode option will work as prescribed by user3135185</p>

Title: Android Device not recognized by adb


问:
why i am getting AttributeError: 'module' object has no attribute 'set_trace'
```<code>import pdb
print("program started")
c=100
d=200
pdb.set_trace()
def fun(a,b):
    print a,b
    return a+b
fun(c,d)
for i in [1,2,3,4,5]:
    print 10/i
    print ("other statements in program")
print ("program ended")
</code>```

答: Its because of the name of your python file being same as the file you are trying to import, in this case your filename being pdb.py and you are trying to import pdb. This could result in a circular import. Rename the file and it will work.


问:
ASP.NET Core -- Upload .json file and convert to List<T>
So I managed to export a .json file by serializing my List. Now i'm trying to upload a .json file and desearialize it and add it back to my list. The idea is to be able to click on import, choose a file, then convert it so i can add it to my list. Here is the function in my controller that doesn't work:

** Update **
So now I managed to convert the .json file back to my List but if the list is empty and I want to add the new list to it, then I get this error:

```<code>[HttpPost]
    public async Task<IActionResult> Import(IFormFile file)
    {
        if (file == null || file.Length == 0)
            return Content("file not selected");

        var path = Path.Combine(Directory.GetCurrentDirectory(), "Import", file.FileName);

        using (var stream = new FileStream(path, FileMode.Create))
        {
            await file.CopyToAsync(stream);
        }

        String jsonImport = System.IO.File.ReadAllText(path);
        Console.WriteLine(jsonImport);
        List<Booking> bookings;
        _cache.TryGetValue("key", out bookings);
        List<Booking> newList = new List<Booking>();

        newList = JsonConvert.DeserializeObject<List<Booking>>(jsonImport);

        foreach (var item in newList)
        {
            bookings.Add(item);
            _cache.Set<List<Booking>>("key", bookings);
        }
        return RedirectToAction("Index");
    }
</code>```

So I want to choose a file (user should only be allowed to upload .json format nothing else but idk how to do that yet) and then from that .json I want to add every entry to my bookings List.
Here is the Booking Model:

```<code>public class Booking
{
    [Required]
    [Display(Name = "Ladestand")]
    [Range(0, 100)]
    public double chargeState { get; set; }

    [Required]
    [Display(Name = "Benötigte Fahrstrecke")]
    [Range(1, 1000)]
    public double distance { get; set; }

    [Required]
    [Display(Name = "Beginn")]

    public DateTime startTime { get; set; }

    [Required]
    [Display(Name = "Ende")]

    public DateTime endTime { get; set; }

    [Required]
    [Display(Name = "Anschlusstyp")]
    [EnumDataType(typeof(ConnectorType))]
    public ConnectorType connectorType { get; set; }
}
</code>```

And here is the export function:

```<code>public ActionResult Export()
    {
        string fileName = "BookingsExport.json";
        List<Booking> bookingsList;
        _cache.TryGetValue("key", out bookingsList);

        string json = JsonConvert.SerializeObject(bookingsList);
        FileInfo file = new FileInfo(fileName);
        using (StreamWriter writer = file.CreateText())
        {
            writer.Write(json);
        }

        byte[] fileBytes = System.IO.File.ReadAllBytes(fileName);

        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Json, fileName);
    }
</code>```

答:
That is because if you do not has value in the cache,it would set the value null to the bookings.You need to change like below:

```<code>List<Booking> bookings;
var flag = _cache.TryGetValue("key", out bookings);
if(!flag)
{
    bookings = new List<Booking>();
}
</code>```

Body:
So I managed to export a .json file by serializing my List. Now i'm trying to upload a .json file and desearialize it and add it back to my list. The idea is to be able to click on import, choose a file, then convert it so i can add it to my list. Here is the function in my controller that doesn't work:

** Update **
So now I managed to convert the .json file back to my List but if the list is empty and I want to add the new list to it, then I get this error:

[HttpPost]
    public async Task<IActionResult> Import(IFormFile file)
    {
        if (file == null || file.Length == 0)
            return Content("file not selected");

        var path = Path.Combine(Directory.GetCurrentDirectory(), "Import", file.FileName);

        using (var stream = new FileStream(path, FileMode.Create))
        {
            await file.CopyToAsync(stream);
        }

        String jsonImport = System.IO.File.ReadAllText(path);
        Console.WriteLine(jsonImport);
        List<Booking> bookings;
        _cache.TryGetValue("key", out bookings);
        List<Booking> newList = new List<Booking>();

        newList = JsonConvert.DeserializeObject<List<Booking>>(jsonImport);

        foreach (var item in newList)
        {
            bookings.Add(item);
            _cache.Set<List<Booking>>("key", bookings);
        }
        return RedirectToAction("Index");
    }

So I want to choose a file (user should only be allowed to upload .json format nothing else but idk how to do that yet) and then from that .json I want to add every entry to my bookings List.
Here is the Booking Model:

public class Booking
{
    [Required]
    [Display(Name = "Ladestand")]
    [Range(0, 100)]
    public double chargeState { get; set; }

    [Required]
    [Display(Name = "Benötigte Fahrstrecke")]
    [Range(1, 1000)]
    public double distance { get; set; }

    [Required]
    [Display(Name = "Beginn")]

    public DateTime startTime { get; set; }

    [Required]
    [Display(Name = "Ende")]

    public DateTime endTime { get; set; }

    [Required]
    [Display(Name = "Anschlusstyp")]
    [EnumDataType(typeof(ConnectorType))]
    public ConnectorType connectorType { get; set; }
}

And here is the export function:

public ActionResult Export()
    {
        string fileName = "BookingsExport.json";
        List<Booking> bookingsList;
        _cache.TryGetValue("key", out bookingsList);

        string json = JsonConvert.SerializeObject(bookingsList);
        FileInfo file = new FileInfo(fileName);
        using (StreamWriter writer = file.CreateText())
        {
            writer.Write(json);
        }

        byte[] fileBytes = System.IO.File.ReadAllBytes(fileName);

        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Json, fileName);
    }

Body:
That is because if you do not has value in the cache,it would set the value null to the bookings.You need to change like below:

List<Booking> bookings;
var flag = _cache.TryGetValue("key", out bookings);
if(!flag)
{
    bookings = new List<Booking>();
}


问:
AWS word press site missing content after EC2 reboot
I deployed wordpress site on EC2 and connected it using RDS mysql. Everything works perfect on the first run and as long as EC2 and RDS are running. As soon as i stop the ec2 and rds and try to reboot it next morning or straight away, i can get to word press site but content is not layed out properly and images are missing too. I searched through internet and found closely related issues which recommend using of elastic ip, i also used elastic ip and assign that to EC2 but still content of WP is missing. Any suggestion</p>

答:
I also faced same issue, when i installed wordpress on aws ec2 instance, i have created some posts and pages, and after some time i have stopped ec2 instance. When started ec2 instance, wordpress site did not showing contents.

So the Solution was i found is that, wordpress require static IP address, so i have created new ec2, assigned Elastic IP address to the ec2 instance and created wordpress blog, it worked fine for me even restarting the ec2 multiple times.


问:
What does the following algorithm approximate? (Assume m>1,ϵ>0)
```<code>x = m;
y = 1;
While (x-y > ϵ)
{
    x = (x+y)/2;
    y = m/x;
}
print(x);
</code>```

Answer is \sqrt{m}

I don't know how to reach that conclusion because i don't know the value of ϵ, I have tried but i result in bunch of equations which doesn't make sense to me.

Please help me to understand how to understand and breakdown this type of questions
Thank you

答:
Note that:

the loop will continue until x and y are within ϵ of each other;

y = m / x  ⇒ y * x = m at each iteration.

When the stopping condition is met we know that x * (x - ϵ) = x2 - ϵx = m.  Consequently, as ϵ → 0, that means x2 → m, so x (and y) must converge to sqrt(m). ϵ is the tolerance you specify for that convergence.

Body:
x = m;
y = 1;
While (x-y > ϵ)
{
    x = (x+y)/2;
    y = m/x;
}
print(x);

Answer is \sqrt{m}

I don't know how to reach that conclusion because i don't know the value of ϵ, I have tried but i result in bunch of equations which doesn't make sense to me.

Please help me to understand how to understand and breakdown this type of questions
Thank you


问:
OAuth 1.0 "Could not authenticate you."
Hı first of all this is a twitter auth. I can login, I can get the timeline etc etc. I can get those things because they dont want an extra paramaters. But now ı want to add "tweet_mode=extended" paramaters to that.

```<code> public String extendedtweet(String token, String secret,String id) throws IOException{

    String url="https://api.twitter.com/1.1/statuses/lookup.json";
    headercreator hc=new headercreator(outhconsumerkey,consumersecret,token,secret);
    Map<String,String> requestparams = new HashMap<String, String>();
    Log.e("id",id);
    requestparams.put("id",id);
    String header=hc.generateHeader("GET",url,requestparams);
    Log.e("header",header);

    Response response =request(url,"","GET","Authorization",header);
    String jsonData=response.body().string();
    JsonObject js=new Gson().fromJson(jsonData, JsonObject.class);
    return js.get("full_text").getAsString();

}
</code>```

When ı Delete the

```<code>        requestparams.put("id",id);
</code>```

Line at there it says id paramaters is missing.That is Nice because that shows me the problem is at the Headercreator class which is here :

```<code>   package com.example.twittertestvol1;

import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * Class to generate Oauth 1.0a header for Twitter
 *
 */
@RequiresApi(api = Build.VERSION_CODES.N)
public class headercreator {

    private String consumerKey;
    private String consumerSecret;
    private String signatureMethod;
    private String token;
    private String tokenSecret;
    private String version;

    public headercreator(String consumerKey, String consumerSecret, String token, String tokenSecret) {
        this.consumerKey = consumerKey;
        this.consumerSecret = consumerSecret;
        this.token = token;
        this.tokenSecret = tokenSecret;
        this.signatureMethod = "HMAC-SHA1";
        this.version = "1.0";
    }

    private static final String oauth_consumer_key = "oauth_consumer_key";
    private static final String oauth_token = "oauth_token";
    private static final String oauth_signature_method = "oauth_signature_method";
    private static final String oauth_timestamp = "oauth_timestamp";
    private static final String oauth_nonce = "oauth_nonce";
    private static final String oauth_version = "oauth_version";
    private static final String oauth_signature = "oauth_signature";
    private static final String HMAC_SHA1 = "HmacSHA1";

    /**
     * Generates oAuth 1.0a header which can be pass as Authorization header
     *
     * @param httpMethod
     * @param url
     * @param requestParams
     * @return
     */
    public String generateHeader(String httpMethod, String url, Map<String, String> requestParams) {
        StringBuilder base = new StringBuilder();
        String nonce = getNonce();
        String timestamp = getTimestamp();
        String baseSignatureString = generateSignatureBaseString(httpMethod, url, requestParams, nonce, timestamp);
        String signature = encryptUsingHmacSHA1(baseSignatureString);
        base.append("OAuth ");
        append(base, oauth_consumer_key, consumerKey);
        append(base, oauth_token, token);
        append(base, oauth_signature_method, signatureMethod);
        append(base, oauth_timestamp, timestamp);
        append(base, oauth_nonce, nonce);
        append(base, oauth_version, version);
        append(base, oauth_signature, signature);
        base.deleteCharAt(base.length() - 1);
        return base.toString();
    }

    /**
     * Generate base string to generate the oauth_signature
     *
     * @param httpMethod
     * @param url
     * @param requestParams
     * @return
     */
    private String generateSignatureBaseString(String httpMethod, String url, Map<String, String> requestParams, String nonce, String timestamp) {
        Map<String, String> params = new HashMap<>();
        if (requestParams!=null)
        {
            requestParams.entrySet().forEach(entry -> {
                put(params, entry.getKey(), entry.getValue());
            });

        }
        put(params, oauth_consumer_key, consumerKey);
        put(params, oauth_nonce, nonce);
        put(params, oauth_signature_method, signatureMethod);
        put(params, oauth_timestamp, timestamp);
        put(params, oauth_token, token);
        put(params, oauth_version, version);
        Map<String, String> sortedParams = params.entrySet().stream().sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        StringBuilder base = new StringBuilder();
        sortedParams.entrySet().forEach(entry -> {
            base.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        });
        base.deleteCharAt(base.length() - 1);
        String baseString = httpMethod.toUpperCase() + "&" + encode(url) + "&" + encode(base.toString());
        return baseString;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private String encryptUsingHmacSHA1(String input) {
        String secret = new StringBuilder().append(encode(consumerSecret)).append("&").append(encode(tokenSecret)).toString();
        byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8);
        SecretKey key = new SecretKeySpec(keyBytes, HMAC_SHA1);
        Mac mac;
        try {
            mac = Mac.getInstance(HMAC_SHA1);
            mac.init(key);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
            return null;
        }
        byte[] signatureBytes = mac.doFinal(input.getBytes(StandardCharsets.UTF_8));
        return new String(Base64.getEncoder().encode(signatureBytes));
    }

    /**
     * Percentage encode String as per RFC 3986, Section 2.1
     *
     * @param value
     * @return
     */
    private String encode(String value) {
        String encoded = "";
        try {
            encoded = URLEncoder.encode(value, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String sb = "";
        char focus;
        for (int i = 0; i < encoded.length(); i++) {
            focus = encoded.charAt(i);
            if (focus == '*') {
                sb += "%2A";
            } else if (focus == '+') {
                sb += "%20";
            } else if (focus == '%' && i + 1 < encoded.length() && encoded.charAt(i + 1) == '7' && encoded.charAt(i + 2) == 'E') {
                sb += '~';
                i += 2;
            } else {
                sb += focus;
            }
        }
        return sb.toString();
    }

    private void put(Map<String, String> map, String key, String value) {
        map.put(encode(key), encode(value));
    }

    private void append(StringBuilder builder, String key, String value) {
        builder.append(encode(key)).append("=\"").append(encode(value)).append("\",");
    }

    private String getNonce() {
        int leftLimit = 48; // numeral '0'
        int rightLimit = 122; // letter 'z'
        int targetStringLength = 10;
        Random random = new Random();

        String generatedString = random.ints(leftLimit, rightLimit + 1).filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97)).limit(targetStringLength)
                .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
        return generatedString;

    }

    private String getTimestamp() {
        return Math.round((new Date()).getTime() / 1000.0) + "";
    }

}
</code>```

Nowı wonder if someone shows me where is the problem why ı cant solve that. And that is the error code and error for that

{"errors":[{"code":32,"message":"Could not authenticate you."}]}

Here is thre request function

```<code>private Response request(String url, String bodys, String type, String Headername, String Header) throws IOException {

    OkHttpClient client = new OkHttpClient();
    MediaType mediaType = MediaType.parse("text/plain");
    RequestBody body = RequestBody.create(mediaType,bodys);
    Request request;
    if (!Headername.equals(""))
    {
        if (type.equals("GET"))
        {

            request = new Request.Builder()
                    .url(url)
                    .method(type,null)
                    .addHeader(Headername,Header)
                    .build();

        }
        else{
            request = new Request.Builder()
                    .url(url)
                    .method(type, body)
                    .addHeader(Headername,Header)
                    .build();
        }

    }
    else {
        request = new Request.Builder()
                .url(url)
                .method(type, body)
                .build();

    }

    return client.newCall(request).execute();
}
</code>```

答:
Issue is at Response response =request(url,"","GET","Authorization",header);.

You need to pass in the request params when calling the service but you are not passing the id or any other param when calling the request() method. For me following code works:

    public void getTweet() {
        Map<String, String> requestParams = new HashMap<>();
        String id = "1263213348000325633";
        // Pass all request params for header generation
        requestParams.put("id", id);
        requestParams.put("tweet_mode", "extended");
        String url = "https://api.twitter.com/1.1/statuses/lookup.json";
        String header = generator.generateHeader(HttpMethod.GET.name(), url, requestParams);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", header);
        HttpEntity<String> httpEntity = new HttpEntity<String>("body", headers);
        // Pass all request params in the request
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
                .queryParam("id", id)
                .queryParam("tweet_mode", "extended");
        ResponseEntity<String> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, String.class);
        String responseBody = response.getBody();
        assertNotNull(responseBody);
        System.out.println(responseBody);
    }
```

Working code available here as a junit.

Title: OAuth 1.0 "Could not authenticate you."

Body:
Hı first of all this is a twitter auth. I can login, I can get the timeline etc etc. I can get those things because they dont want an extra paramaters. But now ı want to add "tweet_mode=extended" paramaters to that.

 public String extendedtweet(String token, String secret,String id) throws IOException{

    String url="https://api.twitter.com/1.1/statuses/lookup.json";
    headercreator hc=new headercreator(outhconsumerkey,consumersecret,token,secret);
    Map<String,String> requestparams = new HashMap<String, String>();
    Log.e("id",id);
    requestparams.put("id",id);
    String header=hc.generateHeader("GET",url,requestparams);
    Log.e("header",header);

    Response response =request(url,"","GET","Authorization",header);
    String jsonData=response.body().string();
    JsonObject js=new Gson().fromJson(jsonData, JsonObject.class);
    return js.get("full_text").getAsString();

}

When ı Delete the

        requestparams.put("id",id);

Line at there it says id paramaters is missing.That is Nice because that shows me the problem is at the Headercreator class which is here :

   package com.example.twittertestvol1;

import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * Class to generate Oauth 1.0a header for Twitter
 *
 */
@RequiresApi(api = Build.VERSION_CODES.N)
public class headercreator {

    private String consumerKey;
    private String consumerSecret;
    private String signatureMethod;
    private String token;
    private String tokenSecret;
    private String version;

    public headercreator(String consumerKey, String consumerSecret, String token, String tokenSecret) {
        this.consumerKey = consumerKey;
        this.consumerSecret = consumerSecret;
        this.token = token;
        this.tokenSecret = tokenSecret;
        this.signatureMethod = "HMAC-SHA1";
        this.version = "1.0";
    }

    private static final String oauth_consumer_key = "oauth_consumer_key";
    private static final String oauth_token = "oauth_token";
    private static final String oauth_signature_method = "oauth_signature_method";
    private static final String oauth_timestamp = "oauth_timestamp";
    private static final String oauth_nonce = "oauth_nonce";
    private static final String oauth_version = "oauth_version";
    private static final String oauth_signature = "oauth_signature";
    private static final String HMAC_SHA1 = "HmacSHA1";

    /**
     * Generates oAuth 1.0a header which can be pass as Authorization header
     *
     * @param httpMethod
     * @param url
     * @param requestParams
     * @return
     */
    public String generateHeader(String httpMethod, String url, Map<String, String> requestParams) {
        StringBuilder base = new StringBuilder();
        String nonce = getNonce();
        String timestamp = getTimestamp();
        String baseSignatureString = generateSignatureBaseString(httpMethod, url, requestParams, nonce, timestamp);
        String signature = encryptUsingHmacSHA1(baseSignatureString);
        base.append("OAuth ");
        append(base, oauth_consumer_key, consumerKey);
        append(base, oauth_token, token);
        append(base, oauth_signature_method, signatureMethod);
        append(base, oauth_timestamp, timestamp);
        append(base, oauth_nonce, nonce);
        append(base, oauth_version, version);
        append(base, oauth_signature, signature);
        base.deleteCharAt(base.length() - 1);
        return base.toString();
    }

    /**
     * Generate base string to generate the oauth_signature
     *
     * @param httpMethod
     * @param url
     * @param requestParams
     * @return
     */
    private String generateSignatureBaseString(String httpMethod, String url, Map<String, String> requestParams, String nonce, String timestamp) {
        Map<String, String> params = new HashMap<>();
        if (requestParams!=null)
        {
            requestParams.entrySet().forEach(entry -> {
                put(params, entry.getKey(), entry.getValue());
            });

        }
        put(params, oauth_consumer_key, consumerKey);
        put(params, oauth_nonce, nonce);
        put(params, oauth_signature_method, signatureMethod);
        put(params, oauth_timestamp, timestamp);
        put(params, oauth_token, token);
        put(params, oauth_version, version);
        Map<String, String> sortedParams = params.entrySet().stream().sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        StringBuilder base = new StringBuilder();
        sortedParams.entrySet().forEach(entry -> {
            base.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        });
        base.deleteCharAt(base.length() - 1);
        String baseString = httpMethod.toUpperCase() + "&" + encode(url) + "&" + encode(base.toString());
        return baseString;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private String encryptUsingHmacSHA1(String input) {
        String secret = new StringBuilder().append(encode(consumerSecret)).append("&").append(encode(tokenSecret)).toString();
        byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8);
        SecretKey key = new SecretKeySpec(keyBytes, HMAC_SHA1);
        Mac mac;
        try {
            mac = Mac.getInstance(HMAC_SHA1);
            mac.init(key);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
            return null;
        }
        byte[] signatureBytes = mac.doFinal(input.getBytes(StandardCharsets.UTF_8));
        return new String(Base64.getEncoder().encode(signatureBytes));
    }

    /**
     * Percentage encode String as per RFC 3986, Section 2.1
     *
     * @param value
     * @return
     */
    private String encode(String value) {
        String encoded = "";
        try {
            encoded = URLEncoder.encode(value, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String sb = "";
        char focus;
        for (int i = 0; i < encoded.length(); i++) {
            focus = encoded.charAt(i);
            if (focus == '*') {
                sb += "%2A";
            } else if (focus == '+') {
                sb += "%20";
            } else if (focus == '%' && i + 1 < encoded.length() && encoded.charAt(i + 1) == '7' && encoded.charAt(i + 2) == 'E') {
                sb += '~';
                i += 2;
            } else {
                sb += focus;
            }
        }
        return sb.toString();
    }

    private void put(Map<String, String> map, String key, String value) {
        map.put(encode(key), encode(value));
    }

    private void append(StringBuilder builder, String key, String value) {
        builder.append(encode(key)).append("=\"").append(encode(value)).append("\",");
    }

    private String getNonce() {
        int leftLimit = 48; // numeral '0'
        int rightLimit = 122; // letter 'z'
        int targetStringLength = 10;
        Random random = new Random();

        String generatedString = random.ints(leftLimit, rightLimit + 1).filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97)).limit(targetStringLength)
                .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
        return generatedString;

    }

    private String getTimestamp() {
        return Math.round((new Date()).getTime() / 1000.0) + "";
    }

}

Nowı wonder if someone shows me where is the problem why ı cant solve that. And that is the error code and error for that

{"errors":[{"code":32,"message":"Could not authenticate you."}]}

Here is thre request function

private Response request(String url, String bodys, String type, String Headername, String Header) throws IOException {

    OkHttpClient client = new OkHttpClient();
    MediaType mediaType = MediaType.parse("text/plain");
    RequestBody body = RequestBody.create(mediaType,bodys);
    Request request;
    if (!Headername.equals(""))
    {
        if (type.equals("GET"))
        {

            request = new Request.Builder()
                    .url(url)
                    .method(type,null)
                    .addHeader(Headername,Header)
                    .build();

        }
        else{
            request = new Request.Builder()
                    .url(url)
                    .method(type, body)
                    .addHeader(Headername,Header)
                    .build();
        }

    }
    else {
        request = new Request.Builder()
                .url(url)
                .method(type, body)
                .build();

    }

    return client.newCall(request).execute();
}

Body:
Issue is at Response response =request(url,"","GET","Authorization",header);.

You need to pass in the request params when calling the service but you are not passing the id or any other param when calling the request() method. For me following code works:

    public void getTweet() {
        Map<String, String> requestParams = new HashMap<>();
        String id = "1263213348000325633";
        // Pass all request params for header generation
        requestParams.put("id", id);
        requestParams.put("tweet_mode", "extended");
        String url = "https://api.twitter.com/1.1/statuses/lookup.json";
        String header = generator.generateHeader(HttpMethod.GET.name(), url, requestParams);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", header);
        HttpEntity<String> httpEntity = new HttpEntity<String>("body", headers);
        // Pass all request params in the request
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
                .queryParam("id", id)
                .queryParam("tweet_mode", "extended");
        ResponseEntity<String> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, String.class);
        String responseBody = response.getBody();
        assertNotNull(responseBody);
        System.out.println(responseBody);
    }

Working code available here as a junit.


问:
How to combine the results of different metrics and generate a score out of them?
I have the following dataframe that shows the performance of my 6 models using different metrics.
I want to generate a score out of the result of all the metrics, and then detect the best model.
I can't use average because the metrics are not in the same direction. (For example higher AUC is better but on the other hand lower MAE,MSE, and RMSE are better)

```<code>  Model RMSE    MAE     MSE     AUC    Score
0   a   0.29    0.187   0.084   0.65     ?
1   b   0.29    0.187   0.084   0.649    ?
2   c   0.299   0.17    0.09    0.64     ?
3   d   0.308   0.149   0.095   0.663    ?
4   e   0.314   0.143   0.099   0.675    ?
5   f   0.319   0.146   0.102   0.682    ?
</code>```

Is it reasonable if I just multiply all of them together and then multiply them by 1/AUC and use this value as the score?

Any ideas?

答:
It depends on your objective function and problem which you are trying to solve.

Typically the "best" model performs better than other models using some metrics, but does not perform as well in other metrics. Such as in your example, an increase in RMSE gives better AUC but worse MAE. Have a look at the scikit documentation for an extensive list of error metrics you could possibly use: https://scikit-learn.org/stable/modules/model_evaluation.html. You will need to decide if all receive equal weights, or not.

You may wish to consider bagging, where you combine the weighted combination of all your models, instead of picking just 1 model to reduce generalization errors when dealing with out-of-sample data.

Also consider generating out-of-sample data that follows the random distribution of your trained dataset. You may find out-of-sample data generates error metrics for each model that are quite different from in-sample results, and Monte Carlo simulation of these out-of-sample tests will give you better clarity as to which model(s) and error metrics to focus on.

Body:
I have the following dataframe that shows the performance of my 6 models using different metrics.
I want to generate a score out of the result of all the metrics, and then detect the best model.
I can't use average because the metrics are not in the same direction. (For example higher AUC is better but on the other hand lower MAE,MSE, and RMSE are better)

  Model RMSE    MAE     MSE     AUC    Score
0   a   0.29    0.187   0.084   0.65     ?
1   b   0.29    0.187   0.084   0.649    ?
2   c   0.299   0.17    0.09    0.64     ?
3   d   0.308   0.149   0.095   0.663    ?
4   e   0.314   0.143   0.099   0.675    ?
5   f   0.319   0.146   0.102   0.682    ?

Is it reasonable if I just multiply all of them together and then multiply them by 1/AUC and use this value as the score?

Any ideas?


问:
How to async parse/write json in webflux? ObjectMapper methods are blocking
I saw that jackson supports non-blocking since 2.9, but how to use it with webflux? Is there a demo?</p>

答:
Here is how you can use WebClient to make a GET request to Github’s List Repositories API

```<code>public Flux<GithubRepo> listGithubRepositories(String username, String token) {
     return webClient.get()
            .uri("/user/repos")
            .header("Authorization", "Basic " + Base64Utils
                    .encodeToString((username + ":" + token).getBytes(UTF_8)))
            .retrieve()
            .bodyToFlux(GithubRepo.class);
}
</code>```

Assuming we have a class named GithubRepo that confirms to the Github’s API response, the above function will return a Flux of GithubRepo objects.

Body:
Here is how you can use WebClient to make a GET request to Github’s List Repositories API

public Flux<GithubRepo> listGithubRepositories(String username, String token) {
     return webClient.get()
            .uri("/user/repos")
            .header("Authorization", "Basic " + Base64Utils
                    .encodeToString((username + ":" + token).getBytes(UTF_8)))
            .retrieve()
            .bodyToFlux(GithubRepo.class);
}

Assuming we have a class named GithubRepo that confirms to the Github’s API response, the above function will return a Flux of GithubRepo objects.


问:
Create Max and Min column values from a single column value pandas
I have a dataframe like the one below and I need to create two columns out of the base column.

Input

```<code>Kg
0.5
0.5
1
1
1
2
2
5
5
5
</code>```

Expected Output

```<code>Kg_From  Kg_To
0      0.5
0      0.5
0.5    1
0.5    1
0.5    1
1      2
1      2
2      5
2      5
2      5
</code>```

How can this be done in pandas ?

答:
Code:

```<code>kgs = df.Kg.unique()

lower = [0] + list(kgs[:-1])
kg_dict = {k:v for v,k in zip(lower,kgs)}

# new dataframe
new_df = pd.DataFrame({
             'Kg_From': df['Kg'].map(kg_dict),
             'Kg_To': df['Kg']
         })

# or if you want new columns:
df['Kg_from'] = df['Kg'].map(kg_dict)
</code>```

Output:

```<code>   Kg_From  Kg_To
0      0.0    0.5
1      0.0    0.5
2      0.5    1.0
3      0.5    1.0
4      0.5    1.0
5      1.0    2.0
6      1.0    2.0
7      2.0    5.0
8      2.0    5.0
9      2.0    5.0
</code>```

Body:
I have a dataframe like the one below and I need to create two columns out of the base column.

Input

Kg
0.5
0.5
1
1
1
2
2
5
5
5

Expected Output

Kg_From  Kg_To
0      0.5
0      0.5
0.5    1
0.5    1
0.5    1
1      2
1      2
2      5
2      5
2      5

How can this be done in pandas ?

Body:
Code:

kgs = df.Kg.unique()

lower = [0] + list(kgs[:-1])
kg_dict = {k:v for v,k in zip(lower,kgs)}

# new dataframe
new_df = pd.DataFrame({
             'Kg_From': df['Kg'].map(kg_dict),
             'Kg_To': df['Kg']
         })

# or if you want new columns:
df['Kg_from'] = df['Kg'].map(kg_dict)

Output:

   Kg_From  Kg_To
0      0.0    0.5
1      0.0    0.5
2      0.5    1.0
3      0.5    1.0
4      0.5    1.0
5      1.0    2.0
6      1.0    2.0
7      2.0    5.0
8      2.0    5.0
9      2.0    5.0


问:
MySQL: Insert if this ip dont have any records
I use:

```<code>INSERT INTO `rating` (`name`, `user`, `rating`, `section`, `ip`)
VALUES ('$name', '{$_SESSION['user']}', '$rate', '$section',
        '{$_SERVER['REMOTE_ADDR']}');";
</code>```

I would like to add an if condition in the IF statement so that.

```<code>IF SELECT ip from rating
where ip={$_SERVER['REMOTE_ADDR']} AND section=$section AND name=$name
then update ELSE INSERT new row
</code>```

is it doable or I better code it in php ?
thank you very much

P.s: I know how to do it with php, I want to learn it with MySQL.

Also i require that all 3 name,section,ip matchs not only ip

答:
Assuming you have a unique constraint (UNIQUE index or PRIMARY KEY) on ip, section and name, you can use this syntax:

```<code>INSERT INTO `rating` (`name`, `user`, `rating`, `section`, `ip`)
VALUES ('$name', '{$_SESSION['user']}', '$rate', '$section', '{$_SERVER['REMOTE_ADDR']}')
ON DUPLICATE KEY UPDATE user = VALUES(user), rating = VALUES(rating);
</code>```

Body:
I use:

INSERT INTO `rating` (`name`, `user`, `rating`, `section`, `ip`)
VALUES ('$name', '{$_SESSION['user']}', '$rate', '$section',
        '{$_SERVER['REMOTE_ADDR']}');";

I would like to add an if condition in the IF statement so that.

IF SELECT ip from rating
where ip={$_SERVER['REMOTE_ADDR']} AND section=$section AND name=$name
then update ELSE INSERT new row

is it doable or I better code it in php ?
thank you very much

P.s: I know how to do it with php, I want to learn it with MySQL.

Also i require that all 3 name,section,ip matchs not only ip

Body:
Assuming you have a unique constraint (UNIQUE index or PRIMARY KEY) on ip, section and name, you can use this syntax:

INSERT INTO `rating` (`name`, `user`, `rating`, `section`, `ip`)
VALUES ('$name', '{$_SESSION['user']}', '$rate', '$section', '{$_SERVER['REMOTE_ADDR']}')
ON DUPLICATE KEY UPDATE user = VALUES(user), rating = VALUES(rating);


问:
git commit error: pathspec 'xxx' did not match any file(s) known to git
I wrote a bash script to update my files through git automatically, but I keep getting error for the git commit line, if my message contains error.

I have already wrapped my message with quote, what's wrong here?

My bash script:

```<code>##Handle local git update
remote='
cd express-demo-nonbare;
git pull origin master;
';

echo "Process for updating Git begin";
git add . ;
read -p "Message for this commit: " comment;
comment=\"${comment}\";
echo $comment;
git commit --message=$comment;
git push backup master;
</code>```

答:
Really you just need to quote the comment variable when supplying it to git commit.  You can replace:

```<code>read -p "Message for this commit: " comment;
comment=\"${comment}\";
echo $comment;
git commit --message=$comment;
</code>```

with

```<code>read -p "Message for this commit: " comment;
echo $comment;
git commit --message="$comment";
</code>```

The quotes will not be part of the commit message, rather they are consumed by bash in ensuring that the entire content of the comment variable is submitted as part of a single --message=... argument to git, even if it contains whitespace characters.

Body:
I wrote a bash script to update my files through git automatically, but I keep getting error for the git commit line, if my message contains error.

I have already wrapped my message with quote, what's wrong here?

My bash script:

##Handle local git update
remote='
cd express-demo-nonbare;
git pull origin master;
';

echo "Process for updating Git begin";
git add . ;
read -p "Message for this commit: " comment;
comment=\"${comment}\";
echo $comment;
git commit --message=$comment;
git push backup master;

Body:
Really you just need to quote the comment variable when supplying it to git commit.  You can replace:

read -p "Message for this commit: " comment;
comment=\"${comment}\";
echo $comment;
git commit --message=$comment;

with

read -p "Message for this commit: " comment;
echo $comment;
git commit --message="$comment";

The quotes will not be part of the commit message, rather they are consumed by bash in ensuring that the entire content of the comment variable is submitted as part of a single --message=... argument to git, even if it contains whitespace characters.


问:
How to change content of UILabel inside of a closure
I can't change content of UILabel inside of a closure. I googled, yet solution is nowhere to be found.

Here is related piece of my code:

```<code>class ViewController: UIViewController {

    @IBOutlet var city: UITextField!
    @IBOutlet var message: UILabel!
    @IBAction func buttonPressed(sender: AnyObject) {

        var urlString = "http://google.com"
        var url = NSURL(string: urlString)

        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url!) {(data, response, error) in

            self.message.text = "try"
            println("done")
        }

        task.resume()
    }
    ... //rest of the code
</code>```

It should change contents of UILabel message with "try" when I click the button. It prints out "done" in the console, but it does not change content of UILabel.

答:
I just had the same issue. I already wrapped the
UILabel.text = newTitle in DispatchQueue.main.async{}block, but it didn't work. After checking carefully, I found I accidentally declared the function outside of the view controller where the UILabel was declared. Thought I'd write this in case anyone else runs into the same problem! Don't forget to check your indentations:D

Body:
I can't change content of UILabel inside of a closure. I googled, yet solution is nowhere to be found.

Here is related piece of my code:

class ViewController: UIViewController {

    @IBOutlet var city: UITextField!
    @IBOutlet var message: UILabel!
    @IBAction func buttonPressed(sender: AnyObject) {

        var urlString = "http://google.com"
        var url = NSURL(string: urlString)

        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url!) {(data, response, error) in

            self.message.text = "try"
            println("done")
        }

        task.resume()
    }
    ... //rest of the code

It should change contents of UILabel message with "try" when I click the button. It prints out "done" in the console, but it does not change content of UILabel.


问:
Unique ID on NSViews
Is there any kind of ID that can be used and set in the .nib/.xib via Xcode that can be queried at runtime to identify a particular view instance from code?

In particular when having multiple copies of the same NSView subclass in our interface how can we tell which one we're currently looking at?

答:
Here's how to simulate  "tags" in OSX without subclassing.

In iOS:

```<code>{
    // iOS:
    // 1. You add a tag to a view and add it as a subView, as in:
    UIView *masterView = ... // the superview
    UIView *aView = ... // a subview
    aView.tag = 13;
    [masterView addSubview:aView];

    // 2.  Later, to retrieve the tagged view:
    UIView *aView = [masterView viewWithTag:13];
    // returns nil if there's no subview with that tag
}
</code>```

The equivalent in OSX:

```<code>#import <objc/runtime.h> // for associated objects
{
    // OSX:
    // 1.  Somewhere early, create an invariant memory address
    static void const *tag13 = &tag13; // put at the top of the file

    // 2.  Attach an object to the view to which you'll be adding the subviews:
    NSView *masterView = ... // the superview
    NSView *aView = ...  // a subview
    [masterView addSubview:aView];
    objc_setAssociatedObject(masterView, tag13, aView, OBJC_ASSOCIATION_ASSIGN);

    // 3.  Later, to retrieve the "tagged" view:
    NSView *aView = objc_getAssociatedObject(masterView, tag13);
    // returns nil if there's no subview with that associated object "tag"
}
</code>```

Edit: The associated object "key" (declared as const void *key) needs to be invariant.  I'm using an idea by Will Pragnell (https://stackoverflow.com/a/18548365/236415).
Search Stack Overflow for other schemes for making the key.

Title: Unique ID on NSViews

Body:
Here's how to simulate  "tags" in OSX without subclassing.

In iOS:

{
    // iOS:
    // 1. You add a tag to a view and add it as a subView, as in:
    UIView *masterView = ... // the superview
    UIView *aView = ... // a subview
    aView.tag = 13;
    [masterView addSubview:aView];

    // 2.  Later, to retrieve the tagged view:
    UIView *aView = [masterView viewWithTag:13];
    // returns nil if there's no subview with that tag
}

The equivalent in OSX:

#import <objc/runtime.h> // for associated objects
{
    // OSX:
    // 1.  Somewhere early, create an invariant memory address
    static void const *tag13 = &tag13; // put at the top of the file

    // 2.  Attach an object to the view to which you'll be adding the subviews:
    NSView *masterView = ... // the superview
    NSView *aView = ...  // a subview
    [masterView addSubview:aView];
    objc_setAssociatedObject(masterView, tag13, aView, OBJC_ASSOCIATION_ASSIGN);

    // 3.  Later, to retrieve the "tagged" view:
    NSView *aView = objc_getAssociatedObject(masterView, tag13);
    // returns nil if there's no subview with that associated object "tag"
}

Edit: The associated object "key" (declared as const void *key) needs to be invariant.  I'm using an idea by Will Pragnell (https://stackoverflow.com/a/18548365/236415).
Search Stack Overflow for other schemes for making the key.