问:
Is there a way to know what is volley going to parse?
I use this code to make requests to a server, it usually works fine but sometimes it throws some errors since its under development, however if it throws an error volley tries to parse it into a JsonObject and will inevitably fail. </p>

```<code>final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                (Request.Method.POST, baseUrl, postparams, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.w("Response", response.toString());
                        callBackActivity.JsonCallback(response, "grupos");
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        callBackActivity.ErrorCallback(error, "grupos");

                    }
                });
</code>```

<p>So is there any way to know whats the raw response of the server before parsing it into a JsonObject? </p>

答:
Instead of JSONObjecRequest try StringRequest which will give the response in string. Log this response and look what is causing the error, then you can revert it back to JSONObjectRequest

```<code>StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Log.v(response)
        try {
                JSONObject object = new JSONObject(response);
            }
            } catch (Exception e) {
                Log.v("exception is " + e.toString());
            }        }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        //error log
    }
});
</code>```

Body:
I use this code to make requests to a server, it usually works fine but sometimes it throws some errors since its under development, however if it throws an error volley tries to parse it into a JsonObject and will inevitably fail.

final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                (Request.Method.POST, baseUrl, postparams, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.w("Response", response.toString());
                        callBackActivity.JsonCallback(response, "grupos");
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        callBackActivity.ErrorCallback(error, "grupos");

                    }
                });

So is there any way to know whats the raw response of the server before parsing it into a JsonObject?

Body:
Instead of JSONObjecRequest try StringRequest which will give the response in string. Log this response and look what is causing the error, then you can revert it back to JSONObjectRequest

StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Log.v(response)
        try {
                JSONObject object = new JSONObject(response);
            }
            } catch (Exception e) {
                Log.v("exception is " + e.toString());
            }        }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        //error log
    }
});


来源: stackexchange

问:
Simple Ruby Regex for JSON string
I have the following simple JSON string:

```<code>{\"exclude\"=>[4, 5, 6, 10], \"include\"=>[]}
</code>```

and I'd like to extract each number in the array following "exclude".  In other words, I'd expect my 0th match to be all numbers, my first match to be 4, my second 5, and so on.  Many thanks.

答:
As pointed by DigitalRoss, your String does not contain JSON, but apparently plain Ruby code.

You can easily evaluate it and access it simply:

```<code>lStr = "{\"exclude\"=>[4, 5, 6, 10], \"include\"=>[]}"

# Evaluate the string: you get a map
lMap = eval(lStr)
# => {"exclude"=>[4, 5, 6, 10], "include"=>[]}

# Read the properties
lMap['exclude']
# => [4, 5, 6, 10]
lMap['include']
# => []
lMap['exclude'][2]
# => 6
</code>```

ContentLicense: CC BY-SA 3.0

Title: Simple Ruby Regex for JSON string

Body:
I have the following simple JSON string:

{\"exclude\"=>[4, 5, 6, 10], \"include\"=>[]}

and I'd like to extract each number in the array following "exclude".  In other words, I'd expect my 0th match to be all numbers, my first match to be 4, my second 5, and so on.  Many thanks.

Body:
As pointed by DigitalRoss, your String does not contain JSON, but apparently plain Ruby code.

You can easily evaluate it and access it simply:

lStr = "{\"exclude\"=>[4, 5, 6, 10], \"include\"=>[]}"

# Evaluate the string: you get a map
lMap = eval(lStr)
# => {"exclude"=>[4, 5, 6, 10], "include"=>[]}

# Read the properties
lMap['exclude']
# => [4, 5, 6, 10]
lMap['include']
# => []
lMap['exclude'][2]
# => 6


问:
Searching a tuple element in a list of lists without changing the data structure
I'd like to search user input in a tuple located in a list of lists.

```<code>data = [[('tick1',12),4],[('tick2', 16),7],...]

if user input: 'tick1'
desired output:[('tick1',12),4]
</code>```

I can do this if I change my list to a dictionary:

```<code>data = [[('tick1',12),4],[('tick2', 16),7]]

data = dict(data)

if not any('tick2' in x for x in data):
    print('not found')
else:
    print('found:', x)

#Output
found: [('tick2', 16), 7]
</code>```

But how can I do this if I want to maintain the list type?

答:
you can use the next() function to get the first match and use its default parameter for the case where the item is not in the list:</p>

```<code>data = [[('tick1',12),4],[('tick2', 16),7]]
result = next( (item for item in data if item[0][0] == 'tick1'), "not found")
print(result) # [('tick1', 12), 4]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'd like to search user input in a tuple located in a list of lists.

data = [[('tick1',12),4],[('tick2', 16),7],...]

if user input: 'tick1'
desired output:[('tick1',12),4]

I can do this if I change my list to a dictionary:

data = [[('tick1',12),4],[('tick2', 16),7]]

data = dict(data)

if not any('tick2' in x for x in data):
    print('not found')
else:
    print('found:', x)

#Output
found: [('tick2', 16), 7]

But how can I do this if I want to maintain the list type?

Body:
you can use the next() function to get the first match and use its default parameter for the case where the item is not in the list:

data = [[('tick1',12),4],[('tick2', 16),7]]
result = next( (item for item in data if item[0][0] == 'tick1'), "not found")
print(result) # [('tick1', 12), 4]


问:
Apply all regexp_replaces from table sequentally to one string
I need to sequentially apply all regex_replace's from the table to one given string. How could I do that with one SQL request?

PostgreSQL is 11.2.

```<code>xbox=> \d presence_regex
           Table "public.presence_regex"
 Column  |  Type   | Collation | Nullable | Default
---------+---------+-----------+----------+---------
 match   | text    |           |          |
 replace | text    |           |          |

xbox=> select regexp_replace('Playing FIFA 19 Pro Clubs 2-1 LIL V BVB, 1st Half',
                                match, replace) from presence_regex;
</code>```

Select above performs replace to the original string and returns number of strings but I need the only one: the result after applying all the regex_replaces from the table.

Is it possible?

答:
You need dynamic SQL for this. Meaning, you have to first build your SQL statement using data in table presence_regex, then execute it in the next step. You can wrap it up in a plpgsql function as single step.

Assuming

there is a column to indicate the order in which replacements shall be applied (which is meaningful).

you want to replace all occurrences, not just the first.

This function would achieve it:

```<code>CREATE OR REPLACE FUNCTION f_serial_regexp(_string text, OUT _result text) AS
$func$
BEGIN
   EXECUTE (
   SELECT 'SELECT '
       || string_agg('regexp_replace(', '')
       || '$1'
       || string_agg(format(', %L, %L, ''g'')', match, replace), '')
   FROM   (
      SELECT match, replace
      FROM   presence_regex
      ORDER  BY order_id    -- column indicating the order
      ) sub
   )
   USING $1
   INTO _result;
END
$func$  LANGUAGE plpgsql;
</code>```

It builds and executes a SELECT query of the form (example for two rows in the table):

```<code>SELECT regexp_replace(regexp_replace($1, 'FIFA \d+', 'bab', 'g'), 'bab', 'XXX', 'g')
</code>```

Remove the 4th parameter 'g' from regexp_replace() to only replace the first occurrence.

Call:

```<code>SELECT f_serial_regexp('Playing FIFA 19 Pro Clubs 2-1 LIL V BVB, 1st Half');
</code>```

db<>fiddle here

Closely related, with more explanation:

Store a formula in a table and use the formula in a function

Body:
I need to sequentially apply all regex_replace's from the table to one given string. How could I do that with one SQL request?

PostgreSQL is 11.2.

xbox=> \d presence_regex
           Table "public.presence_regex"
 Column  |  Type   | Collation | Nullable | Default
---------+---------+-----------+----------+---------
 match   | text    |           |          |
 replace | text    |           |          |

xbox=> select regexp_replace('Playing FIFA 19 Pro Clubs 2-1 LIL V BVB, 1st Half',
                                match, replace) from presence_regex;

Select above performs replace to the original string and returns number of strings but I need the only one: the result after applying all the regex_replaces from the table.

Is it possible?

Body:
You need dynamic SQL for this. Meaning, you have to first build your SQL statement using data in table presence_regex, then execute it in the next step. You can wrap it up in a plpgsql function as single step.

Assuming

there is a column to indicate the order in which replacements shall be applied (which is meaningful).

you want to replace all occurrences, not just the first.

This function would achieve it:

CREATE OR REPLACE FUNCTION f_serial_regexp(_string text, OUT _result text) AS
$func$
BEGIN
   EXECUTE (
   SELECT 'SELECT '
       || string_agg('regexp_replace(', '')
       || '$1'
       || string_agg(format(', %L, %L, ''g'')', match, replace), '')
   FROM   (
      SELECT match, replace
      FROM   presence_regex
      ORDER  BY order_id    -- column indicating the order
      ) sub
   )
   USING $1
   INTO _result;
END
$func$  LANGUAGE plpgsql;

It builds and executes a SELECT query of the form (example for two rows in the table):

SELECT regexp_replace(regexp_replace($1, 'FIFA \d+', 'bab', 'g'), 'bab', 'XXX', 'g')

Remove the 4th parameter 'g' from regexp_replace() to only replace the first occurrence.

Call:

SELECT f_serial_regexp('Playing FIFA 19 Pro Clubs 2-1 LIL V BVB, 1st Half');

db<>fiddle here

Closely related, with more explanation:

Store a formula in a table and use the formula in a function


问:
AWS Cloudwatch can not publish to SNS Topic with SSE
I have a Route53 health check, which submits its metrics into Cloudwatch, and finally Cloudwatch specifies thresholds and should send alerts through SNS.

However, I would like my SNS Topic to be encrypted. When I turn on SNS Topic encryption using the alias/aws/sns key I receive these messages in the Cloudwatch message history:

```<code>{
  "actionState": "Failed",
  "stateUpdateTimestamp": 123456778899,
  "notificationResource": "arn:aws:sns:xx-region-y:zzzzzzzzzz:topic_name",
  "publishedMessage": null,
  "error": "null (Service: AWSKMS; Status Code: 400; Error Code: AccessDeniedException; Request ID: ccccccccccccccccccc)"
}
</code>```

This appears to not be an IAM issue with Cloudwatch, but with SNS itself being unauthorized to use the KMS resources.

I enjoy using the IAM Policy Simulator for IAM users to identify where their permissions are lacking, but there doesn't seem to be a way to validate a Service's access to other services. Is that a thing I can manage?

https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_testing-policies.html

I have also tried this with a CMK with the following policy:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "sns.amazonaws.com"
            },
            "Action": [
                "kms:GenerateDataKey*",
                "kms:Decrypt"
            ],
            "Resource": "*"
        },
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "route53.amazonaws.com"
            },
            "Action": [
                "kms:GenerateDataKey*",
                "kms:Decrypt"
            ],
            "Resource": "*"
        },
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "events.amazonaws.com"
            },
            "Action": [
                "kms:GenerateDataKey*",
                "kms:Decrypt"
            ],
            "Resource": "*"
        },
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::XXXXXXXX:role/OrganizationAccountAccessRole"
            },
            "Action": "kms:*",
            "Resource": "*"
        }
    ]
}
</code>```

I'm pretty much throwing darts at a wall with the principals, but I think there's validation for sns.amazonaws.comfor SNS and events.amazonaws.com for Cloudwatch.

I received the exact same error, "null (Service: AWSKMS; Status Code: 400; Error Code: AccessDeniedException; Request ID: ccccccccccccccccccc)", when using a CMK in this manner as well. I can understand my CMK not working properly, but the Amazon managed key I think should just work out of the box.

I've tried using a CMK which grants sns.amazonaws.com and events.amazonaws.com with kms:* permissions. Same error.

答:
Update: It's likely this information is out of date. Please try the other answers and let everyone know if they work for you.

Apparently, CloudWatch can't send messages to encrypted SNS topics according to Protecting Amazon SNS Data Using Server-Side Encryption (SSE) and AWS KMS:

Currently, CloudWatch alarms don't work with Amazon SNS encrypted topics. For information about publishing alarms to unencrypted topics, see Using Amazon CloudWatch Alarms in the Amazon CloudWatch User Guide.

However, the blog post Encrypting messages published to Amazon SNS with AWS KMS seems to indicate you can...

Body:
I have a Route53 health check, which submits its metrics into Cloudwatch, and finally Cloudwatch specifies thresholds and should send alerts through SNS.

However, I would like my SNS Topic to be encrypted. When I turn on SNS Topic encryption using the alias/aws/sns key I receive these messages in the Cloudwatch message history:

{
  "actionState": "Failed",
  "stateUpdateTimestamp": 123456778899,
  "notificationResource": "arn:aws:sns:xx-region-y:zzzzzzzzzz:topic_name",
  "publishedMessage": null,
  "error": "null (Service: AWSKMS; Status Code: 400; Error Code: AccessDeniedException; Request ID: ccccccccccccccccccc)"
}

This appears to not be an IAM issue with Cloudwatch, but with SNS itself being unauthorized to use the KMS resources.

I enjoy using the IAM Policy Simulator for IAM users to identify where their permissions are lacking, but there doesn't seem to be a way to validate a Service's access to other services. Is that a thing I can manage?

https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_testing-policies.html

I have also tried this with a CMK with the following policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "sns.amazonaws.com"
            },
            "Action": [
                "kms:GenerateDataKey*",
                "kms:Decrypt"
            ],
            "Resource": "*"
        },
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "route53.amazonaws.com"
            },
            "Action": [
                "kms:GenerateDataKey*",
                "kms:Decrypt"
            ],
            "Resource": "*"
        },
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "events.amazonaws.com"
            },
            "Action": [
                "kms:GenerateDataKey*",
                "kms:Decrypt"
            ],
            "Resource": "*"
        },
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::XXXXXXXX:role/OrganizationAccountAccessRole"
            },
            "Action": "kms:*",
            "Resource": "*"
        }
    ]
}

