问:
Python rq.worker not honoring Django's LOGGING config
I am trying to run a standalone script outside of a Django app that interfaces with a Redis queue and uses the Python rq module. Everything is working fine but somewhere in either upgrading to Python 3.8 (from 2.7) or upgrading from Django 2.2 (from 1.11) or from rq to 1.2.2 (from 0.13) rq stopped honoring the Django LOGGING config. Here is what my Django settings.py file looks like:

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "verbose": {
            "format": "%(asctime)s [%(process)d] [%(levelname)s] pathname=%(pathname)s lineno=%(lineno)s %(message)s",
            "datefmt": "%Y-%m-%d %H:%M:%S"
        },
        "simple": {
            "format": "%(asctime)s [%(name)s] %(levelname)s - %(message)s"
        }
    },
    "handlers": {
        "null": {
            "level": "DEBUG",
            "class": "logging.NullHandler"
        },
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "formatter": "simple"
        }
    },
    "loggers": {
        "django.request": {
          "handlers": ["console"],
          "level": "ERROR",
          "propagate": True
        },
        "api": {
          "handlers": ["console"],
          "level": "DEBUG",
          "propagate": True
        },
        "worker": {
          "handlers": ["console"],
          "level": "DEBUG",
          "propagate": True
        },
        "rq.worker": {
          "handlers": ["console"],
          "level": "ERROR",
          "propagate": True
         }
    }
}
```

<p>And here is what my <code>worker.py</code> looks like:</p>

<pre class="lang-py prettyprint-override"><code>import django
django.setup()

import os
import logging
import redis
import multiprocessing
from rq import Queue, Connection
from rq.worker import HerokuWorker

logger = logging.getLogger("worker")

if __name__ == "__main__":
    redis_url = os.getenv("REDISTOGO_URL", None)
    if redis_url:
        conn = redis.from_url(redis_url)
        listen = ["high", "default", "low"]
        thread_count = int(os.getenv("WORKER_THREAD_COUNT", "4"))
        logger.debug("Setting up worker script, threads=%d", thread_count)

        with Connection(conn):
            workers = []
            for i in range(thread_count):
                worker = HerokuWorker(map(Queue, listen))
                p = multiprocessing.Process(target=worker.work)
                workers.append(p)
                p.start()
    else:
        logger.error("Could not find REDISTOGO_URL environment variable")

</code>```

You can see I have rq.worker set to an ERROR level, but I'm getting INFO messages out on the console. This used to work just fine, but unfortunately I didn't notice this until after I finished upgrading everything. I tried removing the rq.worker section out of settings.py and the messages still get printed, but not in the format I defined. So I know my settings.py file is getting read properly. Has anyone else come across this or have any suggestions? I really do not want to have to fork rq just to resolve this.

答:
Naturally, 5 minutes after posting this I decided to look at the python-rq source and I found that the work method takes in a logging_level. This is what the new work line looks like:

p = multiprocessing.Process(target=worker.work, kwargs={"logging_level": "ERROR"})
```

Everything seems to be working as expected now.

Body:
I am trying to run a standalone script outside of a Django app that interfaces with a Redis queue and uses the Python rq module. Everything is working fine but somewhere in either upgrading to Python 3.8 (from 2.7) or upgrading from Django 2.2 (from 1.11) or from rq to 1.2.2 (from 0.13) rq stopped honoring the Django LOGGING config. Here is what my Django settings.py file looks like:

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "verbose": {
            "format": "%(asctime)s [%(process)d] [%(levelname)s] pathname=%(pathname)s lineno=%(lineno)s %(message)s",
            "datefmt": "%Y-%m-%d %H:%M:%S"
        },
        "simple": {
            "format": "%(asctime)s [%(name)s] %(levelname)s - %(message)s"
        }
    },
    "handlers": {
        "null": {
            "level": "DEBUG",
            "class": "logging.NullHandler"
        },
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "formatter": "simple"
        }
    },
    "loggers": {
        "django.request": {
          "handlers": ["console"],
          "level": "ERROR",
          "propagate": True
        },
        "api": {
          "handlers": ["console"],
          "level": "DEBUG",
          "propagate": True
        },
        "worker": {
          "handlers": ["console"],
          "level": "DEBUG",
          "propagate": True
        },
        "rq.worker": {
          "handlers": ["console"],
          "level": "ERROR",
          "propagate": True
         }
    }
}

And here is what my worker.py looks like:

import django
django.setup()

import os
import logging
import redis
import multiprocessing
from rq import Queue, Connection
from rq.worker import HerokuWorker

logger = logging.getLogger("worker")

if __name__ == "__main__":
    redis_url = os.getenv("REDISTOGO_URL", None)
    if redis_url:
        conn = redis.from_url(redis_url)
        listen = ["high", "default", "low"]
        thread_count = int(os.getenv("WORKER_THREAD_COUNT", "4"))
        logger.debug("Setting up worker script, threads=%d", thread_count)

        with Connection(conn):
            workers = []
            for i in range(thread_count):
                worker = HerokuWorker(map(Queue, listen))
                p = multiprocessing.Process(target=worker.work)
                workers.append(p)
                p.start()
    else:
        logger.error("Could not find REDISTOGO_URL environment variable")

You can see I have rq.worker set to an ERROR level, but I'm getting INFO messages out on the console. This used to work just fine, but unfortunately I didn't notice this until after I finished upgrading everything. I tried removing the rq.worker section out of settings.py and the messages still get printed, but not in the format I defined. So I know my settings.py file is getting read properly. Has anyone else come across this or have any suggestions? I really do not want to have to fork rq just to resolve this.

Body:
Naturally, 5 minutes after posting this I decided to look at the python-rq source and I found that the work method takes in a logging_level. This is what the new work line looks like:

p = multiprocessing.Process(target=worker.work, kwargs={"logging_level": "ERROR"})

Everything seems to be working as expected now.


来源: stackexchange

问:
MongoDB C# Driver - update all fields in embedded array of documents
I have this entity in DB

```<code>{
    "_id" : ObjectId("XXX"),
    "Bets" : [
        {
            "IsPublic" : false
        },
        {
            "IsPublic" : false
        }
    ]
}
</code>```

And I want to update all fileds IsPublic in nested documents. I have this query which works perfectly:

```<code>db.getCollection('bets').update({"_id": ObjectId("XXX")}, {$set : { "Bets.$[].IsPublic" : true }})
</code>```

I want to write the same query with C# driver and I would prefer strongly typed query, something like this:

```<code>var filter = Builders<TrackerBet>.Filter.Eq(b => b.Id, "XXX");
var update = Builders<TrackerBet>.Update.Set(b => b.Bets[-1].IsPublic, true);
var result = mongoDb.Bets.UpdateOneAsync(filter, update).Result;
</code>```

But it doesn't work. If I give up strongly typed query it works:

```<code>var update = Builders<TrackerBet>.Update.Set("Bets.$[].IsPublic", true);
</code>```

Is it even possible to achieve a strongly-typed query? I thought that b.Bets[-1].IsPublic should do the trick, but I get the error The positional operator did not find the match needed from the query.

答:
i'm not aware of any built-in way to get this done using the official driver. i've written a static utility class that returns string paths for supplied lambda expressions. with it you can eliminate the hard-coded string like so:

    var path = Prop.PosAll<TrackerBet>(t => t.Bets[0].IsPublic);
    var update = Builders<TrackerBet>.Update.Set(path, true);
```

here's more info on all the methods of the static class.

ContentLicense: CC BY-SA 4.0

Body:
I have this entity in DB

{
    "_id" : ObjectId("XXX"),
    "Bets" : [
        {
            "IsPublic" : false
        },
        {
            "IsPublic" : false
        }
    ]
}

And I want to update all fileds IsPublic in nested documents. I have this query which works perfectly:

db.getCollection('bets').update({"_id": ObjectId("XXX")}, {$set : { "Bets.$[].IsPublic" : true }})

I want to write the same query with C# driver and I would prefer strongly typed query, something like this:

var filter = Builders<TrackerBet>.Filter.Eq(b => b.Id, "XXX");
var update = Builders<TrackerBet>.Update.Set(b => b.Bets[-1].IsPublic, true);
var result = mongoDb.Bets.UpdateOneAsync(filter, update).Result;

But it doesn't work. If I give up strongly typed query it works:

var update = Builders<TrackerBet>.Update.Set("Bets.$[].IsPublic", true);

Is it even possible to achieve a strongly-typed query? I thought that b.Bets[-1].IsPublic should do the trick, but I get the error The positional operator did not find the match needed from the query.

Body:
i'm not aware of any built-in way to get this done using the official driver. i've written a static utility class that returns string paths for supplied lambda expressions. with it you can eliminate the hard-coded string like so:

    var path = Prop.PosAll<TrackerBet>(t => t.Bets[0].IsPublic);
    var update = Builders<TrackerBet>.Update.Set(path, true);

here's more info on all the methods of the static class.


问:
What is better solution, to keep test data in feature file with scenarios or in seperate files (xml, json, yml) when using Cucumber Java?
According to me, keeping it with scenarios make more sense because of following
1. We can use same scenarios steps with different data set.
2. Readability also increase if we specify them in feature file.
3. Cucumber as already given functionality of test data management

But in all my previous company framework, test data was kept in separate files.

Please let me know what is best way.

答:
Below are some of the factors that will decides whether we should use data table/examples or external data files.

Number of columns

Is data static/dynamic

source of data

Let's discuss each of the above.

1. Number of Columns:
It would be ideal to pass the data from feature file, when you have less than 10 columns. But having more than 10 columns make it harder to read the scenario. More the columns, more complex to read and maintain (error prone). In that case having the data in external file makes it easy.

2.Is data Static/Dynamic:
If you are sure that the data is static meaning you don't have to change the data often then you can stick to feature file. But consider the scenario, where your data will change every time (eg: if you want to place 100 orders and then wait for some time and want to check the status of each order based on OrderID. In this case you better store the order ids' in an external file and pull them as part other validation feature(s)).

3. source of data
If you are sure that data will be filled/updated by the people who have access to the feature files you can use feature files. But, consider the case where the test data will be filled by the external team/ external source (like data base) then it's better to maintain it separate by that way you can get the file and replace it when there is a newer version. (make sure to provide the template in this case, so that job would be easy for the external team and you when filling the data).

There might be other cases that will decide the right place for your test data, but those are the 3 points that I have on top of my head.


问:
Open base64 encoded pdf file using javascript. Issue with file size larger than 2 MB
I'm using below code to open base64 encoded pdf file using javascript. It works well with small pdf files below 1MB. But it doesn't work if the file size is greater than 2MB. Please let me know if you have a working code for similar scenario.</p>

