问:
How to extract a value from a Pandas data frame from a reference in the frame, then "walk up" the frame to another specified value?
I have the following toy data set:

```<code>import pandas as pd
from StringIO import StringIO

# read the data
df = pd.read_csv(StringIO("""
    Date         Return
    1/28/2009   -0.825148
    1/29/2009   -0.859997
    1/30/2009   0.000000
    2/2/2009    -0.909546
    2/3/2009    0.000000
    2/4/2009    -0.899110
    2/5/2009    -0.866104
    2/6/2009    0.000000
    2/9/2009    -0.830099
    2/10/2009   -0.885111
    2/11/2009   -0.878320
    2/12/2009   -0.881853
    2/13/2009   -0.884432
    2/17/2009   -0.947781
    2/18/2009   -0.966414
    2/19/2009   -1.016344
    2/20/2009   -1.029667
    2/23/2009   -1.087432
    2/24/2009   -1.050808
    2/25/2009   -1.089594
    2/26/2009   -1.121556
    2/27/2009   -1.105873
    3/2/2009    -1.205019
    3/3/2009    -1.191488
    3/4/2009    -1.059311
    3/5/2009    -1.135962
    3/6/2009    -1.147031
    3/9/2009    -1.117328
    3/10/2009   -1.009050"""), sep="\s+").reset_index()
</code>```

My goals are to:

a) find the most negative value in the "Return" column

b) find the date the this value occurred

c) then "walk up" the "Return" column to find the first instance a specific value (in this case, 0.000000).

d) find the date associated with the value returned in step "c"

The results I'm looking for are:

a) -1.20519

b) March 2, 2009

c) 0.000000

d) February 6, 2009

I can find "a" with the following code:

```<code>max_dd = df['Maximum_Drawdown'].min()
</code>```

To get "b", I tried to use the following code:

```<code>df.loc[df['Return'] == max_dd, 'Date']
</code>```

But, the error message says:

```<code>KeyError: 'Date'
</code>```

Note: I can get "b" to work in this toy example, but the actual data throws the error message.  Here is actual code used to import the data from the csv file:

```<code>df = pd.read_csv(FILE_NAME, parse_dates=True).reset_index()

df.set_index('Date', inplace = True)  <<--- this is causing the problem
</code>```

答:
To solve all of your problems your code could be written as follows:</p>

```<code>import pandas as pd
from io import StringIO

# read the data
df = pd.read_csv(StringIO("""
    Date         Return
    1/28/2009   -0.825148
    1/29/2009   -0.859997
    1/30/2009   0.000000
    2/2/2009    -0.909546
    2/3/2009    0.000000
    2/4/2009    -0.899110
    2/5/2009    -0.866104
    2/6/2009    0.000000
    2/9/2009    -0.830099
    2/10/2009   -0.885111
    2/11/2009   -0.878320
    2/12/2009   -0.881853
    2/13/2009   -0.884432
    2/17/2009   -0.947781
    2/18/2009   -0.966414
    2/19/2009   -1.016344
    2/20/2009   -1.029667
    2/23/2009   -1.087432
    2/24/2009   -1.050808
    2/25/2009   -1.089594
    2/26/2009   -1.121556
    2/27/2009   -1.105873
    3/2/2009    -1.205019
    3/3/2009    -1.191488
    3/4/2009    -1.059311
    3/5/2009    -1.135962
    3/6/2009    -1.147031
    3/9/2009    -1.117328
    3/10/2009   -1.009050"""), sep="\s+").reset_index()

# a) find the most negative value in the "Return" column
min_value = df["Return"].min()
print("The minimum value in the dataset is: {}".format(min_value))

# b) find the date that this minimum value occurred at
min_value_date = df.iloc[df["Return"].idxmin(), :]["Date"]
print("The minimum value in the dataset occurred on: {}".format(min_value_date))

# c) find the first instance of a specified value in the dataset closest to this
# minimum value with an index less than the minimum value index
found_value = 0
found_indices = df.index[df["Return"] == found_value].tolist()
found_correct_index = -1
for index in found_indices:
    if index > df["Return"].idxmin():
        break
    previous_index = index

found_correct_index = previous_index
try:
    print("The value searched for is {0} and it is found in the index of {1}.".format(found_value, found_correct_index))
except:
    print("The value searched for of {0} was not found in the dataset.".format(found_value))

# d) find the date associated with that value
found_value_date = df.iloc[found_correct_index, :]["Date"]
print("The date associated with that found value of {0} is {1}.".format(found_value, found_value_date))
</code>```

Body:
I have the following toy data set:

import pandas as pd
from StringIO import StringIO

# read the data
df = pd.read_csv(StringIO("""
    Date         Return
    1/28/2009   -0.825148
    1/29/2009   -0.859997
    1/30/2009   0.000000
    2/2/2009    -0.909546
    2/3/2009    0.000000
    2/4/2009    -0.899110
    2/5/2009    -0.866104
    2/6/2009    0.000000
    2/9/2009    -0.830099
    2/10/2009   -0.885111
    2/11/2009   -0.878320
    2/12/2009   -0.881853
    2/13/2009   -0.884432
    2/17/2009   -0.947781
    2/18/2009   -0.966414
    2/19/2009   -1.016344
    2/20/2009   -1.029667
    2/23/2009   -1.087432
    2/24/2009   -1.050808
    2/25/2009   -1.089594
    2/26/2009   -1.121556
    2/27/2009   -1.105873
    3/2/2009    -1.205019
    3/3/2009    -1.191488
    3/4/2009    -1.059311
    3/5/2009    -1.135962
    3/6/2009    -1.147031
    3/9/2009    -1.117328
    3/10/2009   -1.009050"""), sep="\s+").reset_index()

My goals are to:

a) find the most negative value in the "Return" column

b) find the date the this value occurred

c) then "walk up" the "Return" column to find the first instance a specific value (in this case, 0.000000).

d) find the date associated with the value returned in step "c"

The results I'm looking for are:

a) -1.20519

b) March 2, 2009

c) 0.000000

d) February 6, 2009

I can find "a" with the following code:

max_dd = df['Maximum_Drawdown'].min()

To get "b", I tried to use the following code:

df.loc[df['Return'] == max_dd, 'Date']

But, the error message says:

KeyError: 'Date'

Note: I can get "b" to work in this toy example, but the actual data throws the error message.  Here is actual code used to import the data from the csv file:

df = pd.read_csv(FILE_NAME, parse_dates=True).reset_index()

df.set_index('Date', inplace = True)  <<--- this is causing the problem

Body:
To solve all of your problems your code could be written as follows:

import pandas as pd
from io import StringIO

# read the data
df = pd.read_csv(StringIO("""
    Date         Return
    1/28/2009   -0.825148
    1/29/2009   -0.859997
    1/30/2009   0.000000
    2/2/2009    -0.909546
    2/3/2009    0.000000
    2/4/2009    -0.899110
    2/5/2009    -0.866104
    2/6/2009    0.000000
    2/9/2009    -0.830099
    2/10/2009   -0.885111
    2/11/2009   -0.878320
    2/12/2009   -0.881853
    2/13/2009   -0.884432
    2/17/2009   -0.947781
    2/18/2009   -0.966414
    2/19/2009   -1.016344
    2/20/2009   -1.029667
    2/23/2009   -1.087432
    2/24/2009   -1.050808
    2/25/2009   -1.089594
    2/26/2009   -1.121556
    2/27/2009   -1.105873
    3/2/2009    -1.205019
    3/3/2009    -1.191488
    3/4/2009    -1.059311
    3/5/2009    -1.135962
    3/6/2009    -1.147031
    3/9/2009    -1.117328
    3/10/2009   -1.009050"""), sep="\s+").reset_index()

# a) find the most negative value in the "Return" column
min_value = df["Return"].min()
print("The minimum value in the dataset is: {}".format(min_value))

# b) find the date that this minimum value occurred at
min_value_date = df.iloc[df["Return"].idxmin(), :]["Date"]
print("The minimum value in the dataset occurred on: {}".format(min_value_date))

# c) find the first instance of a specified value in the dataset closest to this
# minimum value with an index less than the minimum value index
found_value = 0
found_indices = df.index[df["Return"] == found_value].tolist()
found_correct_index = -1
for index in found_indices:
    if index > df["Return"].idxmin():
        break
    previous_index = index

found_correct_index = previous_index
try:
    print("The value searched for is {0} and it is found in the index of {1}.".format(found_value, found_correct_index))
except:
    print("The value searched for of {0} was not found in the dataset.".format(found_value))

# d) find the date associated with that value
found_value_date = df.iloc[found_correct_index, :]["Date"]
print("The date associated with that found value of {0} is {1}.".format(found_value, found_value_date))


来源: stackexchange

问:
setPlaybackContent and network audio
ref: https://developer.sony.com/develop/audio-control-api/api-references/api-overview-2#_setplaycontent_v1_2

Is it possible to play an mp3 stored on a webserver, e.g. http://example.com/myfile.mp3? Or even better, a Shoutcast mp3 stream URL?

The API docs do not really give many examples of the URI parameter for the setPlayContent function. Just a single DLNA mp3 example. And the Device URI page is very vague:
https://developer.sony.com/develop/audio-control-api/api-references/device-uri

Thanks in advance.

答:
It is not possible to play streaming audio from the internet (e.g. Shoutcast, etc) on the Sony STR-DN1080 using the Sony Audio Control API. However, it can be done using the built-in Chromecast Audio device, as per this answer on another question. For example, one can use the Google Cast SDK or an alternative such as Chromecast Java API v2.

I cannot speak of the Google Cast SDK, but I managed to get Shoutcast streams to play on the Sony STR-DN1080 using Chromecast Java API v2. In some cases one may need to append ;stream.mp3 to the Shoutcast stream URL, e.g. http://s2.onweb.gr:8604/ becomes http://s2.onweb.gr:8604/;stream.mp3.

I have had success playing MP3, AAC, Opus, FLAC, and Ogg streams. I hope that this helps someone.

ContentLicense: CC BY-SA 4.0

Title: setPlaybackContent and network audio


问:
Adding a index to collection using EF 4.1 and XAML (For a highscore table)
I have a webservice I call from a WP7 app. I get a list of high scores in a table (name/score).. What is the simpliest way to add a 3rd column on the far left which is simply the row?

Do I need to add a property to the entity? Is there someway to get the row #?

I tried these things below with no success..

```<code> [OperationContract]
    public List<DMHighScore> GetScores()
    {
        using (var db = new DMModelContainer())
        {
            //  return db.DMHighScores.ToList();

            var collOrderedHighScoreItem = (from o in db.DMHighScores
                                            orderby o.UserScore ascending
                                            select new
                                            {
                                                o.UserName,
                                                o.UserScore
                                            }).Take(20);

            var collOrderedHighScoreItem2 = collOrderedHighScoreItem.AsEnumerable().Select((x, i) => new DMHighScoreDTO
            {
                UserName = x.UserName,
                UserScore = x.UserScore
            }).ToList();

        }

    }
  [DataContract]
public class DMHighScoreDTO
{
    int Rank;
    string UserName;
    string UserScore;
}
</code>```

