问:
Spring Expression Language (SpEL) for json access with list
I'm trying to understand why this doesn't work?

```<code>  context.addPropertyAccessor(new JsonPropertyAccessor());

  Object j = mapper.readTree(
"{\"foo\": {\"bar\": [ { \"fizz\": 5, \"buzz\": 6, \"doo\": 9 }, {\"fizz\": 7}, {\"fizz\": 8} ] } })");

System.out.println(evaluate(j, "foo.bar.![doo == 9]"));
</code>```

It always prints:

```<code>[false, false, false]
</code>```

I need to check if any of the doo contains a 9.

答:
If you don't need use SPEL necessarily you can do it easily with Jayway JsonPath

Include dependency:

```<code><dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>
</code>```

Then use the JsonPath and query:

```<code>Srgin json = "{\"foo\": {\"bar\": [ { \"fizz\": 5, \"buzz\": 6, \"doo\": 9 },
    {\"fizz\": 7}, {\"fizz\": 8, \"doo\": 6} ] } })";

JSONArray array = JsonPath.read(json, "foo.bar[?(@.doo==9)]");

// now array is a List of size 1, since second "doo" is not equal 9
// using array.get(0) you can get first object as a HashMap<String, Object>
</code>```

By the link mentioned above you can find more details about JsonPath queries.

If you still need to integrate JsonPath with SPEL you can add parsing function to the evaluation context. Fortunately you already use spring-integration which has JsonPathUtils class with evaluate(String, String) method.

```<code>StandardEvaluationContext evaluationContext = new StandardEvaluationContext();
Method method = BeanUtils.resolveSignature("evaluate", JsonPathUtils.class);
evaluationContext.registerFunction("jsonPath", method);

String json = "{\"foo\": {\"bar\": [ { \"fizz\": 5, \"buzz\": 6, \"doo\": 9 }, " +
            "{\"fizz\": 7}, {\"fizz\": 8, \"doo\": 7} ] } })";
evaluationContext.setVariable("foo", json);

ExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression("#jsonPath(#foo, 'foo.bar[?(@.doo>6)]')");
Object result = expression.getValue(evaluationContext);
//now result contains still the same JSONArray
</code>```

And finally I figured out the reason of your issue. First of all: guess what returns the expression foo.bar.doo? It's not a String or Integer value. It returns an instance of ToStringFriendlyJsonNode. So doo==9 will always give you false since they can't be equal. Moreover you can't use > or < because it's not allowed to compare Object and Integer. Therefore you need to cast to suitable type before comparison.

```<code> expression.getValue("foo.bar.![doo!=null and new Integer(doo.toString()) == 9]");
</code>```

Also we need to check if doo exists that's why we need to check for null. ToStringFriendlyJsonNode can provide only string value. That's why we have to use ToString(). As you see native SPEL is inconvenient and too verbose because it's not supposed to be used for complex Json queries.

Body:
I'm trying to understand why this doesn't work?

  context.addPropertyAccessor(new JsonPropertyAccessor());

  Object j = mapper.readTree(
"{\"foo\": {\"bar\": [ { \"fizz\": 5, \"buzz\": 6, \"doo\": 9 }, {\"fizz\": 7}, {\"fizz\": 8} ] } })");

System.out.println(evaluate(j, "foo.bar.![doo == 9]"));

It always prints:

[false, false, false]

I need to check if any of the doo contains a 9.

Body:
If you don't need use SPEL necessarily you can do it easily with Jayway JsonPath

Include dependency:

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>

Then use the JsonPath and query:

Srgin json = "{\"foo\": {\"bar\": [ { \"fizz\": 5, \"buzz\": 6, \"doo\": 9 },
    {\"fizz\": 7}, {\"fizz\": 8, \"doo\": 6} ] } })";

JSONArray array = JsonPath.read(json, "foo.bar[?(@.doo==9)]");

// now array is a List of size 1, since second "doo" is not equal 9
// using array.get(0) you can get first object as a HashMap<String, Object>

By the link mentioned above you can find more details about JsonPath queries.

If you still need to integrate JsonPath with SPEL you can add parsing function to the evaluation context. Fortunately you already use spring-integration which has JsonPathUtils class with evaluate(String, String) method.

StandardEvaluationContext evaluationContext = new StandardEvaluationContext();
Method method = BeanUtils.resolveSignature("evaluate", JsonPathUtils.class);
evaluationContext.registerFunction("jsonPath", method);

String json = "{\"foo\": {\"bar\": [ { \"fizz\": 5, \"buzz\": 6, \"doo\": 9 }, " +
            "{\"fizz\": 7}, {\"fizz\": 8, \"doo\": 7} ] } })";
evaluationContext.setVariable("foo", json);

ExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression("#jsonPath(#foo, 'foo.bar[?(@.doo>6)]')");
Object result = expression.getValue(evaluationContext);
//now result contains still the same JSONArray

And finally I figured out the reason of your issue. First of all: guess what returns the expression foo.bar.doo? It's not a String or Integer value. It returns an instance of ToStringFriendlyJsonNode. So doo==9 will always give you false since they can't be equal. Moreover you can't use > or < because it's not allowed to compare Object and Integer. Therefore you need to cast to suitable type before comparison.

 expression.getValue("foo.bar.![doo!=null and new Integer(doo.toString()) == 9]");

Also we need to check if doo exists that's why we need to check for null. ToStringFriendlyJsonNode can provide only string value. That's why we have to use ToString(). As you see native SPEL is inconvenient and too verbose because it's not supposed to be used for complex Json queries.


来源: stackexchange

问:
How to have more than one handler in AWS Lambda Function?
I have a very large python file that consists of multiple defined functions. If you're familiar with AWS Lambda, when you create a lambda function, you specify a handler, which is a function in the code that AWS Lambda can invoke when service executes my code, which is represented below in my_handler.py file:

```<code>    def handler_name(event, context):
        ...
        return some_value
</code>```

Link Source: https://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html

However, as I mentioned above, I have multiple defined functions in my_handler.py that have their own events and contexts. Therefore, this will result in an error. Are there any ways around this in python3.6?

答:
Little late to the game but thought it wouldn't hurt to share. Best practices suggest that one separate the handler from the Lambda's core logic. Not only is it okay to add additional definitions, it can lead to more legible code and reduce waste--e.g. multiple API calls to S3. So, although it can get out of hand, I disagree with some of those critiques to your initial question. It's effective to use your handler as a logical interface to the additional functions that will accomplish your various work. In Data Architecture & Engineering land it's often less-costly and more efficient to work in this manner. Particularly if you are building out ETL pipelines, following service-oriented architectural patterns. Admittedly, I'm a bit of a Maverick and some may find this unruly/egregious but I've gone so far as to build classes into my Lambdas for various reasons--e.g. centralized, data-lake-ish S3 buckets that accommodate a variety of file types, reduce unnecessary requests, etc...--and I stand by it. Here's an example of one of my handler files from a CDK example project I put on the hub awhile back. Hopefully it'll give you some useful ideas, or at the very least not feel alone in wanting to beef up your Lambdas.

import requests
import json
from requests.exceptions import Timeout
from requests.exceptions import HTTPError
from botocore.exceptions import ClientError
from datetime import date
import csv
import os
import boto3
import logging

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

class Asteroids:
    """Client to NASA API and execution interface to branch data processing by file type.
    Notes:
        This class doesn't look like a normal class. It is a simple example of how one might
        workaround AWS Lambda's limitations of class use in handlers. It also allows for
        better organization of code to simplify this example. If one planned to add
        other NASA endpoints or process larger amounts of Asteroid data for both .csv and .json formats,
        asteroids_json and asteroids_csv should be modularized and divided into separate lambdas
        where stepfunction orchestration is implemented for a more comprehensive workflow.
        However, for the sake of this demo I'm keeping it lean and easy.
    """

    def execute(self, format):
        """Serves as Interface to assign class attributes and execute class methods
        Raises:
            Exception: If file format is not of .json or .csv file types.
        Notes:
            Have fun!
        """
        self.file_format=format
        self.today=date.today().strftime('%Y-%m-%d')
        # method call below used when Secrets Manager integrated. See get_secret.__doc__ for more.
        # self.api_key=get_secret('nasa_api_key')
        self.api_key=os.environ["NASA_KEY"]
        self.endpoint=f"https://api.nasa.gov/neo/rest/v1/feed?start_date={self.today}&end_date={self.today}&api_key={self.api_key}"
        self.response_object=self.nasa_client(self.endpoint)
        self.processed_response=self.process_asteroids(self.response_object)
        if self.file_format == "json":
            self.asteroids_json(self.processed_response)
        elif self.file_format == "csv":
            self.asteroids_csv(self.processed_response)
        else:
            raise Exception("FILE FORMAT NOT RECOGNIZED")
        self.write_to_s3()

    def nasa_client(self, endpoint):
        """Client component for API call to NASA endpoint.
        Args:
            endpoint (str): Parameterized url for API call.
        Raises:
            Timeout: If connection not made in 5s and/or data not retrieved in 15s.
            HTTPError & Exception: Self-explanatory
        Notes:
            See Cloudwatch logs for debugging.
        """
        try:
            response = requests.get(endpoint, timeout=(5, 15))
        except Timeout as timeout:
            print(f"NASA GET request timed out: {timeout}")
        except HTTPError as http_err:
            print(f"HTTP error occurred: {http_err}")
        except Exception as err:
            print(f'Other error occurred: {err}')
        else:
            return json.loads(response.content)

    def process_asteroids(self, payload):
        """Process old, and create new, data object with content from response.
        Args:
            payload (b'str'): Binary string of asteroid data to be processed.
        """
        near_earth_objects = payload["near_earth_objects"][f"{self.today}"]
        asteroids = []
        for neo in near_earth_objects:
            asteroid_object = {
                "id" : neo['id'],
                "name" : neo['name'],
                "hazard_potential" : neo['is_potentially_hazardous_asteroid'],
                "est_diameter_min_ft": neo['estimated_diameter']['feet']['estimated_diameter_min'],
                "est_diameter_max_ft": neo['estimated_diameter']['feet']['estimated_diameter_max'],
                "miss_distance_miles": [item['miss_distance']['miles'] for item in neo['close_approach_data']],
                "close_approach_exact_time": [item['close_approach_date_full'] for item in neo['close_approach_data']]
            }
            asteroids.append(asteroid_object)

        return asteroids

    def asteroids_json(self, payload):
        """Creates json object from payload content then writes to .json file.
        Args:
            payload (b'str'): Binary string of asteroid data to be processed.
        """
        json_file = open(f"/tmp/asteroids_{self.today}.json",'w')
        json_file.write(json.dumps(payload, indent=4))
        json_file.close()

    def asteroids_csv(self, payload):
        """Creates .csv object from payload content then writes to .csv file.
        """
        csv_file=open(f"/tmp/asteroids_{self.today}.csv",'w', newline='\n')
        fields=list(payload[0].keys())
        writer=csv.DictWriter(csv_file, fieldnames=fields)
        writer.writeheader()
        writer.writerows(payload)
        csv_file.close()

    def get_secret(self):
        """Gets secret from AWS Secrets Manager
        Notes:
            Have yet to integrate into the CDK. Leaving as example code.
        """
        secret_name = os.environ['TOKEN_SECRET_NAME']
        region_name = os.environ['REGION']
        session = boto3.session.Session()
        client = session.client(service_name='secretsmanager', region_name=region_name)
        try:
            get_secret_value_response = client.get_secret_value(SecretId=secret_name)
        except ClientError as e:
            raise e
        else:
            if 'SecretString' in get_secret_value_response:
                secret = get_secret_value_response['SecretString']
            else:
                secret = b64decode(get_secret_value_response['SecretBinary'])
        return secret

    def write_to_s3(self):
        """Uploads both .json and .csv files to s3
        """
        s3 = boto3.client('s3')
        s3.upload_file(f"/tmp/asteroids_{self.today}.{self.file_format}", os.environ['S3_BUCKET'], f"asteroid_data/asteroids_{self.today}.{self.file_format}")

def handler(event, context):
    """Instantiates class and triggers execution method.
    Args:
        event (dict): Lists a custom dict that determines interface control flow--i.e. `csv` or `json`.
        context (obj): Provides methods and properties that contain invocation, function and
            execution environment information.
            *Not used herein.
    """
    asteroids = Asteroids()
    asteroids.execute(event)
```

ContentLicense: CC BY-SA 4.0

Body:
I have a very large python file that consists of multiple defined functions. If you're familiar with AWS Lambda, when you create a lambda function, you specify a handler, which is a function in the code that AWS Lambda can invoke when service executes my code, which is represented below in my_handler.py file:

    def handler_name(event, context):
        ...
        return some_value

Link Source: https://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html

However, as I mentioned above, I have multiple defined functions in my_handler.py that have their own events and contexts. Therefore, this will result in an error. Are there any ways around this in python3.6?


问:
AzureStorageEmulator 5.1 doesn't to start
After my Win10 update the AzureStorageEmulator (5.10.0.0) embedded into VS2019 (16.4.5) doesn't to start. I have tried to start it separately, but the same problem

```<code>AzureStorageEmulator.exe start -inprocess
Windows Azure Storage Emulator 5.10.0.0 command line tool
Service Status: Blob http://127.0.0.1:10000/ False
The network location cannot be reached. For information about network troubleshooting, see Windows Help
Error: Unable to start the storage emulator.
</code>```

I tried in addition to initialize AzureStorage

```<code>AzureStorageEmulator.exe init
Windows Azure Storage Emulator 5.10.0.0 command line tool
Found SQL Instance (localdb)\MSSQLLocalDB.
Creating database AzureStorageEmulatorDb510 on SQL instance '(localdb)\MSSQLLocalDB'.
Granting database access to user EVN-TEAMVIEWER\simon.hunanyan.
Database access for user EVN-TEAMVIEWER\simon.hunanyan was granted.
Initialization successful. The storage emulator is now ready for use.
The storage emulator was successfully initialized and is ready to use.
</code>```

But the result the same:(

Maybe somebody already bumped to this problem? Any idea - how to resolve it?

答:
seems, I found the reason  - the net access for local machine was closed somehow:(
I have ran the command

```<code>netsh http add iplisten 127.0.0.1
</code>```

and surprisingly AzureStorageEmulator was started

```<code>AzureStorageEmulator.exe start -inprocess
Windows Azure Storage Emulator 5.10.0.0 command line tool
Service Status: Blob http://127.0.0.1:10000/ True
Service Status: Queue http://127.0.0.1:10001/ True
Service Status: Table http://127.0.0.1:10002/ True
</code>```

Body:
After my Win10 update the AzureStorageEmulator (5.10.0.0) embedded into VS2019 (16.4.5) doesn't to start. I have tried to start it separately, but the same problem

AzureStorageEmulator.exe start -inprocess
Windows Azure Storage Emulator 5.10.0.0 command line tool
Service Status: Blob http://127.0.0.1:10000/ False
The network location cannot be reached. For information about network troubleshooting, see Windows Help
Error: Unable to start the storage emulator.

I tried in addition to initialize AzureStorage

AzureStorageEmulator.exe init
Windows Azure Storage Emulator 5.10.0.0 command line tool
Found SQL Instance (localdb)\MSSQLLocalDB.
Creating database AzureStorageEmulatorDb510 on SQL instance '(localdb)\MSSQLLocalDB'.
Granting database access to user EVN-TEAMVIEWER\simon.hunanyan.
Database access for user EVN-TEAMVIEWER\simon.hunanyan was granted.
Initialization successful. The storage emulator is now ready for use.
The storage emulator was successfully initialized and is ready to use.

But the result the same:(

Maybe somebody already bumped to this problem? Any idea - how to resolve it?

Body:
seems, I found the reason  - the net access for local machine was closed somehow:(
I have ran the command

netsh http add iplisten 127.0.0.1

and surprisingly AzureStorageEmulator was started

AzureStorageEmulator.exe start -inprocess
Windows Azure Storage Emulator 5.10.0.0 command line tool
Service Status: Blob http://127.0.0.1:10000/ True
Service Status: Queue http://127.0.0.1:10001/ True
Service Status: Table http://127.0.0.1:10002/ True


问:
how to split a string value that contains characters and numbers
I have a std::string s=n8Name4Surname. How can I obtain in 2 strings the Name and the Surname? THX

答:
You can detect numerical characters in the string using function isdigit(mystring.at(position), then extract substring between those positions.

See:

http://www.cplusplus.com/reference/clibrary/cctype/isdigit/

ContentLicense: CC BY-SA 3.0


问:
Prevent Recyclerview from losing focus
I am developping this android TV app which has one activity containing some buttons. After clicking a button, a RecyclerView (in the same activity) gets populated and automatically focused.

The problem is when navigating with DPAD toward the direction of the buttons, the RecyclerView loses focus to the buttons. I want to prevent this behavior, i.e. prevent the RecyclerView from losing focus to anything else on the activity. Later, the only way to select another button is by clicking the back button, this I can do, no problem.

Here is what I have tried, and did not work:

```<code><androidx.recyclerview.widget.RecyclerView
        android:id="@+id/categories_rv"
        android:layout_width="@dimen/categories_list_width"
        android:layout_height="wrap_content"
        android:focusable="true"
        android:nextFocusForward="@id/categories_rv"
        android:nextFocusUp="@id/categories_rv"
        android:nextFocusRight="@id/categories_rv"
        android:nextFocusLeft="@id/categories_rv"
        android:nextFocusDown="@id/categories_rv"
        android:focusableInTouchMode="true" />
</code>```

And this:

```<code> binding.categoriesRv.setOnFocusChangeListener { v, hasFocus ->
     if (!hasFocus)
        v.requestFocus()
  }
</code>```

In the second way, the FocusChangeListener never gets called unless I use android:descendantFocusability="blocksDescendants" in the RecyclerView, but this prevents the items of the RecyclerView of being focused.

答: No matter what you do if you using recyclerview in android tv app it will lose focus. Only solution is using leanback fragments.</p>

Title: Prevent Recyclerview from losing focus

Body:
I am developping this android TV app which has one activity containing some buttons. After clicking a button, a RecyclerView (in the same activity) gets populated and automatically focused.

The problem is when navigating with DPAD toward the direction of the buttons, the RecyclerView loses focus to the buttons. I want to prevent this behavior, i.e. prevent the RecyclerView from losing focus to anything else on the activity. Later, the only way to select another button is by clicking the back button, this I can do, no problem.

Here is what I have tried, and did not work:

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/categories_rv"
        android:layout_width="@dimen/categories_list_width"
        android:layout_height="wrap_content"
        android:focusable="true"
        android:nextFocusForward="@id/categories_rv"
        android:nextFocusUp="@id/categories_rv"
        android:nextFocusRight="@id/categories_rv"
        android:nextFocusLeft="@id/categories_rv"
        android:nextFocusDown="@id/categories_rv"
        android:focusableInTouchMode="true" />

And this:

 binding.categoriesRv.setOnFocusChangeListener { v, hasFocus ->
     if (!hasFocus)
        v.requestFocus()
  }

In the second way, the FocusChangeListener never gets called unless I use android:descendantFocusability="blocksDescendants" in the RecyclerView, but this prevents the items of the RecyclerView of being focused.


问:
convert month-day-year into day-month-year using javascript
I'm trying to convert a MM/DD/YYYY date to a long date. So for example, 02/16/2020 would convert to something like 16/02/2020.

Is there a way to make this date conversion accurately?

Body:
2 || 1 liners ?

var src = '02/16/2020'
var a = src.split('/');
console.log(a.concat(a.splice(0, 2)).join('/'));
console.log(src.replace(/(\d+)\/(\d+)\/(\d+)/, '$3/$1/$2'));


问:
Python: Calling a module in same directory
I have trouble importing a module in same directory.
Basically, here is my organization

```<code>alex (folder)
 |
 |- alex (folder)
 |   |- __init__.py
 |   |- commons.py
 |   |- KnowledgeBase.py
 |
 |- test.py
</code>```

in my init.py file, I have the following lines to make import of commons & KnowledgeBase easier in test.py.
It appears to work.

```<code>from .KnowledgeBase import KnowledgeBase
from .commons import *
</code>```

In my KnowledgeBase.py file, I have a class called KnowledgeBase.

In commons.py, I have different objects:

a namedtuple called CDE

an object called TimePeriod

And then, in test.py, I can call my objects this way.

```<code>import alex as al
do stuff with al.KnowledgeBase
do stuff with al.CDE
do stuff with al.TimePeriod
</code>```

What doesn't work now.

I am calling in KnowledgeBase.py the module commons.py.

```<code>import alex as al
stuff with al.CDE ...
</code>```

I get the following error message.

```<code>AttributeError: module 'alex' has no attribute 'CDE'
</code>```

If I do it the traditional way:

```<code>import commons as AC
stuff with AC.CDE ...
</code>```

I get the following error message.

```<code>ModuleNotFoundError: No module named 'commons'
</code>```

And if I remove everything in the init.py file, it works, but then, I cannot use "easy module call" in test.py.

If I keep an empty init.py file, in test.py, instead of simply writing

```<code>import alex
</code>```

I have to declare all imports:

```<code>from alex import KnowledgeBase
from alex import commons
</code>```

Please, what can I do to keep the import of the different python modules in alex "simple" and at the same time, being able to import module from alex folder into other modules in alex folder?

I thank you in advance for your help.
Have a good afternoon,
Bests,

答:
I come back after having found the appropriate formatting.
In KnowledgeBase.py, the correct way to import functions or objects from commons is by typing:</p>

```<code>from . import commons as AC
</code>```

Body:
I have trouble importing a module in same directory.
Basically, here is my organization

alex (folder)
 |
 |- alex (folder)
 |   |- __init__.py
 |   |- commons.py
 |   |- KnowledgeBase.py
 |
 |- test.py

in my init.py file, I have the following lines to make import of commons & KnowledgeBase easier in test.py.
It appears to work.

from .KnowledgeBase import KnowledgeBase
from .commons import *

In my KnowledgeBase.py file, I have a class called KnowledgeBase.

In commons.py, I have different objects:

a namedtuple called CDE

an object called TimePeriod

And then, in test.py, I can call my objects this way.

import alex as al
do stuff with al.KnowledgeBase
do stuff with al.CDE
do stuff with al.TimePeriod

What doesn't work now.

I am calling in KnowledgeBase.py the module commons.py.

import alex as al
stuff with al.CDE ...

I get the following error message.

AttributeError: module 'alex' has no attribute 'CDE'

If I do it the traditional way:

import commons as AC
stuff with AC.CDE ...

I get the following error message.

ModuleNotFoundError: No module named 'commons'

And if I remove everything in the init.py file, it works, but then, I cannot use "easy module call" in test.py.

If I keep an empty init.py file, in test.py, instead of simply writing

import alex

I have to declare all imports:

from alex import KnowledgeBase
from alex import commons

Please, what can I do to keep the import of the different python modules in alex "simple" and at the same time, being able to import module from alex folder into other modules in alex folder?

I thank you in advance for your help.
Have a good afternoon,
Bests,

Body:
I come back after having found the appropriate formatting.
In KnowledgeBase.py, the correct way to import functions or objects from commons is by typing:

from . import commons as AC


问:
React, unable to display the data received by an api, after doing a GET in componentDidMount()
I have done a function in my react call which calls an api, and sets a state based on the data received by that api

```<code>getUserList() {
    API.get('/userlist')
        .then(response => {
            this.setState({
                userList: response.data
            }, () => {
                console.log(this.state.userList) //I can see this
            });
        })
}
</code>```

This is how my constructor looks

```<code>constructor(props) {
    super(props)
    this.state = {
        retracted: false,
        userList: []

    }
    this.getUserList = this.getUserList.bind(this);
}
</code>```

I call it in componentDidMount()

```<code>componentDidMount() {
    this.getUserList();
}
</code>```

But then my render crashes, because both console.log return undefined

```<code>render() {
    var users = this.state.userList;
    var user = users[0].email //cannot read email of undefined

    console.log(this.state.userList)
    console.log(users)
    return (
        <div class="maincontainer">
            <div className="content-landing">
                 <p>{user}</p>
            </div>

        </div>
    )
}
</code>```

答:
I have tried with Axios, please find below code snippet, as setting the state will result in render to execute:</p>

```<code>var self = this;
axios.get('/url')
.then(function (response) {
  console.log(response);
  self.setState({userList: response.data})
})
.catch(function (error) {
  console.log(error);
});
</code>```

Body:
I have done a function in my react call which calls an api, and sets a state based on the data received by that api

getUserList() {
    API.get('/userlist')
        .then(response => {
            this.setState({
                userList: response.data
            }, () => {
                console.log(this.state.userList) //I can see this
            });
        })
}

This is how my constructor looks

constructor(props) {
    super(props)
    this.state = {
        retracted: false,
        userList: []

    }
    this.getUserList = this.getUserList.bind(this);
}

I call it in componentDidMount()

componentDidMount() {
    this.getUserList();
}

But then my render crashes, because both console.log return undefined

render() {
    var users = this.state.userList;
    var user = users[0].email //cannot read email of undefined

    console.log(this.state.userList)
    console.log(users)
    return (

{user}

    )
}

Body:
I have tried with Axios, please find below code snippet, as setting the state will result in render to execute:

var self = this;
axios.get('/url')
.then(function (response) {
  console.log(response);
  self.setState({userList: response.data})
})
.catch(function (error) {
  console.log(error);
});


问:
Keras minibatch gradient descent with Dropout layer
I have a question about Dropout implementation in Keras/Tensorflow with mini-batch gradient descent optimization when batch_size parameter is bigger than one. The original paper says:

The only difference is that for each training case in a mini-batch, we
  sample a thinned network by dropping out units. Forward and
  backpropagation for that training case are done only on this thinned
  network. The gradients for each parameter are averaged over the
  training cases in each mini-batch. Any training case which does not
  use a parameter contributes a gradient of zero for that parameter.

But how is it implemented in Keras? As I understand, for each sample in a batch, individual gradient is calculated depending on the current model (as different units as dropped for different samples). Next after all samples from the batch are processed, for each weight respective gradients are summed, these sums are divided by batch_size and then applied to respective weights.

Going through source code I cannot see if and where it is handled. In the function _process_single_batch, the overall\avereged batch loss is computed and based on that batch gradient is calculated. This works fine for models without Dropout layer, but what about Dropout layer, how individual model settings for each sample (with different neurons dropped) are remembered and then taken into account during gradient descent calculation?

I think that I am missing something and I want to be sure that I understand correctly Keras implementation of mini-batch gradient descent when Dropout layer is involved.

答:
TensorFlow not really "drops out" some neurons out of the model, but just multiplies by zero their outputs. Let's take a look at implementation of dropout:

```<code>def dropout_v2(x, rate, noise_shape=None, seed=None, name=None):
    <...>
    # Sample a uniform distribution on [0.0, 1.0) and select values larger than
    # rate.
    #
    # NOTE: Random uniform actually can only generate 2^23 floats on [1.0, 2.0)
    # and subtract 1.0.
    random_tensor = random_ops.random_uniform(
        noise_shape, seed=seed, dtype=x.dtype)
    keep_prob = 1 - rate
    scale = 1 / keep_prob
    # NOTE: if (1.0 + rate) - 1 is equal to rate, then we want to consider that
    # float to be selected, hence we use a >= comparison.
    keep_mask = random_tensor >= rate
    ret = x * scale * math_ops.cast(keep_mask, x.dtype)
    <...>
    return ret
</code>```

So x is the dropout layer's input and rate is a rate of droppped out neurons. Based on this rate mask is generated - with probability of rate each value in this mask is 0, otherwise it's 1. When we multiply neuron's output by zero, its gradient also becomes zero. So we're not actually sample some subnetwork, but just zeroing out some of its neurons. Hope that will help :)

Body:
TensorFlow not really "drops out" some neurons out of the model, but just multiplies by zero their outputs. Let's take a look at implementation of dropout:

def dropout_v2(x, rate, noise_shape=None, seed=None, name=None):
    <...>
    # Sample a uniform distribution on [0.0, 1.0) and select values larger than
    # rate.
    #
    # NOTE: Random uniform actually can only generate 2^23 floats on [1.0, 2.0)
    # and subtract 1.0.
    random_tensor = random_ops.random_uniform(
        noise_shape, seed=seed, dtype=x.dtype)
    keep_prob = 1 - rate
    scale = 1 / keep_prob
    # NOTE: if (1.0 + rate) - 1 is equal to rate, then we want to consider that
    # float to be selected, hence we use a >= comparison.
    keep_mask = random_tensor >= rate
    ret = x * scale * math_ops.cast(keep_mask, x.dtype)
    <...>
    return ret

So x is the dropout layer's input and rate is a rate of droppped out neurons. Based on this rate mask is generated - with probability of rate each value in this mask is 0, otherwise it's 1. When we multiply neuron's output by zero, its gradient also becomes zero. So we're not actually sample some subnetwork, but just zeroing out some of its neurons. Hope that will help :)


问:
STL container with a specific type as a generic argument
Is there any way that I can make a function which takes a container with a specific type (lets say std::string) as a parameter

```<code>void foo(const std::container<std::string> &cont)
{
   for(std::string val: cont) {
      std::cout << val << std::endl;
   }
}
</code>```

and call it for every type of stl container as input? like above?

```<code>std::set<std::string> strset;
std::vector<std::string> strvec;
std::list<std::string> strlist;

foo(strset);
foo(strvec);
foo(strlist);
</code>```

答:
Adding on to @songyuanyao's answer, I think we can generalize it further to: </p>

```<code>template<template<typename...> typename C, typename ... D>
void foo(const C<D...> &cont)
{
   for(const auto& val: cont) {
      std::cout << val << std::endl;
   }
}
</code>```

Body:
Is there any way that I can make a function which takes a container with a specific type (lets say std::string) as a parameter

void foo(const std::container<std::string> &cont)
{
   for(std::string val: cont) {
      std::cout << val << std::endl;
   }
}

and call it for every type of stl container as input? like above?

std::set<std::string> strset;
std::vector<std::string> strvec;
std::list<std::string> strlist;

foo(strset);
foo(strvec);
foo(strlist);

Body:
Adding on to @songyuanyao's answer, I think we can generalize it further to:

template<template<typename...> typename C, typename ... D>
void foo(const C<D...> &cont)
{
   for(const auto& val: cont) {
      std::cout << val << std::endl;
   }
}


问:
Different scenarios for git merge conflicts
I am trying to understand which are the situations when a git conflict can happen after a git merge and how they could be avoided.

I've created a git repository and added a text file to it.

I've added "1" to the text file and committed it to master.

I've created a new branch from master(branch2) and appended a new line to the text file with the content "2".

I've created a new branch from master(branch3) and appended a new line to the text file with the content "3".

After this, I've done the following :

I've merged branch2 into master. No conflicts which is right and I've expected.

I've merged master into branch3. I had conflicts because the second line of the text file has different content. I've fixed the conflicts by keeping "3" instead of "2".

I want to merge branch3 into master. Now my questions are : 1. Are there any possibilities to have conflicts when I do that merge? If yes, why? If no, why? 2. If there shouldn't be conflicts, but I still have conflicts, what could be the reasons?

答: You shouldn't have any conflicts when you merge branch3 in to master, you would have done if you hadn't already merged master in to branch3. The reason is simply because you've added a commit to branch3 which resolves the conflict between it and master. So now merging to master can be fast-forwarded.


问:
MSAL/ADAL C++ equivalent to get access tokens
Is there a MSAL/ADAL equivalent for C++ ? I would like to natively support getting access tokens for Azure in C++ (rather than build a bridge of some kind by using python version.)

Thank you

答:
There actually is a C++ ADAL SDK, Microsoft releases it to partners and uses it internally.
It is not generally available, but if your company has a liaison with Microsoft, you can ask for it.</p>


问:
How to get the total page number in iText7 when adding that info to the document footer?
In iTextSharp, we can override the OnCloseDocument() event and add the Page # of #total on the footer of the document. However, the PdfDocument does not have this document close event anymore. Since we cannot determine the total number of pages while adding new pages, how can we determine this total number and put it on the footer while generating the document?

I've seen some suggestions with brute force method: after the PDF document is generated and before it's flushed, use PdfReader to read through it to get the total number before updating the footer. Is this the only way? Is there any better way of doing this?

Thanks.

答:
That is one of the ways of doing it.

Another way of doing that is described in this code sample:

```<code>protected void manipulatePdf(String dest) throws Exception {
    PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
    Document doc = new Document(pdfDoc);

    int numberOfPages = pdfDoc.getNumberOfPages();
    for (int i = 1; i <= numberOfPages; i++) {

        // Write aligned text to the specified by parameters point
        doc.showTextAligned(new Paragraph(String.format("page %s of %s", i, numberOfPages)),
                559, 806, i, TextAlignment.RIGHT, VerticalAlignment.TOP, 0);
    }

    doc.close();
}
</code>```

In that code sample you would add the footer after creating and flushing the PDF. This is a very simple and easy way of doing this request.

Body:
That is one of the ways of doing it.

Another way of doing that is described in this code sample:

protected void manipulatePdf(String dest) throws Exception {
    PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
    Document doc = new Document(pdfDoc);

    int numberOfPages = pdfDoc.getNumberOfPages();
    for (int i = 1; i <= numberOfPages; i++) {

        // Write aligned text to the specified by parameters point
        doc.showTextAligned(new Paragraph(String.format("page %s of %s", i, numberOfPages)),
                559, 806, i, TextAlignment.RIGHT, VerticalAlignment.TOP, 0);
    }

    doc.close();
}

In that code sample you would add the footer after creating and flushing the PDF. This is a very simple and easy way of doing this request.


问:
How can I catch the Material Datepicker month pagination event?
I would like to catch the event that comes from the month "left" and "right" selection buttons, but I couldn't find any documentation about it.

What events are fired when the "left" and "right" month selection boxes are clicked in the Material Datepicker?

答:
There's a work-around too that is use the dateClass

```<code>@ViewChild('picker',{static:false}) calendar: MatDatepicker<any>;
  setClass() {
    return (date: any) => {
      if (date.getDate() == 1) this.changeMonth(
         {month:date.getMonth()+1,
          year:date.getFullYear()
          });
    };
  }

  changeMonth(date)
  {
    console.log(date)
  }
</code>```

where you has

```<code> <mat-form-field>
  <mat-label>Choose a date</mat-label>
  <input matInput [matDatepicker]="picker">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker [dateClass]="setClass()"></mat-datepicker>
</mat-form-field>
</code>```

See stackblitz

Well, nobody has interest in know when the month change if he has no good reason. The typical reason is call to an API that return an array with "specials" days and show in the calendar.

To change the aspect of this specials days we can think that we can use the own function dateClass but remember that we are looking for the days after the function is executed (*). So we need use Renderer2 to add the class.

If the data we received is some like (see that "day" is a string)

```<code>  [
    {day:'2020-02-06',data:'one'},
    {day:'2020-02-16',data:'two'},
    {day:'2020-02-22',data:'three'}
  ]
</code>```

Our function changeMonth becomes like:

```<code>changeMonth(date) {
    this.dataService.getData(date.month, date.year).subscribe(res => {
      setTimeout(() => {
        let elements = document.querySelectorAll(".calendar");
        if (elements && elements.length) {
          const cells = elements[0].querySelectorAll(".mat-calendar-body-cell");
          cells.forEach(x => {
            const date = new Date(x.getAttribute("aria-label"));
            const dateTxt =
              date.getFullYear() +
              "-" +
              ("00" + (date.getMonth() + 1)).slice(-2) +
              "-" +
              ("00" + date.getDate()).slice(-2);

            if (res.find(x => x.day == dateTxt))
            {
              this.renderer.addClass(x, "special");
            }
          });
        }
      });
    });
  }
</code>```

(*) we can also ask for the "special days" in ngOnInit and, then simple use the dateClass function

Body:
There's a work-around too that is use the dateClass

@ViewChild('picker',{static:false}) calendar: MatDatepicker<any>;
  setClass() {
    return (date: any) => {
      if (date.getDate() == 1) this.changeMonth(
         {month:date.getMonth()+1,
          year:date.getFullYear()
          });
    };
  }

  changeMonth(date)
  {
    console.log(date)
  }

where you has

 <mat-form-field>
  <mat-label>Choose a date</mat-label>
  <input matInput [matDatepicker]="picker">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker [dateClass]="setClass()"></mat-datepicker>
</mat-form-field>

See stackblitz

Well, nobody has interest in know when the month change if he has no good reason. The typical reason is call to an API that return an array with "specials" days and show in the calendar.

To change the aspect of this specials days we can think that we can use the own function dateClass but remember that we are looking for the days after the function is executed (*). So we need use Renderer2 to add the class.

If the data we received is some like (see that "day" is a string)

  [
    {day:'2020-02-06',data:'one'},
    {day:'2020-02-16',data:'two'},
    {day:'2020-02-22',data:'three'}
  ]

Our function changeMonth becomes like:

changeMonth(date) {
    this.dataService.getData(date.month, date.year).subscribe(res => {
      setTimeout(() => {
        let elements = document.querySelectorAll(".calendar");
        if (elements && elements.length) {
          const cells = elements[0].querySelectorAll(".mat-calendar-body-cell");
          cells.forEach(x => {
            const date = new Date(x.getAttribute("aria-label"));
            const dateTxt =
              date.getFullYear() +
              "-" +
              ("00" + (date.getMonth() + 1)).slice(-2) +
              "-" +
              ("00" + date.getDate()).slice(-2);

            if (res.find(x => x.day == dateTxt))
            {
              this.renderer.addClass(x, "special");
            }
          });
        }
      });
    });
  }

(*) we can also ask for the "special days" in ngOnInit and, then simple use the dateClass function


问:
How to access values in array column?
I have a Dataframe with one column.  Each row of that column has an Array of String values:

Values in my Spark 2.2 Dataframe

```<code>["123", "abc", "2017", "ABC"]
["456", "def", "2001", "ABC"]
["789", "ghi", "2017", "DEF"]

org.apache.spark.sql.DataFrame = [col: array]

root
|-- col: array (nullable = true)
|    |-- element: string (containsNull = true)
</code>```

What is the best way to access elements in the array?  For example, I would like extract distinct values in the fourth element for the year 2017 (answer "ABC", "DEF").

答:
you can do something like below</p>

```<code>import org.apache.spark.sql.functions._

val ds = Seq(
 Array("123", "abc", "2017", "ABC"),
 Array("456", "def", "2001", "ABC"),
 Array("789", "ghi", "2017", "DEF")).toDF("col")

ds.withColumn("col1",element_at('col,1))
.withColumn("col2",element_at('col,2))
.withColumn("col3",element_at('col,3))
.withColumn("col4",element_at('col,4))
.drop('col)
.show()

+----+----+----+----+
|col1|col2|col3|col4|
+----+----+----+----+
| 123| abc|2017| ABC|
| 456| def|2001| ABC|
| 789| ghi|2017| DEF|
+----+----+----+----+
</code>```

Title: How to access values in array column?

Body:
I have a Dataframe with one column.  Each row of that column has an Array of String values:

Values in my Spark 2.2 Dataframe

["123", "abc", "2017", "ABC"]
["456", "def", "2001", "ABC"]
["789", "ghi", "2017", "DEF"]

org.apache.spark.sql.DataFrame = [col: array]

root
|-- col: array (nullable = true)
|    |-- element: string (containsNull = true)

What is the best way to access elements in the array?  For example, I would like extract distinct values in the fourth element for the year 2017 (answer "ABC", "DEF").

Body:
you can do something like below

import org.apache.spark.sql.functions._

val ds = Seq(
 Array("123", "abc", "2017", "ABC"),
 Array("456", "def", "2001", "ABC"),
 Array("789", "ghi", "2017", "DEF")).toDF("col")

ds.withColumn("col1",element_at('col,1))
.withColumn("col2",element_at('col,2))
.withColumn("col3",element_at('col,3))
.withColumn("col4",element_at('col,4))
.drop('col)
.show()

+----+----+----+----+
|col1|col2|col3|col4|
+----+----+----+----+
| 123| abc|2017| ABC|
| 456| def|2001| ABC|
| 789| ghi|2017| DEF|
+----+----+----+----+


问:
Java Single Client Thread for multiple Server communication for IOT project
I want to create a client Thread for TCP IP communication. But the client thread should be able to communicate with minimum 10000 servers in the same time. As I want to communicate with millions of servers(Practically GPRS based field devices), its not a good practice to start millions of client threads and manage it.
I have tried with NIO Selector to do this. But I found that its only possible for the server thread.
ThreadPoolExecutor also I have tried. That also failed to manage huge number of connections in the same time.
Please give a good suggestion to manage huge number of servers without starting too many threads.</p>

答:
Maybe use something non-blocking like Play framework (uses either Akka or Netty under the hood) or Vert.x to handle those requests. They use dispatch the work to your custom thread pools in order to avoid blocking.

https://www.lightbend.com/blog/why-is-play-framework-so-fast

Because Play is non-blocking, threads are not blocked when the network
  is slow, but are free to serve another HTTP request–and because Play
  is stateless, there is no session information tied to the thread that
  would confuse it.

It is pretty much the same thing for Vert.x

Maybe also have a look at Erlang and Go (Go routine), also look into UDP.
In any case the hardware (network, RAM, SSD) will ultimately be the bottleneck.
As others here and other answers stated Netty is the go to library, or something using it may be of interest.


问:
Parametrized twig date
I need how to check if a custom date is inside a range.

The problem is that the API returns a calendar but year and month are sent separately and I can't create a date with twig.

This part of the code seems to return my variables as expected

```<code><script>console.log("Year"+{{CurrYear| json_encode()| raw}});</script>
<script>console.log("Month: "+{{CurrMonth| json_encode()| raw}});</script>
</code>```

while I can retrieve the day within the loop

```<code><script>console.log("Day: "+{{key| json_encode()| raw}});</script>
</code>```

I'm trying to create a data item so I can use the native comparisons. I know I can split the other date and compare it one by one, but I'm trying to avoid this

```<code><script>console.log({{ annoForm."-".mesForm."-".key |date('Y-m-d')}}) ;</script>
</code>```

So I can use it afterwards like

```<code>{% set auxDate = annoForm."-".mesForm."-".key |date('Y-m-d') %}
</code>```

BUT, I can't seem to construct a valid date here so I could use it in:

```<code>{% datestart < auxDate  and dateend > auxDate  %}
  {# condition met #}
{% endif %}
</code>```

答:
Main problem here was concatenating correctly the string when instantiating date():

```<code>{% set auxDate = ("#{annoForm}-#{mesForm}-#{key} " | date('Y-m-d') ) %}
</code>```

I want to add a couple of issues i found while working on this.
First the importance of using date('Y-m-d') instead of "date()" because it will consider July before June (due alphabetic order).

Take nulls or open fields into account (in my case datestart is mandatory)

```<code>{% if  datestart < auxDate and ( dateend is null or dateend > auxDate ) %}
</code>```

Hope it helps!

Title: Parametrized twig date

Body:
I need how to check if a custom date is inside a range.

The problem is that the API returns a calendar but year and month are sent separately and I can't create a date with twig.

This part of the code seems to return my variables as expected

while I can retrieve the day within the loop

I'm trying to create a data item so I can use the native comparisons. I know I can split the other date and compare it one by one, but I'm trying to avoid this

So I can use it afterwards like

{% set auxDate = annoForm."-".mesForm."-".key |date('Y-m-d') %}

BUT, I can't seem to construct a valid date here so I could use it in:

{% datestart < auxDate  and dateend > auxDate  %}
  {# condition met #}
{% endif %}

Body:
Main problem here was concatenating correctly the string when instantiating date():

{% set auxDate = ("#{annoForm}-#{mesForm}-#{key} " | date('Y-m-d') ) %}

I want to add a couple of issues i found while working on this.
First the importance of using date('Y-m-d') instead of "date()" because it will consider July before June (due alphabetic order).

Take nulls or open fields into account (in my case datestart is mandatory)

{% if  datestart < auxDate and ( dateend is null or dateend > auxDate ) %}

Hope it helps!


问:
Can't click on web element with flutter appium driver that is covered by other element
I tried to test a webview in flutter app using flutter appium driver and faced a problem:
In a webview I have a text, that is placed in two lines. Because of that placing text is covered by another element.
I tried 3 approaches:

1.appium driver: mouse.moveTo then mouse.click.
Solution with mouse.moveTo then mouse.click did not work because appium need other parametr called duration, that is not included to parameters in our appium_driver.

2. Used flutter inspector to locate elements on the webview - solution was not succeed because this webviews are external and were not covered by any flutter overlay.

3. Clicking by bounds
Got all objects from the webview with TESTWorld().appiumDriver.pageSource. Found out that we have the xml with all objects on webview with properties as bounds,text. Made a list with 3 objects of “MyString“ string and clicked on them one by one with click() method from appium_driver. Second element “MyString“ is clickable, appium can click on it, but first instance of this string is in two lines, so this element is part of other big element, that’s why appium_driver can’t click on it.

Maybe someone knows another approach?

答:
Because of that placing text is covered by another element

In a particular case, it sounds like an AUT issue. Appium uses WebDriver API for testing WebView and it is expected to not be able to interact with the overlapped element.

If there is no way to address and fix it in the app, you can try JS to send a click action (the same way we do in Webdriver):

```<code>WebElement textElement = driver.findElement(...);
JavascriptExecutor jsEx = (JavascriptExecutor)driver;
jsEx.executeScript("arguments[0].click();", textElement);
</code>```

Body:
Because of that placing text is covered by another element

In a particular case, it sounds like an AUT issue. Appium uses WebDriver API for testing WebView and it is expected to not be able to interact with the overlapped element.

If there is no way to address and fix it in the app, you can try JS to send a click action (the same way we do in Webdriver):

WebElement textElement = driver.findElement(...);
JavascriptExecutor jsEx = (JavascriptExecutor)driver;
jsEx.executeScript("arguments[0].click();", textElement);


问:
How to get in ASP.NET Core 3.0 API the client API
How to get in ASP.NET Core 3.0 API the client API

On the start up class I have added this line:

```<code>services.AddControllersWithViews();
services.AddSingleton <IActionContextAccessor,ActionContextAccessor>();
</code>```

IndexController.cs

```<code>    private readonly IActionContextAccessor _accessor;
    public IndexController(IActionContextAccessor accessor)
    {
            _accessor = accessor;
    }

    [HttpGet()]
    [Route("[action]")]
    public string GetIPAddress(string id)
    {
        //var ip = HttpContext.Connection.RemoteIpAddress.ToString();
        var ip = _accessor.ActionContext.HttpContext.Connection.RemoteIpAddress.ToString();
        return ip;

    }
</code>```

After trying many methods, we can't get the IP address of the client. The result is：

::1

答:
If you're developing locally with localhost, this is normal and you should be able to get the IP address you're looking for when you publish to production (it's probably worth testing at staging first).

If you're wondering why, it's to do with the loopback address, take a look here for more information.

Body:
How to get in ASP.NET Core 3.0 API the client API

On the start up class I have added this line:

services.AddControllersWithViews();
services.AddSingleton <IActionContextAccessor,ActionContextAccessor>();

IndexController.cs

    private readonly IActionContextAccessor _accessor;
    public IndexController(IActionContextAccessor accessor)
    {
            _accessor = accessor;
    }

    [HttpGet()]
    [Route("[action]")]
    public string GetIPAddress(string id)
    {
        //var ip = HttpContext.Connection.RemoteIpAddress.ToString();
        var ip = _accessor.ActionContext.HttpContext.Connection.RemoteIpAddress.ToString();
        return ip;

    }

After trying many methods, we can't get the IP address of the client. The result is：

::1


问:
Xcode Sqlite Encoding Turkish characters
We have records like 'GÜLHAN', 'Yılan', 'çekiç' in our Sqlite database.

These words include Turkish characters and the problem is that we can not read these words correctly, for example; we read 'GEDf∞k' instead of 'GEDİK'.

How can we solve this sqlite reading problem in xcode?

答:
What encoding did you use to store data in DB? Should not be any problems if it's UTF8.

```<code>char *data = (char *) sqlite3_column_text (stmt, 1);
NSString *string = [NSString stringWithUTF8String:data];
</code>```

If this gives you unexpected results, then it's not UTF8 and it's probably a good idea to re-encode everything in DB to UTF8 first.

Body:
What encoding did you use to store data in DB? Should not be any problems if it's UTF8.

char *data = (char *) sqlite3_column_text (stmt, 1);
NSString *string = [NSString stringWithUTF8String:data];

If this gives you unexpected results, then it's not UTF8 and it's probably a good idea to re-encode everything in DB to UTF8 first.


答:
A roundabout way of doing it</p>

```<code>tmp=as.numeric(lapply(strsplit(as.character(df$Time),"\\."),function(x){nchar(x[1])}))
ifelse(tmp>2,
       substr(as.POSIXct(df$Time,format="%H%M.%S"),12,19),
       substr(as.POSIXct(df$Time,format="%M.%S"),12,19))
</code>```

Title: How can I get my time strings in a right format?

Body:
I am stuck with converting strings to times. I am aware that there are many topics on Stack regarding converting strings-to-times, however I couldn't fix this problem with the solutions.

Situation
I have a file with times like this:

> dput(df$Time[1:50])
c("1744.3", "2327.54", "1718.51", "2312.3200000000002", "1414.16",
"2046.15", "1442.5", "1912.22", "2303.2199999999998", "2146.3200000000002",
"1459.02", "1930.15", "1856.23", "2319.15", "1451.05", "25.460000000000036",
"1453.25", "2309.02", "2342.48", "2322.5300000000002", "2101.5",
"2026.07", "1245.04", "1945.15", "5.4099999999998545", "1039.5",
"1731.37", "2058.41", "2030.36", "1814.31", "1338.18", "1858.33",
"1731.36", "2343.38", "1733.27", "2304.59", "1309.47", "1916.11",
"1958.3", "1929.54", "1756.4", "1744.23", "1731.26", "1844.47",
"1353.25", "1958.3", "1746.44", "1857.53", "2047.15", "2327.2199999999998", "1915"
)

In this example, the times should be like this:

"1744.3"   = 17:44:30
"2327.54"  = 23:27:54
"1718.51"  = 17:18:51
"2312.3200000000002" = 23:12:32
...
"25.460000000000036" = 00:25:46 # as you can see, the first two 00 are missing.

"1915" = 19:15:00

However, I tried multiple things (and now I am even stuck with str_replace()). Hopefully some one knows how I can transform this.

What have I tried?

format(df$Time, "%H%M.%S") # Yes I know...

# So therefore I thought, lets replace the strings to get them in a proper format
# like HH:MM:SS. First step was to replace the "." for a ":"

str_replace("." , ":", df$Time) # this was leading to "." (don't know why)

And that was the point that I was so frustrated that I posted it on Stack. Hope that you guys can help me.

Many thanks in advance!

Body:
A roundabout way of doing it

tmp=as.numeric(lapply(strsplit(as.character(df$Time),"\\."),function(x){nchar(x[1])}))
ifelse(tmp>2,
       substr(as.POSIXct(df$Time,format="%H%M.%S"),12,19),
       substr(as.POSIXct(df$Time,format="%M.%S"),12,19))


问:
How to detect emotions with Azure API?
I'd like to create a simple Python app recognizing face emotions from given URL via Azure Face/Emotions API.
I'm following this documentation:

https://learn.microsoft.com/en-us/azure/cognitive-services/face/quickstarts/python-sdk#authenticate-the-client

https://learn.microsoft.com/en-us/python/api/azure-cognitiveservices-vision-face/azure.cognitiveservices.vision.face.models.emotion?view=azure-python

So, far, I did the face recognition part, but I'm kinda stuck how to call the Emotion model and display results.

```<code>import urllib.request
from azure.cognitiveservices.vision.face import FaceClient
from azure.cognitiveservices.vision.face.models import Emotion
from msrest.authentication import CognitiveServicesCredentials

# Image
URL = "https://upload.wikimedia.org/wikipedia/commons/5/55/Dalailama1_20121014_4639.jpg"

# API
KEY = "xxx"
ENDPOINT = "https://happyai.cognitiveservices.azure.com/"

# Now there is a trained endpoint that can be used to make a prediction
predictor = FaceClient(ENDPOINT, CognitiveServicesCredentials(KEY))

detected_faces = predictor.face.detect_with_url(url=URL)
if not detected_faces:
    raise Exception('No face detected from image {}'.format(URL))

# Display the detected face ID in the first single-face image.
# Face IDs are used for comparison to faces (their IDs) detected in other images.
print('Detected face ID from', URL, ':')
for face in detected_faces: print (face.face_id)
print()

# Save this ID for use in Find Similar
first_image_face_ID = detected_faces[0].face_id

# Call Emotion model

# Display the results.
</code>```

Any help would be greatly appreciated.
Thanks!

答:
You can use the following code to do the emotion detection,</p>

```<code>def det_emotion(self, frame, count):

        image_path = self.path_folder + "/img/frame%d.jpg" % count
        image_data = open(image_path, "rb")

        params = {
            'returnFaceId': 'true',
            'returnFaceLandmarks': 'false',
            'returnRecognitionModel':'false',
        }

        response = requests.post(self.face_api_url, params=params,data=image_data)
        response.raise_for_status()
        faces = response.json()
        frame = self.add_square(frame, faces)

        return frame
</code>```

Title: How to detect emotions with Azure API?

Body:
I'd like to create a simple Python app recognizing face emotions from given URL via Azure Face/Emotions API.
I'm following this documentation:

https://learn.microsoft.com/en-us/azure/cognitive-services/face/quickstarts/python-sdk#authenticate-the-client

https://learn.microsoft.com/en-us/python/api/azure-cognitiveservices-vision-face/azure.cognitiveservices.vision.face.models.emotion?view=azure-python

So, far, I did the face recognition part, but I'm kinda stuck how to call the Emotion model and display results.

import urllib.request
from azure.cognitiveservices.vision.face import FaceClient
from azure.cognitiveservices.vision.face.models import Emotion
from msrest.authentication import CognitiveServicesCredentials

# Image
URL = "https://upload.wikimedia.org/wikipedia/commons/5/55/Dalailama1_20121014_4639.jpg"

# API
KEY = "xxx"
ENDPOINT = "https://happyai.cognitiveservices.azure.com/"

# Now there is a trained endpoint that can be used to make a prediction
predictor = FaceClient(ENDPOINT, CognitiveServicesCredentials(KEY))

detected_faces = predictor.face.detect_with_url(url=URL)
if not detected_faces:
    raise Exception('No face detected from image {}'.format(URL))

# Display the detected face ID in the first single-face image.
# Face IDs are used for comparison to faces (their IDs) detected in other images.
print('Detected face ID from', URL, ':')
for face in detected_faces: print (face.face_id)
print()

# Save this ID for use in Find Similar
first_image_face_ID = detected_faces[0].face_id

# Call Emotion model

# Display the results.

Any help would be greatly appreciated.
Thanks!

Body:
You can use the following code to do the emotion detection,

def det_emotion(self, frame, count):

        image_path = self.path_folder + "/img/frame%d.jpg" % count
        image_data = open(image_path, "rb")

        params = {
            'returnFaceId': 'true',
            'returnFaceLandmarks': 'false',
            'returnRecognitionModel':'false',
        }

        response = requests.post(self.face_api_url, params=params,data=image_data)
        response.raise_for_status()
        faces = response.json()
        frame = self.add_square(frame, faces)

        return frame


问:
How to get the qualified name of the currently executing function?
Python 3.3 introduced the __qualname__ attribute for function objects and class objects.

It's easy to get the (unqualified) name and a code object for the currently executing function.

But how to get the qualified name for the currently executing function?

答:
You can use executing:

```<code>executing.Source.for_frame(frame).code_qualname(frame.f_code)
</code>```

Body:
You can use executing:

executing.Source.for_frame(frame).code_qualname(frame.f_code)


问:
Programmatically click a button in Xamarin.Forms
I have 2 buttons on a xamarin form,

scannerButton and checkOrderButton

scannerButton opens the scanner page, scans a QRCode and populates it into a order entry field

checkOrderButton reads whatever is in the order entry field and processes validations and sends it to server for verification

what I want - is to call the checkOrderButton.Click from within the scannerButton.Click - after it has scanned the text

code:

```<code>private async void scanCameraButton_Clicked(object sender, EventArgs e)
{
    var options = new ZXing.Mobile.MobileBarcodeScanningOptions();
    options.PossibleFormats = new List<ZXing.BarcodeFormat>() {
        ZXing.BarcodeFormat.QR_CODE,ZXing.BarcodeFormat.EAN_8, ZXing.BarcodeFormat.EAN_13
    };

    var scanPage = new ZXingScannerPage(options);
    scanPage.OnScanResult += (result) =>
    {
        //stop scan
        scanPage.IsScanning = false;

        Device.BeginInvokeOnMainThread(() =>
        {
            //pop the page and get the result
            Navigation.PopAsync();
            orderNoEntry.Text = result.Text;
        });

            //invoke checkOrderButton.Click here

    };
</code>```

what would be the best approach to do this?

one alternate is to dump all the functionality from checkOrderButton.Click handler into a function and then call that function from both button clicks, but I'm interested in learning how I can invoke the click event programmatically

答:
I wrote an extension method for this purposes. This not only works in Xamarin-Forms-projects but also in WPF projects.</p>

```<code>using System;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
#if !NETSTANDARD
using System.Windows.Controls;
#else
using Xamarin.Forms;
#endif

public static class ButtonExtensions
{
    public static void PerformClick(this Button sourceButton)
    {
        // Check parameters
        if (sourceButton == null)
            throw new ArgumentNullException(nameof(sourceButton));

        // 1.) Raise the Click-event
#if !NETSTANDARD
        sourceButton.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));
#else
        sourceButton.RaiseEventViaReflection(nameof(sourceButton.Clicked), EventArgs.Empty);
#endif

        // 2.) Execute the command, if bound and can be executed
        ICommand boundCommand = sourceButton.Command;
        if (boundCommand != null)
        {
            object parameter = sourceButton.CommandParameter;
            if (boundCommand.CanExecute(parameter) == true)
                boundCommand.Execute(parameter);
        }
    }

#if NETSTD
    private static void RaiseEventViaReflection<TEventArgs>(this object source, string eventName, TEventArgs eventArgs) where TEventArgs : EventArgs
    {
        var eventDelegate = (MulticastDelegate)source.GetType().GetField(eventName, BindingFlags.Instance | BindingFlags.NonPublic).GetValue(source);
        if (eventDelegate == null)
            return;
        foreach (var handler in eventDelegate.GetInvocationList())
        {
#if !(NETSTANDARD1_6 || NETSTANDARD1_5 || NETSTANDARD1_4 || NETSTANDARD1_3 || NETSTANDARD1_2 || NETSTANDARD1_1 || NETSTANDARD1_0)
            handler.Method?.Invoke(handler.Target, new object[] { source, eventArgs });
#else
            handler.GetMethodInfo()?.Invoke(handler.Target, new object[] { source, eventArgs });
#endif
        }
    }
#endif
}
</code>```

Body:
I have 2 buttons on a xamarin form,

scannerButton and checkOrderButton

scannerButton opens the scanner page, scans a QRCode and populates it into a order entry field

checkOrderButton reads whatever is in the order entry field and processes validations and sends it to server for verification

what I want - is to call the checkOrderButton.Click from within the scannerButton.Click - after it has scanned the text

code:

private async void scanCameraButton_Clicked(object sender, EventArgs e)
{
    var options = new ZXing.Mobile.MobileBarcodeScanningOptions();
    options.PossibleFormats = new List<ZXing.BarcodeFormat>() {
        ZXing.BarcodeFormat.QR_CODE,ZXing.BarcodeFormat.EAN_8, ZXing.BarcodeFormat.EAN_13
    };

    var scanPage = new ZXingScannerPage(options);
    scanPage.OnScanResult += (result) =>
    {
        //stop scan
        scanPage.IsScanning = false;

        Device.BeginInvokeOnMainThread(() =>
        {
            //pop the page and get the result
            Navigation.PopAsync();
            orderNoEntry.Text = result.Text;
        });

            //invoke checkOrderButton.Click here

    };

what would be the best approach to do this?

one alternate is to dump all the functionality from checkOrderButton.Click handler into a function and then call that function from both button clicks, but I'm interested in learning how I can invoke the click event programmatically

Body:
I wrote an extension method for this purposes. This not only works in Xamarin-Forms-projects but also in WPF projects.

using System;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
#if !NETSTANDARD
using System.Windows.Controls;
#else
using Xamarin.Forms;
#endif

public static class ButtonExtensions
{
    public static void PerformClick(this Button sourceButton)
    {
        // Check parameters
        if (sourceButton == null)
            throw new ArgumentNullException(nameof(sourceButton));

        // 1.) Raise the Click-event
#if !NETSTANDARD
        sourceButton.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));
#else
        sourceButton.RaiseEventViaReflection(nameof(sourceButton.Clicked), EventArgs.Empty);
#endif

        // 2.) Execute the command, if bound and can be executed
        ICommand boundCommand = sourceButton.Command;
        if (boundCommand != null)
        {
            object parameter = sourceButton.CommandParameter;
            if (boundCommand.CanExecute(parameter) == true)
                boundCommand.Execute(parameter);
        }
    }

#if NETSTD
    private static void RaiseEventViaReflection<TEventArgs>(this object source, string eventName, TEventArgs eventArgs) where TEventArgs : EventArgs
    {
        var eventDelegate = (MulticastDelegate)source.GetType().GetField(eventName, BindingFlags.Instance | BindingFlags.NonPublic).GetValue(source);
        if (eventDelegate == null)
            return;
        foreach (var handler in eventDelegate.GetInvocationList())
        {
#if !(NETSTANDARD1_6 || NETSTANDARD1_5 || NETSTANDARD1_4 || NETSTANDARD1_3 || NETSTANDARD1_2 || NETSTANDARD1_1 || NETSTANDARD1_0)
            handler.Method?.Invoke(handler.Target, new object[] { source, eventArgs });
#else
            handler.GetMethodInfo()?.Invoke(handler.Target, new object[] { source, eventArgs });
#endif
        }
    }
#endif
}


问:
Array of objects how do i check for deeply nested text string duplicates & remove from array?
I have an array of objects
Deep inside those objects is a text string
I want to check if other objects in the same array have the same text string / are duplicates.
Then i need a new array with those duplicates removed.

I thought this would be quite simple but it's been testing my intellect for two days now.

```<code>const arr = [
   {..obj 1}
   {..obj 2}
   {..obj 3}
   {
      id: 4,
      uid: 24872-2847-249249892842,
      tags: ['some', 'stuff'],
      type: "blogpage",
      href: "https://link-to-stuff",
      first_publication_date: "2020-02-12T16:05:04+0000",
      last_publication_date: "2020-02-18T21:52:06+0000",
      data: {
            ...some stuff
                  heading: [
                        { type: "heading1", text: "Here Is My Text I Need To Check Duplicates
                   Of"}
                  ]
      }

   }
   {..obj 5}
   {..obj 6}
   {..obj 7}
   {..obj 8}
   {..obj 9}
   {..obj 10}
]

I figured something like:

</code>```

filterOutDuplicates = (blogIndexContent) => {

```<code>let arr = blogIndexContent.pages;

let results = [];

arr.map(each => {
  if (!results || !results.length) {
    results.push(each);
  } else {
    for (let i = 0; i < results.length; i++) {
      const headline = results[i].data.heading[0].text;
      if (headline === each.data.heading[0].text) {
        return;
      } else {
        return results.push(each);
      }
    }
  }
})

console.log('Results :', results); // <-- this just gives me the same 9 blog stories again, no duplicates removed.
</code>```

}

```<code>
What am i doing wrong guys?
</code>```

答:
Try this</p>

```<code>const arr = [
  {
    id: 4,
    data: {
      heading: [
        {
          type: "heading1",
          text: "Here Is My Text I Need To Check Duplicates Of"
        }
      ]
    }
  },
  {
    id: 5,
    data: {
      heading: [
        {
          type: "heading1",
          text: "Here Is My Text I Need To Check Duplicates Of"
        }
      ]
    }
  },
  {
    id: 6,
    data: {
      heading: [
        {
          type: "heading1",
          text: "Not Duplicates"
        }
      ]
    }
  }
];

const withoutDuplicates = arr.reduce(
  (prev, curr) =>
    prev
      .map(d => d["data"]["heading"][0]["text"])
      .includes(curr["data"]["heading"][0]["text"])
      ? [curr]
      : [...prev, curr],
  []
);
console.log(withoutDuplicates);

</code>```

Body:
I have an array of objects
Deep inside those objects is a text string
I want to check if other objects in the same array have the same text string / are duplicates.
Then i need a new array with those duplicates removed.

I thought this would be quite simple but it's been testing my intellect for two days now.

const arr = [
   {..obj 1}
   {..obj 2}
   {..obj 3}
   {
      id: 4,
      uid: 24872-2847-249249892842,
      tags: ['some', 'stuff'],
      type: "blogpage",
      href: "https://link-to-stuff",
      first_publication_date: "2020-02-12T16:05:04+0000",
      last_publication_date: "2020-02-18T21:52:06+0000",
      data: {
            ...some stuff
                  heading: [
                        { type: "heading1", text: "Here Is My Text I Need To Check Duplicates
                   Of"}
                  ]
      }

   }
   {..obj 5}
   {..obj 6}
   {..obj 7}
   {..obj 8}
   {..obj 9}
   {..obj 10}
]

I figured something like:

filterOutDuplicates = (blogIndexContent) => {

let arr = blogIndexContent.pages;

let results = [];

arr.map(each => {
  if (!results || !results.length) {
    results.push(each);
  } else {
    for (let i = 0; i < results.length; i++) {
      const headline = results[i].data.heading[0].text;
      if (headline === each.data.heading[0].text) {
        return;
      } else {
        return results.push(each);
      }
    }
  }
})

console.log('Results :', results); // <-- this just gives me the same 9 blog stories again, no duplicates removed.

}

What am i doing wrong guys?

Body:
Try this

const arr = [
  {
    id: 4,
    data: {
      heading: [
        {
          type: "heading1",
          text: "Here Is My Text I Need To Check Duplicates Of"
        }
      ]
    }
  },
  {
    id: 5,
    data: {
      heading: [
        {
          type: "heading1",
          text: "Here Is My Text I Need To Check Duplicates Of"
        }
      ]
    }
  },
  {
    id: 6,
    data: {
      heading: [
        {
          type: "heading1",
          text: "Not Duplicates"
        }
      ]
    }
  }
];

const withoutDuplicates = arr.reduce(
  (prev, curr) =>
    prev
      .map(d => d["data"]["heading"][0]["text"])
      .includes(curr["data"]["heading"][0]["text"])
      ? [curr]
      : [...prev, curr],
  []
);
console.log(withoutDuplicates);


问:
Rails - How to set 1 scss file for 1 view
I can't figure out how make certain .scss files work with certain views.  I removed the *= require_tree . from the application.css.scss but I'm not sure where to go from there.  The stylesheet_link_tag doesn't seem to recognize .scss files.  What tag can I use to import .scss files to views?

I also tried creating a different controller for the different view but after I removed the require_tree the controller doesn't use the .scss file that was automatically generated with it.

答:
if the scss file is in the root of the asset folder then

add line to your view file

```<code>=stylesheet_link_tag 'your_scss_file_name'
</code>```

in \config\initializers\assets.rb

add this line

```<code>Rails.application.config.assets.precompile + =% w (your_scss_file_name.css)
</code>```

Body:
if the scss file is in the root of the asset folder then

add line to your view file

=stylesheet_link_tag 'your_scss_file_name'

in \config\initializers\assets.rb

add this line

Rails.application.config.assets.precompile + =% w (your_scss_file_name.css)


问:
How to join table to itself when it references to itself
I have table which have two columns which references to itself.

```<code>select * from cgroups;
+----+--------------+-------------+-----------+----------+----------+
| id | title        | description | cunixperm | cgroup_1 | cgroup_2 |
+----+--------------+-------------+-----------+----------+----------+
| 1  | admin        | <null>      | 32        | 1        | <null>   |
| 2  | tag_mng      | <null>      | 32        | 1        | <null>   |
| 3  | tags         | <null>      | 32        | 1        | <null>   |
| 4  | exam_mng     | <null>      | 32        | 1        | <null>   |
| 5  | exam_writer  | <null>      | 32        | 1        | <null>   |
| 6  | exam_viewer  | <null>      | 32        | 1        | <null>   |
| 7  | exam_starter | <null>      | 32        | 1        | <null>   |
+----+--------------+-------------+-----------+----------+----------+
</code>```

here is its code:-

```<code>create table cgroups
(
    id int unsigned primary key auto_increment,
    title varchar(100) not null unique,
    description varchar(255),

    cunixperm  tinyint unsigned not null default 32 ,# r=2 w=1
    cgroup_1   int unsigned not null default 1 references cgroups (id) on delete cascade on update cascade,
    cgroup_2   int unsigned references cgroups (id) on delete cascade on update cascade

);
</code>```

I want to create views in which cgroup_1 column is replaced with actual title of of c_group

something like this:- http://sqlfiddle.com/#!9/7af382/1

```<code>select c.id, c.title, c.description, c.cunixperm, c1.title cgroup_1 from cgroups c , cgroups c1
                             where c.cgroup_1 = c1.id;
+----+--------------+-------------+-----------+----------+
| id | title        | description | cunixperm | cgroup_1 |
+----+--------------+-------------+-----------+----------+
| 1  | admin        | <null>      | 32        | admin    |
| 2  | tag_mng      | <null>      | 32        | admin    |
| 3  | tags         | <null>      | 32        | admin    |
| 4  | exam_mng     | <null>      | 32        | admin    |
| 5  | exam_writer  | <null>      | 32        | admin    |
| 6  | exam_viewer  | <null>      | 32        | admin    |
| 7  | exam_starter | <null>      | 32        | admin    |
+----+--------------+-------------+-----------+----------+
</code>```

problem with this approach is that it only works with 1 refereed column while I have two ( 8 in some other tables)

if I do following ,

```<code>select c.id, c.title, c.description, c.cunixperm, c1.title, c2.title
from cgroups c , cgroups c1, cgroups c2
where c.cgroup_1 = c1.id and c.cgroup_2 = c2.id;
</code>```

I get zero rows.http://sqlfiddle.com/#!9/7af382/4

答:
Using your fiddle seems work; anyway you should use explicit join syntax:

```<code>select c.id, c.title, c.description, c.cunixperm, c1.title, c.cgroup_1
from cgroups c
INNER JOIN cgroups c1  ON c.cgroup_1 = c1.id;
</code>```

http://sqlfiddle.com/#!9/7af382/3

and for two join

```<code>select c.id, c.title, c.description, c.cunixperm, c1.title, c.cgroup_1 , c2.title cgroup_2
from cgroups c
INNER JOIN cgroups c1  ON c.cgroup_1 = c1.id
INNER JOIN cgroups c2  ON c.cgroup_2 = c2.id
</code>```

Body:
I have table which have two columns which references to itself.

select * from cgroups;
+----+--------------+-------------+-----------+----------+----------+
| id | title        | description | cunixperm | cgroup_1 | cgroup_2 |
+----+--------------+-------------+-----------+----------+----------+
| 1  | admin        | <null>      | 32        | 1        | <null>   |
| 2  | tag_mng      | <null>      | 32        | 1        | <null>   |
| 3  | tags         | <null>      | 32        | 1        | <null>   |
| 4  | exam_mng     | <null>      | 32        | 1        | <null>   |
| 5  | exam_writer  | <null>      | 32        | 1        | <null>   |
| 6  | exam_viewer  | <null>      | 32        | 1        | <null>   |
| 7  | exam_starter | <null>      | 32        | 1        | <null>   |
+----+--------------+-------------+-----------+----------+----------+

here is its code:-

create table cgroups
(
    id int unsigned primary key auto_increment,
    title varchar(100) not null unique,
    description varchar(255),

    cunixperm  tinyint unsigned not null default 32 ,# r=2 w=1
    cgroup_1   int unsigned not null default 1 references cgroups (id) on delete cascade on update cascade,
    cgroup_2   int unsigned references cgroups (id) on delete cascade on update cascade

);

I want to create views in which cgroup_1 column is replaced with actual title of of c_group

something like this:- http://sqlfiddle.com/#!9/7af382/1

select c.id, c.title, c.description, c.cunixperm, c1.title cgroup_1 from cgroups c , cgroups c1
                             where c.cgroup_1 = c1.id;
+----+--------------+-------------+-----------+----------+
| id | title        | description | cunixperm | cgroup_1 |
+----+--------------+-------------+-----------+----------+
| 1  | admin        | <null>      | 32        | admin    |
| 2  | tag_mng      | <null>      | 32        | admin    |
| 3  | tags         | <null>      | 32        | admin    |
| 4  | exam_mng     | <null>      | 32        | admin    |
| 5  | exam_writer  | <null>      | 32        | admin    |
| 6  | exam_viewer  | <null>      | 32        | admin    |
| 7  | exam_starter | <null>      | 32        | admin    |
+----+--------------+-------------+-----------+----------+

problem with this approach is that it only works with 1 refereed column while I have two ( 8 in some other tables)

if I do following ,

select c.id, c.title, c.description, c.cunixperm, c1.title, c2.title
from cgroups c , cgroups c1, cgroups c2
where c.cgroup_1 = c1.id and c.cgroup_2 = c2.id;

I get zero rows.http://sqlfiddle.com/#!9/7af382/4

Body:
Using your fiddle seems work; anyway you should use explicit join syntax:

select c.id, c.title, c.description, c.cunixperm, c1.title, c.cgroup_1
from cgroups c
INNER JOIN cgroups c1  ON c.cgroup_1 = c1.id;

http://sqlfiddle.com/#!9/7af382/3

and for two join

select c.id, c.title, c.description, c.cunixperm, c1.title, c.cgroup_1 , c2.title cgroup_2
from cgroups c
INNER JOIN cgroups c1  ON c.cgroup_1 = c1.id
INNER JOIN cgroups c2  ON c.cgroup_2 = c2.id


问:
How to prevent CSS from displaying the ::after content on a new line?
I'm trying to display a list of names, separated by a comma, using CSS:

a:after {
  content: ', \00a0';
  display: inline-block;
  text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Foo
Bar</code>```

The problem is that the result looks something like this:

```<code>Foo, Baz
, Bar
</code>```

答:
You only need to add some css properties to you a:after and a like shown bellow  :</p>

```<code>a{
  margin-right: 5px;
  text-decoration: underline
}
a:after {
    content: ',';
    display: inline-block;
}
</code>```

Body:
I'm trying to display a list of names, separated by a comma, using CSS:

a:after {
  content: ', \00a0';
  display: inline-block;
  text-decoration: none;
}

Foo
Bar

The problem is that the result looks something like this:

Foo, Baz
, Bar

Body:
You only need to add some css properties to you a:after and a like shown bellow  :

a{
  margin-right: 5px;
  text-decoration: underline
}
a:after {
    content: ',';
    display: inline-block;
}


问:
How do I make the Kotlin compiler treat warnings as errors?
I have a Kotlin project where I'd like to have Kotlin warnings treated as errors. How can I do that?</p>

答:
With the Kotlin DSL:</p>

```<code>tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
    kotlinOptions {
        kotlinOptions.allWarningsAsErrors = true
    }
}
</code>```

Body:
With the Kotlin DSL:

tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
    kotlinOptions {
        kotlinOptions.allWarningsAsErrors = true
    }
}


问:
python mechanize to access Sharepoint website
I'm trying to access Sharepoint using mechanize but i got a 401 error. Here's the code i'm using:

```<code>import mechanize

url = "http://sharepoint:8080/foo/bar/foobar.aspx"

br.addheaders = [('User-agent', 'Mozilla/4.0(compatible; MSIE 7.0b; Windows NT 6.0)')]
br.add_password(url, 'domain\\user', 'myPassword')
r = br.open(url)
html = r.read()
</code>```

Did i miss anything?

答:
Did you happen to try Python Ntlm for accessing SharePoint?

Examples in the Ntlm doc will explain how to use it with Urllib2. Pasted below the code for using NTLM authentication using mechanize.

```<code>import mechanize
from ntlm import HTTPNtlmAuthHandler
pass_manager = mechanize.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, user, password)
auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(pass_manager)

browser = mechanize.Browser()
browser.add_handler(auth_NTLM)

r = browser.open(url)
html = r.read()
</code>```

Body:
I'm trying to access Sharepoint using mechanize but i got a 401 error. Here's the code i'm using:

import mechanize

url = "http://sharepoint:8080/foo/bar/foobar.aspx"

br.addheaders = [('User-agent', 'Mozilla/4.0(compatible; MSIE 7.0b; Windows NT 6.0)')]
br.add_password(url, 'domain\\user', 'myPassword')
r = br.open(url)
html = r.read()

Did i miss anything?

Body:
Did you happen to try Python Ntlm for accessing SharePoint?

Examples in the Ntlm doc will explain how to use it with Urllib2. Pasted below the code for using NTLM authentication using mechanize.

import mechanize
from ntlm import HTTPNtlmAuthHandler
pass_manager = mechanize.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, user, password)
auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(pass_manager)

browser = mechanize.Browser()
browser.add_handler(auth_NTLM)

r = browser.open(url)
html = r.read()


问:
Why django can be tested without running server?
I want to test the reachability of home page of a demo app.

So I do this:

from django.test import TestCase

class TestHomePageView(TestCase):
    def test_reachable_home(self):
        response = self.client.get('/home/')
        self.assertEqual(response.status_code, 200)
```

<p>and the <code>views.py</code></p>

<pre class="lang-py prettyprint-override"><code>from django.shortcuts import render

def home_view(request):
    return render(request, 'home.html', {})
</code>```

home.html is a simple one:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Home</title>

    Hi, circleci and django

```

<p>and <code>urls.py</code>:</p>

<pre class="lang-py prettyprint-override"><code>from django.contrib import admin
from django.urls import path

from demo_app.views import home_view

urlpatterns = [
    path('admin/', admin.site.urls),
    path('home/', home_view)
]

</code>```

It's a really simple demo app.

What I am curious is "Why I can test the status code without running django server?"
Just simply $ python manage.py test without $ python manage.py runserver

and get the test result:

```<code>$ python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.
----------------------------------------------------------------------
Ran 1 test in 0.011s

OK
Destroying test database for alias 'default'...
</code>```

Any idea or suggestion is welcome, thanks.

答:
Testing allows you to modify your code with more confidence: tests are ok, you modify your code, if tests are still ok, then, you didn't break anything.

Thus, you want to be able to execute your tests often and fast, so you can modify your code more easily, with more confidence.

Framworks and languages provide means of testing that are the lighter possible, so tests are more flexible and runs faster.

Also, you want to test your code, not others, if your tests runs through http, you also test your http server.

Moreover, HTTP, is a transport protocol, we don't need a transport protocol to provide arguments to functions, to check it behaves as intended.

To sum up, you want to be able to run your test often, the fastest it is, the more you are able to run your tests, plus, you want to test only your code, not the code of your webserver.

Body:
I want to test the reachability of home page of a demo app.

So I do this:

from django.test import TestCase

class TestHomePageView(TestCase):
    def test_reachable_home(self):
        response = self.client.get('/home/')
        self.assertEqual(response.status_code, 200)

and the views.py

from django.shortcuts import render

def home_view(request):
    return render(request, 'home.html', {})

home.html is a simple one:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Home</title>

    Hi, circleci and django

and urls.py:

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

from demo_app.views import home_view

urlpatterns = [
    path('admin/', admin.site.urls),
    path('home/', home_view)
]

It's a really simple demo app.

What I am curious is "Why I can test the status code without running django server?"
Just simply $ python manage.py test without $ python manage.py runserver

and get the test result:

$ python manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.
----------------------------------------------------------------------
Ran 1 test in 0.011s

OK
Destroying test database for alias 'default'...

Any idea or suggestion is welcome, thanks.


问:
how to use DrawText() to write text in a given window whose handle is known?
I want to know how to write text on a particular window starting at a given location in the window using the Windows API.

For example if the coordinates within the window where the text is to be written are (x,y) = (40,10) then what do I need to do to write a line of text to a particular window at that location in the window?

答:
I am hoping this a more complete answer...

```<code>void OnPaint(HWND hWnd)
{
    RECT  rect;
    PAINTSTRUCT ps;
    HDC hdc = BeginPaint(hWnd, &ps);

    GetClientRect(hWnd, &rect);
    SetTextColor(hdc, RGB(0xFF, 0x00, 0x00));
    SetBkMode(hdc, TRANSPARENT);
    rect.left = 40;
    rect.top = 10;
    DrawText(hdc, L"Hello World!", -1, &rect, DT_SINGLELINE | DT_NOCLIP);
    SelectObject(hdc, oldPen);
    DeleteObject(hPen);
    EndPaint(hWnd, &ps);
}
</code>```

This would then be called from the WM_PAINT message in the WndProc.

OwnerDisplayName: Vicky

Body:
I am hoping this a more complete answer...

void OnPaint(HWND hWnd)
{
    RECT  rect;
    PAINTSTRUCT ps;
    HDC hdc = BeginPaint(hWnd, &ps);

    GetClientRect(hWnd, &rect);
    SetTextColor(hdc, RGB(0xFF, 0x00, 0x00));
    SetBkMode(hdc, TRANSPARENT);
    rect.left = 40;
    rect.top = 10;
    DrawText(hdc, L"Hello World!", -1, &rect, DT_SINGLELINE | DT_NOCLIP);
    SelectObject(hdc, oldPen);
    DeleteObject(hPen);
    EndPaint(hWnd, &ps);
}

This would then be called from the WM_PAINT message in the WndProc.


问:
why my Tensorflow CNN's accuracy is zero while loss is not?
i am trying to make twin CNN,
my database has two inputs that finally merge together and a single neuron as output of IC50.

when i'm trying to do so, i get 0 accuracy while the loss is ok.
am i using the wrong loss function? it is currently mean_squared_error

OS: Windows10
tensorflow version:2.3.0

my code"

```<code>encoded_drugs=np.load('encoded_drugs.npy')
encoded_cells=np.load('encoded_cells.npy')
encoded_ICs=np.load('encoded_ICs.npy')
encoded_drugs_train, encoded_drugs_test,encoded_cells_train, encoded_cells_test, encoded_ICs_train, encoded_ICs_test = train_test_split(encoded_drugs,encoded_cells, encoded_ICs, test_size=0.2)

input1=keras.layers.Input(shape=(139,32,))
x1=keras.layers.Flatten(input_shape=(139,32,))(input1)
x2=keras.layers.Dense(64,activation='relu')(x1)
x3=keras.layers.Dense(64,activation='relu')(x2)

input2=keras.layers.Input(shape=(735,2,))
y1=keras.layers.Flatten(input_shape=(735,2,))(input2)
y2=keras.layers.Dense(128,activation='relu')(y1)
y3=keras.layers.Dense(64,activation='relu')(y2)

merged=keras.layers.concatenate([x3,y3],axis=-1)

z=keras.layers.Dense(64,activation='relu')(merged)
out=keras.layers.Dense(1,activation='sigmoid')(z)

model=keras.models.Model(inputs=[input1,input2], outputs=out)

model.compile(optimizer='sgd',loss='mean_squared_error',metrics=['accuracy'])

model.fit([encoded_drugs_train,encoded_cells_train],encoded_ICs_train,validation_split = 0.2,epochs=2)

test_loss, test_accuracy= model.evaluate([encoded_drugs_test,encoded_cells_test],encoded_ICs_test)

print('Accuracy=', test_accuracy)
</code>```

my output:

```<code>2020-02-18 11:06:00.759824: I tensorflow/core/platform/cpu_feature_guard.cc:145] This TensorFlow binary is optimized with Intel(R) MKL-DNN to use the following CPU instructions in performance critical operations:  AVX AVX2
To enable them in non-MKL-DNN operations, rebuild TensorFlow with the appropriate compiler flags.
2020-02-18 11:06:00.774869: I tensorflow/core/common_runtime/process_util.cc:115] Creating new thread pool with default inter op setting: 4. Tune using inter_op_parallelism_threads for best performance.
Train on 75793 samples, validate on 18949 samples
Epoch 1/2
75793/75793 [==============================] - 17s 229us/sample - loss: 10.3671 - accuracy: 0.0000e+00 - val_loss: 10.4082 - val_accuracy: 0.0000e+00
Epoch 2/2
75793/75793 [==============================] - 11s 146us/sample - loss: 10.2673 - accuracy: 0.0000e+00 - val_loss: 10.3852 - val_accuracy: 0.0000e+00

3s 125us/sample - loss: 8.3239 - accuracy: 0.0000e+00
Accuracy= 0.0
</code>```

答:
You are trying to solve a regression problem(using the mean_squared_error loss) while using the accuracy as a metric. In such a case, the accuracy is not a valid metric.

First of all, ensure that the problem you are trying to solve is indeed a regression or a classification one.

In case of the regression, use Dense(1,activation='linear') as the last output layer, and model.compile(optimizer='sgd',loss='mean_squared_error',metrics=['mse']).

In case of the classification, use Dense(1,activation='sigmoid') as the last output layers, and model.compile(optimizer='sgd',loss='binary_crossentropy',metrics=['accuracy']).

Second of all, you need to train for more epochs(29 seconds is really not enough to provide a good overview on your results).

Body:
i am trying to make twin CNN,
my database has two inputs that finally merge together and a single neuron as output of IC50.

when i'm trying to do so, i get 0 accuracy while the loss is ok.
am i using the wrong loss function? it is currently mean_squared_error

OS: Windows10
tensorflow version:2.3.0

my code"

encoded_drugs=np.load('encoded_drugs.npy')
encoded_cells=np.load('encoded_cells.npy')
encoded_ICs=np.load('encoded_ICs.npy')
encoded_drugs_train, encoded_drugs_test,encoded_cells_train, encoded_cells_test, encoded_ICs_train, encoded_ICs_test = train_test_split(encoded_drugs,encoded_cells, encoded_ICs, test_size=0.2)

input1=keras.layers.Input(shape=(139,32,))
x1=keras.layers.Flatten(input_shape=(139,32,))(input1)
x2=keras.layers.Dense(64,activation='relu')(x1)
x3=keras.layers.Dense(64,activation='relu')(x2)

input2=keras.layers.Input(shape=(735,2,))
y1=keras.layers.Flatten(input_shape=(735,2,))(input2)
y2=keras.layers.Dense(128,activation='relu')(y1)
y3=keras.layers.Dense(64,activation='relu')(y2)

merged=keras.layers.concatenate([x3,y3],axis=-1)

z=keras.layers.Dense(64,activation='relu')(merged)
out=keras.layers.Dense(1,activation='sigmoid')(z)

model=keras.models.Model(inputs=[input1,input2], outputs=out)

model.compile(optimizer='sgd',loss='mean_squared_error',metrics=['accuracy'])

model.fit([encoded_drugs_train,encoded_cells_train],encoded_ICs_train,validation_split = 0.2,epochs=2)

test_loss, test_accuracy= model.evaluate([encoded_drugs_test,encoded_cells_test],encoded_ICs_test)

print('Accuracy=', test_accuracy)

my output:

2020-02-18 11:06:00.759824: I tensorflow/core/platform/cpu_feature_guard.cc:145] This TensorFlow binary is optimized with Intel(R) MKL-DNN to use the following CPU instructions in performance critical operations:  AVX AVX2
To enable them in non-MKL-DNN operations, rebuild TensorFlow with the appropriate compiler flags.
2020-02-18 11:06:00.774869: I tensorflow/core/common_runtime/process_util.cc:115] Creating new thread pool with default inter op setting: 4. Tune using inter_op_parallelism_threads for best performance.
Train on 75793 samples, validate on 18949 samples
Epoch 1/2
75793/75793 [==============================] - 17s 229us/sample - loss: 10.3671 - accuracy: 0.0000e+00 - val_loss: 10.4082 - val_accuracy: 0.0000e+00
Epoch 2/2
75793/75793 [==============================] - 11s 146us/sample - loss: 10.2673 - accuracy: 0.0000e+00 - val_loss: 10.3852 - val_accuracy: 0.0000e+00

3s 125us/sample - loss: 8.3239 - accuracy: 0.0000e+00
Accuracy= 0.0


问:
React, unable to display the data received by an api, after doing a GET in componentDidMount()
I have done a function in my react call which calls an api, and sets a state based on the data received by that api

```<code>getUserList() {
    API.get('/userlist')
        .then(response => {
            this.setState({
                userList: response.data
            }, () => {
                console.log(this.state.userList) //I can see this
            });
        })
}
</code>```

This is how my constructor looks

```<code>constructor(props) {
    super(props)
    this.state = {
        retracted: false,
        userList: []

    }
    this.getUserList = this.getUserList.bind(this);
}
</code>```

I call it in componentDidMount()

```<code>componentDidMount() {
    this.getUserList();
}
</code>```

But then my render crashes, because both console.log return undefined

```<code>render() {
    var users = this.state.userList;
    var user = users[0].email //cannot read email of undefined

    console.log(this.state.userList)
    console.log(users)
    return (
        <div class="maincontainer">
            <div className="content-landing">
                 <p>{user}</p>
            </div>

        </div>
    )
}
</code>```

答:
```<code>var user = users[0].email //cannot read email of undefined
</code>```

this code is the culprit. because on the first render is empty.

can you try a null check before accessing users[0].email heres an example

```<code>var user = users.length > 0 ? users[0].email : ""
</code>```

Body:
I have done a function in my react call which calls an api, and sets a state based on the data received by that api

getUserList() {
    API.get('/userlist')
        .then(response => {
            this.setState({
                userList: response.data
            }, () => {
                console.log(this.state.userList) //I can see this
            });
        })
}

This is how my constructor looks

constructor(props) {
    super(props)
    this.state = {
        retracted: false,
        userList: []

    }
    this.getUserList = this.getUserList.bind(this);
}

I call it in componentDidMount()

componentDidMount() {
    this.getUserList();
}

But then my render crashes, because both console.log return undefined

render() {
    var users = this.state.userList;
    var user = users[0].email //cannot read email of undefined

    console.log(this.state.userList)
    console.log(users)
    return (

{user}

    )
}

Body:
var user = users[0].email //cannot read email of undefined

this code is the culprit. because on the first render is empty.

can you try a null check before accessing users[0].email heres an example

var user = users.length > 0 ? users[0].email : ""