```<code>var base64 = "base64 content";
let pdfWindow = window.open("");
pdfWindow.document.write("<iframe width='100%' height='100%' src='data:application/pdf;base64, " + base64 + "'></iframe>");
</code>```

答: You could instead try to read/store the file as Blob then use saveAs from FileSaver.js to download or open the pdf file</p>

Body:
I'm using below code to open base64 encoded pdf file using javascript. It works well with small pdf files below 1MB. But it doesn't work if the file size is greater than 2MB. Please let me know if you have a working code for similar scenario.

var base64 = "base64 content";
let pdfWindow = window.open("");
pdfWindow.document.write("");


问:
Using AWS to do product lookup by UPC to get the products ASIN
I am tasked right now to figure out a way my company can do a product search by UPC so we can grab the ASIN (Amazon Serial Identification Number). I was hoping someone could lead me in the right direction into what Amazon API I could use to do this. I would think they would have some API that allows a product search.

Also I am looking to implement this in C#/.NET.

Thanks for the help!
-Lewis

答:
You're looking for the Product Advertising API, more specifically the ItemLookup API with an IdType of UPC. There is sample C# code available here.

Make sure you read the licensing terms of the API though, as they are quite restrictive.

ContentLicense: CC BY-SA 3.0


问:
SpashScreen React Native
So Im trying to create a splash screen for my react native app on android and I'm running into a problem where it seems its not able to SpashScreen.hide() due to my aws-amplify withAuthenticator. It just constantly stays on the splash screen

```<code>const AppContainer = createAppContainer(App);

class RealApp extends React.Component {

  componentDidMount() {
     SplashScreen.hide();
  }
  constructor(props) {
    super(props);

  }

  render() {

    return(

        <AppContainer></AppContainer>
    );
  }
}

export default withAuthenticator(RealApp, {
  signUpConfig,
  usernameAttributes
});
</code>```

With this it constantly stays on the SplashScreen Image. I then changed it around a little and got rid of the 'WithAuthenticator' like so:

```<code>const AppContainer = createAppContainer(App);

export default class RealApp extends React.Component {

  componentDidMount() {
     SplashScreen.hide();
  }
  constructor(props) {
    super(props);

  }

  render() {

    return(

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

That sort of worked in the sense it showed the SplashScreen then my Amplify Login Page but had the bottom Navbar already rendered with the Login page so could switch to different pages just the amplify login UI was still on the home page etc.

答:
Instead of hide splash screen just navigate your self to another screen with setTimeout function</p>

```<code>componentDidMount() {
    globalAny.isEditable = true;

    if (Constant.isIosDevice()) {
      if (CommonTask != undefined) {
        CommonTask.getStatusHeight((error: any, events: any) => {
          // console.log(events);
          Constant.setStatusHeight({
            top: events.top,
            bottom: events.bottom
          });
        });
      }
    } else {
      Constant.setStatusHeight({
        top: StatusBar.currentHeight,
        bottom: 0
      });
    }

    // AsyncStorage.setItem("defaultUserData","0");
    setTimeout(() => {
      this._token();
    }, 3000);
  }
</code>```

Title: SpashScreen React Native

Body:
So Im trying to create a splash screen for my react native app on android and I'm running into a problem where it seems its not able to SpashScreen.hide() due to my aws-amplify withAuthenticator. It just constantly stays on the splash screen

const AppContainer = createAppContainer(App);

class RealApp extends React.Component {

  componentDidMount() {
     SplashScreen.hide();
  }
  constructor(props) {
    super(props);

  }

  render() {

    return(

        <AppContainer></AppContainer>
    );
  }
}

export default withAuthenticator(RealApp, {
  signUpConfig,
  usernameAttributes
});

With this it constantly stays on the SplashScreen Image. I then changed it around a little and got rid of the 'WithAuthenticator' like so:

const AppContainer = createAppContainer(App);

export default class RealApp extends React.Component {

  componentDidMount() {
     SplashScreen.hide();
  }
  constructor(props) {
    super(props);

  }

  render() {

    return(

        <AppContainer></AppContainer>
    );
  }
}

That sort of worked in the sense it showed the SplashScreen then my Amplify Login Page but had the bottom Navbar already rendered with the Login page so could switch to different pages just the amplify login UI was still on the home page etc.

Body:
Instead of hide splash screen just navigate your self to another screen with setTimeout function

componentDidMount() {
    globalAny.isEditable = true;

    if (Constant.isIosDevice()) {
      if (CommonTask != undefined) {
        CommonTask.getStatusHeight((error: any, events: any) => {
          // console.log(events);
          Constant.setStatusHeight({
            top: events.top,
            bottom: events.bottom
          });
        });
      }
    } else {
      Constant.setStatusHeight({
        top: StatusBar.currentHeight,
        bottom: 0
      });
    }

    // AsyncStorage.setItem("defaultUserData","0");
    setTimeout(() => {
      this._token();
    }, 3000);
  }


问:
How can I call a function on a button being enabled in Angular 8?
Below is a snippet of my sign-in.component.html file. I have a function within the corresponding sign-in.component.ts file which I would like to call on the button below becoming enabled. An example of what I hope to achieve:</p>

```<code><div class="button-container">
    <button mat-raised-button [disabled]="!signInForm.valid" (enabled)="callAFunction()" type="submit">Sign in</button>
</div>
</code>```

答:
You can do this if the callAFunction() is not returning anything this is the method you can use:

```<code><div class="button-container">
    <button mat-raised-button [disabled]="!signInForm.valid" type="submit">Sign in</button>
    {{ signInForm.valid ? callAFunction() : '' }}
</div>
</code>```

if callAFunction() is returning something then you need to subscribe for change in the signInForm.valid like:

```<code>ngOnInit(){
   this.signInSub = this.signInForm.valueChanges.subscribe(val => {
     this.signedIn.vaild ? callAFunction() : '';
   });
}
ngOnDestroy(){
   this.signInSub.unsubscribe();
}
</code>```

Body:
Below is a snippet of my sign-in.component.html file. I have a function within the corresponding sign-in.component.ts file which I would like to call on the button below becoming enabled. An example of what I hope to achieve:

    <button mat-raised-button [disabled]="!signInForm.valid" (enabled)="callAFunction()" type="submit">Sign in</button>

Body:
You can do this if the callAFunction() is not returning anything this is the method you can use:

<div class="button-container">
    <button mat-raised-button [disabled]="!signInForm.valid" type="submit">Sign in</button>
    {{ signInForm.valid ? callAFunction() : '' }}
</div>

if callAFunction() is returning something then you need to subscribe for change in the signInForm.valid like:

ngOnInit(){
   this.signInSub = this.signInForm.valueChanges.subscribe(val => {
     this.signedIn.vaild ? callAFunction() : '';
   });
}
ngOnDestroy(){
   this.signInSub.unsubscribe();
}


问:
My function to find the factorial is returning the wrong number after anything greater than 12 is inputted (user input)
I just learned of integer overflow but I need help fixing it</p>

```<code>int factorial()
{
    int answer = 1;
    int n;
    int factNum;
    printf("Please enter a postive integer:\n");
    // user input is stored in factNum
    scanf("%i", &factNum);

    for(n =1; n <= factNum;n++)
    {
        answer = answer * n;
    }
    return answer;
}
</code>```

答:
An int can only store numbers up to 2^31 - 1 (though technically this is implementation defined). If you want numbers up to 2^64 (roughly 21!), change your int answer = 1; to unsigned long long answer = 1;.

If you want more than that, you'll have to use some sort of struct or array of numbers to keep track of numbers with more than 64 bits. You can write your own (which may be tricky) or use an existing library such as https://en.wikipedia.org/wiki/GNU_Multiple_Precision_Arithmetic_Library

Body:
I just learned of integer overflow but I need help fixing it

int factorial()
{
    int answer = 1;
    int n;
    int factNum;
    printf("Please enter a postive integer:\n");
    // user input is stored in factNum
    scanf("%i", &factNum);

    for(n =1; n <= factNum;n++)
    {
        answer = answer * n;
    }
    return answer;
}


问:
I am getting a 'Cannot set property 'variable' of undefined' in the following component
The component will render a list of values fetched from an API. I am getting the following component initialization issue:

```<code>Cannot set property 'hits' of undefined
</code>```

display-recipes.component.ts:

```<code>import { Component, OnInit, Input} from '@angular/core';
import { SearchRecipeService } from '../search-recipe.service';
import { RecipeGlobal } from '../pojos/RecipeGlobal';

@Component({
  selector: 'app-display-recipes',
  templateUrl: './display-recipes.component.html',
  styleUrls: ['./display-recipes.component.css']
})
export class DisplayRecipesComponent implements OnInit {

  @Input() calories: String;
  @Input() recipe: String;
  recipeResult: RecipeGlobal;
  constructor(private searchRecipeService: SearchRecipeService) { }

  ngOnInit() {
     this.recipeResult.hits = [];
  }

  ngOnChanges(){
    this.getRecipeInfo();
  }

  getRecipeInfo(){
     this.searchRecipeService.getRecipeInfo().
     subscribe(recipeResult => this.recipeResult = recipeResult);
  }

}
</code>```

display-recipes.component.html

```<code><p>display-recipes works!</p>
<div id='display_recipe'  *ngFor="let recipe of recipeResult.hits">
    {{recipe.label}}
</div>
</code>```

RecipeGlobal.ts

```<code>export class RecipeGlobal{
    q: String;
    hits: Recipe[];
}

export class Recipe{
    image: String;
    calories: String;
    label: String
}
</code>```

I am failing to understand how objects are initialized in typescript. If I declare a non primitive inside the object, do I have to initialize it?. If so, in this case how should I initialize the array?.

答:
You can also create a new instance of RecipeGlobal

```<code> recipeResult: RecipeGlobal = new RecipeGlobal()
</code>```

Body:
The component will render a list of values fetched from an API. I am getting the following component initialization issue:

Cannot set property 'hits' of undefined

display-recipes.component.ts:

import { Component, OnInit, Input} from '@angular/core';
import { SearchRecipeService } from '../search-recipe.service';
import { RecipeGlobal } from '../pojos/RecipeGlobal';

@Component({
  selector: 'app-display-recipes',
  templateUrl: './display-recipes.component.html',
  styleUrls: ['./display-recipes.component.css']
})
export class DisplayRecipesComponent implements OnInit {

  @Input() calories: String;
  @Input() recipe: String;
  recipeResult: RecipeGlobal;
  constructor(private searchRecipeService: SearchRecipeService) { }

  ngOnInit() {
     this.recipeResult.hits = [];
  }

  ngOnChanges(){
    this.getRecipeInfo();
  }

  getRecipeInfo(){
     this.searchRecipeService.getRecipeInfo().
     subscribe(recipeResult => this.recipeResult = recipeResult);
  }

}

display-recipes.component.html

display-recipes works!

    {{recipe.label}}

RecipeGlobal.ts

export class RecipeGlobal{
    q: String;
    hits: Recipe[];
}

export class Recipe{
    image: String;
    calories: String;
    label: String
}

I am failing to understand how objects are initialized in typescript. If I declare a non primitive inside the object, do I have to initialize it?. If so, in this case how should I initialize the array?.

Body:
You can also create a new instance of RecipeGlobal

 recipeResult: RecipeGlobal = new RecipeGlobal()


问:
I am learning to use android studio to make an app, so I am making a simple calculator, but I have run into a problem getting the correct answer
I have tried several things to get it to work, but the answers it is returning are very wrong. For example, it returns 1+2 = 99.0 and 1*2 = 2450.0, etc.. All of the buttons work and the main method is fine I think. Below is the way that I am converting the CharSequence in the TextView into a String when the equals button is clicked.

```<code>Button btnEquals = (Button)findViewById(R.id.btnEquals);
    btnEquals.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            String problem = textDisplay.getText().toString();
            double intermediate = evalProblem(problem);
            String answer = "" + intermediate;

            textDisplay.setText(answer);

        }
    });