答:
what will the row number be used for? if this is for ordering might I suggest adding a column named Order, then map the column to your entity.

if you require a row index, you could also call the .ToList() on the query and fetch the index locations for each entity.

Edit:

you could add the Rank property and set it to Ignore. This will enable you to go through the collection set the rank with a simple for loop. This will also not be persisted in the database. It will also not have any required columns in the database.

It does add an extra iteration.

the other way to go about it. This would be to add the rank number in the generated UI and not in the data collection being used to bind.

ContentLicense: CC BY-SA 3.0

Body:
I have a webservice I call from a WP7 app. I get a list of high scores in a table (name/score).. What is the simpliest way to add a 3rd column on the far left which is simply the row?

Do I need to add a property to the entity? Is there someway to get the row #?

I tried these things below with no success..

 [OperationContract]
    public List<DMHighScore> GetScores()
    {
        using (var db = new DMModelContainer())
        {
            //  return db.DMHighScores.ToList();

            var collOrderedHighScoreItem = (from o in db.DMHighScores
                                            orderby o.UserScore ascending
                                            select new
                                            {
                                                o.UserName,
                                                o.UserScore
                                            }).Take(20);

            var collOrderedHighScoreItem2 = collOrderedHighScoreItem.AsEnumerable().Select((x, i) => new DMHighScoreDTO
            {
                UserName = x.UserName,
                UserScore = x.UserScore
            }).ToList();

        }

    }
  [DataContract]
public class DMHighScoreDTO
{
    int Rank;
    string UserName;
    string UserScore;
}


问:
Creating responsive nav that aligns to the right on mobile but snaps to the center on larger screens
I'm trying to create a nav with a logo and links. I want the logo to always remain in the same position, vertically centered on the left, but I want the link items to change depending on the screen size.

On small screens, I want a small font size with the links aligned to the right
2.On medium screens, I want a medium font size with the links aligned in the center

On large screens, I want a larger font size with the links aligned in the center

Ideally, I want the changes to happen whenever the text is right about to hit the logo.

Here's a link to what I'm picturing.

答:
You could use media queries to adjust font size and positioning based on screen size.  <code>@media (max-width 600px) {
[your nav name] a { font-size: .7rem; float: right; }}</code> for example.  Adjust for different screens accordingly.  </p>

Body:
You could use media queries to adjust font size and positioning based on screen size.  @media (max-width 600px) {
[your nav name] a { font-size: .7rem; float: right; }} for example.  Adjust for different screens accordingly.


问:
Need help joining 2 tables and rolling them up in a unique way using BigQuery SQL
I have 2 tables at different granularity in a BigQuery dataset. I need to join those two and roll it up using BigQuery SQL in such a way that the value in one of the columns of the 2nd table becomes the columns in the final table

Table 1 - tb1 looks like this

```<code>user_id     event_date
A          2019-02-01
B          2019-02-10
C          2019-01-15
</code>```

Table 2 - tb2 looks like this

```<code>user_id    activity_id   activity_date
A          1             2019-01-01
A          1             2019-02-05
A          2             2019-01-15
B          2             2019-02-02
B          3             2019-02-01
C          1             2019-01-02
</code>```

I am trying to write a SQL query to create the final table which tells us the number of records for each activity for a user_id where the activity_date is within (event_date - 90 days) for that user_id i.e the activity_date is in the 90 days leading up to the event_date.
So, in this case, the output will look like this

```<code>user_id   event_date  act_1   act_2    act_3
A         2019-02-01   1        1        0
B         2019-02-10   0        2        1
C         2019-01-15   1        0        0
</code>```

act_1 column corresponds to activity_id=1 and so on.

There are some additional complications like :-

The number of distinct activity_ids in Table 2 can change over time. So, I don't know before hand how many columns will be created in the output table.

I cannot do this in python but has to be done in BQ. This is because the actual table 2 is very large (42TB with 31bn rows) and pulling it out of BQ into another GCS product to run python might be cumbersome.

Any help is appreciated.

答:
Below is for BigQuery Standard SQL and just to demonstrate you approach of pivoting data

If you would know in advance how many distinct activity_id you have and if the number of such is low - for example three - as in your example - you would do as simple as below

```<code>#standardSQL
SELECT
  user_id,
  event_date,
  COUNTIF(activity_id = 1) act_1,
  COUNTIF(activity_id = 2) act_2,
  COUNTIF(activity_id = 3) act_3
FROM `project.dataset.table1` t1
JOIN `project.dataset.table2` t2
USING(user_id)
GROUP BY user_id, event_date
ORDER BY user_id, event_date
</code>```

if to apply to sample data as in your question - result will be

```<code>Row user_id event_date  act_1   act_2   act_3
1   A       2019-02-01  2       1       0
2   B       2019-02-10  0       1       1
3   C       2019-01-15  1       0       0
</code>```

But as you mentioned

The number of distinct activity_ids in Table 2 can change over time. So, I don't know before hand how many columns will be created in the output table

So, you need to generate above query dynamically - below is an example of such

```<code>#standardSQL
WITH activities AS (
  SELECT DISTINCT activity_id
  FROM `project.dataset.table2`
), generate_query AS (
  SELECT CONCAT(
    'SELECT user_id, event_date',
    STRING_AGG(CONCAT(',COUNTIF(activity_id = ', CAST(activity_id AS STRING), ') act_', CAST(activity_id AS STRING)), ''),
    ' FROM `project.dataset.table1` t1 JOIN `project.dataset.table2` t2 USING(user_id) GROUP BY user_id, event_date ORDER BY user_id, event_date'
  ) AS query
  FROM activities
)
SELECT query FROM generate_query
</code>```

Again, if to apply to your sample data - result will be

```<code>SELECT user_id, event_date,COUNTIF(activity_id = 1) act_1,COUNTIF(activity_id = 2) act_2,COUNTIF(activity_id = 3) act_3 FROM `project.dataset.table1` t1 JOIN `project.dataset.table2` t2 USING(user_id) GROUP BY user_id, event_date ORDER BY user_id, event_date
</code>```

if to look closer to above result - you can see  - it is exactly the query that we initially wrote manually - but now it was generated for us - and no matter how many distinct activity_id you have (obviously limitations on columns number is still apply) - it will product needed query

So, now you just need to copy the text of query from above result and just simply run it - which will produce desired result

```<code>Row user_id event_date  act_1   act_2   act_3
1   A       2019-02-01  2       1       0
2   B       2019-02-10  0       1       1
3   C       2019-01-15  1       0       0
</code>```

As you can see this is two-steps process - but you can script it using client of your choice

Note: i focused on substance of the question and have not addressed at all 90 days related stuff - I feel it was secondary detail in your question

Body:
I have 2 tables at different granularity in a BigQuery dataset. I need to join those two and roll it up using BigQuery SQL in such a way that the value in one of the columns of the 2nd table becomes the columns in the final table

Table 1 - tb1 looks like this

user_id     event_date
A          2019-02-01
B          2019-02-10
C          2019-01-15

Table 2 - tb2 looks like this

user_id    activity_id   activity_date
A          1             2019-01-01
A          1             2019-02-05
A          2             2019-01-15
B          2             2019-02-02
B          3             2019-02-01
C          1             2019-01-02

I am trying to write a SQL query to create the final table which tells us the number of records for each activity for a user_id where the activity_date is within (event_date - 90 days) for that user_id i.e the activity_date is in the 90 days leading up to the event_date.
So, in this case, the output will look like this

user_id   event_date  act_1   act_2    act_3
A         2019-02-01   1        1        0
B         2019-02-10   0        2        1
C         2019-01-15   1        0        0

act_1 column corresponds to activity_id=1 and so on.

There are some additional complications like :-

The number of distinct activity_ids in Table 2 can change over time. So, I don't know before hand how many columns will be created in the output table.

I cannot do this in python but has to be done in BQ. This is because the actual table 2 is very large (42TB with 31bn rows) and pulling it out of BQ into another GCS product to run python might be cumbersome.

Any help is appreciated.

Body:
Below is for BigQuery Standard SQL and just to demonstrate you approach of pivoting data

If you would know in advance how many distinct activity_id you have and if the number of such is low - for example three - as in your example - you would do as simple as below

#standardSQL
SELECT
  user_id,
  event_date,
  COUNTIF(activity_id = 1) act_1,
  COUNTIF(activity_id = 2) act_2,
  COUNTIF(activity_id = 3) act_3
FROM `project.dataset.table1` t1
JOIN `project.dataset.table2` t2
USING(user_id)
GROUP BY user_id, event_date
ORDER BY user_id, event_date

if to apply to sample data as in your question - result will be

Row user_id event_date  act_1   act_2   act_3
1   A       2019-02-01  2       1       0
2   B       2019-02-10  0       1       1
3   C       2019-01-15  1       0       0

But as you mentioned

The number of distinct activity_ids in Table 2 can change over time. So, I don't know before hand how many columns will be created in the output table

So, you need to generate above query dynamically - below is an example of such

#standardSQL
WITH activities AS (
  SELECT DISTINCT activity_id
  FROM `project.dataset.table2`
), generate_query AS (
  SELECT CONCAT(
    'SELECT user_id, event_date',
    STRING_AGG(CONCAT(',COUNTIF(activity_id = ', CAST(activity_id AS STRING), ') act_', CAST(activity_id AS STRING)), ''),
    ' FROM `project.dataset.table1` t1 JOIN `project.dataset.table2` t2 USING(user_id) GROUP BY user_id, event_date ORDER BY user_id, event_date'
  ) AS query
  FROM activities
)
SELECT query FROM generate_query

Again, if to apply to your sample data - result will be

SELECT user_id, event_date,COUNTIF(activity_id = 1) act_1,COUNTIF(activity_id = 2) act_2,COUNTIF(activity_id = 3) act_3 FROM `project.dataset.table1` t1 JOIN `project.dataset.table2` t2 USING(user_id) GROUP BY user_id, event_date ORDER BY user_id, event_date

if to look closer to above result - you can see  - it is exactly the query that we initially wrote manually - but now it was generated for us - and no matter how many distinct activity_id you have (obviously limitations on columns number is still apply) - it will product needed query

So, now you just need to copy the text of query from above result and just simply run it - which will produce desired result

Row user_id event_date  act_1   act_2   act_3
1   A       2019-02-01  2       1       0
2   B       2019-02-10  0       1       1
3   C       2019-01-15  1       0       0

As you can see this is two-steps process - but you can script it using client of your choice

Note: i focused on substance of the question and have not addressed at all 90 days related stuff - I feel it was secondary detail in your question


问:
Is it possible to define c-type variable in python and pass its address to cython wrapped function
I am wrapping a C-library with Cython and for now I do not know how to workaround passing address to C function from python. Details below:

I have some C-function that takes address to some defined beforehand C variable and changes its value:

void c_func(int* x) {
*x=5;
}
```

<p>As a C user I can use this function in following way:</p>

<pre class="lang-c prettyprint-override"><code>def int var1
def int var2
c_func(&var1)
c_func(&var2)
</code>```