I'm pretty much throwing darts at a wall with the principals, but I think there's validation for sns.amazonaws.comfor SNS and events.amazonaws.com for Cloudwatch.

I received the exact same error, "null (Service: AWSKMS; Status Code: 400; Error Code: AccessDeniedException; Request ID: ccccccccccccccccccc)", when using a CMK in this manner as well. I can understand my CMK not working properly, but the Amazon managed key I think should just work out of the box.

I've tried using a CMK which grants sns.amazonaws.com and events.amazonaws.com with kms:* permissions. Same error.


问:
Are there built-in extension methods in the .NET framework that don't apply to LINQ?
For the purpose of a course I am developing, I am looking for some examples of where Microsoft has already implemented extension methods themselves. But since the students are not yet acquainted to LINQ, I would like to find some other example.

So, are there any methods defined in the .NET framework that are defined as an extension method, but do not refer to the LINQ framework or IEnumerable?

答:
Yes there are tons of examples here are some highlights:

AsSpan() method on string that is implemented as an extension method. Here are the docs on it.

IsNormalized() and Normailize() are two more string extension methods that are easy enough to use. Here are the docs on those.

If you are willing to walk your students into Dependency Injection then there are plenty of examples in the Startup class for just about any asp.net core project.


问:
Is it possible to apply css rules using json content in a data attribute?
Is it possible to put green background on the spans that have an id represented in the div?

//Edit. If it makes it easier, just using the keys in the div attribute would work too. data-ids='["1", "2"]' or even data-ids="1,2". Not sure what's possible. If not, is there any clever JS/jQuery implementation that could help out?

```<code><div data-ids='{"1":"Name A", "2":"Name B"}'>
    <span data-id="1">This should have green background</span>
    <span data-id="2">This should have green background</span>
    <span data-id="3">This should have no background</span>
</div>
</code>```

Dummy code:

```<code>div[data-ids=*] span[data-id=*] {
    background: green;
}
</code>```

答:
You can't dynamically set styles using CSS. If you must do it, you need to manually type all possibilities out.

For example, if you need green background for  with id == 1 or id == 2, you need to write your CSS like this:

div[data-ids] span[data-id="1"],
div[data-ids] span[data-id="2"] {
  background: #0f0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div data-ids='{"1":"Name A", "2":"Name B"}'>
  <span data-id="1">This should have green background</span>
  <span data-id="2">This should have green background</span>
  <span data-id="3">This should have no background</span>
</div></code>```

You have to use JS or jQuery to do what you need to do:

JavaScript (ES6 for simplicity) - see comments for explanation

// Get the div with `data-ids` attribute
const div = document.querySelector('div[data-ids]');

// Get the data in `data-ids`
const ids = div.dataset.ids;

// Parse the string data into Object
const data = JSON.parse(ids);

// Loop over the keys (id) of the data
// Selecting matching span to style them.
for (const id in data){
  const spans = document.querySelectorAll(`span[data-id="${id}"]`);
  spans.forEach(span => {
    span.style.background = '#0f0';
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div data-ids='{"1":"Name A", "2":"Name B"}'>
  <span data-id="1">This should have green background</span>
  <span data-id="2">This should have green background</span>
  <span data-id="3">This should have no background</span>
</div></code>```

jQuery (ES6 for simplicity) - see comments for explanation

// Get the div with `data-ids` attribute
const $div = $('div[data-ids]');

// Get the `ids` from attribute.
// jQuery automatically parse string data into JSON if valid.
const data = $div.data('ids');

// Loops through the ids and set matching span background color.
$.each(data, function(id){
  $(`span[data-id="${id}"]`).css('background', '#0f0');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div data-ids='{"1":"Name A", "2":"Name B"}'>
  <span data-id="1">This should have green background</span>
  <span data-id="2">This should have green background</span>
  <span data-id="3">This should have no background</span>
</div></code>```

Body:
Is it possible to put green background on the spans that have an id represented in the div?

//Edit. If it makes it easier, just using the keys in the div attribute would work too. data-ids='["1", "2"]' or even data-ids="1,2". Not sure what's possible. If not, is there any clever JS/jQuery implementation that could help out?

    This should have green background
    This should have green background
    This should have no background

Dummy code:

div[data-ids=*] span[data-id=*] {
    background: green;
}

Body:
You can't dynamically set styles using CSS. If you must do it, you need to manually type all possibilities out.

For example, if you need green background for <span> with id == 1 or id == 2, you need to write your CSS like this:

div[data-ids] span[data-id="1"],
div[data-ids] span[data-id="2"] {
  background: #0f0;
}

<div data-ids='{"1":"Name A", "2":"Name B"}'>
  <span data-id="1">This should have green background</span>
  <span data-id="2">This should have green background</span>
  <span data-id="3">This should have no background</span>
</div>

You have to use JS or jQuery to do what you need to do:

JavaScript (ES6 for simplicity) - see comments for explanation

// Get the div with `data-ids` attribute
const div = document.querySelector('div[data-ids]');

// Get the data in `data-ids`
const ids = div.dataset.ids;

// Parse the string data into Object
const data = JSON.parse(ids);

// Loop over the keys (id) of the data
// Selecting matching span to style them.
for (const id in data){
  const spans = document.querySelectorAll(`span[data-id="${id}"]`);
  spans.forEach(span => {
    span.style.background = '#0f0';
  });
}

<div data-ids='{"1":"Name A", "2":"Name B"}'>
  <span data-id="1">This should have green background</span>
  <span data-id="2">This should have green background</span>
  <span data-id="3">This should have no background</span>
</div>

jQuery (ES6 for simplicity) - see comments for explanation

// Get the div with `data-ids` attribute
const $div = $('div[data-ids]');

// Get the `ids` from attribute.
// jQuery automatically parse string data into JSON if valid.
const data = $div.data('ids');

// Loops through the ids and set matching span background color.
$.each(data, function(id){
  $(`span[data-id="${id}"]`).css('background', '#0f0');
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div data-ids='{"1":"Name A", "2":"Name B"}'>
  <span data-id="1">This should have green background</span>
  <span data-id="2">This should have green background</span>
  <span data-id="3">This should have no background</span>
</div>


问:
How can out the total expenditure for each poly with group by?
I get this error:

Msg 102, Level 15, State 1, Line 3

  Incorrect syntax near ','.

when running this code:

```<code>SELECT
    CAST(Times.bulan AS VARCHAR(7)) AS bulan,
    CAST(FinanceFact.id_poli AS VARCHAR(7)) AS IDpoli,
    SUM(FinanceFact.Pengeluaran) AS TotalPengeluaran
FROM
    FinanceFact
LEFT JOIN
    Times ON FinanceFact.id_time = Times.id_time
GROUP BY
    (CAST(Times.bulan AS VARCHAR(7)),
     CAST(FinanceFact.id_poli AS VARCHAR(7)))
</code>```

I want to bring out the total expenditure for each poly based on the month

答:
Error is caused by extra parentheses in the last line.
Try:</p>

```<code>GROUP BY CAST(Times.bulan AS VARCHAR(7)),CAST(FinanceFact.id_poli AS VARCHAR(7))
</code>```

Body:
I get this error:

Msg 102, Level 15, State 1, Line 3

  Incorrect syntax near ','.

when running this code:

SELECT
    CAST(Times.bulan AS VARCHAR(7)) AS bulan,
    CAST(FinanceFact.id_poli AS VARCHAR(7)) AS IDpoli,
    SUM(FinanceFact.Pengeluaran) AS TotalPengeluaran
FROM
    FinanceFact
LEFT JOIN
    Times ON FinanceFact.id_time = Times.id_time
GROUP BY
    (CAST(Times.bulan AS VARCHAR(7)),
     CAST(FinanceFact.id_poli AS VARCHAR(7)))

I want to bring out the total expenditure for each poly based on the month

Body:
Error is caused by extra parentheses in the last line.
Try:

GROUP BY CAST(Times.bulan AS VARCHAR(7)),CAST(FinanceFact.id_poli AS VARCHAR(7))


问:
Using before_create in rails3
I'm creating a tag system right now where Post has_many :tags, :through => :tag_joins

Right now when a new tag is created, a join is automatically created, connecting the tag and post the tag was created on. The problem is I'm trying to use before_create to check if a tag with the same name and user ID has already been created. If it has already been created, I'd like the join to use the original tag ID, instead of letting it create a new tag ID.

Any tips for how I can accomplish this?

答:
This should take care of duplicate records between the Post and the Tag but not sure how your associations are set up with the User.</p>

```<code>class Post < ActiveRecord::Base
  has_many :tags, :through => :tag_joins, :uniq => true
end
</code>```

ContentLicense: CC BY-SA 2.5

Title: Using before_create in rails3

Body:
This should take care of duplicate records between the Post and the Tag but not sure how your associations are set up with the User.

class Post < ActiveRecord::Base
  has_many :tags, :through => :tag_joins, :uniq => true
end


答:
Collect all list with first item equals input_value. Then check the size if found or not.</p>

```<code>data = [[('tick1',12),4],[('tick12', 16),7], [('tick1', 11), 4]]
x = 'tick1'
search=[n for n in data for t in n[0] if t==x ]
if len(search) > 0:
    print('found:', search)
else:
    print('not found:', x)

Result: found: [[('tick1', 12), 4], [('tick1', 11), 4]]
</code>```

Title: Searching a tuple element in a list of lists without changing the data structure

Body:
Collect all list with first item equals input_value. Then check the size if found or not.

data = [[('tick1',12),4],[('tick12', 16),7], [('tick1', 11), 4]]
x = 'tick1'
search=[n for n in data for t in n[0] if t==x ]
if len(search) > 0:
    print('found:', search)
else:
    print('not found:', x)

Result: found: [[('tick1', 12), 4], [('tick1', 11), 4]]


问:
React-Router not correctly rendering Styled-Components Styles
The issue is that when I navigate to a 'Post', expanded screen, then use my browser to go back, it is not showing the correct CSS styles, it is using the styles from the expanded view, rather than the 'non-expanded' view. If I toggle a style on the Component using Inspect Element it fixes the issue immediately. I know I could probably circumvent this by adding a back button on the page, and I probably will, but what about the people who use the browser back button?

I am trying to use the same StyledComponent for different pages. Here is the code for my router

```<code><Router>
      <Route
        exact
        path="/"
        render={() => posts.map((post, key) => <Post data={post} key={key} />)}
      />
      <Route
        exact
        path={`/posts/:post`}
        render={currentPath => renderCurrentPost(currentPath)}
      />
    </Router>
</code>```

All that the second route does is find the correct post to render, then render it.

Here is my code for the specific styled component.

```<code>import Styled from 'styled-components';
const Title = Styled.h1`
    @import url('https://fonts.googleapis.com/css?family=Roboto&display=swap');
    font-family: 'Roboto', sans-serif;
    font-style: medium;
    color: ${props => (props.expanded ? `white` : `#111111`)}
    font-size: ${props => (props.expanded ? `5vh` : `1.2em`)}
    margin: 0 0 0 0;
    align-self: flex-end;
    /* display: inline; */
    position: ${props => (props.expanded ? `relative` : ``)};
    top: ${props => (props.expanded ? `70%` : ``)};
    left: ${props => (props.expanded ? `5%` : ``)};
     `;

export default Title;
</code>```

I am using props heavily in these components as it will change the way it renders.

Here is the desired style that renders correctly when you first navigate to the landing page.

Here is the non-desired styling that happens when you navigate back from a expanded post page using the browser back button.

答:
I answered this myself by slowly removing each CSS line from my styled component to find the problem, which turned out to be this line of code</p>

```<code>padding: ${props => (props.expanded ? `` : `0 2% 0 10%`)};
</code>```

Body:
The issue is that when I navigate to a 'Post', expanded screen, then use my browser to go back, it is not showing the correct CSS styles, it is using the styles from the expanded view, rather than the 'non-expanded' view. If I toggle a style on the Component using Inspect Element it fixes the issue immediately. I know I could probably circumvent this by adding a back button on the page, and I probably will, but what about the people who use the browser back button?

I am trying to use the same StyledComponent for different pages. Here is the code for my router

<Router>
      <Route
        exact
        path="/"
        render={() => posts.map((post, key) => <Post data={post} key={key} />)}
      />
      <Route
        exact
        path={`/posts/:post`}
        render={currentPath => renderCurrentPost(currentPath)}
      />
    </Router>

All that the second route does is find the correct post to render, then render it.

Here is my code for the specific styled component.

import Styled from 'styled-components';
const Title = Styled.h1`
    @import url('https://fonts.googleapis.com/css?family=Roboto&display=swap');
    font-family: 'Roboto', sans-serif;
    font-style: medium;
    color: ${props => (props.expanded ? `white` : `#111111`)}
    font-size: ${props => (props.expanded ? `5vh` : `1.2em`)}
    margin: 0 0 0 0;
    align-self: flex-end;
    /* display: inline; */
    position: ${props => (props.expanded ? `relative` : ``)};
    top: ${props => (props.expanded ? `70%` : ``)};
    left: ${props => (props.expanded ? `5%` : ``)};
     `;

export default Title;

I am using props heavily in these components as it will change the way it renders.

Here is the desired style that renders correctly when you first navigate to the landing page.

Here is the non-desired styling that happens when you navigate back from a expanded post page using the browser back button.

Body:
I answered this myself by slowly removing each CSS line from my styled component to find the problem, which turned out to be this line of code

padding: ${props => (props.expanded ? `` : `0 2% 0 10%`)};


问:
Get only string in T-SQL
Given the below strings,

```<code>DECLARE @Text1 = 'This is the 1st time I found the Car# CAR:8 #NumberIncluded#'
</code>```

I would like to know if there is a way to get the character "#"

答:
I would like to suggest this one:

```<code>DECLARE @Text1 NVARCHAR(MAX) = 'This is the 1st time I found the Car# CAR:8 #NumberIncluded#'

DECLARE @Text2 NVARCHAR(MAX) = 'This is the 1st time I found the Car# CAR:8 #NumberIncluded# with no ID tied to it, the prices is 588USD for  CAR:7 #NumberIncluded##NumberIncluded#'

DECLARE @Text3 NVARCHAR(MAX) = 'My CAR:A5, CAR:9 AND CAR:10'

SELECT SUBSTRING(@Text1, PATINDEX('%CAR:[0-9]%', @Text1) + 4, 1)
SELECT SUBSTRING(@Text2, PATINDEX('%CAR:[0-9]%', @Text2) + 4, 1)
SELECT SUBSTRING(@Text3, PATINDEX('%CAR:[0-9]%', @Text3) + 4, 1)
</code>```

Expected results: 8, 8, 9

Title: Get only string in T-SQL

Body:
Given the below strings,

DECLARE @Text1 = 'This is the 1st time I found the Car# CAR:8 #NumberIncluded#'

I would like to know if there is a way to get the character "#"

Body:
I would like to suggest this one:

DECLARE @Text1 NVARCHAR(MAX) = 'This is the 1st time I found the Car# CAR:8 #NumberIncluded#'

DECLARE @Text2 NVARCHAR(MAX) = 'This is the 1st time I found the Car# CAR:8 #NumberIncluded# with no ID tied to it, the prices is 588USD for  CAR:7 #NumberIncluded##NumberIncluded#'

DECLARE @Text3 NVARCHAR(MAX) = 'My CAR:A5, CAR:9 AND CAR:10'

SELECT SUBSTRING(@Text1, PATINDEX('%CAR:[0-9]%', @Text1) + 4, 1)
SELECT SUBSTRING(@Text2, PATINDEX('%CAR:[0-9]%', @Text2) + 4, 1)
SELECT SUBSTRING(@Text3, PATINDEX('%CAR:[0-9]%', @Text3) + 4, 1)

Expected results: 8, 8, 9


问:
Why doesn't my website look the same on the mobile chrome browser as the desktop version of chrome at the same resolution?
So I couldn't find an answer on here pertaining to my specific problem but I just finished my first ever professional site using chrome. Made it responsive. Looks good for smaller devices. But when I put it online(view here) and viewed it on my Iphone 6s using chrome. It  has so many errors. Here's just a few examples.

Button is being pushed out of parent div as well as input styles have changed https://imgur.com/a/ZFjyK6J

Button color has changed and and the my underlines have shifted. But again it looks good on mobile in my dekstop?? https://imgur.com/a/IyVPOjq

input elements are shown larger here https://imgur.com/a/SiyDCI1

image is really distorted here https://imgur.com/a/5SO3IS9

here's my github https://github.com/spabsa/kaneConcrete

答:
For the button color just add the background color you want in the css

```<code>.footer button {
    position: absolute;
    right: 0;
    top: -50px;
    border: none;
    font-family: 'Rajdhani';
    font-size: 1.2rem;
    transition: all ease 0.4s;
    outline: none;
    background-color: gainsboro; //or any other color
}
</code>```

For the input elements try

```<code>@media screen and (max-width: 924px)
.row-2 input {
    width: -webkit-fill-available;
    margin-bottom: 5px;
}
</code>```

"Think of Device Mode as a first-order approximation of how your page looks and feels on a mobile device. With Device Mode you don't actually run your code on a mobile device. You simulate the mobile user experience from your laptop or desktop." You can check more here.

"The -webkit prefix on CSS selectors are properties that only this engine is intended to process, very similar to -moz properties."

Body:
For the button color just add the background color you want in the css

.footer button {
    position: absolute;
    right: 0;
    top: -50px;
    border: none;
    font-family: 'Rajdhani';
    font-size: 1.2rem;
    transition: all ease 0.4s;
    outline: none;
    background-color: gainsboro; //or any other color
}

For the input elements try

@media screen and (max-width: 924px)
.row-2 input {
    width: -webkit-fill-available;
    margin-bottom: 5px;
}

"Think of Device Mode as a first-order approximation of how your page looks and feels on a mobile device. With Device Mode you don't actually run your code on a mobile device. You simulate the mobile user experience from your laptop or desktop." You can check more here.

"The -webkit prefix on CSS selectors are properties that only this engine is intended to process, very similar to -moz properties."


问:
Detecting touch inside bounding box (alpha mask) of Sprite using SpriteKit
I am starting to learn Swift2 to develop on iOS using SpriteKit and I cannot seem to detect if I touched a visible part of my Sprite.

I can find which node was touched like this:

```<code>let touchedNode = self.nodeAtPoint(location)
</code>```

But this detect the touch on the sprite. I would like to detect the touch on the "not transparent" part of the sprite only.

I tried creating a PhysicsBody with an alpha mask bounding box and testing if the bounding box of the node I selected contains the location of the touch like this:

```<code>sprite.physicsBody = SKPhysicsBody.init(texture: sprite.texture!, size: sprite.size)
sprite.physicsBody?.affectedByGravity = false
if (touchedNode.containsPoint(location)){
</code>```

But it didn't help. If I click in a transparent part of my sprite, the event still triggers.

The documentation says "A new physics body is created that includes all of the texels in the texture that have a nonzero alpha value.", so shouldn't it work?

Thanks for your time.

PS: I also tried to be more generous on my alpha threshold, but this also did not work (in case my transparency wasn't perfect).

UPDATE:

To add a little more details, I am building a level editor. This means that I will create many nodes, depending on what the user chooses, and I need to be able to select/move/rotate/etc those nodes. I am actually using SKSpriteNodes as  my PNG pictures are automatically added in xcassette that way. I decided to use the PhysicsBody's Alpha Mask bounding box, as this value is shown in the Scene Editor (Xcode) when you select a node, and when selected, the Alpha Mask highlights exactly the part of my Sprite that I want to be able to detect a touch inside.

If I am using the wrong ideas/techniques, please tell me. This is possible as I am only starting to use Swift and SpriteKit.

UPDATE 2

I queried the physicsWord (as recommended) to get the right physicsBody and got the name of the attached node like this:

```<code>let body = self.physicsWorld.bodyAtPoint(location)
print(body?.node?.name)
</code>```

But this is still printing the name of the node even if I touch outside the bounding box, which makes no sense to me.

Thank you anyway for your help.

答: I was having the same problem.  You actually can't perform the touch on the alpha mask of a Sprite Node and it says it right in the Apple documentation.  You have to use a Composite Box.  I used a shape Node and changed the "line width" to 0 so essentially the composite box is invisible.  Make sure that the Z axis is higher for the composite box and then run the touch event through the composite box shape node instead of the original node.</p>

Body:
I am starting to learn Swift2 to develop on iOS using SpriteKit and I cannot seem to detect if I touched a visible part of my Sprite.

I can find which node was touched like this:

let touchedNode = self.nodeAtPoint(location)

But this detect the touch on the sprite. I would like to detect the touch on the "not transparent" part of the sprite only.

I tried creating a PhysicsBody with an alpha mask bounding box and testing if the bounding box of the node I selected contains the location of the touch like this:

sprite.physicsBody = SKPhysicsBody.init(texture: sprite.texture!, size: sprite.size)
sprite.physicsBody?.affectedByGravity = false
if (touchedNode.containsPoint(location)){

But it didn't help. If I click in a transparent part of my sprite, the event still triggers.

The documentation says "A new physics body is created that includes all of the texels in the texture that have a nonzero alpha value.", so shouldn't it work?

Thanks for your time.

PS: I also tried to be more generous on my alpha threshold, but this also did not work (in case my transparency wasn't perfect).

UPDATE:

To add a little more details, I am building a level editor. This means that I will create many nodes, depending on what the user chooses, and I need to be able to select/move/rotate/etc those nodes. I am actually using SKSpriteNodes as  my PNG pictures are automatically added in xcassette that way. I decided to use the PhysicsBody's Alpha Mask bounding box, as this value is shown in the Scene Editor (Xcode) when you select a node, and when selected, the Alpha Mask highlights exactly the part of my Sprite that I want to be able to detect a touch inside.

If I am using the wrong ideas/techniques, please tell me. This is possible as I am only starting to use Swift and SpriteKit.

UPDATE 2

I queried the physicsWord (as recommended) to get the right physicsBody and got the name of the attached node like this:

let body = self.physicsWorld.bodyAtPoint(location)
print(body?.node?.name)

But this is still printing the name of the node even if I touch outside the bounding box, which makes no sense to me.

Thank you anyway for your help.


问:
Why doesn't the {% empty %} option show when no items available?
I have set up a "for/in" loop in a django template with an "empty" option, but when my view produces no items I get a 404 page instead of my "empty" option.

I have tried subbing in an "if" tag, but get the same result.

Template code:

```<code>{% for item in object_list %}
    <p>{{ item.desc }}
{% empty %}
  <p>Nothing scheduled
{% endfor %}
</code>```

views.py:

```<code>class ItemTodayArchiveView(LoginRequiredMixin, TodayArchiveView):
    login_url = '/admin/'
    redirect_field_name= 'redirect_to'
    date_field = 'airpub_date'
    allow_future= True

def get_queryset(self):
    destination = self.kwargs['destination']
    return Item.objects.filter(airpub_date__gte=date.today()).filter(destination=destination)
</code>```

When the queryset is empty (i.e., there's nothing with that airpub_date) I want the template page to show "Nothing scheduled". Instead I'm getting a 404 debug page:

```<code>Page not found (404)
Request Method: GET
Request URL:    http://xxx.xxx.xxx/items/atc/today/
Raised by:  items.views.ItemTodayArchiveView
No items available
</code>```

答: The code doesn't even reach the template, because the view checks your queryset is not empty first. To disable this check, set allow_empty = True in the class - see the docs.

Body:
I have set up a "for/in" loop in a django template with an "empty" option, but when my view produces no items I get a 404 page instead of my "empty" option.

I have tried subbing in an "if" tag, but get the same result.

Template code:

{% for item in object_list %}

{{ item.desc }}
{% empty %}

Nothing scheduled
{% endfor %}

views.py:

class ItemTodayArchiveView(LoginRequiredMixin, TodayArchiveView):
    login_url = '/admin/'
    redirect_field_name= 'redirect_to'
    date_field = 'airpub_date'
    allow_future= True

def get_queryset(self):
    destination = self.kwargs['destination']
    return Item.objects.filter(airpub_date__gte=date.today()).filter(destination=destination)

When the queryset is empty (i.e., there's nothing with that airpub_date) I want the template page to show "Nothing scheduled". Instead I'm getting a 404 debug page:

Page not found (404)
Request Method: GET
Request URL:    http://xxx.xxx.xxx/items/atc/today/
Raised by:  items.views.ItemTodayArchiveView
No items available


问:
Arduino and electronics beginner beginnering
I'm working through a set of beginner exercises with the Arduino Uno microcontroller. (A generic one, though, as this is what I've been supplied with.)

The program I'm running, which alternates between sending 1's and 0's to serial output depending on the state of a momentary switch, has set pin 2 to be the input for the switch. But. Whilst wiring up, I accidentally plugged the jumper cable in to pin 3 initially, and found it still mostly sent the 1's when the button was pushed. Some 0's, yet mostly 1's.

Initially I thought maybe it was just the board was a bit dodgy, but thought I'd experiment a bit. Plugging into pin 3 instead of pin 2 still fairly consistently sent 1's when the button was pushed, though the 1's flowed a little bit less consistently than when it was in pin 2. In pin 2 it was completely consistent by comparison. So I tried pin 4, but with that one there's no response at all.

Am I right in presuming the program's readings seems to get a little bit less responsive the further away I move the cable from the pin that I've programmed to act as input? Can anyone help me understand why this happens?

It's probably quite obvious that I'm new to electronics. :)

The program I've got uploaded to the board is as follows:

```<code>// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 2;
// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);
}
// the loop routine runs over and over again forever:
void loop() {
  // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial.println(buttonState);
  delay(1); // delay in between reads for stability
}
</code>```

答:
Leaving input pins open makes the microcontroller read a floating value which swings between 0 to 1. Also when wiring a switch to any pin, make sure to hook some pull-down resistor to make the input 0.
These are common for many electronics and proper notice to be taken while designing circuits of your own.</p>

Body:
I'm working through a set of beginner exercises with the Arduino Uno microcontroller. (A generic one, though, as this is what I've been supplied with.)

The program I'm running, which alternates between sending 1's and 0's to serial output depending on the state of a momentary switch, has set pin 2 to be the input for the switch. But. Whilst wiring up, I accidentally plugged the jumper cable in to pin 3 initially, and found it still mostly sent the 1's when the button was pushed. Some 0's, yet mostly 1's.

Initially I thought maybe it was just the board was a bit dodgy, but thought I'd experiment a bit. Plugging into pin 3 instead of pin 2 still fairly consistently sent 1's when the button was pushed, though the 1's flowed a little bit less consistently than when it was in pin 2. In pin 2 it was completely consistent by comparison. So I tried pin 4, but with that one there's no response at all.

Am I right in presuming the program's readings seems to get a little bit less responsive the further away I move the cable from the pin that I've programmed to act as input? Can anyone help me understand why this happens?

It's probably quite obvious that I'm new to electronics. :)

The program I've got uploaded to the board is as follows:

// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 2;
// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  // make the pushbutton's pin an input:
  pinMode(pushButton, INPUT);
}
// the loop routine runs over and over again forever:
void loop() {
  // read the input pin:
  int buttonState = digitalRead(pushButton);
  // print out the state of the button:
  Serial.println(buttonState);
  delay(1); // delay in between reads for stability
}


问:
Clarification on why my JS closure is not returning properly?
I'm working on a solution for Two-Sum (perhaps a bit overengineered, but it's mostly to get me comfortable with recursion and closures) and I'm trying to avoid having a counter globally if necessary. However, my function is returning undefined and I don't really know what I'm doing wrong.

So I wrapped my functionality (originally innerFunction was the entirety of the function and startingIndex was global) in an inner function, set returnArray to grab the base case once the recursion in innerFunction finishes, and return... returnArray. It doesn't seem to matter where I assign returnArray to the return value of innerFunction, it still isn't defined. There has to be something about the execution contexts that I'm missing and I'm sure it's obvious but I'm drawing a blank.

function twoSum(numArr, target) {
  let startingIndex = 0;
  let returnArray = [];

  function innerFunction(array, integer) {
    let startNum = array.shift();
    let subtractedNum = integer - startNum;
    let found = array.findIndex(function(element) {
      return element === subtractedNum
    })

    if (found >= 0) {
      //found is the index of the shortened array
      //add 1 for the initial shift
      //add starting index, which doubles to track the amount of shifts thus far
      let endingIndex = found + 1 + startingIndex
      return [startingIndex, endingIndex];
    } else {
      startingIndex++;
      innerFunction(array, integer);
    }
  }
  returnArray = innerFunction(numArr, target)
  return returnArray;
}

console.log(twoSum([4,2,5,7,8,1,9,12,3], 15));```

I expect, say, twoSum([4,2,5,7,8,1,9,12,3], 15) to output [3,4] as it was before I wrapped the function. What am I missing?

答:
your result is undefined because this line needs a return statement:
innerFunction(array, integer);

Here's a working solution:

     function twoSum(position, array, integer) {
        let answer = []
        let startNum = array[position];
        let subtractedNum = integer - startNum;

        let index = -1
        for (var i = position + 1; i < array.length; i++) {
          if( array[i] === subtractedNum ) {
            index = i
          }
        }

        if (index >= 0) {
          answer = [[position, index]]
        }

        if (array.length - position > 1) {
          let theRest = twoSum(position + 1, array, integer);
          answer = [...answer, ...theRest]
        }
        return answer
      }

    console.log(twoSum(0, [4,2,5,7,8,1,9,12,3], 15));```

Even if you add this return statement, your solution currently is only going to return one answer unless you throw your answer onto the global accumulator (returnArray) or merge your answers before returning the recursive function (which is what I chose to do above).

Body:
I'm working on a solution for Two-Sum (perhaps a bit overengineered, but it's mostly to get me comfortable with recursion and closures) and I'm trying to avoid having a counter globally if necessary. However, my function is returning undefined and I don't really know what I'm doing wrong.

So I wrapped my functionality (originally innerFunction was the entirety of the function and startingIndex was global) in an inner function, set returnArray to grab the base case once the recursion in innerFunction finishes, and return... returnArray. It doesn't seem to matter where I assign returnArray to the return value of innerFunction, it still isn't defined. There has to be something about the execution contexts that I'm missing and I'm sure it's obvious but I'm drawing a blank.

function twoSum(numArr, target) {
  let startingIndex = 0;
  let returnArray = [];

  function innerFunction(array, integer) {
    let startNum = array.shift();
    let subtractedNum = integer - startNum;
    let found = array.findIndex(function(element) {
      return element === subtractedNum
    })

    if (found >= 0) {
      //found is the index of the shortened array
      //add 1 for the initial shift
      //add starting index, which doubles to track the amount of shifts thus far
      let endingIndex = found + 1 + startingIndex
      return [startingIndex, endingIndex];
    } else {
      startingIndex++;
      innerFunction(array, integer);
    }
  }
  returnArray = innerFunction(numArr, target)
  return returnArray;
}

console.log(twoSum([4,2,5,7,8,1,9,12,3], 15));

I expect, say, twoSum([4,2,5,7,8,1,9,12,3], 15) to output [3,4] as it was before I wrapped the function. What am I missing?

Body:
your result is undefined because this line needs a return statement:
innerFunction(array, integer);

Here's a working solution:

     function twoSum(position, array, integer) {
        let answer = []
        let startNum = array[position];
        let subtractedNum = integer - startNum;

        let index = -1
        for (var i = position + 1; i < array.length; i++) {
          if( array[i] === subtractedNum ) {
            index = i
          }
        }

        if (index >= 0) {
          answer = [[position, index]]
        }

        if (array.length - position > 1) {
          let theRest = twoSum(position + 1, array, integer);
          answer = [...answer, ...theRest]
        }
        return answer
      }

    console.log(twoSum(0, [4,2,5,7,8,1,9,12,3], 15));

Even if you add this return statement, your solution currently is only going to return one answer unless you throw your answer onto the global accumulator (returnArray) or merge your answers before returning the recursive function (which is what I chose to do above).


问:
Event toggle listener
I'm trying to change some styles with the ui.activeFilter() method but it says:

Cannot read property toggle of undefined.

And I set the variable filterLinks to global scope. I can't figure why it's not working.

```<code>"use strict";

// UI elements
const filterLinks = document.querySelectorAll('a');
const itemsLeft = document.querySelectorAll('span');

// Event listeners
filterLinks.forEach(function(link) {
  link.addEventListener('click', check);
});

// Laptops
class Laptop {
    constructor(availability, price, brand) {
      this.availability = availability;
      this.price = price;
      this.brand = brand;
    }
}

// Filter methods
class UiMethod {
    activeFilter(dddd) {
        dddd.classList.toggle('checked');

        if(dddd.className === 'checked') {
            console.log("test");
        } else {
            console.log('Try again you can do it, you are close to the succes');
        }
    }
}

const ui = new UiMethod;

// Function helpers
function check(e) {

    ui.activeFilter(filterLinks);
    e.preventDefault();
}
</code>```

答:
Cannot read property toggle of undefined.

Looks like toggle is referenced here: dddd.classList.toggle. Therefore, dddd.classList is undefined. classList is a defined property on all DOM element objects, so dddd must not be what you think it is.

Looking back at the definition for dddd, we can see that it's defined as filterLinks. Looking at filterLinks, it is clear that it is set by document.querySelectorAll('a').

Examining the documentation for querySelectorAll tells us that  it returns:

A non-live NodeList containing one Element object for each element that matches at least one of the specified selectors or an empty NodeList in case of no matches.

So to access the actual DOM element object found by the query, we need to pull that object from the NodeList. If you want to perform the toggle operation on every element that is found, the simplest way to do so is to loop through the NodeList and run the function on every element. A NodeList is array-like, but it is not an array, so we need to convert it to an array to be able to use forEach on it. This results in the following code:

```<code>Array.from(dddd).forEach(element => element.classList.toggle('checked'));
</code>```

which would replace this:

```<code>dddd.classList.toggle('checked');
</code>```

Title: Event toggle listener

Body:
I'm trying to change some styles with the ui.activeFilter() method but it says:

Cannot read property toggle of undefined.

And I set the variable filterLinks to global scope. I can't figure why it's not working.

"use strict";

// UI elements
const filterLinks = document.querySelectorAll('a');
const itemsLeft = document.querySelectorAll('span');

// Event listeners
filterLinks.forEach(function(link) {
  link.addEventListener('click', check);
});

// Laptops
class Laptop {
    constructor(availability, price, brand) {
      this.availability = availability;
      this.price = price;
      this.brand = brand;
    }
}

// Filter methods
class UiMethod {
    activeFilter(dddd) {
        dddd.classList.toggle('checked');

        if(dddd.className === 'checked') {
            console.log("test");
        } else {
            console.log('Try again you can do it, you are close to the succes');
        }
    }
}

const ui = new UiMethod;

// Function helpers
function check(e) {

    ui.activeFilter(filterLinks);
    e.preventDefault();
}

Body:
Cannot read property toggle of undefined.

Looks like toggle is referenced here: dddd.classList.toggle. Therefore, dddd.classList is undefined. classList is a defined property on all DOM element objects, so dddd must not be what you think it is.

Looking back at the definition for dddd, we can see that it's defined as filterLinks. Looking at filterLinks, it is clear that it is set by document.querySelectorAll('a').

Examining the documentation for querySelectorAll tells us that  it returns:

A non-live NodeList containing one Element object for each element that matches at least one of the specified selectors or an empty NodeList in case of no matches.

So to access the actual DOM element object found by the query, we need to pull that object from the NodeList. If you want to perform the toggle operation on every element that is found, the simplest way to do so is to loop through the NodeList and run the function on every element. A NodeList is array-like, but it is not an array, so we need to convert it to an array to be able to use forEach on it. This results in the following code:

Array.from(dddd).forEach(element => element.classList.toggle('checked'));

which would replace this:

dddd.classList.toggle('checked');


问:
How compare an Excel file with a web page using Katalon Studio?
Hey guys i am working with Katalon Studio as an automation tool.

My problem is that i want to compare a table in a web page with an excel file.
The table is generated after applying several filters (select multiple options from the web page and then click on see products).

And all of this process should be automatic, the code must choose the filters and display the products in a table and then compare it with an excel file to see how accurate it is.

答:
You can use Apache POI (https://mvnrepository.com/artifact/org.apache.poi/poi/4.1.0) to interact with XLS files.

You can download JAR file and simply add to your project: https://docs.katalon.com/katalon-studio/tutorials/import_java_library.html#using-katalon-project-settings


问:
Springboot failed to map properties file to variable
i want to map values between a yaml file with a Map<String, List<String>> in springboot

country.yml file:

```<code>entries:
  map:
     MY:
      - en
      - zh
</code>```

SampleConfig file:

```<code>@Configuration
@EnableConfigurationProperties
@ConfigurationProperties("entries")
public class SampleConfig {

    private Map<String, List<String>> map = new HashMap<>();

    @Bean
    public void bean1(){
        System.err.println("map has size: "+map.size());
    }
}
</code>```

But the map.size() is always 0, not sure what i do wrong.

答:
Assuming your application is picking the configuration from country.yml (I would check that as well) - You need getters and setters to get it to work. just add:

```<code>@Configuration
@EnableConfigurationProperties
@ConfigurationProperties("entries")
public class SampleConfig {

    private Map<String, List<String>> map = new HashMap<>();

    public Map<String, List<String>> getMap(){
        return map;
    }
    public void setMap(Map<String, List<String>> map){
        this.map=map;
    }

}
</code>```

Body:
i want to map values between a yaml file with a Map<String, List<String>> in springboot

country.yml file:

entries:
  map:
     MY:
      - en
      - zh

SampleConfig file:

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties("entries")
public class SampleConfig {

    private Map<String, List<String>> map = new HashMap<>();

    @Bean
    public void bean1(){
        System.err.println("map has size: "+map.size());
    }
}

But the map.size() is always 0, not sure what i do wrong.

Body:
Assuming your application is picking the configuration from country.yml (I would check that as well) - You need getters and setters to get it to work. just add:

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties("entries")
public class SampleConfig {

    private Map<String, List<String>> map = new HashMap<>();

    public Map<String, List<String>> getMap(){
        return map;
    }
    public void setMap(Map<String, List<String>> map){
        this.map=map;
    }

}


问:
Find a substring in a dictionary; value substring of key; Python
Question: Find a substring

You are given a dictionary of the US states and their capitals (my actual list is larger than provided below). The keys in the dictionary are states and the values are capital names.

Write a code to return a list of all capitals that contain the name of a state in their name as a substring.

HINT: For example, Indianapolis as a capital name and Indiana as a state name is one of the key/value pairs that your code would find. Your code should add Indianapolis to the list. After you found all capitals and added them to the list, print out the list.

```<code># Run this cell to create a dictionary of states' capitals

capitals={
    'Illinios': 'Springfield',
    'Indiana': 'Indianapolis',
    'Oklahoma': 'Oklahoma City',
    'Oregon': 'Salem',
}
</code>```

I believe I have to use substring or contains. I am new to Python. I appreciate it, thank you.

```<code>capitals={capital:state}
list_of_all_capitals=[]
for capital in state
list_of_all_capitals.append=[capital]
print(list_of_all_capitals)
</code>```

答:
Use list-comprehension that iterates over dictionary and check for the existence of substring using the membership operator:

```<code>[y for x, y in capitals.items() if x in y]
</code>```

In code:

```<code>capitals = {
    'Illinios': 'Springfield',
    'Indiana': 'Indianapolis',
    'Oklahoma': 'Oklahoma City',
    'Oregon': 'Salem',
}

print([y for x, y in capitals.items() if x in y])
# ['Indianapolis', 'Oklahoma City']
</code>```

Body:
Question: Find a substring

You are given a dictionary of the US states and their capitals (my actual list is larger than provided below). The keys in the dictionary are states and the values are capital names.

Write a code to return a list of all capitals that contain the name of a state in their name as a substring.

HINT: For example, Indianapolis as a capital name and Indiana as a state name is one of the key/value pairs that your code would find. Your code should add Indianapolis to the list. After you found all capitals and added them to the list, print out the list.

# Run this cell to create a dictionary of states' capitals

capitals={
    'Illinios': 'Springfield',
    'Indiana': 'Indianapolis',
    'Oklahoma': 'Oklahoma City',
    'Oregon': 'Salem',
}

I believe I have to use substring or contains. I am new to Python. I appreciate it, thank you.

capitals={capital:state}
list_of_all_capitals=[]
for capital in state
list_of_all_capitals.append=[capital]
print(list_of_all_capitals)

Body:
Use list-comprehension that iterates over dictionary and check for the existence of substring using the membership operator:

[y for x, y in capitals.items() if x in y]

In code:

capitals = {
    'Illinios': 'Springfield',
    'Indiana': 'Indianapolis',
    'Oklahoma': 'Oklahoma City',
    'Oregon': 'Salem',
}

print([y for x, y in capitals.items() if x in y])
# ['Indianapolis', 'Oklahoma City']


问:
How to change object value within an array of objects with one from another array of objects?
Considering the two arrays bellow:

```<code>let aaa = [{label: "nu", angle: 5}, {label: "na", angle: 3}]
let bbb= [{label: "nu", angle: 2}, {label: "na", angle: 6}]
</code>```

How can I add the value on the angle key from one object with the corresponding one from the next array of objects and return one object or the other.

the result should be:

```<code>let ccc= [{label: "nu", angle: 7}, {label: "na", angle: 9}]
</code>```

I have no idea how to solve this

答:
You can use Array.reduce() and Array.findIndex() like this:

let aaa = [{label: "nu", angle: 5}, {label: "na", angle: 3}];
let bbb= [{label: "nu", angle: 2}, {label: "na", angle: 6}];

const ccc = [...aaa, ...bbb].reduce((acc, a) => {
  const i = acc.findIndex(o => o.label === a.label);

  if(i === -1) { acc.push(a); return acc; }

  acc[i].angle += a.angle;
  return acc;
 }, []);

 console.log(ccc);```

Body:
Considering the two arrays bellow:

let aaa = [{label: "nu", angle: 5}, {label: "na", angle: 3}]
let bbb= [{label: "nu", angle: 2}, {label: "na", angle: 6}]

How can I add the value on the angle key from one object with the corresponding one from the next array of objects and return one object or the other.

the result should be:

let ccc= [{label: "nu", angle: 7}, {label: "na", angle: 9}]

I have no idea how to solve this


问:
Cancelling commands
I am making a command to enable/disable bot commands per-channel. Though having problems cancelling the command if found in the database.

@Nao.event
async def on_command(ctx):
    if ctx.command.parent is None:
        database = mysql.connector.connect(
            host='',
            user='',
            passwd='',
            database=''
        )
        cursor = database.cursor()
        query = "SELECT command FROM cmdsdisabled WHERE channel = %s AND command = %s"
        values = (ctx.channel.id, ctx.command.name,)
        cursor.execute(query, values)
        result = cursor.fetchall()
        for command in result:
            await ctx.send('That command is disabled in this channel.')
        cursor.close()
        return
```

The code works, it checks if the command is in the database and if so, the bot says "That command is disabled in this channel." however, continues to execute the actual command.

I am wanting it to not continue to execute the actual command and only say "That command is disabled in this channel." if the command is found in the database.

答:
You can write a check that raises a custom exception, then handle that exception in a custom exception handler across all of your commands.  The below code just requires you to write some command_is_disabled function to actually determine if the command is disabled.

```<code>from discord.ext.commands import DisabledCommand, check, Bot

bot = Bot("!")

class DisabledInChannel(DisabledCommand):
    pass

def check_disabled():
    def predicate(ctx):
        if command_is_disabled(ctx.command.name, ctx.channel.id):
            raise DisabledInChannel(f"{ctx.command.name} is disabled in {ctx.channel.name}")
        return True
    return check(predicate)

@bot.command()
@check_disabled()
async def some_command(ctx):
    ...

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, DisabledInChannel):
        await ctx.send(error.message)
    else:
        raise error
</code>```

Title: Cancelling commands

Body:
I am making a command to enable/disable bot commands per-channel. Though having problems cancelling the command if found in the database.

@Nao.event
async def on_command(ctx):
    if ctx.command.parent is None:
        database = mysql.connector.connect(
            host='',
            user='',
            passwd='',
            database=''
        )
        cursor = database.cursor()
        query = "SELECT command FROM cmdsdisabled WHERE channel = %s AND command = %s"
        values = (ctx.channel.id, ctx.command.name,)
        cursor.execute(query, values)
        result = cursor.fetchall()
        for command in result:
            await ctx.send('That command is disabled in this channel.')
        cursor.close()
        return

The code works, it checks if the command is in the database and if so, the bot says "That command is disabled in this channel." however, continues to execute the actual command.

I am wanting it to not continue to execute the actual command and only say "That command is disabled in this channel." if the command is found in the database.

Body:
You can write a check that raises a custom exception, then handle that exception in a custom exception handler across all of your commands.  The below code just requires you to write some command_is_disabled function to actually determine if the command is disabled.

from discord.ext.commands import DisabledCommand, check, Bot

bot = Bot("!")

class DisabledInChannel(DisabledCommand):
    pass

def check_disabled():
    def predicate(ctx):
        if command_is_disabled(ctx.command.name, ctx.channel.id):
            raise DisabledInChannel(f"{ctx.command.name} is disabled in {ctx.channel.name}")
        return True
    return check(predicate)

@bot.command()
@check_disabled()
async def some_command(ctx):
    ...

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, DisabledInChannel):
        await ctx.send(error.message)
    else:
        raise error


问:
Django connection to Mongo Atlas Cluster
I am trying to connect my Django1.9 application with cloud DB instance at Mongo Atlas using Pymongo. Our DB name is accounts.

So far I was connecting my local mongodb instance using

```<code>mongoengine.connect(
    username=MONGODB_DATABASES[db]['user'],
    password=MONGODB_DATABASES[db]['password'],
    host=MONGODB_DATABASES[db]['host'],
    port=MONGODB_DATABASES[db]['port'],
    db=MONGODB_DATABASES[db]['name']
)
</code>```

According to example, I have to use below string to connect.

```<code>import pymongo

client = pymongo.MongoClient("mongodb+srv://<DB USER>:<password>@clustername-osaot.mongodb.net/test?retryWrites=true&w=majority")

db = client.test
</code>```

I am able to connect to cluster via mongo shell. But when I run above code, I get errors

```<code>
>>> client = pymongo.MongoClient("mongodb://BackendUser:Xunison_123@cluster0-osaot.mongodb.net/test?retryWrites=true&w=majority")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/site-packages/pymongo/mongo_client.py", line 248, in __init__
    res = uri_parser.parse_uri(entity, port)
  File "/usr/lib/python3.6/site-packages/pymongo/uri_parser.py", line 308, in parse_uri
    options = split_options(opts)
  File "/usr/lib/python3.6/site-packages/pymongo/uri_parser.py", line 211, in split_options
    return validate_options(options)
  File "/usr/lib/python3.6/site-packages/pymongo/uri_parser.py", line 153, in validate_options
    option, value = validate(option, value)
  File "/usr/lib/python3.6/site-packages/pymongo/common.py", line 306, in validate
    value = validator(option, value)
  File "/usr/lib/python3.6/site-packages/pymongo/common.py", line 53, in raise_config_error
    raise ConfigurationError("Unknown option %s" % (key,))
pymongo.errors.ConfigurationError: Unknown option retryWrites

>>> client = pymongo.MongoClient("mongodb://BackendUser:Xunison_123@cluster0-osaot.mongodb.net/test?w=majority")
Traceback (most recent call last):
  File "/usr/lib/python3.6/site-packages/pymongo/mongo_client.py", line 363, in __init__
    self._ensure_connected(True)
  File "/usr/lib/python3.6/site-packages/pymongo/mongo_client.py", line 924, in _ensure_connected
    self.__ensure_member()
  File "/usr/lib/python3.6/site-packages/pymongo/mongo_client.py", line 797, in __ensure_member
    member, nodes = self.__find_node()
  File "/usr/lib/python3.6/site-packages/pymongo/mongo_client.py", line 888, in __find_node
    raise AutoReconnect(', '.join(errors))
pymongo.errors.AutoReconnect: [Errno -5] No address associated with hostname

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/site-packages/pymongo/mongo_client.py", line 366, in __init__
    raise ConnectionFailure(str(e))
pymongo.errors.ConnectionFailure: [Errno -5] No address associated with hostname
>>>

</code>```

I am not able to connect even if I remove everything after clustername.

Can someone please help me?

答: Per the documentation - you will need to upgrade to version 3.4 or later. This documentation can be found under the Atlas Cluster -- Connect menu (same location where you found the connection string).</p>

Body:
I am trying to connect my Django1.9 application with cloud DB instance at Mongo Atlas using Pymongo. Our DB name is accounts.

So far I was connecting my local mongodb instance using

mongoengine.connect(
    username=MONGODB_DATABASES[db]['user'],
    password=MONGODB_DATABASES[db]['password'],
    host=MONGODB_DATABASES[db]['host'],
    port=MONGODB_DATABASES[db]['port'],
    db=MONGODB_DATABASES[db]['name']
)

According to example, I have to use below string to connect.

import pymongo

client = pymongo.MongoClient("mongodb+srv://<DB USER>:<password>@clustername-osaot.mongodb.net/test?retryWrites=true&w=majority")

db = client.test

I am able to connect to cluster via mongo shell. But when I run above code, I get errors

>>> client = pymongo.MongoClient("mongodb://BackendUser:Xunison_123@cluster0-osaot.mongodb.net/test?retryWrites=true&w=majority")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/site-packages/pymongo/mongo_client.py", line 248, in __init__
    res = uri_parser.parse_uri(entity, port)
  File "/usr/lib/python3.6/site-packages/pymongo/uri_parser.py", line 308, in parse_uri
    options = split_options(opts)
  File "/usr/lib/python3.6/site-packages/pymongo/uri_parser.py", line 211, in split_options
    return validate_options(options)
  File "/usr/lib/python3.6/site-packages/pymongo/uri_parser.py", line 153, in validate_options
    option, value = validate(option, value)
  File "/usr/lib/python3.6/site-packages/pymongo/common.py", line 306, in validate
    value = validator(option, value)
  File "/usr/lib/python3.6/site-packages/pymongo/common.py", line 53, in raise_config_error
    raise ConfigurationError("Unknown option %s" % (key,))
pymongo.errors.ConfigurationError: Unknown option retryWrites

>>> client = pymongo.MongoClient("mongodb://BackendUser:Xunison_123@cluster0-osaot.mongodb.net/test?w=majority")
Traceback (most recent call last):
  File "/usr/lib/python3.6/site-packages/pymongo/mongo_client.py", line 363, in __init__
    self._ensure_connected(True)
  File "/usr/lib/python3.6/site-packages/pymongo/mongo_client.py", line 924, in _ensure_connected
    self.__ensure_member()
  File "/usr/lib/python3.6/site-packages/pymongo/mongo_client.py", line 797, in __ensure_member
    member, nodes = self.__find_node()
  File "/usr/lib/python3.6/site-packages/pymongo/mongo_client.py", line 888, in __find_node
    raise AutoReconnect(', '.join(errors))
pymongo.errors.AutoReconnect: [Errno -5] No address associated with hostname

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/site-packages/pymongo/mongo_client.py", line 366, in __init__
    raise ConnectionFailure(str(e))
pymongo.errors.ConnectionFailure: [Errno -5] No address associated with hostname
>>>

I am not able to connect even if I remove everything after clustername.

Can someone please help me?


问:
How to convert string containing AM/PM to datetime in python using %p
I need to convert a string formatted as '2000-01-01 12:00:00 AM' but it doesn't matter if it is AM or PM the result is the same (see example below).

```<code>from datetime import datetime
frmt = '%Y-%d-%m %H:%M:%S %p'
datetime.strptime('2000-01-01 12:00:00 AM', frmt).isoformat()
datetime.strptime('2000-01-01 12:00:00 PM', frmt).isoformat()
</code>```

Output is:

```<code>'2000-01-01T12:00:00'
'2000-01-01T12:00:00'
</code>```

I thought it could be a problem related to no definition if 12AM is midnight or noon but even when executing the same code for other different hours the result is still the same:

```<code>datetime.strptime('2000-01-01 06:00:00 AM', frmt).isoformat()
datetime.strptime('2000-01-01 06:00:00 PM', frmt).isoformat()
</code>```

Output is:

```<code>'2000-01-01T06:00:00'
'2000-01-01T06:00:00'
</code>```

The strftime.org website says the format I am using should work, but it is not. What should I do?

答:
You can use dateutil.parser.parse to parse any datetime string without providing a format string, this is available in the dateutil module</p>

```<code>In [22]: from dateutil import parser

In [25]: parser.parse('2000-01-01 12:00:00 PM').isoformat()
Out[25]: '2000-01-01T12:00:00'

In [26]: parser.parse('2000-01-01 12:00:00 AM').isoformat()
Out[26]: '2000-01-01T00:00:00'
</code>```

Body:
I need to convert a string formatted as '2000-01-01 12:00:00 AM' but it doesn't matter if it is AM or PM the result is the same (see example below).

from datetime import datetime
frmt = '%Y-%d-%m %H:%M:%S %p'
datetime.strptime('2000-01-01 12:00:00 AM', frmt).isoformat()
datetime.strptime('2000-01-01 12:00:00 PM', frmt).isoformat()

Output is:

'2000-01-01T12:00:00'
'2000-01-01T12:00:00'

I thought it could be a problem related to no definition if 12AM is midnight or noon but even when executing the same code for other different hours the result is still the same:

datetime.strptime('2000-01-01 06:00:00 AM', frmt).isoformat()
datetime.strptime('2000-01-01 06:00:00 PM', frmt).isoformat()

Output is:

'2000-01-01T06:00:00'
'2000-01-01T06:00:00'

The strftime.org website says the format I am using should work, but it is not. What should I do?

Body:
You can use dateutil.parser.parse to parse any datetime string without providing a format string, this is available in the dateutil module

In [22]: from dateutil import parser

In [25]: parser.parse('2000-01-01 12:00:00 PM').isoformat()
Out[25]: '2000-01-01T12:00:00'

In [26]: parser.parse('2000-01-01 12:00:00 AM').isoformat()
Out[26]: '2000-01-01T00:00:00'


问:
facility count not using list
I have a SQL statement:

```<code>SELECT
  p.id
  ,SUM(CASE WHEN pf.facility_code in ('S','H','E') then 1 ELSE 0 END) as facility_count
FROM people p
  inner JOIN people_facilities pf ON p.ID = pf.ID
group by p.id
</code>```

and from the above statement, you'd understand that the facility_count can't be greater than 3.  However, the first one in the list has 18 facilities in the count.

I'm referring to count with case and list

Why is this count not working?

答:
After the join, there may exist multiple rows with the same id and the same facility_code.

So first get distinct pairs of these columns and then group and aggregate:

```<code>SELECT
  t.id,
  SUM(CASE WHEN t.facility_code in ('S','H','E') then 1 ELSE 0 END) as facility_count
FROM (
  SELECT DISTINCT p.id, pf.facility_code
  FROM people p inner JOIN people_facilities pf
  ON p.ID = pf.ID
) t
group by t.id
</code>```

Title: facility count not using list

Body:
I have a SQL statement:

SELECT
  p.id
  ,SUM(CASE WHEN pf.facility_code in ('S','H','E') then 1 ELSE 0 END) as facility_count
FROM people p
  inner JOIN people_facilities pf ON p.ID = pf.ID
group by p.id

and from the above statement, you'd understand that the facility_count can't be greater than 3.  However, the first one in the list has 18 facilities in the count.

I'm referring to count with case and list

Why is this count not working?

Body:
After the join, there may exist multiple rows with the same id and the same facility_code.

So first get distinct pairs of these columns and then group and aggregate:

SELECT
  t.id,
  SUM(CASE WHEN t.facility_code in ('S','H','E') then 1 ELSE 0 END) as facility_count
FROM (
  SELECT DISTINCT p.id, pf.facility_code
  FROM people p inner JOIN people_facilities pf
  ON p.ID = pf.ID
) t
group by t.id


问:
Recursive using expand() and concatMap() in Angular 7
I have following API list below:

```<code>1. https://www.something.com/?filter=something

Result:
{
  id: 12
  previous: null
  next: https://www.something.com/?filter=something&page=2
  data: ...
}

2. https://www.something.com/?filter=something&page=2

Result:
{
  id: 13
  previous: https://www.something.com/?filter=something
  next: https://www.something.com/?filter=something&page=3
  data: ...
}

3. https://www.something.com/?filter=something&page=3

Result:
{
  id: 14
  previous: https://www.something.com/?filter=something&page=2
  next: null
  data: ...
}
</code>```

I want to loop through all of the urls after getting the data back of each API call, check if the   next variable is null. If it is not null, it will keep continue going. while it's going through, the data of each API call will be concat and return to output.

This is what i have been trying so far

```<code> getByURL(url: string): any {
    return this.apiService.get(url).pipe(map(data => data));
  }

  getData(): Observable<any> {
    const url = 'https://www.something.com/?filter=something';
    return this.getByURL(url).pipe(
      expand(({ data }) => {
        if (!data.next) return this.getByURL(data.next);
        else return empty();
      }),
      concatMap(({ content }) => {
        return of(content.data);
      })
    );
  }
</code>```

But i got undefined result, i have struggled it for several day. Thanks

UPDATED

I put my code here in stackblitz:
I have 3 api call :

```<code>http://5cf15627c936cb001450bd0a.mockapi.io/users
http://5cf15627c936cb001450bd0a.mockapi.io/users2
http://5cf15627c936cb001450bd0a.mockapi.io/users3
</code>```

I want to gather all of the data after each requests. Please see the console to see the output. i always get undefined. Thanks

https://stackblitz.com/edit/angular-rai6az?file=src%2Fapp%2Fapp.component.ts

答:
I fixed your code as below (fixed stackblitz)

```<code>  ngOnInit() {
    this.getByPageNext()
      .subscribe(data => {
        console.log(data);
      });
  }

  get(url: string): Observable<any> {
    return this.httpClient
      .get(url)
      .pipe(catchError(this.formatErrors));
  }

  formatErrors(error: any) {
    console.error('error', error);
    return throwError(error.error);
  }

  getByURL(url: string): any {
    return this.get(url);
  }

  getByPageNext(): Observable<any> {
    const url = 'https://5cf15627c936cb001450bd0a.mockapi.io/users2';
    return this.getByURL(url)
      .pipe(
        expand((response: Array<any>) => {
          if (response && response.length && response[0].next) {
              return this.getByURL(response[0].next);
          }
          else {
            return empty()
          }
        }),
        map(obj => obj[0]),
        reduce((acc, x: any) => acc.concat([x.data]), []),
      );
  }
</code>```

so it will concat all data as array and recursive calling http works fine.

The only problem is when calling 'https://5cf15627c936cb001450bd0a.mockapi.io/users' the next url is http not https which will result in HttpError -> ProgressEvent.

So I started form 'https://5cf15627c936cb001450bd0a.mockapi.io/users2' and rest is working fine. So after you changed the backend to fix the next link, then change it back to your original request.

The other point was your result from api comes back as an array not an object, this is why I accesses result[0]

The other point was your condition to return empty() was vice versa

Body:
I have following API list below:

1. https://www.something.com/?filter=something

Result:
{
  id: 12
  previous: null
  next: https://www.something.com/?filter=something&page=2
  data: ...
}

2. https://www.something.com/?filter=something&page=2

Result:
{
  id: 13
  previous: https://www.something.com/?filter=something
  next: https://www.something.com/?filter=something&page=3
  data: ...
}

3. https://www.something.com/?filter=something&page=3

Result:
{
  id: 14
  previous: https://www.something.com/?filter=something&page=2
  next: null
  data: ...
}

I want to loop through all of the urls after getting the data back of each API call, check if the   next variable is null. If it is not null, it will keep continue going. while it's going through, the data of each API call will be concat and return to output.

This is what i have been trying so far

 getByURL(url: string): any {
    return this.apiService.get(url).pipe(map(data => data));
  }

  getData(): Observable<any> {
    const url = 'https://www.something.com/?filter=something';
    return this.getByURL(url).pipe(
      expand(({ data }) => {
        if (!data.next) return this.getByURL(data.next);
        else return empty();
      }),
      concatMap(({ content }) => {
        return of(content.data);
      })
    );
  }

But i got undefined result, i have struggled it for several day. Thanks

UPDATED

I put my code here in stackblitz:
I have 3 api call :

http://5cf15627c936cb001450bd0a.mockapi.io/users
http://5cf15627c936cb001450bd0a.mockapi.io/users2
http://5cf15627c936cb001450bd0a.mockapi.io/users3

I want to gather all of the data after each requests. Please see the console to see the output. i always get undefined. Thanks

https://stackblitz.com/edit/angular-rai6az?file=src%2Fapp%2Fapp.component.ts

Body:
I fixed your code as below (fixed stackblitz)

  ngOnInit() {
    this.getByPageNext()
      .subscribe(data => {
        console.log(data);
      });
  }

  get(url: string): Observable<any> {
    return this.httpClient
      .get(url)
      .pipe(catchError(this.formatErrors));
  }

  formatErrors(error: any) {
    console.error('error', error);
    return throwError(error.error);
  }

  getByURL(url: string): any {
    return this.get(url);
  }

  getByPageNext(): Observable<any> {
    const url = 'https://5cf15627c936cb001450bd0a.mockapi.io/users2';
    return this.getByURL(url)
      .pipe(
        expand((response: Array<any>) => {
          if (response && response.length && response[0].next) {
              return this.getByURL(response[0].next);
          }
          else {
            return empty()
          }
        }),
        map(obj => obj[0]),
        reduce((acc, x: any) => acc.concat([x.data]), []),
      );
  }

so it will concat all data as array and recursive calling http works fine.

The only problem is when calling 'https://5cf15627c936cb001450bd0a.mockapi.io/users' the next url is http not https which will result in HttpError -> ProgressEvent.

So I started form 'https://5cf15627c936cb001450bd0a.mockapi.io/users2' and rest is working fine. So after you changed the backend to fix the next link, then change it back to your original request.

The other point was your result from api comes back as an array not an object, this is why I accesses result[0]

The other point was your condition to return empty() was vice versa


问:
Simple Java name based locks?
MySQL has a handy function:

```<code>SELECT GET_LOCK("SomeName")
</code>```

This can be used to create simple, but very specific, name-based locks for an application. However, it requires a database connection.

I have many situations like:

```<code>someMethod() {
    // do stuff to user A for their data for feature X
}
</code>```

It doesn't make sense to simply synchronize this method, because, for example, if this method is called for user B in the meantime, user B does not need to wait for user A to finish before it starts, only operations for the user A and feature X combination need to wait.

With the MySql lock I could do something like:

```<code>someMethod() {
    executeQuery("SELECT GET_LOCK('userA-featureX')")
    // only locked for user A for their data for feature X
    executeQuery("SELECT RELEASE_LOCK('userA-featureX')")
}
</code>```

Since Java locking is based on objects, it seems like I would need to create a new object to represent the situation for this lock and then put it in a static cache somewhere so all the threads can see it. Subsequent requests to lock for that situation would then locate the lock object in the cache and acquire its lock. I tried to create something like this, but then the lock cache itself needs synchronization. Also, it is difficult to detect when a lock object is no longer being used so that it can be removed from the cache.

I have looked at the Java concurrent packages, but nothing stands out as being able to handle something like this. Is there an easy way to implement this, or am I looking at this from the wrong perspective?

Edit:

To clarify, I am not looking to create a predefined pool of locks ahead of time, I would like to create them on demand. Some pseudo-code for what I am thinking of is:

```<code>LockManager.acquireLock(String name) {
    Lock lock;

    synchronized (map) {
        lock = map.get(name);

        // doesn't exist yet - create and store
        if(lock == null) {
            lock = new Lock();
            map.put(name, lock);
        }
    }

    lock.lock();
}

LockManager.releaseLock(String name) {
    // unlock
    // if this was the last hold on the lock, remove it from the cache
}
</code>```

答:
Your idea about a shared static repository of lock objects for each situation is correct.

You don't need the cache itself to be synchronized ... it can be as simple as a hash map.

Threads can simultaneously get a lock object from the map. The actual synchronization logic should be encapsulated within each such object separately (see the java.util.concurrent package for that - http://download.oracle.com/javase/6/docs/api/java/util/concurrent/locks/package-summary.html)

Title: Simple Java name based locks?

Body:
MySQL has a handy function:

SELECT GET_LOCK("SomeName")

This can be used to create simple, but very specific, name-based locks for an application. However, it requires a database connection.

I have many situations like:

someMethod() {
    // do stuff to user A for their data for feature X
}

It doesn't make sense to simply synchronize this method, because, for example, if this method is called for user B in the meantime, user B does not need to wait for user A to finish before it starts, only operations for the user A and feature X combination need to wait.

With the MySql lock I could do something like:

someMethod() {
    executeQuery("SELECT GET_LOCK('userA-featureX')")
    // only locked for user A for their data for feature X
    executeQuery("SELECT RELEASE_LOCK('userA-featureX')")
}

Since Java locking is based on objects, it seems like I would need to create a new object to represent the situation for this lock and then put it in a static cache somewhere so all the threads can see it. Subsequent requests to lock for that situation would then locate the lock object in the cache and acquire its lock. I tried to create something like this, but then the lock cache itself needs synchronization. Also, it is difficult to detect when a lock object is no longer being used so that it can be removed from the cache.

I have looked at the Java concurrent packages, but nothing stands out as being able to handle something like this. Is there an easy way to implement this, or am I looking at this from the wrong perspective?

Edit:

To clarify, I am not looking to create a predefined pool of locks ahead of time, I would like to create them on demand. Some pseudo-code for what I am thinking of is:

LockManager.acquireLock(String name) {
    Lock lock;

    synchronized (map) {
        lock = map.get(name);

        // doesn't exist yet - create and store
        if(lock == null) {
            lock = new Lock();
            map.put(name, lock);
        }
    }

    lock.lock();
}

LockManager.releaseLock(String name) {
    // unlock
    // if this was the last hold on the lock, remove it from the cache
}