</code>```

And this is the method that I am calling in order to calculate the equation.

```<code>public static Double evalProblem(String s) {
    double output;
    double mult = 0.0;
    double add = 0.0;
    double sub = 0.0;
    double div = 0.0;

    if (s.contains("*")) {
        int x = s.indexOf("*");
        mult = s.charAt(x-1)*s.charAt(x+1);
    }
    if (s.contains("/")) {
        int x = s.indexOf("/");
        div = s.charAt(x - 1) / s.charAt(x + 1);
    }
    if (s.contains("+")) {
        int x = s.indexOf(("+"));
        add = s.charAt(x-1) + s.charAt(x+1);
    }
    if (s.contains("-")) {
        int x = s.indexOf("-");
        sub = s.charAt(x - 1) - s.charAt(x + 1);
    }

    output = mult + add + sub + div;
    return output;
}
</code>```

答:
.charAt() returns a character, not an integer. For example, "8*8" has 3 characters - '8', '*', and '8'. When you perform a mathematical operation with a character, it uses the ASCII value of the character eg: 'A' has an ASCII value of 65. '0' has a value of 48.

Thus, '1' + '2' = 49 + 50 = 99

You need to convert the String part before the '*' into a number, right? Java has an easy solution for that: the Double.parseDouble() method:

```<code>String text = "567";
int number = Double.parseDouble(text);
</code>```

To solve your particular question, you should try this:

```<code>int x = s.indexOf('*');
mult = Double.parseDouble(s.substring(0, x)) * Double.parseDouble(s.substring(x+1));
</code>```

The best part of this solution is that you can use numbers which have more than one digit, because the code takes everything before and after '*' in s, and converts them to numbers.

Edit: As u/markspace has mentioned in the comment below, you should consider using the in-built parsing library in Java, as seen here: Algebra equation parser for java

Edit 2: I had recommended using Integer.parseInt() to convert the string into a number, but as u/MartinZeitler has pointed out in the comment below, converting to a double value using Double.parseDouble() would be better.

Body:
I have tried several things to get it to work, but the answers it is returning are very wrong. For example, it returns 1+2 = 99.0 and 1*2 = 2450.0, etc.. All of the buttons work and the main method is fine I think. Below is the way that I am converting the CharSequence in the TextView into a String when the equals button is clicked.

Button btnEquals = (Button)findViewById(R.id.btnEquals);
    btnEquals.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            String problem = textDisplay.getText().toString();
            double intermediate = evalProblem(problem);
            String answer = "" + intermediate;

            textDisplay.setText(answer);

        }
    });

And this is the method that I am calling in order to calculate the equation.

public static Double evalProblem(String s) {
    double output;
    double mult = 0.0;
    double add = 0.0;
    double sub = 0.0;
    double div = 0.0;

    if (s.contains("*")) {
        int x = s.indexOf("*");
        mult = s.charAt(x-1)*s.charAt(x+1);
    }
    if (s.contains("/")) {
        int x = s.indexOf("/");
        div = s.charAt(x - 1) / s.charAt(x + 1);
    }
    if (s.contains("+")) {
        int x = s.indexOf(("+"));
        add = s.charAt(x-1) + s.charAt(x+1);
    }
    if (s.contains("-")) {
        int x = s.indexOf("-");
        sub = s.charAt(x - 1) - s.charAt(x + 1);
    }

    output = mult + add + sub + div;
    return output;
}

Body:
.charAt() returns a character, not an integer. For example, "8*8" has 3 characters - '8', '*', and '8'. When you perform a mathematical operation with a character, it uses the ASCII value of the character eg: 'A' has an ASCII value of 65. '0' has a value of 48.

Thus, '1' + '2' = 49 + 50 = 99

You need to convert the String part before the '*' into a number, right? Java has an easy solution for that: the Double.parseDouble() method:

String text = "567";
int number = Double.parseDouble(text);

To solve your particular question, you should try this:

int x = s.indexOf('*');
mult = Double.parseDouble(s.substring(0, x)) * Double.parseDouble(s.substring(x+1));

The best part of this solution is that you can use numbers which have more than one digit, because the code takes everything before and after '*' in s, and converts them to numbers.

Edit: As u/markspace has mentioned in the comment below, you should consider using the in-built parsing library in Java, as seen here: Algebra equation parser for java

Edit 2: I had recommended using Integer.parseInt() to convert the string into a number, but as u/MartinZeitler has pointed out in the comment below, converting to a double value using Double.parseDouble() would be better.


问:
How to get current property name via reflection?
I would like to get property name when I'm in it via reflection. Is it possible?

I have code like this:

```<code>public CarType Car
{
    get { return (Wheel) this["Wheel"];}
    set { this["Wheel"] = value; }
}
</code>```

And because I need more properties like this I would like to do something like this:

```<code>public CarType Car
{
    get { return (Wheel) this[GetThisPropertyName()];}
    set { this[GetThisPropertyName()] = value; }
}
</code>```

答:
FWIW I implemented a system like this:

```<code>    [CrmAttribute("firstname")]
    public string FirstName
    {
       get { return GetPropValue<string>(MethodBase.GetCurrentMethod().Name); }
       set { SetPropValue(MethodBase.GetCurrentMethod().Name, value); }
    }

    // this is in a base class, skipped that bit for clairty
    public T GetPropValue<T>(string propName)
    {
        propName = propName.Replace("get_", "").Replace("set_", "");
        string attributeName = GetCrmAttributeName(propName);
        return GetAttributeValue<T>(attributeName);
    }

    public void SetPropValue(string propName, object value)
    {
        propName = propName.Replace("get_", "").Replace("set_", "");
        string attributeName = GetCrmAttributeName(propName);
        SetAttributeValue(attributeName, value);
    }

    private static Dictionary<string, string> PropToAttributeMap = new Dictionary<string, string>();
    private string GetCrmAttributeName(string propertyName)
    {
         // keyName for our propertyName to (static) CrmAttributeName cache
         string keyName = this.GetType().Name + propertyName;
         // have we already done this mapping?
         if (!PropToAttributeMap.ContainsKey(keyName))
         {
             Type t = this.GetType();
             PropertyInfo info = t.GetProperty(propertyName);
             if (info == null)
             {
                 throw new Exception("Cannot find a propety called " + propertyName);
             }

             object[] attrs = info.GetCustomAttributes(false);
             foreach (object o in attrs)
             {
                 CrmAttributeAttribute attr = o as CrmAttributeAttribute ;
                 if (attr != null)
                 {
                     // found it. Save the mapping for next time.
                     PropToAttributeMap[keyName] = attr.AttributeName;
                     return attr.AttributeName;
                 }
              }
              throw new Exception("Missing MemberOf attribute for " + info.Name + "." + propertyName + ". Could not auto-access value");
           }

           // return the existing mapping
           string result = PropToAttributeMap[keyName];
           return result;
        }