After execution both var1 and var2 will be equal to 5. Now I want to wrap c_func with cython. I'd like to have py_func that might be imported from wrapper package and used, but I do not know how to define c variables from python.

What I have already done(in jupyter):

%load_ext cython

%%cython

cdef int some_int

cdef extern from *:
    """
    void c_func(int* x) {
    *x=5;
    }

    """
    int c_func(int* x)

c_func(&some_int)

print(some_int)
```

<p>What I want to get:</p>

<pre class="lang-py prettyprint-override"><code>%%cython

# This part should be in separate pyx file
cdef extern from *:
    """
    void c_func(int* x) {
    *x=5;
    }

    """
    int c_func(int* x)

def py_func(var):
    c_func(&var)

# The following part is user API
from wrapper import py_func

var_to_pass_in_py_func = ... # somehow defined C variable

py_func(var_to_pass_in_py_func)

print(var_to_pass_in_py_func) # should print 5
</code>```

var_to_pass_in_py_func might not be converted to python object, but C functions wrapped with python should not conflict with it.

Is it possible?

答:
I have no idea how your example makes sense in practice, but one possible way is to pass a buffer, which managed by python, to the C function. For example:

```<code>%%cython -a -f

# Suppose this is the external C function needed to wrap
cdef void c_func(int* value_to_change):
    value_to_change[0] = 123;

def py_func(int[:] buffer_to_change):
    c_func(&buffer_to_change[0]);
</code>```

```<code>from array import array
from ctypes import *

a = array('i', [0]);
py_func(a)
print(a[0])

b = (c_int*1)() # c_int array with length 1
py_func(b)
print(b[0])
</code>```

Body:
I am wrapping a C-library with Cython and for now I do not know how to workaround passing address to C function from python. Details below:

I have some C-function that takes address to some defined beforehand C variable and changes its value:

void c_func(int* x) {
*x=5;
}

As a C user I can use this function in following way:

def int var1
def int var2
c_func(&var1)
c_func(&var2)

After execution both var1 and var2 will be equal to 5. Now I want to wrap c_func with cython. I'd like to have py_func that might be imported from wrapper package and used, but I do not know how to define c variables from python.

What I have already done(in jupyter):

%load_ext cython

%%cython

cdef int some_int

cdef extern from *:
    """
    void c_func(int* x) {
    *x=5;
    }

    """
    int c_func(int* x)

c_func(&some_int)

print(some_int)

What I want to get:

%%cython

# This part should be in separate pyx file
cdef extern from *:
    """
    void c_func(int* x) {
    *x=5;
    }

    """
    int c_func(int* x)

def py_func(var):
    c_func(&var)

# The following part is user API
from wrapper import py_func

var_to_pass_in_py_func = ... # somehow defined C variable

py_func(var_to_pass_in_py_func)

print(var_to_pass_in_py_func) # should print 5

var_to_pass_in_py_func might not be converted to python object, but C functions wrapped with python should not conflict with it.

Is it possible?

Body:
I have no idea how your example makes sense in practice, but one possible way is to pass a buffer, which managed by python, to the C function. For example:

%%cython -a -f

# Suppose this is the external C function needed to wrap
cdef void c_func(int* value_to_change):
    value_to_change[0] = 123;

def py_func(int[:] buffer_to_change):
    c_func(&buffer_to_change[0]);

from array import array
from ctypes import *

a = array('i', [0]);
py_func(a)
print(a[0])

b = (c_int*1)() # c_int array with length 1
py_func(b)
print(b[0])


问:
How to assign rows to different cohorts based on aggregation criteria
I have a list of transactions in a postgresql table and I need to bucket them into groups based on when they took place, and whether the running total of transactions has surpassed a threshold.

A "Cohort" here is defined by the last day of the month and whether a threshold of $100 has been met.

Example: A "Cohort" becomes a "Cohort" on the last day of the month when a batch of transactions is >= $100

SAMPLE DATA:

```<code>|TRANS_DATE|AMOUNT|

2018-01-01 | $10
2018-01-15 | $10
2018-01-30 | $50
2018-02-27 | $80
2018-03-05 | $101
2018-04-05 | $1
2018-05-15 | $80
2018-06-05 | $1
2018-07-26 | $18
</code>```

Given this data, I would expect the results of an aggregate query to be:

```<code>DATE | AMOUNT | COHORT

2018-02-28 | $150 | 1
2018-03-31 | $101 | 2
2018-07-31 | $100 | 3
</code>```

I keep thinking I would need some type of loop for this problem, which I don't believe is possible.

I've been trying stuff similar to:

```<code>with st as
(
select distinct(date_trunc('month', "date") + interval '1 month' - interval '1 day') as date,
sum(amount) over (order by date_trunc('month', date) + interval '1 month' - interval '1 day') as total
from a1
order by 1
)
select st.*
, case when lag(total) over (order by date) <= 100 then 1 end as cohort1
, floor(total/100)
from st
</code>```

答:
This is quite complicated.  I'm pretty sure you need recursive CTEs -- because you are hitting a boundary and then starting over.

Try this:

```<code>with tt as (
      select date_trunc('mon', trans_date) as mon, sum(amount) as amount,
             lead(sum(amount)) over (order by min(trans_date)) as next_amount,
             row_number() over (order by min(trans_date)) as seqnum
      from t
      group by 1
     ),
     cte as (
      select mon, amount, seqnum, 1 as cohort, (amount >= 100) as is_new_cohort
      from tt
      where seqnum = 1
      union all
      select tt.mon,
             (case when is_new_cohort then tt.amount else cte.amount + tt.amount end) as amount,
             tt.seqnum,
             (case when is_new_cohort then cohort + 1 else cohort end) as cohort,
             ( (case when is_new_cohort then tt.amount else cte.amount + tt.amount end) >= 100) as is_new_cohort
      from cte join
           tt
           on tt.seqnum = cte.seqnum + 1
     )
select cohort, max(amount), max(cte.mon + interval '1 month' - interval '1 day') as mon
from cte
group by 1
order by 1;
</code>```

Here is a db<>fiddle.

Body:
I have a list of transactions in a postgresql table and I need to bucket them into groups based on when they took place, and whether the running total of transactions has surpassed a threshold.

A "Cohort" here is defined by the last day of the month and whether a threshold of $100 has been met.

Example: A "Cohort" becomes a "Cohort" on the last day of the month when a batch of transactions is >= $100

SAMPLE DATA:

|TRANS_DATE|AMOUNT|

2018-01-01 | $10
2018-01-15 | $10
2018-01-30 | $50
2018-02-27 | $80
2018-03-05 | $101
2018-04-05 | $1
2018-05-15 | $80
2018-06-05 | $1
2018-07-26 | $18

Given this data, I would expect the results of an aggregate query to be:

DATE | AMOUNT | COHORT

2018-02-28 | $150 | 1
2018-03-31 | $101 | 2
2018-07-31 | $100 | 3

I keep thinking I would need some type of loop for this problem, which I don't believe is possible.

I've been trying stuff similar to:

with st as
(
select distinct(date_trunc('month', "date") + interval '1 month' - interval '1 day') as date,
sum(amount) over (order by date_trunc('month', date) + interval '1 month' - interval '1 day') as total
from a1
order by 1
)
select st.*
, case when lag(total) over (order by date) <= 100 then 1 end as cohort1
, floor(total/100)
from st

Body:
This is quite complicated.  I'm pretty sure you need recursive CTEs -- because you are hitting a boundary and then starting over.

Try this:

with tt as (
      select date_trunc('mon', trans_date) as mon, sum(amount) as amount,
             lead(sum(amount)) over (order by min(trans_date)) as next_amount,
             row_number() over (order by min(trans_date)) as seqnum
      from t
      group by 1
     ),
     cte as (
      select mon, amount, seqnum, 1 as cohort, (amount >= 100) as is_new_cohort
      from tt
      where seqnum = 1
      union all
      select tt.mon,
             (case when is_new_cohort then tt.amount else cte.amount + tt.amount end) as amount,
             tt.seqnum,
             (case when is_new_cohort then cohort + 1 else cohort end) as cohort,
             ( (case when is_new_cohort then tt.amount else cte.amount + tt.amount end) >= 100) as is_new_cohort
      from cte join
           tt
           on tt.seqnum = cte.seqnum + 1
     )
select cohort, max(amount), max(cte.mon + interval '1 month' - interval '1 day') as mon
from cte
group by 1
order by 1;

Here is a db<>fiddle.


问:
Build Excel from visual ms access from function
I am trying to build a document in Excel from Visual Basic 6 of MS-Access with the following code, which calls the function TraeDatosCorteAnterior, which performs a query in the Database, generates the Excel application and adds a Worksheet. Work, however, by continuing to generate the document from the function ** ConstruyeTablayCampo **, the application of an error 424 with the following message ** "An object is required" **:

** Excel object declaration **

```<code>Option Compare Database
Dim ba As Excel.Application
</code>```

Initial Funcion

```<code>  Public Sub TraeDatosCorteAnterior()

    RstName = "SELECT conc.CP, conc.etapa, conc.total FROM t_conclusion as conc;"
    Dim dbs As Database
    Set dbs = CurrentDb
    Dim iRec As Long
    Dim i As Long
    Dim RstOrig As Recordset
    Dim nTotalReg As Integer
    Dim nCP As Integer
    Dim nEtapa As Integer
    Dim nTotal As Integer

    Set RstOrig = CurrentDb.OpenRecordset(RstName, dbOpenDynaset)
    RstOrig.Sort = fldName
    Dim RstSorted As Recordset
    Set RstSorted = RstOrig.OpenRecordset()
    RstOrig.Sort = fldName
    Dim RstSorted As Recordset
    Set RstSorted = RstOrig.OpenRecordset()
    RstSorted.MoveLast
    RstSorted.MoveFirst

    nTotalReg = RstSorted.RecordCount

    nCP = RstSorted("CP")

    nEtapa = IIf(IsNull(RstSorted("etapa")) = True, 0, RstSorted("etapa"))
    nTotal = IIf(IsNull(RstSorted("Total")) = True, 0, RstSorted("Total"))

    RstSorted.MoveNext

    Set ba = New Excel.Application
    Set xlwbook = ba.Workbooks.Add
    ba.Visible = True

    ConstruyeTablayCampo "Cuadro I", "Cuenta Pública", "A", "A", ba, False, 1

  End Sub
</code>```

** Function that builds the document **, from the first line marks the error.

** Excel object declaration **

```<code> Sub ConstruyeTablayCampo(ByRef sHoja As String, ByRef sTexto As String, ByRef col1 As String, ByRef col2 As String, ByRef ba As Excel.Application, Optional bCreaHoja As Boolean, Optional nHoja As Integer)

        Set xlsheet = xlwbook.Sheets.Item(nHoja)
        xlwbook.Sheets.Item(nHoja).Name = sHoja

        xlsheet.Cells.Range("A11:A11") = sTexto
        Worksheets("Cuadro I").Range("B:B,D:D,H:H,J:J,N:N,Q:Q").ColumnWidth = 1

        With xlsheet.Cells.Range(col1 & "11:" & col2 & "12")
                .HorizontalAlignment = xlCenter
                .VerticalAlignment = xlCenter
                .WrapText = True
                .Select
                .Font.Bold = True
                .MergeCells = True
                .Interior.Color = RGB(244, 244, 244)
        End With

End Sub
</code>```

Thanks in advance, I hope you can help me!

答:
Finally i resolve it, the solution was do this:

First declare this

```<code>Option Compare Database

Dim ba As Excel.Application
Dim xlwsheet As Excel.Worksheet
</code>```

Second initialize the object in the second line:

```<code> Sub ConstruyeTablayCampo(ByRef sHoja As String, ByRef sTexto As String, ByRef col1 As String, ByRef sRango1 As String, ByRef col2 As String, ByRef sRango2 As String, ByRef ba As Excel.Application, ByRef color1 As String, ByRef color2 As String, ByRef color3 As String, ByRef nHoja As Integer)

        Set xlwsheet = ba.Worksheets.Item(nHoja)
        xlwsheet.Name = sHoja
        xlwsheet.Range("B:B,D:D,H:H,J:J,N:N,Q:Q").ColumnWidth = 1

        With xlwsheet.Cells.Range(col1 & "11" & ":" & col2 & "12")
                .HorizontalAlignment = xlCenter
                .VerticalAlignment = xlCenter
                .WrapText = True
                .Select
                .Font.Bold = True
                .MergeCells = True
                .Interior.Color = RGB(color1, color2, color3)
        End With

        xlwsheet.Range(col1 & "11:" & col2 & "12").Cells = sTexto

End Sub
</code>```

Thank you for your help!

Body:
I am trying to build a document in Excel from Visual Basic 6 of MS-Access with the following code, which calls the function TraeDatosCorteAnterior, which performs a query in the Database, generates the Excel application and adds a Worksheet. Work, however, by continuing to generate the document from the function ** ConstruyeTablayCampo **, the application of an error 424 with the following message ** "An object is required" **:

** Excel object declaration **

Option Compare Database
Dim ba As Excel.Application

Initial Funcion

  Public Sub TraeDatosCorteAnterior()

    RstName = "SELECT conc.CP, conc.etapa, conc.total FROM t_conclusion as conc;"
    Dim dbs As Database
    Set dbs = CurrentDb
    Dim iRec As Long
    Dim i As Long
    Dim RstOrig As Recordset
    Dim nTotalReg As Integer
    Dim nCP As Integer
    Dim nEtapa As Integer
    Dim nTotal As Integer

    Set RstOrig = CurrentDb.OpenRecordset(RstName, dbOpenDynaset)
    RstOrig.Sort = fldName
    Dim RstSorted As Recordset
    Set RstSorted = RstOrig.OpenRecordset()
    RstOrig.Sort = fldName
    Dim RstSorted As Recordset
    Set RstSorted = RstOrig.OpenRecordset()
    RstSorted.MoveLast
    RstSorted.MoveFirst

    nTotalReg = RstSorted.RecordCount

    nCP = RstSorted("CP")

    nEtapa = IIf(IsNull(RstSorted("etapa")) = True, 0, RstSorted("etapa"))
    nTotal = IIf(IsNull(RstSorted("Total")) = True, 0, RstSorted("Total"))

    RstSorted.MoveNext

    Set ba = New Excel.Application
    Set xlwbook = ba.Workbooks.Add
    ba.Visible = True

    ConstruyeTablayCampo "Cuadro I", "Cuenta Pública", "A", "A", ba, False, 1

  End Sub

** Function that builds the document **, from the first line marks the error.

** Excel object declaration **

 Sub ConstruyeTablayCampo(ByRef sHoja As String, ByRef sTexto As String, ByRef col1 As String, ByRef col2 As String, ByRef ba As Excel.Application, Optional bCreaHoja As Boolean, Optional nHoja As Integer)

        Set xlsheet = xlwbook.Sheets.Item(nHoja)
        xlwbook.Sheets.Item(nHoja).Name = sHoja

        xlsheet.Cells.Range("A11:A11") = sTexto
        Worksheets("Cuadro I").Range("B:B,D:D,H:H,J:J,N:N,Q:Q").ColumnWidth = 1

        With xlsheet.Cells.Range(col1 & "11:" & col2 & "12")
                .HorizontalAlignment = xlCenter
                .VerticalAlignment = xlCenter
                .WrapText = True
                .Select
                .Font.Bold = True
                .MergeCells = True
                .Interior.Color = RGB(244, 244, 244)
        End With

End Sub

Thanks in advance, I hope you can help me!

Body:
Finally i resolve it, the solution was do this:

First declare this

Option Compare Database

Dim ba As Excel.Application
Dim xlwsheet As Excel.Worksheet

Second initialize the object in the second line:

 Sub ConstruyeTablayCampo(ByRef sHoja As String, ByRef sTexto As String, ByRef col1 As String, ByRef sRango1 As String, ByRef col2 As String, ByRef sRango2 As String, ByRef ba As Excel.Application, ByRef color1 As String, ByRef color2 As String, ByRef color3 As String, ByRef nHoja As Integer)

        Set xlwsheet = ba.Worksheets.Item(nHoja)
        xlwsheet.Name = sHoja
        xlwsheet.Range("B:B,D:D,H:H,J:J,N:N,Q:Q").ColumnWidth = 1

        With xlwsheet.Cells.Range(col1 & "11" & ":" & col2 & "12")
                .HorizontalAlignment = xlCenter
                .VerticalAlignment = xlCenter
                .WrapText = True
                .Select
                .Font.Bold = True
                .MergeCells = True
                .Interior.Color = RGB(color1, color2, color3)
        End With

        xlwsheet.Range(col1 & "11:" & col2 & "12").Cells = sTexto

End Sub

Thank you for your help!


问:
Swift pushViewController Works on iPad but not iPhone
I have no idea what is happening but my code stopped working on iPhone but works fine on iPad.  (Using Xcode 10 and Swift 4)

I first check for the data and if not set it transfers to the ConfigVC.

Nothing happens on the simulator for any phone settings.  I went so far as to reinstall my system software and Xcode.

I use this same approach on other apps and it is fine.  For some strange reason it just stopped working on this app.

```<code>func dataCheck(){

    // make sure the required data is set
    if User.getInfo() == nil || Index.getAll() == nil  {

        let vc = UIStoryboard.init(name: "Config", bundle: Bundle.main).instantiateViewController(withIdentifier: "ConfigVC") as? ConfigVC
        self.navigationController?.pushViewController(vc!, animated: true)

    }
}
</code>```

The code shows it just ending.

答: You're trying to push/present a vc while the current isn't yet loaded inside viewDidLoad so move the call to dataCheck inside viewWillAppear/viewDidAppear

Body:
I have no idea what is happening but my code stopped working on iPhone but works fine on iPad.  (Using Xcode 10 and Swift 4)

I first check for the data and if not set it transfers to the ConfigVC.

Nothing happens on the simulator for any phone settings.  I went so far as to reinstall my system software and Xcode.

I use this same approach on other apps and it is fine.  For some strange reason it just stopped working on this app.

func dataCheck(){

    // make sure the required data is set
    if User.getInfo() == nil || Index.getAll() == nil  {

        let vc = UIStoryboard.init(name: "Config", bundle: Bundle.main).instantiateViewController(withIdentifier: "ConfigVC") as? ConfigVC
        self.navigationController?.pushViewController(vc!, animated: true)

    }
}

The code shows it just ending.


问:
Arranging the number 1 in a 2d matrix
Given the number of rows and columns of a 2d matrix

Initially all elements of matrix are 0

Given the number of 1's that should be present in each row

Given the number of 1's that should be present in each column

Determine if it is possible to form such matrix.

Example:

```<code>Input: r=3 c=2 (no. of rows and columns)
2 1 0 (number of 1's that should be present in each row respectively)
1 2 (number of 1's that should be present in each column respectively)
</code>```

Output: Possible

Explanation:

```<code>1 1
0 1
0 0
</code>```

I tried solving this problem for like 12 hours by checking if summation of Ri = summation of Ci

But I wondered if wouldn't be possible for cases like

```<code>3 3
1 3 0
0 2 2
</code>```

r and c can be upto 10^5

Any ideas how should I move further?

Edit: Constraints added and output should only be "possible" or "impossible". The possible matrix need not be displayed.

Can anyone help me now?

答:
I will illustrate the algorithm with an example.

Assume we have m rows and n columns. Let rows[i] be the number of 1s in row i, for 0 <= i < m,
and cols[j] be the number of 1s in column j, for 0 <= j < n.

For example, for m = 3, and n = 4, we could have: rows = {4 2 3}, cols = {1 3 2 3}, and
the solution array would be:

```<code>    1 3 2 3
  +--------
4 | 1 1 1 1
2 | 0 1 0 1
3 | 0 1 1 1
</code>```

Because we only want to know whether a solution exists, the values in rows and cols may be permuted in any order. The solution of each permutation is just a permutation of the rows and columns of the above solution.

So, given rows and cols, sort cols in decreasing order, and rows in increasing order. For our example, we have cols = {3 3 2 1} and rows = {2 3 4}, and the equivalent problem.

```<code>    3 3 2 1
  +--------
2 | 1 1 0 0
3 | 1 1 1 0
4 | 1 1 1 1
</code>```

We transform cols into a form that is better suited for the algorithm. What cols tells us is that we have two series of 1s of length 3, one series of 1s of length 2, and one series of 1s of length 1, that are to be distributed among the rows of the array. We rewrite cols to capture just that, that is COLS = {2/3 1/2 1/1}, 2 series of length 3, 1 series of length 2, and 1 series of length 1.

Because we have 2 series of length 3, a solution exists only if we can put two 1s in the first row. This is possible because rows[0] = 2. We do not actually put any 1 in the first row, but record the fact that 1s have been placed there by decrementing the length of the series of length 3. So COLS becomes:

```<code>COLS = {2/2 1/2 1/1}
</code>```

and we combine our two counts for series of length 2, yielding:

```<code>COLS = {3/2 1/1}
</code>```

We now have the reduced problem:

```<code>3 | 1 1 1 0
4 | 1 1 1 1
</code>```

Again we need to place 1s from our series of length 2 to have a solution. Fortunately, rows[1] = 3 and we can do this. We decrement the length of 3/2 and get:

```<code>COLS = {3/1 1/1} = {4/1}
</code>```

We have the reduced problem:

```<code>4 | 1 1 1 1
</code>```

Which is solved by 4 series of length 1, just what we have left. If at any step, the series in COLS cannot be used to satisfy a row count, then no solution is possible.

The general processing for each row may be stated as follows. For each row r, starting from the first element in COLS, decrement the lengths of as many elements count[k]/length[k] of COLS as needed, so that the sum of the count[k]'s equals rows[r]. Eliminate series of length 0 in COLS and combine series of same length.

Note that because elements of COLS are in decreasing order of lengths, the length of the last element decremented is always less than or equal to the next element in COLS (if there is a next element).