</code>```

There's also a custom attribute class called CrmAttributeAttribute.

I'd strongly recommend against using GetStackFrame() as part of your solution, my original version of the solution was originally the much neater:

```<code>return GetPropValue<string>();
</code>```

But it was 600x slower than the version above.

Body:
I would like to get property name when I'm in it via reflection. Is it possible?

I have code like this:

public CarType Car
{
    get { return (Wheel) this["Wheel"];}
    set { this["Wheel"] = value; }
}

And because I need more properties like this I would like to do something like this:

public CarType Car
{
    get { return (Wheel) this[GetThisPropertyName()];}
    set { this[GetThisPropertyName()] = value; }
}

Body:
FWIW I implemented a system like this:

    [CrmAttribute("firstname")]
    public string FirstName
    {
       get { return GetPropValue<string>(MethodBase.GetCurrentMethod().Name); }
       set { SetPropValue(MethodBase.GetCurrentMethod().Name, value); }
    }

    // this is in a base class, skipped that bit for clairty
    public T GetPropValue<T>(string propName)
    {
        propName = propName.Replace("get_", "").Replace("set_", "");
        string attributeName = GetCrmAttributeName(propName);
        return GetAttributeValue<T>(attributeName);
    }

    public void SetPropValue(string propName, object value)
    {
        propName = propName.Replace("get_", "").Replace("set_", "");
        string attributeName = GetCrmAttributeName(propName);
        SetAttributeValue(attributeName, value);
    }

    private static Dictionary<string, string> PropToAttributeMap = new Dictionary<string, string>();
    private string GetCrmAttributeName(string propertyName)
    {
         // keyName for our propertyName to (static) CrmAttributeName cache
         string keyName = this.GetType().Name + propertyName;
         // have we already done this mapping?
         if (!PropToAttributeMap.ContainsKey(keyName))
         {
             Type t = this.GetType();
             PropertyInfo info = t.GetProperty(propertyName);
             if (info == null)
             {
                 throw new Exception("Cannot find a propety called " + propertyName);
             }

             object[] attrs = info.GetCustomAttributes(false);
             foreach (object o in attrs)
             {
                 CrmAttributeAttribute attr = o as CrmAttributeAttribute ;
                 if (attr != null)
                 {
                     // found it. Save the mapping for next time.
                     PropToAttributeMap[keyName] = attr.AttributeName;
                     return attr.AttributeName;
                 }
              }
              throw new Exception("Missing MemberOf attribute for " + info.Name + "." + propertyName + ". Could not auto-access value");
           }

           // return the existing mapping
           string result = PropToAttributeMap[keyName];
           return result;
        }

There's also a custom attribute class called CrmAttributeAttribute.

I'd strongly recommend against using GetStackFrame() as part of your solution, my original version of the solution was originally the much neater:

return GetPropValue<string>();

But it was 600x slower than the version above.


问:
is it possible to change the default version of python anaconda installs when creating a new env?
I did some quick searching around but couldn't actually find the answer to my question.

Does anaconda default to the newest version of python when you create a new environment and don't specify a python version?

For the last while, every environment I created use 3.7.6. I updated my anaconda not too long ago and went to create a new environment and it was 3.8.1.

Doing conda search python returned this:

```<code>Loading channels: done
# Name                       Version           Build  Channel
python                        2.7.12               0  conda-forge
python                        2.7.12               1  conda-forge
python                        2.7.12               2  conda-forge
python                        2.7.13               1  conda-forge
python                        2.7.13     h1b6d89f_16  pkgs/main
python                        2.7.13     h9912b81_15  pkgs/main
python                        2.7.13     hb034564_12  pkgs/main
python                        2.7.14               0  conda-forge
python                        2.7.14               1  conda-forge
python                        2.7.14               2  conda-forge
python                        2.7.14               3  conda-forge
python                        2.7.14               4  conda-forge
python                        2.7.14               5  conda-forge
python                        2.7.14     h2765ee6_18  pkgs/main
python                        2.7.14     h3e68818_15  pkgs/main
python                        2.7.14     h4084c39_22  pkgs/main
python                        2.7.14     h4a10d90_30  pkgs/main
python                        2.7.14     h4a10d90_31  pkgs/main
python                        2.7.14     h59f5a59_20  pkgs/main
python                        2.7.14     h819644d_16  pkgs/main
python                        2.7.14     h8c3f1cb_23  pkgs/main
python                        2.7.15               0  conda-forge
python                        2.7.15      h2880e7c_0  conda-forge
python                        2.7.15   h2880e7c_1001  conda-forge
python                        2.7.15   h2880e7c_1002  conda-forge
python                        2.7.15   h2880e7c_1003  conda-forge
python                        2.7.15   h2880e7c_1004  conda-forge
python                        2.7.15   h2880e7c_1005  conda-forge
python                        2.7.15   h2880e7c_1006  conda-forge
python                        2.7.15   h2880e7c_1008  conda-forge
python                        2.7.15   h2880e7c_1009  conda-forge
python                        2.7.15      h2880e7c_2  pkgs/main
python                        2.7.15      h2880e7c_3  pkgs/main
python                        2.7.15      h2880e7c_4  pkgs/main
python                        2.7.15     hcb6e200_15  pkgs/main
python                        2.7.15      hcb6e200_5  pkgs/main
python                        2.7.15      hcb6e200_7  pkgs/main
python                        2.7.15      he216670_0  pkgs/main
python                        2.7.16      hcb6e200_0  pkgs/main
python                        2.7.17      h930f6bb_0  pkgs/main
python                         3.4.5               0  conda-forge
python                         3.4.5               1  conda-forge
python                         3.4.5               2  conda-forge
python                         3.5.1               0  conda-forge
python                         3.5.1               1  conda-forge
python                         3.5.2               0  conda-forge
python                         3.5.2               1  conda-forge
python                         3.5.2               2  conda-forge
python                         3.5.2               3  conda-forge
python                         3.5.2               4  conda-forge
python                         3.5.2               5  conda-forge
python                         3.5.3               0  conda-forge
python                         3.5.3               1  conda-forge
python                         3.5.3               2  conda-forge
python                         3.5.3               3  conda-forge
python                         3.5.4               0  conda-forge
python                         3.5.4               1  conda-forge
python                         3.5.4               2  conda-forge
python                         3.5.4               3  conda-forge
python                         3.5.4     h1357f44_23  pkgs/main
python                         3.5.4     hc495aa9_21  pkgs/main
python                         3.5.4     hd3c4935_11  pkgs/main
python                         3.5.4     hdec4e59_20  pkgs/main
python                         3.5.4     hedc2606_15  pkgs/main
python                         3.5.5               0  conda-forge
python                         3.5.5               1  conda-forge
python                         3.5.5      h0c2934d_0  pkgs/main
python                         3.5.5      h0c2934d_1  pkgs/main
python                         3.5.5      h0c2934d_2  pkgs/main
python                         3.5.5      he025d50_2  conda-forge
python                         3.5.6      he025d50_0  pkgs/main
python                       3.6.0a3               0  conda-forge
python                       3.6.0a4               0  conda-forge
python                       3.6.0b1               0  conda-forge
python                       3.6.0b2               0  conda-forge
python                       3.6.0b3               0  conda-forge
python                       3.6.0b4               0  conda-forge
python                      3.6.0rc1               0  conda-forge
python                         3.6.0               0  conda-forge
python                         3.6.0               1  conda-forge
python                         3.6.0               2  conda-forge
python                         3.6.1               0  conda-forge
python                         3.6.1               1  conda-forge
python                         3.6.1               2  conda-forge
python                         3.6.1               3  conda-forge
python                         3.6.2               0  conda-forge
python                         3.6.2     h09676a0_15  pkgs/main
python                         3.6.2     h6679aeb_11  pkgs/main
python                         3.6.3               0  conda-forge
python                         3.6.3               1  conda-forge
python                         3.6.3               2  conda-forge
python                         3.6.3               3  conda-forge
python                         3.6.3               4  conda-forge
python                         3.6.3      h210ce5f_2  pkgs/main
python                         3.6.3      h3389d20_0  pkgs/main
python                         3.6.3      h3b118a2_4  pkgs/main
python                         3.6.3      h9e2ca53_1  pkgs/main
python                         3.6.4               0  conda-forge
python                         3.6.4      h0c2934d_2  pkgs/main
python                         3.6.4      h0c2934d_3  pkgs/main
python                         3.6.4      h6538335_0  pkgs/main
python                         3.6.4      h6538335_1  pkgs/main
python                         3.6.5               0  conda-forge
python                         3.6.5               1  conda-forge
python                         3.6.5      h0c2934d_0  pkgs/main
python                         3.6.6      he025d50_0  conda-forge
python                         3.6.6      hea74fb7_0  pkgs/main
python                         3.6.7      h33f27b4_0  pkgs/main
python                         3.6.7      h33f27b4_1  pkgs/main
python                         3.6.7      h9f7ef89_2  pkgs/main
python                         3.6.7   he025d50_1002  conda-forge
python                         3.6.7   he025d50_1004  conda-forge
python                         3.6.7   he025d50_1005  conda-forge
python                         3.6.7   he025d50_1006  conda-forge
python                         3.6.8      h9f7ef89_0  pkgs/main
python                         3.6.8      h9f7ef89_1  pkgs/main
python                         3.6.8      h9f7ef89_7  pkgs/main
python                         3.6.9      h5500b2f_0  pkgs/main
python                        3.6.10      h9f7ef89_0  pkgs/main
python                         3.7.0      h1ce479f_0  conda-forge
python                         3.7.0      hc182675_1  conda-forge
python                         3.7.0   hc182675_1002  conda-forge
python                         3.7.0   hc182675_1003  conda-forge
python                         3.7.0   hc182675_1004  conda-forge
python                         3.7.0   hc182675_1005  conda-forge
python                         3.7.0   hc182675_1006  conda-forge
python                         3.7.0      hea74fb7_0  pkgs/main
python                         3.7.1      h33f27b4_3  pkgs/main
python                         3.7.1      h33f27b4_4  pkgs/main
python                         3.7.1      h8c8aaf0_6  pkgs/main
python                         3.7.1   h9460c21_1002  conda-forge
python                         3.7.1   h9460c21_1003  conda-forge
python                         3.7.1   hc182675_1000  conda-forge
python                         3.7.1   hc182675_1001  conda-forge
python                         3.7.1      he44a216_5  pkgs/main
python                         3.7.2      h8c8aaf0_0  pkgs/main
python                         3.7.2     h8c8aaf0_10  pkgs/main
python                         3.7.2      h8c8aaf0_2  pkgs/main
python                         3.7.2      hb12ca83_0  conda-forge
python                         3.7.3      h510b542_1  conda-forge
python                         3.7.3      h8c8aaf0_0  pkgs/main
python                         3.7.3      h8c8aaf0_1  pkgs/main
python                         3.7.3      hb12ca83_0  conda-forge
python                         3.7.4      h5263a28_0  pkgs/main
python                         3.7.5      h8c8aaf0_0  pkgs/main
python                         3.7.6      h5b45d93_1  conda-forge
python                         3.7.6      h5b45d93_2  conda-forge
python                         3.7.6      h60c2a47_2  pkgs/main
python                         3.8.0      hc9e8b01_0  conda-forge
python                         3.8.0      hc9e8b01_1  conda-forge
python                         3.8.0      hc9e8b01_2  conda-forge
python                         3.8.0      hc9e8b01_3  conda-forge
python                         3.8.0      hc9e8b01_5  conda-forge
python                         3.8.0      hff0d562_0  pkgs/main
python                         3.8.0      hff0d562_1  pkgs/main
python                         3.8.0      hff0d562_2  pkgs/main
python                         3.8.1      h5fd99cc_1  pkgs/main
python                         3.8.1      he1f5543_1  conda-forge
python                         3.8.1      he1f5543_2  conda-forge
</code>```

I know I can create a new environment with 3.7 by doing:

```<code>conda create --name test python=3.7 anaconda
</code>```

but it's annoying to have to specify this each time..

Is it possible to change the default version of anaconda that installs when making a new environment? So I don't have to specify it?

Thanks

答:
You could do

```<code>conda config --add create_default_packages PACKAGENAME1 PACKAGENAME2
</code>```

So

```<code>conda config --add create_default_packages python=3.8
</code>```

Body:
I did some quick searching around but couldn't actually find the answer to my question.

Does anaconda default to the newest version of python when you create a new environment and don't specify a python version?

For the last while, every environment I created use 3.7.6. I updated my anaconda not too long ago and went to create a new environment and it was 3.8.1.

Doing conda search python returned this:

Loading channels: done
# Name                       Version           Build  Channel
python                        2.7.12               0  conda-forge
python                        2.7.12               1  conda-forge
python                        2.7.12               2  conda-forge
python                        2.7.13               1  conda-forge
python                        2.7.13     h1b6d89f_16  pkgs/main
python                        2.7.13     h9912b81_15  pkgs/main
python                        2.7.13     hb034564_12  pkgs/main
python                        2.7.14               0  conda-forge
python                        2.7.14               1  conda-forge
python                        2.7.14               2  conda-forge
python                        2.7.14               3  conda-forge
python                        2.7.14               4  conda-forge
python                        2.7.14               5  conda-forge
python                        2.7.14     h2765ee6_18  pkgs/main
python                        2.7.14     h3e68818_15  pkgs/main
python                        2.7.14     h4084c39_22  pkgs/main
python                        2.7.14     h4a10d90_30  pkgs/main
python                        2.7.14     h4a10d90_31  pkgs/main
python                        2.7.14     h59f5a59_20  pkgs/main
python                        2.7.14     h819644d_16  pkgs/main
python                        2.7.14     h8c3f1cb_23  pkgs/main
python                        2.7.15               0  conda-forge
python                        2.7.15      h2880e7c_0  conda-forge
python                        2.7.15   h2880e7c_1001  conda-forge
python                        2.7.15   h2880e7c_1002  conda-forge
python                        2.7.15   h2880e7c_1003  conda-forge
python                        2.7.15   h2880e7c_1004  conda-forge
python                        2.7.15   h2880e7c_1005  conda-forge
python                        2.7.15   h2880e7c_1006  conda-forge
python                        2.7.15   h2880e7c_1008  conda-forge
python                        2.7.15   h2880e7c_1009  conda-forge
python                        2.7.15      h2880e7c_2  pkgs/main
python                        2.7.15      h2880e7c_3  pkgs/main
python                        2.7.15      h2880e7c_4  pkgs/main
python                        2.7.15     hcb6e200_15  pkgs/main
python                        2.7.15      hcb6e200_5  pkgs/main
python                        2.7.15      hcb6e200_7  pkgs/main
python                        2.7.15      he216670_0  pkgs/main
python                        2.7.16      hcb6e200_0  pkgs/main
python                        2.7.17      h930f6bb_0  pkgs/main
python                         3.4.5               0  conda-forge
python                         3.4.5               1  conda-forge
python                         3.4.5               2  conda-forge
python                         3.5.1               0  conda-forge
python                         3.5.1               1  conda-forge
python                         3.5.2               0  conda-forge
python                         3.5.2               1  conda-forge
python                         3.5.2               2  conda-forge
python                         3.5.2               3  conda-forge
python                         3.5.2               4  conda-forge
python                         3.5.2               5  conda-forge
python                         3.5.3               0  conda-forge
python                         3.5.3               1  conda-forge
python                         3.5.3               2  conda-forge
python                         3.5.3               3  conda-forge
python                         3.5.4               0  conda-forge
python                         3.5.4               1  conda-forge
python                         3.5.4               2  conda-forge
python                         3.5.4               3  conda-forge
python                         3.5.4     h1357f44_23  pkgs/main
python                         3.5.4     hc495aa9_21  pkgs/main
python                         3.5.4     hd3c4935_11  pkgs/main
python                         3.5.4     hdec4e59_20  pkgs/main
python                         3.5.4     hedc2606_15  pkgs/main
python                         3.5.5               0  conda-forge
python                         3.5.5               1  conda-forge
python                         3.5.5      h0c2934d_0  pkgs/main
python                         3.5.5      h0c2934d_1  pkgs/main
python                         3.5.5      h0c2934d_2  pkgs/main
python                         3.5.5      he025d50_2  conda-forge
python                         3.5.6      he025d50_0  pkgs/main
python                       3.6.0a3               0  conda-forge
python                       3.6.0a4               0  conda-forge
python                       3.6.0b1               0  conda-forge
python                       3.6.0b2               0  conda-forge
python                       3.6.0b3               0  conda-forge
python                       3.6.0b4               0  conda-forge
python                      3.6.0rc1               0  conda-forge
python                         3.6.0               0  conda-forge
python                         3.6.0               1  conda-forge
python                         3.6.0               2  conda-forge
python                         3.6.1               0  conda-forge
python                         3.6.1               1  conda-forge
python                         3.6.1               2  conda-forge
python                         3.6.1               3  conda-forge
python                         3.6.2               0  conda-forge
python                         3.6.2     h09676a0_15  pkgs/main
python                         3.6.2     h6679aeb_11  pkgs/main
python                         3.6.3               0  conda-forge
python                         3.6.3               1  conda-forge
python                         3.6.3               2  conda-forge
python                         3.6.3               3  conda-forge
python                         3.6.3               4  conda-forge
python                         3.6.3      h210ce5f_2  pkgs/main
python                         3.6.3      h3389d20_0  pkgs/main
python                         3.6.3      h3b118a2_4  pkgs/main
python                         3.6.3      h9e2ca53_1  pkgs/main
python                         3.6.4               0  conda-forge
python                         3.6.4      h0c2934d_2  pkgs/main
python                         3.6.4      h0c2934d_3  pkgs/main
python                         3.6.4      h6538335_0  pkgs/main
python                         3.6.4      h6538335_1  pkgs/main
python                         3.6.5               0  conda-forge
python                         3.6.5               1  conda-forge
python                         3.6.5      h0c2934d_0  pkgs/main
python                         3.6.6      he025d50_0  conda-forge
python                         3.6.6      hea74fb7_0  pkgs/main
python                         3.6.7      h33f27b4_0  pkgs/main
python                         3.6.7      h33f27b4_1  pkgs/main
python                         3.6.7      h9f7ef89_2  pkgs/main
python                         3.6.7   he025d50_1002  conda-forge
python                         3.6.7   he025d50_1004  conda-forge
python                         3.6.7   he025d50_1005  conda-forge
python                         3.6.7   he025d50_1006  conda-forge
python                         3.6.8      h9f7ef89_0  pkgs/main
python                         3.6.8      h9f7ef89_1  pkgs/main
python                         3.6.8      h9f7ef89_7  pkgs/main
python                         3.6.9      h5500b2f_0  pkgs/main
python                        3.6.10      h9f7ef89_0  pkgs/main
python                         3.7.0      h1ce479f_0  conda-forge
python                         3.7.0      hc182675_1  conda-forge
python                         3.7.0   hc182675_1002  conda-forge
python                         3.7.0   hc182675_1003  conda-forge
python                         3.7.0   hc182675_1004  conda-forge
python                         3.7.0   hc182675_1005  conda-forge
python                         3.7.0   hc182675_1006  conda-forge
python                         3.7.0      hea74fb7_0  pkgs/main
python                         3.7.1      h33f27b4_3  pkgs/main
python                         3.7.1      h33f27b4_4  pkgs/main
python                         3.7.1      h8c8aaf0_6  pkgs/main
python                         3.7.1   h9460c21_1002  conda-forge
python                         3.7.1   h9460c21_1003  conda-forge
python                         3.7.1   hc182675_1000  conda-forge
python                         3.7.1   hc182675_1001  conda-forge
python                         3.7.1      he44a216_5  pkgs/main
python                         3.7.2      h8c8aaf0_0  pkgs/main
python                         3.7.2     h8c8aaf0_10  pkgs/main
python                         3.7.2      h8c8aaf0_2  pkgs/main
python                         3.7.2      hb12ca83_0  conda-forge
python                         3.7.3      h510b542_1  conda-forge
python                         3.7.3      h8c8aaf0_0  pkgs/main
python                         3.7.3      h8c8aaf0_1  pkgs/main
python                         3.7.3      hb12ca83_0  conda-forge
python                         3.7.4      h5263a28_0  pkgs/main
python                         3.7.5      h8c8aaf0_0  pkgs/main
python                         3.7.6      h5b45d93_1  conda-forge
python                         3.7.6      h5b45d93_2  conda-forge
python                         3.7.6      h60c2a47_2  pkgs/main
python                         3.8.0      hc9e8b01_0  conda-forge
python                         3.8.0      hc9e8b01_1  conda-forge
python                         3.8.0      hc9e8b01_2  conda-forge
python                         3.8.0      hc9e8b01_3  conda-forge
python                         3.8.0      hc9e8b01_5  conda-forge
python                         3.8.0      hff0d562_0  pkgs/main
python                         3.8.0      hff0d562_1  pkgs/main
python                         3.8.0      hff0d562_2  pkgs/main
python                         3.8.1      h5fd99cc_1  pkgs/main
python                         3.8.1      he1f5543_1  conda-forge
python                         3.8.1      he1f5543_2  conda-forge

I know I can create a new environment with 3.7 by doing:

conda create --name test python=3.7 anaconda

but it's annoying to have to specify this each time..

Is it possible to change the default version of anaconda that installs when making a new environment? So I don't have to specify it?

Thanks

Body:
You could do

conda config --add create_default_packages PACKAGENAME1 PACKAGENAME2

So

conda config --add create_default_packages python=3.8


问:
How to select nested ul element using pure javascript
For something seemingly simple, it's causing me some trouble.

I have the following pattern:

```<code>    <div className="row">
      <ul className="col-md-4 options-ul">