EXAMPLE 2 : Solution exists.

```<code>rows = {1 3 3}, cols = {2 2 2 1} => COLS = {3/2 1/1}
</code>```

1 series of length 2 is decremented to satisfy rows[0] = 1, and the 2 other series of length 2 remains at length 2.

```<code>rows[0] = 1
COLS = {2/2 1/1 1/1} = {2/2 2/1}
</code>```

The 2 series of length 2 are decremented, and 1 of the series of length 1.
The series whose length has become 0 is deleted, and the series of length 1 are combined.

```<code>rows[1] = 3
COLS = {2/1 1/0 1/1} = {2/1 1/1} = {3/1}
</code>```

A solution exists for rows[2] can be satisfied.

```<code>    3 3 2 1
  +--------
2 | 1 1 0 0
3 | 1 1 1 0
4 | 1 1 1 1
</code>```0

EXAMPLE 3: Solution does not exists.

```<code>    3 3 2 1
  +--------
2 | 1 1 0 0
3 | 1 1 1 0
4 | 1 1 1 1
</code>```1

SPACE COMPLEXITY

It is easy to see that it is O(m + n).

TIME COMPLEXITY

We iterate over each row only once. For each row i, we need to iterate over at most
rows[i] <= n elements of COLS. Time complexity is O(m x n).

After finding this algorithm, I found the following theorem:

The Havel-Hakimi theorem (Havel 1955, Hakimi 1962) states that there exists a matrix Xn,m of 0’s and 1’s with row totals a0=(a1, a2,… , an) and column totals b0=(b1, b2,… , bm) such that bi ≥ bi+1 for every 0 < i < m if and only if another matrix Xn−1,m of 0’s and 1’s with row totals a1=(a2, a3,… , an) and column totals b1=(b1−1, b2−1,… ,ba1−1, ba1+1,… , bm) also exists.

from the post Finding if binary matrix exists given the row and column sums.

This is basically what my algorithm does, while trying to optimize the decrementing part, i.e., all the -1's in the above theorem. Now that I see the above theorem, I know my algorithm is correct. Nevertheless, I checked the correctness of my algorithm by comparing it with a brute-force algorithm for arrays of up to 50 cells.

Here is the C# implementation.

```<code>    3 3 2 1
  +--------
2 | 1 1 0 0
3 | 1 1 1 0
4 | 1 1 1 1
</code>```2

Title: Arranging the number 1 in a 2d matrix

Body:
Given the number of rows and columns of a 2d matrix

Initially all elements of matrix are 0

Given the number of 1's that should be present in each row

Given the number of 1's that should be present in each column

Determine if it is possible to form such matrix.

Example:

Input: r=3 c=2 (no. of rows and columns)
2 1 0 (number of 1's that should be present in each row respectively)
1 2 (number of 1's that should be present in each column respectively)

Output: Possible

Explanation:

1 1
0 1
0 0

I tried solving this problem for like 12 hours by checking if summation of Ri = summation of Ci

But I wondered if wouldn't be possible for cases like

3 3
1 3 0
0 2 2

r and c can be upto 10^5

Any ideas how should I move further?

Edit: Constraints added and output should only be "possible" or "impossible". The possible matrix need not be displayed.

Can anyone help me now?

Body:
I will illustrate the algorithm with an example.

Assume we have m rows and n columns. Let rows[i] be the number of 1s in row i, for 0 <= i < m,
and cols[j] be the number of 1s in column j, for 0 <= j < n.

For example, for m = 3, and n = 4, we could have: rows = {4 2 3}, cols = {1 3 2 3}, and
the solution array would be:

    1 3 2 3
  +--------
4 | 1 1 1 1
2 | 0 1 0 1
3 | 0 1 1 1

Because we only want to know whether a solution exists, the values in rows and cols may be permuted in any order. The solution of each permutation is just a permutation of the rows and columns of the above solution.

So, given rows and cols, sort cols in decreasing order, and rows in increasing order. For our example, we have cols = {3 3 2 1} and rows = {2 3 4}, and the equivalent problem.

    3 3 2 1
  +--------
2 | 1 1 0 0
3 | 1 1 1 0
4 | 1 1 1 1

We transform cols into a form that is better suited for the algorithm. What cols tells us is that we have two series of 1s of length 3, one series of 1s of length 2, and one series of 1s of length 1, that are to be distributed among the rows of the array. We rewrite cols to capture just that, that is COLS = {2/3 1/2 1/1}, 2 series of length 3, 1 series of length 2, and 1 series of length 1.

Because we have 2 series of length 3, a solution exists only if we can put two 1s in the first row. This is possible because rows[0] = 2. We do not actually put any 1 in the first row, but record the fact that 1s have been placed there by decrementing the length of the series of length 3. So COLS becomes:

COLS = {2/2 1/2 1/1}

and we combine our two counts for series of length 2, yielding:

COLS = {3/2 1/1}

We now have the reduced problem:

3 | 1 1 1 0
4 | 1 1 1 1

Again we need to place 1s from our series of length 2 to have a solution. Fortunately, rows[1] = 3 and we can do this. We decrement the length of 3/2 and get:

COLS = {3/1 1/1} = {4/1}

We have the reduced problem:

4 | 1 1 1 1

Which is solved by 4 series of length 1, just what we have left. If at any step, the series in COLS cannot be used to satisfy a row count, then no solution is possible.

The general processing for each row may be stated as follows. For each row r, starting from the first element in COLS, decrement the lengths of as many elements count[k]/length[k] of COLS as needed, so that the sum of the count[k]'s equals rows[r]. Eliminate series of length 0 in COLS and combine series of same length.

Note that because elements of COLS are in decreasing order of lengths, the length of the last element decremented is always less than or equal to the next element in COLS (if there is a next element).

EXAMPLE 2 : Solution exists.

rows = {1 3 3}, cols = {2 2 2 1} => COLS = {3/2 1/1}

1 series of length 2 is decremented to satisfy rows[0] = 1, and the 2 other series of length 2 remains at length 2.

rows[0] = 1
COLS = {2/2 1/1 1/1} = {2/2 2/1}

The 2 series of length 2 are decremented, and 1 of the series of length 1.
The series whose length has become 0 is deleted, and the series of length 1 are combined.

rows[1] = 3
COLS = {2/1 1/0 1/1} = {2/1 1/1} = {3/1}

A solution exists for rows[2] can be satisfied.

rows[2] = 3
COLS = {3/0} = {}

EXAMPLE 3: Solution does not exists.

rows = {0 2 3}, cols = {3 2 0 0} => COLS = {1/3 1/2}

rows[0] = 0
COLS = {1/3 1/2}

rows[1] = 2
COLS = {1/2 1/1}

rows[2] = 3  => impossible to satisfy; no solution.

SPACE COMPLEXITY

It is easy to see that it is O(m + n).

TIME COMPLEXITY

We iterate over each row only once. For each row i, we need to iterate over at most
rows[i] <= n elements of COLS. Time complexity is O(m x n).

After finding this algorithm, I found the following theorem:

The Havel-Hakimi theorem (Havel 1955, Hakimi 1962) states that there exists a matrix Xn,m of 0’s and 1’s with row totals a0=(a1, a2,… , an) and column totals b0=(b1, b2,… , bm) such that bi ≥ bi+1 for every 0 < i < m if and only if another matrix Xn−1,m of 0’s and 1’s with row totals a1=(a2, a3,… , an) and column totals b1=(b1−1, b2−1,… ,ba1−1, ba1+1,… , bm) also exists.

from the post Finding if binary matrix exists given the row and column sums.

This is basically what my algorithm does, while trying to optimize the decrementing part, i.e., all the -1's in the above theorem. Now that I see the above theorem, I know my algorithm is correct. Nevertheless, I checked the correctness of my algorithm by comparing it with a brute-force algorithm for arrays of up to 50 cells.

Here is the C# implementation.

public class Pair
{
    public int Count;
    public int Length;
}

public class PairsList
{
    public LinkedList<Pair> Pairs;
    public int TotalCount;
}

class Program
{

    static void Main(string[] args)
    {
        int[] rows = new int[] { 0, 0, 1, 1, 2, 2 };
        int[] cols = new int[] { 2, 2, 0 };
        bool success = Solve(cols, rows);
    }

    static bool Solve(int[] cols, int[] rows)
    {
        PairsList pairs = new PairsList() { Pairs = new LinkedList<Pair>(), TotalCount = 0 };

        FillAllPairs(pairs, cols);

        for (int r = 0; r < rows.Length; r++)
        {
            if (rows[r] > 0)
            {
                if (pairs.TotalCount < rows[r])
                    return false;

                if (pairs.Pairs.First != null && pairs.Pairs.First.Value.Length > rows.Length - r)
                    return false;

                DecrementPairs(pairs, rows[r]);
            }
        }

        return pairs.Pairs.Count == 0 || pairs.Pairs.Count == 1 && pairs.Pairs.First.Value.Length == 0;
    }

    static void DecrementPairs(PairsList pairs, int count)
    {
        LinkedListNode<Pair> pair = pairs.Pairs.First;

        while (count > 0 && pair != null)
        {
            LinkedListNode<Pair> next = pair.Next;

            if (pair.Value.Count == count)
            {
                pair.Value.Length--;
                if (pair.Value.Length == 0)
                {
                    pairs.Pairs.Remove(pair);
                    pairs.TotalCount -= count;
                }
                else if (pair.Next != null && pair.Next.Value.Length == pair.Value.Length)
                {
                    pair.Value.Count += pair.Next.Value.Count;
                    pairs.Pairs.Remove(pair.Next);
                    next = pair;
                }
                count = 0;
            }
            else if (pair.Value.Count < count)
            {
                count -= pair.Value.Count;
                pair.Value.Length--;
                if (pair.Value.Length == 0)
                {
                    pairs.Pairs.Remove(pair);
                    pairs.TotalCount -= pair.Value.Count;
                }
                else if(pair.Next != null && pair.Next.Value.Length == pair.Value.Length)
                {
                    pair.Value.Count += pair.Next.Value.Count;
                    pairs.Pairs.Remove(pair.Next);
                    next = pair;
                }
            }
            else // pair.Value.Count > count
            {
                Pair p = new Pair() { Count = count, Length = pair.Value.Length - 1 };
                pair.Value.Count -= count;
                if (p.Length > 0)
                {
                    if (pair.Next != null && pair.Next.Value.Length == p.Length)
                        pair.Next.Value.Count += p.Count;
                    else
                        pairs.Pairs.AddAfter(pair, p);
                }
                else
                    pairs.TotalCount -= count;
                count = 0;
            }

            pair = next;
        }
    }

    static int FillAllPairs(PairsList pairs, int[] cols)
    {
        List<Pair> newPairs = new List<Pair>();

        int c = 0;
        while (c < cols.Length && cols[c] > 0)
        {
            int k = c++;
            if (cols[k] > 0)
                pairs.TotalCount++;
            while (c < cols.Length && cols[c] == cols[k])
            {
                if (cols[k] > 0) pairs.TotalCount++;
                c++;
            }
            newPairs.Add(new Pair() { Count = c - k, Length = cols[k] });
        }

        LinkedListNode<Pair> pair = pairs.Pairs.First;

        foreach (Pair p in newPairs)
        {
            while (pair != null && p.Length < pair.Value.Length)
                pair = pair.Next;

            if (pair == null)
            {
                pairs.Pairs.AddLast(p);
            }
            else if (p.Length == pair.Value.Length)
            {
                pair.Value.Count += p.Count;
                pair = pair.Next;
            }
            else // p.Length > pair.Value.Length
            {
                pairs.Pairs.AddBefore(pair, p);
            }
        }

        return c;
    }
}


问:
Matching User 's Input With Nested Dictionary in Python3.7
I cannot seem to match the user input(num) to id_num to print out the individual license info. I want that when the user is prompted to enter the license number, the code should loop through the dictionary and find its match and print the info that matches the input.

I tried:

if num in driver_license[id_num]:

if num==id_num:

if num==int(id_num):

42456 :{'name': 'jill', 'ethnicity': 'hispanic','eye': 'yellow' ,'height': '6.1'},

44768 :{'name': 'cheroky', 'ethnicity': 'native','eye': 'green' ,'height': '6.7'},

32565 :{'name': 'valentina', 'ethnicity': 'european','eye': 'fair','height': '4.9'}}

print('\n')
print('- ' *45)

for id_num, id_info in driver_license.items():
    num = int(input('Enter your driving license number: '))

    print(f"Id number: {id_num}")
    name=f"{id_info['name']}"
    origin= f"{id_info ['ethnicity']}"
    eye= f"{id_info['eye']}"
    height=f"{id_info['height']}"

    if num in driver_license[id_num]:
        print(f'\nId number is:{num}')
        print(f'Name: {name}')
        print(f'Ethnicity: {origin}')
        print(f'Eyes color: {eye}')
        print(f'Height: {height}\n')
    else:
        print('Invalid ID')
```

There is no error but a mismatch of output than expected.

答:
You don't need to loop through the dictionary.

You can instead use get(key, default) to get the entry from the driver_license dictionary using the input license number as the key.  You can then set default to some value to handle the case where the key is not in the dict (here I used None).

driver_license = {
    "42456" : {'name': 'jill', 'ethnicity': 'hispanic','eye': 'yellow' ,'height': '6.1'},
    "44768" : {'name': 'cheroky', 'ethnicity': 'native','eye': 'green' ,'height': '6.7'},
    "32565" : {'name': 'valentina', 'ethnicity': 'european','eye': 'fair','height': '4.9'}
}

id_num = input('Enter your driving license number: ')
# if user enters "32565"

id_info = driver_license.get(id_num, None)
# id_info would be:
#    {'name': 'valentina', 'ethnicity': 'european','eye': 'fair','height': '4.9'}

if id_info:
    print(f'\nId number is:{id_num }')
    print(f'Name: {id_info["name"]}')
    print(f'Ethnicity: {id_info["ethnicity"]}')
    print(f'Eyes color: {id_info["eye"]}')
    print(f'Height: {id_info["height"]}\n')
else:
    print('Invalid ID')
```

Body:
I cannot seem to match the user input(num) to id_num to print out the individual license info. I want that when the user is prompted to enter the license number, the code should loop through the dictionary and find its match and print the info that matches the input.

I tried:

if num in driver_license[id_num]:

if num==id_num:

if num==int(id_num):

42456 :{'name': 'jill', 'ethnicity': 'hispanic','eye': 'yellow' ,'height': '6.1'},

44768 :{'name': 'cheroky', 'ethnicity': 'native','eye': 'green' ,'height': '6.7'},

32565 :{'name': 'valentina', 'ethnicity': 'european','eye': 'fair','height': '4.9'}}

print('\n')
print('- ' *45)

for id_num, id_info in driver_license.items():
    num = int(input('Enter your driving license number: '))

    print(f"Id number: {id_num}")
    name=f"{id_info['name']}"
    origin= f"{id_info ['ethnicity']}"
    eye= f"{id_info['eye']}"
    height=f"{id_info['height']}"

    if num in driver_license[id_num]:
        print(f'\nId number is:{num}')
        print(f'Name: {name}')
        print(f'Ethnicity: {origin}')
        print(f'Eyes color: {eye}')
        print(f'Height: {height}\n')
    else:
        print('Invalid ID')

There is no error but a mismatch of output than expected.


问:
Ignore commas when enclosed in double quotes
I'd like to extend the code below so it can take double quotes. For example, the string '303,"Candy, Original",45,19' should return [303,"Candy, Original",45,19]. Please help. Thanks.

```<code>def parse(s):
    #If string can be parsed as integer, return integer
    try:
        num = int(s)
        return num
    except:
        pass
    #Else return string
    return s

data=[parse(x) for x in myString.split(",")]
</code>```

答:
The csv module handles quoted commas really well.  You may want to try building a parser around that.

```<code>import csv
from io import StringIO

def to_numeric(x):
    try:
        return int(x)
    except ValueError:
        pass
    try:
        return float(x)
    except ValueError:
        pass
    return x

def parse_line(s):
    f = StringIO(s)
    f.seek(0)
    reader = csv.reader(f)
    out = next(reader)
    return [to_numeric(x) for x in out]

s = '303,"Candy, Original",45,19'
parse_line(s)
# returns:
[303, 'Candy, Original', 45, 19]
</code>```

Body:
I'd like to extend the code below so it can take double quotes. For example, the string '303,"Candy, Original",45,19' should return [303,"Candy, Original",45,19]. Please help. Thanks.

def parse(s):
    #If string can be parsed as integer, return integer
    try:
        num = int(s)
        return num
    except:
        pass
    #Else return string
    return s

data=[parse(x) for x in myString.split(",")]

Body:
The csv module handles quoted commas really well.  You may want to try building a parser around that.

import csv
from io import StringIO

def to_numeric(x):
    try:
        return int(x)
    except ValueError:
        pass
    try:
        return float(x)
    except ValueError:
        pass
    return x

def parse_line(s):
    f = StringIO(s)
    f.seek(0)
    reader = csv.reader(f)
    out = next(reader)
    return [to_numeric(x) for x in out]

s = '303,"Candy, Original",45,19'
parse_line(s)
# returns:
[303, 'Candy, Original', 45, 19]


问:
BlackBerry application autostart and alternate entry point default application icon
I have an application which registers its hotspotclient on autostart with an alternate entry point and on the actual entry point (when the application icon is clicked) it pushes the application UI.

Actual entry point - project properties:
 * Project Type: BlackBerry application and
 * Added Application icon

Alternate entry point - project properties:
 * Project Type: Alternate Blackberry Application entry point
 * Alternate entry point for: "actual project"
 * Argument passed to main: wificlient
 * System module checked
 * Auto start checked
 * and No icon added

When I run the application appln on the device start up the alternate entry point, starts and registers the hotspot client, but it adds the default icon with the project name (.jdp file name) in the background application list. I don't want any icon to be displayed for alternate entry point.

When I click on an application icon from a download folder the app pushed the UI screen and now if I see the background application list, I see my application icon with the given application name and the default application icon with my project name of the alternate entry point. So how do I disable this default icon to display in background application list for the alternate entry point.

Please let me know if I am missing anything and help me with this.

Here is my code:

```<code>class WiFiApplication extends UiApplication
{
    public static void main(String[] args)
    {
        if( args != null && args.length > 0 &&
            args[0].equals("wificlient"))
        {
            //Register the Hotspotclient
            AddRemoveClient.registerHotspotClient();
            WiFiApplication app = new WiFiApplication();
            app.enterEventDispatcher();
        }
        else
        {
            new WiFiApplication().pushUI();
        }
    }

    WiFiApplication() {
    }

    pushUI()
    {
        pushScreen(new WLANScreen());
        enterEventDispatcher();
    }
}
</code>```

答:
I'm not sure if this will fully answer your question, since I am new to alternate entry points, but I have created a background app that doesn't use alternate entry points, and will come to the foreground in the same way as yours.

In my main() method, I do not directly call the constructor, I have a getInstance() method that enforces the Singleton pattern on the application - in other words, if it is already running in the background, it is brought to the front.

```<code>/**
 * Returns a Demo application. If Demo has not been started yet, it is
 * started. If it is already running, this method returns the running
 * instance. In this way, only one copy of the Demo application can ever
 * be running.
 *
 * @return a running instance of the {@link DemoApp}
 */
public static DemoApp getInstance()
{
    // check if Demo is already running in the background
    RuntimeStore runtimeStore = RuntimeStore.getRuntimeStore();
    DemoApp runningInstance = (DemoApp) runtimeStore
        .get(GlobalConstants.Demo_APPLICATION_INSTANCE_ID);

    // if not running, create the app, and store it as an object in the
    // RuntimeStore
    if (runningInstance == null)
    {
        runningInstance = new DemoApp();
        runtimeStore.put(GlobalConstants.Demo_APPLICATION_INSTANCE_ID,
            runningInstance);
    }

    return runningInstance;
}
</code>```

I define Demo_APPLICATION_INSTANCE_ID as a long hash of com.demo.app (some unique name).

This stores a copy of the running app in the RuntimeStore.

Finally I did not implement the part of hiding the background app from the task switcher, since I wanted to be able to switch to it. But if that is what you are trying to do, then go to this link:
http://davidjhinson.wordpress.com/2010/08/24/hiding-blackberry-background-processes/

hth

Body:
I have an application which registers its hotspotclient on autostart with an alternate entry point and on the actual entry point (when the application icon is clicked) it pushes the application UI.

Actual entry point - project properties:
 * Project Type: BlackBerry application and
 * Added Application icon

Alternate entry point - project properties:
 * Project Type: Alternate Blackberry Application entry point
 * Alternate entry point for: "actual project"
 * Argument passed to main: wificlient
 * System module checked
 * Auto start checked
 * and No icon added

When I run the application appln on the device start up the alternate entry point, starts and registers the hotspot client, but it adds the default icon with the project name (.jdp file name) in the background application list. I don't want any icon to be displayed for alternate entry point.

When I click on an application icon from a download folder the app pushed the UI screen and now if I see the background application list, I see my application icon with the given application name and the default application icon with my project name of the alternate entry point. So how do I disable this default icon to display in background application list for the alternate entry point.

Please let me know if I am missing anything and help me with this.

Here is my code:

class WiFiApplication extends UiApplication
{
    public static void main(String[] args)
    {
        if( args != null && args.length > 0 &&
            args[0].equals("wificlient"))
        {
            //Register the Hotspotclient
            AddRemoveClient.registerHotspotClient();
            WiFiApplication app = new WiFiApplication();
            app.enterEventDispatcher();
        }
        else
        {
            new WiFiApplication().pushUI();
        }
    }

    WiFiApplication() {
    }

    pushUI()
    {
        pushScreen(new WLANScreen());
        enterEventDispatcher();
    }
}

Body:
I'm not sure if this will fully answer your question, since I am new to alternate entry points, but I have created a background app that doesn't use alternate entry points, and will come to the foreground in the same way as yours.