</code>```

Question is how do i select the nested ul using plain javascript? I've tried various renditions of querySelector and querySelectorAll to no avail. tia

答:
You would use:

```<code>document.querySelectorAll(".row > ul")
</code>```

to get the immediate ul child of every .row element. Use document.querySelector instead of querySelectorAll if you just want the first result.

Body:
For something seemingly simple, it's causing me some trouble.

I have the following pattern:

Question is how do i select the nested ul using plain javascript? I've tried various renditions of querySelector and querySelectorAll to no avail. tia

Body:
You would use:

document.querySelectorAll(".row > ul")

to get the immediate ul child of every .row element. Use document.querySelector instead of querySelectorAll if you just want the first result.


问:
multiplying an integer by a returned value of a function
noobie here, sorry for what is probably an inane question but couldn't seem to find an explanation when I searched for it... surprised by by the output of multiple numerals instead of a product when multiplying an integer by the returned value of a function.

```<code>def number():
    four=input('input the number 4: ')
    return four
x=number()
y=4
print(4*x)
print(4*y)
print(4*4)
</code>```

output...

```<code>input the number 4: 4
4444
16
16
</code>```

I guess I am not understanding return... I was expecting 16 in the example above, not 4444

答:
The result of:

```<code>four=input('input the number 4: ')
</code>```

when the user does what you ask, is to place the string '4' (not the number) into the variable named four, as per the type output in the following snippet:

```<code>>>> x = input('what: ')
what: 4
>>> print(x, type(x))
4 <class 'str'>
</code>```

And, if you evaluate '4' * 7, you will indeed get 4444444, because addition of strings is concatenation, rather than numeric accumulation:

```<code>>>> print('4' * 7)
4444444
>>> print(4 * 7)
28
</code>```

If you want to turn that string into an integer, try(a) something like:

```<code>four=int(input('input the number 4: '))
</code>```

An apt word in this case, since you should probably do it inside a try..catch block on the off chance the user doesn't do what you ask :-)

Body:
noobie here, sorry for what is probably an inane question but couldn't seem to find an explanation when I searched for it... surprised by by the output of multiple numerals instead of a product when multiplying an integer by the returned value of a function.

def number():
    four=input('input the number 4: ')
    return four
x=number()
y=4
print(4*x)
print(4*y)
print(4*4)

output...

input the number 4: 4
4444
16
16

I guess I am not understanding return... I was expecting 16 in the example above, not 4444

Body:
The result of:

four=input('input the number 4: ')

when the user does what you ask, is to place the string '4' (not the number) into the variable named four, as per the type output in the following snippet:

>>> x = input('what: ')
what: 4
>>> print(x, type(x))
4 <class 'str'>

And, if you evaluate '4' * 7, you will indeed get 4444444, because addition of strings is concatenation, rather than numeric accumulation:

>>> print('4' * 7)
4444444
>>> print(4 * 7)
28

If you want to turn that string into an integer, try(a) something like:

four=int(input('input the number 4: '))

An apt word in this case, since you should probably do it inside a try..catch block on the off chance the user doesn't do what you ask :-)


问:
UWP System.Reflection.TargetInvocationException when including a view in a page?
I have 2 pages. One page contains another, where the Grid looks like the following:

```<code>        <Grid>
            <views:MapViewPage/>
        </Grid>