In my main() method, I do not directly call the constructor, I have a getInstance() method that enforces the Singleton pattern on the application - in other words, if it is already running in the background, it is brought to the front.

/**
 * Returns a Demo application. If Demo has not been started yet, it is
 * started. If it is already running, this method returns the running
 * instance. In this way, only one copy of the Demo application can ever
 * be running.
 *
 * @return a running instance of the {@link DemoApp}
 */
public static DemoApp getInstance()
{
    // check if Demo is already running in the background
    RuntimeStore runtimeStore = RuntimeStore.getRuntimeStore();
    DemoApp runningInstance = (DemoApp) runtimeStore
        .get(GlobalConstants.Demo_APPLICATION_INSTANCE_ID);

    // if not running, create the app, and store it as an object in the
    // RuntimeStore
    if (runningInstance == null)
    {
        runningInstance = new DemoApp();
        runtimeStore.put(GlobalConstants.Demo_APPLICATION_INSTANCE_ID,
            runningInstance);
    }

    return runningInstance;
}

I define Demo_APPLICATION_INSTANCE_ID as a long hash of com.demo.app (some unique name).

This stores a copy of the running app in the RuntimeStore.

Finally I did not implement the part of hiding the background app from the task switcher, since I wanted to be able to switch to it. But if that is what you are trying to do, then go to this link:
http://davidjhinson.wordpress.com/2010/08/24/hiding-blackberry-background-processes/

hth


问:
How to add same values to different keys in dictionaries?
I have 2 JSON files. 1 file with the the student numbers and 1 file with the students.

I have a list of dictionaries with the name, e-mail, and student number of students.

What I want to do is if there are 60 students I want to give them a unique student number. That part is working in the elif statement. The part which I dont know how to implement is:

If there are 20 students, I want to give for example 2 students the same studentnumber(which sounds stupid but I need it). In this case the student is the key and studentnumber is the value.

What I have now:

```<code>
# student
[{"Student1":029182,"e-mail":"example@.com"},{"Student2":0591238,"e-mail":"example@.com"},{"Student3":9213189,"e-mail":"example@.com"}]

studentnumbers = [{"studentnumber":"029182","ID":0},{"studentnumber":"0591238","ID":1},{"studentnumber":"9213189","ID":2}]

students = [list(data.values())[0] for data in studentnumbers]

ID = 0
# students is a list of studentnumbers
if len(students) <= 20:
    # studentInfo is my dictionary with the key and values
    for data in studentnumbers:
        try:
            pass

        except IndexError:
            pass

elif len(students) <= 60:
    for data in studentnumbers:
        try:
            studentnumbers[ID] = students[ID]
            ID += 1
            break
        except IndexError:
            pass
    print("..")
else:
    print("...")

with open('Students.json','w') as instudent:
    json.dump(studentnumbers,instudent,indent=2)

</code>```

output what I have now:

```<code>[{"Student1":029182,"e-mail":"example@.com","studentnumber":029182},
{"Student2":0591238,"e-mail":"example@.com","studentnumber":9213189},
{"Student3":9213189,"e-mail":"example@.com","studentnumber":0591238},
{"Student4":9213189,"e-mail":"example@.com","studentnumber":0294832},
{"Student5":9213189,"e-mail":"example@.com","studentnumber":0591823},
{"Student6":9213189,"e-mail":"example@.com","studentnumber":0501852}]
</code>```

What I want:

```<code>[{"Student1":029182,"e-mail":"example@.com","studentnumber":029182},
{"Student2":0591238,"e-mail":"example@.com","studentnumber":029182},
{"Student3":9213189,"e-mail":"example@.com","studentnumber":029182},
{"Student4":9213189,"e-mail":"example@.com","studentnumber":9213189},
{"Student5":9213189,"e-mail":"example@.com","studentnumber":9213189},
{"Student6":9213189,"e-mail":"example@.com","studentnumber":9213189}]
</code>```

答:
May be the code below can help. I have to figure it out that you can not use int number like 025. So I change it to strings.

# student numbers
studentNunbers = [{"studentnumber": '029182', "ID": 0}, {"studentnumber": '0591238',"ID": 1},{"studentnumber": '9213189', "ID":2}]
# student
studentInfos = [{"Student1":'029182', "e-mail":'example@.com'}, {"Student2":'0591238',"e-mail":'example@.com'},
                {"Student3":'9213189',"e-mail":'example@.com'}, {"Student3":'92189',"e-mail":'example@.com'},
                {"Student2":'0538',"e-mail":'example@.com'}, {"Student2":'238',"e-mail":'example@.com'},
                {"Student2":'0598',"e-mail":'example@.com'}, {"Student2":'08',"e-mail":'example@.com'},]

students = [list(data.values())[0] for data in studentNunbers]

def merge(numRep=1):
    key = "studentnumber"
    stNumberIndex = 0
    iterInd = numRep
    for i in range(len(studentInfos)):
        value = studentNunbers[stNumberIndex][key]
        studentInfos[i][key] = value

        iterInd -= 1
        if iterInd == 0:
            iterInd = numRep
            stNumberIndex += 1

def test():
    if len(studentNunbers) < 20:
        merge(numRep=3)

    elif len(studentNunbers) < 60:
        merge(numRep=1)
    else:
        pass

test()
print(studentInfos)
```

Body:
I have 2 JSON files. 1 file with the the student numbers and 1 file with the students.

I have a list of dictionaries with the name, e-mail, and student number of students.

What I want to do is if there are 60 students I want to give them a unique student number. That part is working in the elif statement. The part which I dont know how to implement is:

If there are 20 students, I want to give for example 2 students the same studentnumber(which sounds stupid but I need it). In this case the student is the key and studentnumber is the value.

What I have now:

# student
[{"Student1":029182,"e-mail":"example@.com"},{"Student2":0591238,"e-mail":"example@.com"},{"Student3":9213189,"e-mail":"example@.com"}]

studentnumbers = [{"studentnumber":"029182","ID":0},{"studentnumber":"0591238","ID":1},{"studentnumber":"9213189","ID":2}]

students = [list(data.values())[0] for data in studentnumbers]

ID = 0
# students is a list of studentnumbers
if len(students) <= 20:
    # studentInfo is my dictionary with the key and values
    for data in studentnumbers:
        try:
            pass

        except IndexError:
            pass

elif len(students) <= 60:
    for data in studentnumbers:
        try:
            studentnumbers[ID] = students[ID]
            ID += 1
            break
        except IndexError:
            pass
    print("..")
else:
    print("...")

with open('Students.json','w') as instudent:
    json.dump(studentnumbers,instudent,indent=2)

output what I have now:

[{"Student1":029182,"e-mail":"example@.com","studentnumber":029182},
{"Student2":0591238,"e-mail":"example@.com","studentnumber":9213189},
{"Student3":9213189,"e-mail":"example@.com","studentnumber":0591238},
{"Student4":9213189,"e-mail":"example@.com","studentnumber":0294832},
{"Student5":9213189,"e-mail":"example@.com","studentnumber":0591823},
{"Student6":9213189,"e-mail":"example@.com","studentnumber":0501852}]

What I want:

[{"Student1":029182,"e-mail":"example@.com","studentnumber":029182},
{"Student2":0591238,"e-mail":"example@.com","studentnumber":029182},
{"Student3":9213189,"e-mail":"example@.com","studentnumber":029182},
{"Student4":9213189,"e-mail":"example@.com","studentnumber":9213189},
{"Student5":9213189,"e-mail":"example@.com","studentnumber":9213189},
{"Student6":9213189,"e-mail":"example@.com","studentnumber":9213189}]


问:
Checking states of Slide toggle not working in Cypress Tests
I am trying to test the states of slide-toggles within my app using Cypress.

These time out and fails the test:

```<code>cy.get('label.mat-slide-toggle-label').eq(2).should('be.checked')
 or
cy.get('div.mat-slide-toggle-bar').eq(2).should('be.checked')
</code>```

Where as these pass

```<code>cy.get('label.mat-slide-toggle-label').eq(2).should('not.checked')
 or
cy.get('div.mat-slide-toggle-bar').eq(2).should('not.checked')
</code>```

The only difference is that the state of the toggle has changed.

Can someone help explain why the "not.checked" tests pass, but the others don't?

答:
The documentation states:

The <mat-slide-toggle> uses an internal <input type="checkbox">
  to provide an accessible experience. This internal checkbox
  receives focus and is automatically labelled by the text content of
  the <mat-slide-toggle> element.

When Angular Material adds the switch, it adds a whole little hierarchy of elements under the outer <mat-slide-toggle> element; divs with classes like mat-slide-toggle-label, mat-slide-toggle-bar, etc. But it also adds a real (but hidden) <input> element.

The 'checked' test only applies to input elements (this is probably why your should('not.be.checked') tests are working--because non-input elements can never be checked. So, to use Cypress's should('be.checked') test, you need to tell Cypress to get a reference to the actual <input> contained within the <mat-slide-toggle>, and not one of the other mat-xxx elements.

Example:

```<code>cy.get('mat-slide-toggle#whateverId input').should('be.checked');
  // get reference to the single <input> inside the <mat-slide-toggle>
</code>```

or:

```<code>cy.get('mat-slide-toggle#whateverId .mat-slide-toggle-input').should('be.checked');
  // get reference to the element with class "mat-slide-toggle-input" inside the <mat-slide-toggle> (which is the <input> itself)