</code>```

I've included the views namespace correctly and everything runs fine but the designer seems to be having a bit of an issue with this.

It underlines the views:MapViewPage line and says object reference not set to an instance of an object, and complains about the constructor. I don't understand why, I've done this in WPF where I've included views in another page or window so I don't understand why the XAML designer complains in UWP. I've restarted visual studio and deleted the bin and obj directories but i still see the error - builds fine and runs fine tho... and includes the view as expected...

答:
It underlines the views:MapViewPage line and says object reference not set to an instance of an object, and complains about the constructor.

Yep, this is common behavior, if you just create folder and make a xaml file in it then use xaml file without build the project, the Visual Studio will not find the specific the namespace (xmlns:views="using:projectname.Views"). Please try to
restore the nuget package (right click the solution Restore Nuget Package) and  build or re-build your project before running it.

Body:
I have 2 pages. One page contains another, where the Grid looks like the following:

        <Grid>
            <views:MapViewPage/>
        </Grid>

I've included the views namespace correctly and everything runs fine but the designer seems to be having a bit of an issue with this.

It underlines the views:MapViewPage line and says object reference not set to an instance of an object, and complains about the constructor. I don't understand why, I've done this in WPF where I've included views in another page or window so I don't understand why the XAML designer complains in UWP. I've restarted visual studio and deleted the bin and obj directories but i still see the error - builds fine and runs fine tho... and includes the view as expected...


问:
Hangman game effect of setSolved() is delayed
I have a hangman game that almost works. The issue is that when I got all letters correct, YOU WIN message is not displayed until I click on a letter once more.

I'll list only parts that I feel relevant.

Game.js is a container.

Game contains state:

```<code>state = {
        lives: 12,
        solution: 'my name is logan',
        correctUsedLetters: [],
        availableLetters: ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'],
        usedLetters: [],
        solved: false
};
</code>```

And many handlers including setSolvedHandler:

```<code>setSolvedHandler = () => {
        const solution = this.state.solution.replace(/\s/g, '').replace(/-/g, '').split('');
        const compare = [ ...this.state.correctUsedLetters].sort();
        const unique = solution.filter(
            (elem,index,self) => (index===self.indexOf(elem))
        ).sort();

        const solved = JSON.stringify(unique) === JSON.stringify(compare);

        this.setState({
            solved: solved
        });
};
</code>```

This handler sets solved to true if correctUsedLetters match solution, in effect if the player has solved the puzzle.

Also inside Game.js Letters is rendered:

```<code><div className={classes.LettersAndHangman}>
                    <Hangman lives={this.state.lives} />
                    <Letters setSolved={this.setSolvedHandler} solution={this.state.solution} correct={this.guessedCorrectHandler} incorrect={this.guessedIncorrectHandler}
                    feed={this.state.availableLetters}
                    />
</div>
</code>```

Game.js calls on Letters so let's have a look at that.

Letters.js has state called lettersMap that contains each letter of the alphabet with a boolean value indicating whether the letter has been clicked or not.

```<code>const [lettersMap, setLettersMap]=useState(
        {
            "a":false,"b":false,"c":false,"d":false,"e":false,"f":false,"g":false,"h":false,"i":false,"j":false,"k":false,"l":false,"m":false,"n":false,"o":false,"p":false,"q":false,"r":false,"s":false,"t":false,"u":false,"v":false,"w":false,"x":false,"y":false,"z":false
        }
);
</code>```

It contains playHandler which tests whether the clicked letter is a correct one or not. But we'll skip this for now.

More importantly, it contains updateClickedHandler which sets the boolean to true for the letter clicked. This updates the lettersMap.

```<code>const updateClickedHandler = (letter) => {
        setLettersMap(
            {
                ...lettersMap,[letter]:true
            }
        );
};
</code>```

Then two things are rendered from Letters.js. AvailableLetter and DisabledLetter. AvailableLetter represents a letter that has not been clicked. DisabledLetter represents a letter that has been clicked and now disabled from clicking again.

```<code> const renderedLetters = Object.keys(lettersMap).map(
        (letter,i)=>{
          if (!lettersMap[letter])     //letter is not yet clicked
          {
            return (
                <AvailableLetter updateClicked={updateClickedHandler} setSolved={props.setSolved} play={()=>playHandler(letter)} correct={()=>props.correct(letter)} incorrect={()=>props.incorrect(letter)} solution={props.solution} key={i} alphabet={letter} />
            )
          }
          else                         //letter is clicked
          {
            return (
                <DisabledLetter alphabet={letter} key={i} />
            )
          }
        }
);
</code>```

Here are codes for AvailableLetter and DisabledLetter:

```<code>const AvailableLetter = (props) => {

    const setStuff = () => {
      if (props.play()) {
        props.correct();
      }
      else {
        props.incorrect();
      }

      props.setSolved();
      props.updateClicked(props.alphabet);
    };

    return (
        <Ax>
          <span className={classes.AvailableLetter} onClick={setStuff}>{props.alphabet}</span>
        </Ax>
    );
}
</code>```

```<code>const DisabledLetter = (props) => {
    return (
    <span className={classes.DisabledLetter} >{props.alphabet}</span>
    );
};
</code>```

Now I'll introduce Model.js which displays messages YOU WIN or GAME OVER.

```<code>const modal = (props) => {
    let show = props.gameOver() || props.solved ? true : false;

    const attachedClasses = [ classes.Message ];
    if (!show) {
        attachedClasses.push(classes.Hide);
    }

    return (
        <div>
            <Backdrop show={show} />
            <div className={attachedClasses.join(' ')} >
                {props.gameOver()?<p>GAME OVER</p>:null}
                {props.solved?<p>YOU WIN!</p>:null}
            </div>
        </div>
    );
};
</code>```

Investigating the code, the show becomes true if either game over or solved. This value is used to show/hide backdrop. It is also used to show/hide messages.

Then depending on game over or solved you get appropriate message: GAME OVER or YOU WIN.

I'm not sure yet what the root of the problem is, but the issue is that YOU WIN does not display even when the puzzle is solved until you click on one more letter(that doesn't do anything other than trigger the message).

Currently, setSolved() is called inside AvailableLetter.js when span is clicked. It seems like effect of calling setSolved when a letter is clicked is somehow delayed.

I'll try to construct the question succinctly as I can. Thank you for your patience.

You can get complete source here:
https://github.com/gunitinug/hangmanclicked/tree/master/src

答:
After learning about redux I'm guessing the functionality in concern here is an asynchronous call. So I need to use redux-thunk, for example, and handle it asynchronously.

I'll follow up on this later and fix the project properly. :)

UPDATE:
I've now learned that React Hooks can only be used inside a functional component OR inside a custom hook. I can't use them, for example, inside a function or inside an if statement. I believe I made these mistake in my code right now. I need to fix them.

UPDATE:
I just learned that using useEffect in the following way in functional component is the same as calling componentDidMount in class component.

```<code>useEffect(()=>{},[]);
</code>```

In this configuration with the dependency [], it gets called just once when the component is first rendered, and just this once. In comparison, the following useEffect causes an infinite loop:

```<code>useEffect(()=> {
   setCustomState({});   // this is a custom set method in useState.
});
</code>```

This is because, in this configuration useEffect is called after every render, and inside of it, setCustomState triggers re-render and useEffect is called again, and so on.

UPDATE:
The useCallback() might be useful also. It caches a function so that when the class is rerendered(and therefore function is recreated) so it avoids creating an infinite loop.

Basically, a function wrapped inside useCallback is cached and not recreated when the component is re-rendered.

Upon creating the function, this is the same as that function being 'changed'. So the following is executed:

```<code>useEffect(()=>{},[f]);    // this gets executed everytime f is 'changed'
</code>```

If

```<code>const cachedF = useCallback(f);
</code>```

Then, useEffect is only executed once because f is cached.

Body:
I have a hangman game that almost works. The issue is that when I got all letters correct, YOU WIN message is not displayed until I click on a letter once more.

I'll list only parts that I feel relevant.

Game.js is a container.

Game contains state:

state = {
        lives: 12,
        solution: 'my name is logan',
        correctUsedLetters: [],
        availableLetters: ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'],
        usedLetters: [],
        solved: false
};

And many handlers including setSolvedHandler:

setSolvedHandler = () => {
        const solution = this.state.solution.replace(/\s/g, '').replace(/-/g, '').split('');
        const compare = [ ...this.state.correctUsedLetters].sort();
        const unique = solution.filter(
            (elem,index,self) => (index===self.indexOf(elem))
        ).sort();

        const solved = JSON.stringify(unique) === JSON.stringify(compare);

        this.setState({
            solved: solved
        });
};

This handler sets solved to true if correctUsedLetters match solution, in effect if the player has solved the puzzle.

Also inside Game.js Letters is rendered:

                    <Hangman lives={this.state.lives} />
                    <Letters setSolved={this.setSolvedHandler} solution={this.state.solution} correct={this.guessedCorrectHandler} incorrect={this.guessedIncorrectHandler}
                    feed={this.state.availableLetters}
                    />

Game.js calls on Letters so let's have a look at that.

Letters.js has state called lettersMap that contains each letter of the alphabet with a boolean value indicating whether the letter has been clicked or not.

const [lettersMap, setLettersMap]=useState(
        {
            "a":false,"b":false,"c":false,"d":false,"e":false,"f":false,"g":false,"h":false,"i":false,"j":false,"k":false,"l":false,"m":false,"n":false,"o":false,"p":false,"q":false,"r":false,"s":false,"t":false,"u":false,"v":false,"w":false,"x":false,"y":false,"z":false
        }
);

It contains playHandler which tests whether the clicked letter is a correct one or not. But we'll skip this for now.

More importantly, it contains updateClickedHandler which sets the boolean to true for the letter clicked. This updates the lettersMap.

const updateClickedHandler = (letter) => {
        setLettersMap(
            {
                ...lettersMap,[letter]:true
            }
        );
};

Then two things are rendered from Letters.js. AvailableLetter and DisabledLetter. AvailableLetter represents a letter that has not been clicked. DisabledLetter represents a letter that has been clicked and now disabled from clicking again.

 const renderedLetters = Object.keys(lettersMap).map(
        (letter,i)=>{
          if (!lettersMap[letter])     //letter is not yet clicked
          {
            return (
                <AvailableLetter updateClicked={updateClickedHandler} setSolved={props.setSolved} play={()=>playHandler(letter)} correct={()=>props.correct(letter)} incorrect={()=>props.incorrect(letter)} solution={props.solution} key={i} alphabet={letter} />
            )
          }
          else                         //letter is clicked
          {
            return (
                <DisabledLetter alphabet={letter} key={i} />
            )
          }
        }
);

Here are codes for AvailableLetter and DisabledLetter:

const AvailableLetter = (props) => {

    const setStuff = () => {
      if (props.play()) {
        props.correct();
      }
      else {
        props.incorrect();
      }

      props.setSolved();
      props.updateClicked(props.alphabet);
    };

    return (
        <Ax>
          {props.alphabet}
        </Ax>
    );
}

const DisabledLetter = (props) => {
    return (
    {props.alphabet}
    );
};

Now I'll introduce Model.js which displays messages YOU WIN or GAME OVER.

const modal = (props) => {
    let show = props.gameOver() || props.solved ? true : false;

    const attachedClasses = [ classes.Message ];
    if (!show) {
        attachedClasses.push(classes.Hide);
    }

    return (

            <Backdrop show={show} />

                {props.gameOver()?
GAME OVER
:null}
                {props.solved?
YOU WIN!
:null}

    );
};

Investigating the code, the show becomes true if either game over or solved. This value is used to show/hide backdrop. It is also used to show/hide messages.

Then depending on game over or solved you get appropriate message: GAME OVER or YOU WIN.

I'm not sure yet what the root of the problem is, but the issue is that YOU WIN does not display even when the puzzle is solved until you click on one more letter(that doesn't do anything other than trigger the message).

Currently, setSolved() is called inside AvailableLetter.js when span is clicked. It seems like effect of calling setSolved when a letter is clicked is somehow delayed.

I'll try to construct the question succinctly as I can. Thank you for your patience.

You can get complete source here:
https://github.com/gunitinug/hangmanclicked/tree/master/src

Body:
After learning about redux I'm guessing the functionality in concern here is an asynchronous call. So I need to use redux-thunk, for example, and handle it asynchronously.

I'll follow up on this later and fix the project properly. :)

UPDATE:
I've now learned that React Hooks can only be used inside a functional component OR inside a custom hook. I can't use them, for example, inside a function or inside an if statement. I believe I made these mistake in my code right now. I need to fix them.

UPDATE:
I just learned that using useEffect in the following way in functional component is the same as calling componentDidMount in class component.

useEffect(()=>{},[]);

In this configuration with the dependency [], it gets called just once when the component is first rendered, and just this once. In comparison, the following useEffect causes an infinite loop:

useEffect(()=> {
   setCustomState({});   // this is a custom set method in useState.
});

This is because, in this configuration useEffect is called after every render, and inside of it, setCustomState triggers re-render and useEffect is called again, and so on.

UPDATE:
The useCallback() might be useful also. It caches a function so that when the class is rerendered(and therefore function is recreated) so it avoids creating an infinite loop.

Basically, a function wrapped inside useCallback is cached and not recreated when the component is re-rendered.

Upon creating the function, this is the same as that function being 'changed'. So the following is executed:

useEffect(()=>{},[f]);    // this gets executed everytime f is 'changed'

If

const cachedF = useCallback(f);

Then, useEffect is only executed once because f is cached.


问:
Unable to set Test.APIKeyAuthToken
This is my code:

```<code>public static final String API_TOKEN = "safasfasdfesareasdadasd";
public static final String APIKeyAuthToken = "Auth-Token";
</code>```

But the Auth-Token is not being found in the header request.

```<code>public Response intercept(Chain chain) throws IOException {
    Request original = chain.request();
    Request.Builder requestBuilder = original.newBuilder()
        .addHeader("Accept", "application/json")
        .addHeader("Content-Type", "application/json");
    requestBuilder.addHeader(Test.APIKeyAuthToken, Test.API_TOKEN);
    Request request = requestBuilder.build();
    return chain.proceed(request);
}
</code>```

答:
Despite it is rather unclear which API you are even talking about - and what you might mean with "not working" (this is not an error description at all) ...the HTTP header probably should  look alike:

```<code>.addHeader("Authorization", API_TOKEN)
</code>```

Just see the API documentation, which string-format is actually being expected... because "not working" might possibly mean, just sending some random header, which the API doesn't accept.

Title: Unable to set Test.APIKeyAuthToken

Body:
This is my code:

public static final String API_TOKEN = "safasfasdfesareasdadasd";
public static final String APIKeyAuthToken = "Auth-Token";

But the Auth-Token is not being found in the header request.

public Response intercept(Chain chain) throws IOException {
    Request original = chain.request();
    Request.Builder requestBuilder = original.newBuilder()
        .addHeader("Accept", "application/json")
        .addHeader("Content-Type", "application/json");
    requestBuilder.addHeader(Test.APIKeyAuthToken, Test.API_TOKEN);
    Request request = requestBuilder.build();
    return chain.proceed(request);
}

Body:
Despite it is rather unclear which API you are even talking about - and what you might mean with "not working" (this is not an error description at all) ...the HTTP header probably should  look alike:

.addHeader("Authorization", API_TOKEN)

Just see the API documentation, which string-format is actually being expected... because "not working" might possibly mean, just sending some random header, which the API doesn't accept.


问:
remove div without an id tag
I need a solution to remove a div without an ID tag in JavaScript only. The div looks like this
.

Here is the full structure.

```<code><tr id="-1">
  <td class="stxt">
    <div align="center">
    </div>
  </td>
</tr>
</code>```

答: You need some way to make this div tag unique. There is another javascipt function called getElementsByTagName that you can use to get an array of all of the div tags. You can then use the DOM to check whether that div tag has the property of align="center".

Title: remove div without an id tag


问:
How to solve "element not interactable" with ChromDriver and yii2?
At first i work with OpenServer and I use ChromeDriver like this

D:\ChromeDriver\chromedriver.exe --url-base=/wd/hub

My Acceptance.suite.yml

```<code>class_name: AcceptanceTester
modules:
    enabled:
        - WebDriver:
              url: http://arctic/
              window_size: false # disabled in ChromeDriver
              port: 9515
              browser: chrome
        - Yii2:
            part: orm
            entryScript: index-test.php
            cleanup: false
</code>```

My acceptance test

```<code>public function _before(AcceptanceTester $I)
{
    $I->amOnPage('/admin');
    $I->fillField('FormLogin[username]', 'admin');
    $I->fillField('FormLogin[password]', 'admin');
    $I->click('Войти');
    $I->click('Меню');
}
</code>```

And i got this error

```<code>1) AdminMenuAcceptCest: Try to test
 Test  tests\acceptance\AdminMenuAcceptCest.php:tryToTest

  [Facebook\WebDriver\Exception\ElementNotInteractableException] element not interactable
  (Session info: chrome=80.0.3987.100)

Scenario Steps:

 2. $I->fillField("FormLogin[username]","admin") at tests\acceptance\AdminMenuAcceptCest.php:8
 1. $I->amOnPage("/admin/main") at tests\acceptance\AdminMenuAcceptCest.php:7

#1  D:\OSPanel-new\domains\arctic_dev\vendor\php-webdriver\webdriver\lib\Exception\WebDriverException.php:95
#2  D:\OSPanel-new\domains\arctic_dev\vendor\php-webdriver\webdriver\lib\Remote\HttpCommandExecutor.php:370
#3  D:\OSPanel-new\domains\arctic_dev\vendor\php-webdriver\webdriver\lib\Remote\RemoteWebDriver.php:584
#4  D:\OSPanel-new\domains\arctic_dev\vendor\php-webdriver\webdriver\lib\Remote\RemoteExecuteMethod.php:27
#5  D:\OSPanel-new\domains\arctic_dev\vendor\php-webdriver\webdriver\lib\Remote\RemoteWebElement.php:60
#6  Codeception\Module\WebDriver->fillField
#7  D:\OSPanel-new\domains\arctic_dev\tests\_support\_generated\AcceptanceTesterActions.php:1505
#8  D:\OSPanel-new\domains\arctic_dev\tests\acceptance\AdminMenuAcceptCest.php:8
#9  AdminMenuAcceptCest->_before
</code>```

I tried to check for existing of field in $I->seeElement() and it didn't see it.

答:
It might be helpful for someone, this is my solution:</p>

```<code>public function _before(AcceptanceTester $I)
    {
        $I->amOnPage('/admin');
        $I->executeInSelenium(function(\Facebook\WebDriver\Remote\RemoteWebDriver $webdriver) {
            $webdriver->executeScript("$('#login_block').modal('show');");
        });
        $I->wait(5);
        $I->fillField('FormLogin[username]', 'admin');
        $I->fillField('FormLogin[password]', 'admin');
        $I->click('Войти');
    }