</code>```

Body:
I am trying to test the states of slide-toggles within my app using Cypress.

These time out and fails the test:

cy.get('label.mat-slide-toggle-label').eq(2).should('be.checked')
 or
cy.get('div.mat-slide-toggle-bar').eq(2).should('be.checked')

Where as these pass

cy.get('label.mat-slide-toggle-label').eq(2).should('not.checked')
 or
cy.get('div.mat-slide-toggle-bar').eq(2).should('not.checked')

The only difference is that the state of the toggle has changed.

Can someone help explain why the "not.checked" tests pass, but the others don't?

Body:
The documentation states:

The <mat-slide-toggle> uses an internal <input type="checkbox">
  to provide an accessible experience. This internal checkbox
  receives focus and is automatically labelled by the text content of
  the <mat-slide-toggle> element.

When Angular Material adds the switch, it adds a whole little hierarchy of elements under the outer <mat-slide-toggle> element; divs with classes like mat-slide-toggle-label, mat-slide-toggle-bar, etc. But it also adds a real (but hidden) <input> element.

The 'checked' test only applies to input elements (this is probably why your should('not.be.checked') tests are working--because non-input elements can never be checked. So, to use Cypress's should('be.checked') test, you need to tell Cypress to get a reference to the actual <input> contained within the <mat-slide-toggle>, and not one of the other mat-xxx elements.

Example:

cy.get('mat-slide-toggle#whateverId input').should('be.checked');
  // get reference to the single <input> inside the <mat-slide-toggle>

or:

cy.get('mat-slide-toggle#whateverId .mat-slide-toggle-input').should('be.checked');
  // get reference to the element with class "mat-slide-toggle-input" inside the <mat-slide-toggle> (which is the <input> itself)


问:
Fetching large paginated data from a REST API with Python
I'm pulling data from a rest API. The problem is that the datasize is huge and so the response is paginated. I've gotten around it by first reading how many pages of data there are and then iterating the request for each page. The only problem here is that the total number of pages are around 1.5K, which take a huge amount of time to actually fetch and append to a CSV. Is there any faster workaround for this?

This is the endpoint I'm targeting: https://developer.keeptruckin.com/reference#get-logs

```<code>import requests
import json
import csv
url='https://api.keeptruckin.com/v1/logs?start_date=2019-03-09'
header={'x-api-key':'API KEY HERE'}
r=requests.get(url,headers=header)
result=r.json()
result = json.loads(r.text)
num_pages=result['pagination']['total']
print(num_pages)
for page in range (2,num_pages+1):
    r=requests.get(url,headers=header, params={'page_no': page})
    result=r.json()
    result = json.loads(r.text)
    csvheader=['First Name','Last Name','Date','Time','Type','Location']
    with open('myfile.csv', 'a+', newline='') as csvfile:
        writer = csv.writer(csvfile, csv.QUOTE_ALL)
        ##writer.writerow(csvheader)
        for log in result['logs']:
            username = log['log']['driver']['username']
            first_name=log['log']['driver']['first_name']
            last_name=log['log']['driver']['last_name']
            for event in log['log']['events']:
                start_time = event['event']['start_time']
                date, time = start_time.split('T')
                event_type = event['event']['type']
                location = event['event']['location']
                if not location:
                    location = "N/A"
                if (username=="barmx1045"  or username=="aposx001" or username=="mcqkl002" or username=="coudx014" or username=="ruscx013" or username=="loumx001" or username=="robkr002" or username=="masgx009"or username=="coxed001" or username=="mcamx009" or username=="linmx024" or username=="woldj002" or username=="fosbl004"):
                    writer.writerow((first_name, last_name,date, time, event_type, location))
</code>```

答:
A first option: Most paginated responses have a page size that you can edit.
https://developer.keeptruckin.com/reference#pagination
Try updating the per_page field to 100 as opposed to the default 25 per pull.

A second option: potentially you can pull more than one page at a time by using multiple threads/processes and splitting up what portion of pages each is responsible for.

Body:
I'm pulling data from a rest API. The problem is that the datasize is huge and so the response is paginated. I've gotten around it by first reading how many pages of data there are and then iterating the request for each page. The only problem here is that the total number of pages are around 1.5K, which take a huge amount of time to actually fetch and append to a CSV. Is there any faster workaround for this?

This is the endpoint I'm targeting: https://developer.keeptruckin.com/reference#get-logs

import requests
import json
import csv
url='https://api.keeptruckin.com/v1/logs?start_date=2019-03-09'
header={'x-api-key':'API KEY HERE'}
r=requests.get(url,headers=header)
result=r.json()
result = json.loads(r.text)
num_pages=result['pagination']['total']
print(num_pages)
for page in range (2,num_pages+1):
    r=requests.get(url,headers=header, params={'page_no': page})
    result=r.json()
    result = json.loads(r.text)
    csvheader=['First Name','Last Name','Date','Time','Type','Location']
    with open('myfile.csv', 'a+', newline='') as csvfile:
        writer = csv.writer(csvfile, csv.QUOTE_ALL)
        ##writer.writerow(csvheader)
        for log in result['logs']:
            username = log['log']['driver']['username']
            first_name=log['log']['driver']['first_name']
            last_name=log['log']['driver']['last_name']
            for event in log['log']['events']:
                start_time = event['event']['start_time']
                date, time = start_time.split('T')
                event_type = event['event']['type']
                location = event['event']['location']
                if not location:
                    location = "N/A"
                if (username=="barmx1045"  or username=="aposx001" or username=="mcqkl002" or username=="coudx014" or username=="ruscx013" or username=="loumx001" or username=="robkr002" or username=="masgx009"or username=="coxed001" or username=="mcamx009" or username=="linmx024" or username=="woldj002" or username=="fosbl004"):
                    writer.writerow((first_name, last_name,date, time, event_type, location))


问:
Cross Entropy Error remains unchanged for various values
I am using Cross Entropy with Softmax as loss function for my neural network.
The cross entropy function I have written is as follows:

```<code>def CrossEntropy(calculated,desired):
    sum=0
    n=len(calculated)
    for i in range(0,n):
        sum+=(desired[i] * math.log(calculated[i])) + ((1-desired[i])* math.log(1-calculated[i]))

    crossentropy=(-1)*sum/n
    return crossentropy
</code>```

Now let us suppose the desired output is [1,0,0,0] and we are testing it for two calculated outputs i.e. a=[0.1,0.9,0.1,0.1] and b=[0.1,0.1,0.1,0.9]. The problem is that for both these calculated outputs will  the function would return the exact same value for cross entropy. So how does the neural network learn that which output is the correct one ?

答:
That is expected because you have a data symmetry in your two calculated cases.

In your example, the desired output is [1, 0, 0, 0]. Thus the true class is the first class. However, in both a and b your prediction for the first class are the same (0.1). Also for other classes (true negatives - 2nd, 3rd and 4th class),  you have this data symmetry (class 2 and class 4 are equally important with respect to the loss calculation).

```<code> a -> 0.9,0.1,0.1
       ^
       |       |
               V
 b -> 0.1,0.1,0.9
</code>```

Thus you have the same loss which is expected.

If you remove this symmetry, you get different cross entropy loss. See examples below:

# The first two are from your examples.
print CrossEntropy(calculated=[0.1,0.9,0.1,0.1], desired=[1, 0, 0, 0])
print CrossEntropy(calculated=[0.1,0.1,0.1,0.9], desired=[1, 0, 0, 0])

# below we have prediction for the last class as 0.75 thus break the data symmetry.
print CrossEntropy(calculated=[0.1,0.1,0.1,0.75], desired=[1, 0, 0, 0])

# below we have prediction for the true class as 0.45.
print CrossEntropy(calculated=[0.45,0.1,0.1,0.9], desired=[1, 0, 0, 0])

result:
1.20397280433
1.20397280433
0.974900121357
0.827953455132
```

Body:
I am using Cross Entropy with Softmax as loss function for my neural network.
The cross entropy function I have written is as follows:

def CrossEntropy(calculated,desired):
    sum=0
    n=len(calculated)
    for i in range(0,n):
        sum+=(desired[i] * math.log(calculated[i])) + ((1-desired[i])* math.log(1-calculated[i]))

    crossentropy=(-1)*sum/n
    return crossentropy

Now let us suppose the desired output is [1,0,0,0] and we are testing it for two calculated outputs i.e. a=[0.1,0.9,0.1,0.1] and b=[0.1,0.1,0.1,0.9]. The problem is that for both these calculated outputs will  the function would return the exact same value for cross entropy. So how does the neural network learn that which output is the correct one ?

Body:
That is expected because you have a data symmetry in your two calculated cases.

In your example, the desired output is [1, 0, 0, 0]. Thus the true class is the first class. However, in both a and b your prediction for the first class are the same (0.1). Also for other classes (true negatives - 2nd, 3rd and 4th class),  you have this data symmetry (class 2 and class 4 are equally important with respect to the loss calculation).

 a -> 0.9,0.1,0.1
       ^
       |       |
               V
 b -> 0.1,0.1,0.9

Thus you have the same loss which is expected.

If you remove this symmetry, you get different cross entropy loss. See examples below:

# The first two are from your examples.
print CrossEntropy(calculated=[0.1,0.9,0.1,0.1], desired=[1, 0, 0, 0])
print CrossEntropy(calculated=[0.1,0.1,0.1,0.9], desired=[1, 0, 0, 0])

# below we have prediction for the last class as 0.75 thus break the data symmetry.
print CrossEntropy(calculated=[0.1,0.1,0.1,0.75], desired=[1, 0, 0, 0])

# below we have prediction for the true class as 0.45.
print CrossEntropy(calculated=[0.45,0.1,0.1,0.9], desired=[1, 0, 0, 0])

result:
1.20397280433
1.20397280433
0.974900121357
0.827953455132


问:
How-to Keep an Android Activity Running when hitting the back key
I have an activity that essentially launches a CountDownTimer.  I need this to continue running while using other Android apps, such as Gmail, and media players etc.

When I hit the back button, my Activity seems to quit.  What do I need to do to keep it running when the user clicks the back/home keys etc.

答: You have to use a Service, you can read the documentation here.


问:
Create a partial view for the imports of css and js asp.net core 2.2
It is a question regarding design. In my ASP.Net Core MVC app I have 2 Layouts. My Default Layout and my Admin Layout which are quite self explanatory by there name. I do import the same js and css for both of my layouts e.g. Bootstrap and jQuery and some more. I wonder if I should create a partial view which contains these.
There might be different solutions which I do not know about.

Any help is appreciated.

答:
You can use nested layouts to have a hierarchy of layouts. I have a similar scenario as yours. I have a _MasterLayout.cshtml in Shared with the full set of CSS and JS I pull in for all pages. Then create a separate layout file for different sections. Reference the master layout at the top and then include all of the other sections adding specific code for that layout.

So you could have a MasterLayout like:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="content-security-policy" content="upgrade-insecure-requests" />

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />

    @RenderSection("Styles", required: false)

    <title>@ViewData["Title"]</title>
</head>
<body>

    <div class="container body-content">
        @RenderBody()
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" crossorigin="anonymous"</script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>

    @RenderSection("Scripts", required: false)
</body>
</html>
</code>```

And a separate nested layout like the following:

```<code>@{
    Layout = "_MasterLayout";
}
@RenderSection("Styles", required: false)

<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
   // custom navbar for anonymous users
</nav>

<div class="container body-content">
    @RenderBody()
</div>

@section Scripts {
    @RenderSection("Scripts", required: false)
}
</code>```

There's not a lot of documentation for nested layouts. Here's one other article I found describing the approach.

Body:
You can use nested layouts to have a hierarchy of layouts. I have a similar scenario as yours. I have a _MasterLayout.cshtml in Shared with the full set of CSS and JS I pull in for all pages. Then create a separate layout file for different sections. Reference the master layout at the top and then include all of the other sections adding specific code for that layout.

So you could have a MasterLayout like:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="content-security-policy" content="upgrade-insecure-requests" />

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />

    @RenderSection("Styles", required: false)

    <title>@ViewData["Title"]</title>
</head>
<body>

    <div class="container body-content">
        @RenderBody()
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" crossorigin="anonymous"</script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    <script src="~/js/site.js" asp-append-version="true"></script>

    @RenderSection("Scripts", required: false)
</body>
</html>

And a separate nested layout like the following:

@{
    Layout = "_MasterLayout";
}
@RenderSection("Styles", required: false)

<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
   // custom navbar for anonymous users
</nav>

<div class="container body-content">
    @RenderBody()
</div>

@section Scripts {
    @RenderSection("Scripts", required: false)
}

There's not a lot of documentation for nested layouts. Here's one other article I found describing the approach.