</code>```

Body:
At first i work with OpenServer and I use ChromeDriver like this

D:\ChromeDriver\chromedriver.exe --url-base=/wd/hub

My Acceptance.suite.yml

class_name: AcceptanceTester
modules:
    enabled:
        - WebDriver:
              url: http://arctic/
              window_size: false # disabled in ChromeDriver
              port: 9515
              browser: chrome
        - Yii2:
            part: orm
            entryScript: index-test.php
            cleanup: false

My acceptance test

public function _before(AcceptanceTester $I)
{
    $I->amOnPage('/admin');
    $I->fillField('FormLogin[username]', 'admin');
    $I->fillField('FormLogin[password]', 'admin');
    $I->click('Войти');
    $I->click('Меню');
}

And i got this error

1) AdminMenuAcceptCest: Try to test
 Test  tests\acceptance\AdminMenuAcceptCest.php:tryToTest

  [Facebook\WebDriver\Exception\ElementNotInteractableException] element not interactable
  (Session info: chrome=80.0.3987.100)

Scenario Steps:

 2. $I->fillField("FormLogin[username]","admin") at tests\acceptance\AdminMenuAcceptCest.php:8
 1. $I->amOnPage("/admin/main") at tests\acceptance\AdminMenuAcceptCest.php:7

#1  D:\OSPanel-new\domains\arctic_dev\vendor\php-webdriver\webdriver\lib\Exception\WebDriverException.php:95
#2  D:\OSPanel-new\domains\arctic_dev\vendor\php-webdriver\webdriver\lib\Remote\HttpCommandExecutor.php:370
#3  D:\OSPanel-new\domains\arctic_dev\vendor\php-webdriver\webdriver\lib\Remote\RemoteWebDriver.php:584
#4  D:\OSPanel-new\domains\arctic_dev\vendor\php-webdriver\webdriver\lib\Remote\RemoteExecuteMethod.php:27
#5  D:\OSPanel-new\domains\arctic_dev\vendor\php-webdriver\webdriver\lib\Remote\RemoteWebElement.php:60
#6  Codeception\Module\WebDriver->fillField
#7  D:\OSPanel-new\domains\arctic_dev\tests\_support\_generated\AcceptanceTesterActions.php:1505
#8  D:\OSPanel-new\domains\arctic_dev\tests\acceptance\AdminMenuAcceptCest.php:8
#9  AdminMenuAcceptCest->_before

I tried to check for existing of field in $I->seeElement() and it didn't see it.

Body:
It might be helpful for someone, this is my solution:

public function _before(AcceptanceTester $I)
    {
        $I->amOnPage('/admin');
        $I->executeInSelenium(function(\Facebook\WebDriver\Remote\RemoteWebDriver $webdriver) {
            $webdriver->executeScript("$('#login_block').modal('show');");
        });
        $I->wait(5);
        $I->fillField('FormLogin[username]', 'admin');
        $I->fillField('FormLogin[password]', 'admin');
        $I->click('Войти');
    }


问:
Spring Config Bean Injection with generic
I have a generic interface-

```<code>Interface A<T1,T2>{

public T1 getSome(T2 input);

}
</code>```

I have a wrapper class-

```<code>Class B implements A<C,D>{

@Override
public D getSome(C input){

  // Do something
  return D;
}}
</code>```

Now I have a spring config class

```<code>@Configuration
public Class BConfig{

@Bean
public A b(){
  return new b();
}}
</code>```

Now I have an AppConfig class

```<code>@Configuration
Class AppConfig(){

@Inject
private A b

public App app(){
  return new App(b);
}}
</code>```

My App class looks like-

```<code>public Class App{
  A b;
  public App(A b){
    this.b=b;}
  public void doSome(){
    C c=new C();
    D d=b.getSome(c);
  }
}
</code>```

Now in my App class do I need to initialize B using-

```<code>A<C,D> b;
</code>```

or

```<code>A b;
</code>```

Since the the bean injection will inject the implementation of A which is B in spring config. I dont want to specify the generic type as this will kind of defeat the purpose of using the generics slightly.

答:
Spring autowires beans by type , qualifier and by name.

It depends how you want to use them.
In case you define them without generics  you will work with java.lang.object which means you will cast to some type when you need to use those logic in some classes

With generics you would not have such problem .

Here is an example :

```<code>@Configuration
public class BConfig{

 @Bean
 public A<C,D> b(){
  return new B();
 }
}

@Component
public class E {
 @Autowired
 private A<C,D> b;
}
</code>```

Body:
I have a generic interface-

Interface A<T1,T2>{

public T1 getSome(T2 input);

}

I have a wrapper class-

Class B implements A<C,D>{

@Override
public D getSome(C input){

  // Do something
  return D;
}}

Now I have a spring config class

@Configuration
public Class BConfig{

@Bean
public A b(){
  return new b();
}}

Now I have an AppConfig class

@Configuration
Class AppConfig(){

@Inject
private A b

public App app(){
  return new App(b);
}}

My App class looks like-

public Class App{
  A b;
  public App(A b){
    this.b=b;}
  public void doSome(){
    C c=new C();
    D d=b.getSome(c);
  }
}

Now in my App class do I need to initialize B using-

A<C,D> b;

or

A b;

Since the the bean injection will inject the implementation of A which is B in spring config. I dont want to specify the generic type as this will kind of defeat the purpose of using the generics slightly.

Body:
Spring autowires beans by type , qualifier and by name.

It depends how you want to use them.
In case you define them without generics  you will work with java.lang.object which means you will cast to some type when you need to use those logic in some classes

With generics you would not have such problem .

Here is an example :

@Configuration
public class BConfig{

 @Bean
 public A<C,D> b(){
  return new B();
 }
}

@Component
public class E {
 @Autowired
 private A<C,D> b;
}


问:
Pygame image is not moving properly when using the right code for it
This is my code for my pygame space invaders.  Right now, I am trying to get the spaceship image to move.  This is my code for it

```<code>import pygame

pygame.init()

screen = pygame.display.set_mode((1600, 900), pygame.RESIZABLE)

window_width, window_height = screen.get_width(), screen.get_height()

pygame.display.set_caption("space invaders")

icon = pygame.image.load('images/space-invaders.png')
pygame.display.set_icon(icon)

player_image = pygame.image.load('images/player.png')
playerX = window_width / 2 - 50
playerY = (window_height / 2) + (window_height / 3)

def player(x, y):
    screen.blit(player_image, (x, y))

running = True
while running:

    playerX_change = 0

    screen.fill((0, 0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        #if keystroke is pressed check whether its right or left
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                 playerX_change = -5
            elif event.key == pygame.K_RIGHT:
                 playerX_change = 5

    playerX += playerX_change
    player(playerX, playerY)
</code>```

When I run this code, the spaceship moves every time I click the arrow keys.  But when I hold them, it moves 5 left or right once and then does not move anymore.  How can I fix this.

答:
You mix two different methods - events and pygame.key.get_pressed()

System sends only one event when you press button so you set playerX_change = -5 only once and you can't set playerX_change = 0 inside loop. But you will have to also use event.type == pygame.KEYUP to stop moving it.

```<code># set start value before loop
playerX_change = 0

running = True
while running:

    screen.fill((0, 0, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        #if keystroke is pressed check whether its right or left
        elif event.type == pygame.KEYDOWN:
            # set "speed"
            if event.key == pygame.K_LEFT:
                 playerX_change = -5
            elif event.key == pygame.K_RIGHT:
                 playerX_change = 5

        elif event.type == pygame.KEYUP:
            # reset "speed"
            if event.key == pygame.K_LEFT:
                 playerX_change = 0
            elif event.key == pygame.K_RIGHT:
                 playerX_change = 0

    playerX += playerX_change
    player(playerX, playerY)

    pygame.display.flip()
</code>```

Using pygame.key.get_pressed() you can check key in every loop and then you have to set  playerX_change = 0 before every check.

```<code>running = True
while running:

    screen.fill((0, 0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    playerX_change = 0

    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT]:
         playerX_change = -5
    if keys[pygame.K_RIGHT]:
         playerX_change = 5

    playerX += playerX_change
    player(playerX, playerY)

    pygame.display.flip()
</code>```

Body:
This is my code for my pygame space invaders.  Right now, I am trying to get the spaceship image to move.  This is my code for it

import pygame

pygame.init()

screen = pygame.display.set_mode((1600, 900), pygame.RESIZABLE)

window_width, window_height = screen.get_width(), screen.get_height()

pygame.display.set_caption("space invaders")

icon = pygame.image.load('images/space-invaders.png')
pygame.display.set_icon(icon)

player_image = pygame.image.load('images/player.png')
playerX = window_width / 2 - 50
playerY = (window_height / 2) + (window_height / 3)

def player(x, y):
    screen.blit(player_image, (x, y))

running = True
while running:

    playerX_change = 0

    screen.fill((0, 0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        #if keystroke is pressed check whether its right or left
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                 playerX_change = -5
            elif event.key == pygame.K_RIGHT:
                 playerX_change = 5

    playerX += playerX_change
    player(playerX, playerY)

When I run this code, the spaceship moves every time I click the arrow keys.  But when I hold them, it moves 5 left or right once and then does not move anymore.  How can I fix this.

Body:
You mix two different methods - events and pygame.key.get_pressed()

System sends only one event when you press button so you set playerX_change = -5 only once and you can't set playerX_change = 0 inside loop. But you will have to also use event.type == pygame.KEYUP to stop moving it.

# set start value before loop
playerX_change = 0

running = True
while running:

    screen.fill((0, 0, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        #if keystroke is pressed check whether its right or left
        elif event.type == pygame.KEYDOWN:
            # set "speed"
            if event.key == pygame.K_LEFT:
                 playerX_change = -5
            elif event.key == pygame.K_RIGHT:
                 playerX_change = 5

        elif event.type == pygame.KEYUP:
            # reset "speed"
            if event.key == pygame.K_LEFT:
                 playerX_change = 0
            elif event.key == pygame.K_RIGHT:
                 playerX_change = 0

    playerX += playerX_change
    player(playerX, playerY)

    pygame.display.flip()

Using pygame.key.get_pressed() you can check key in every loop and then you have to set  playerX_change = 0 before every check.

running = True
while running:

    screen.fill((0, 0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    playerX_change = 0

    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT]:
         playerX_change = -5
    if keys[pygame.K_RIGHT]:
         playerX_change = 5

    playerX += playerX_change
    player(playerX, playerY)

    pygame.display.flip()


问:
ASP.NET Core 3.1 ignoring System.Text.Json.JsonPropertyName when returning response body
I recently changed my ASP.NET Core application to target 3.1 from 2.2.  I also changed from using Newtonsoft for JSON serialization to System.Text.Json.  In the process I have changed a number of response class properties to use JsonPropertyNameAttribute (from the Newtonsoft JsonPropertyAttribute).

However, I have now noticed the application is ignoring the JsonPropertyNameAttribute and serializing the property name to camel case instead.

For example:

[JsonPropertyName("handsets")]
public IEnumerable<GetHandsetResponse> AllHandsets { get; set; }
```

The response object field is being output as allHandsets in the response and not handsets as specified by the JsonPropertyName.

I'm guessing I'm missing something in the Startup.cs of the application to tell it to use System.Text.Json however I have no idea what.  What might I be missing?

答: It appears that deep down in the common code called from Startup.cs - ConfigureServices() of the application there is a call to .AddNewtonsoftJson() (on the returned IMvcBuilder type).  Removing that method call appears to properly revert the application back to using the System.Text.Json serializer.

Body:
I recently changed my ASP.NET Core application to target 3.1 from 2.2.  I also changed from using Newtonsoft for JSON serialization to System.Text.Json.  In the process I have changed a number of response class properties to use JsonPropertyNameAttribute (from the Newtonsoft JsonPropertyAttribute).

However, I have now noticed the application is ignoring the JsonPropertyNameAttribute and serializing the property name to camel case instead.

For example:

[JsonPropertyName("handsets")]
public IEnumerable<GetHandsetResponse> AllHandsets { get; set; }

The response object field is being output as allHandsets in the response and not handsets as specified by the JsonPropertyName.

I'm guessing I'm missing something in the Startup.cs of the application to tell it to use System.Text.Json however I have no idea what.  What might I be missing?