问:
handling stripe webhook in multiple stripe account laravel
I've multiple stripe account on my site, and each stripe account is associated with a webhook.

My webhook is returning 403 Error "No signatures found matching the expected signature for payload"

i've checked the Cashier middleware and its getting the webhook secret key from the env file.

Since this project attached to multiple stripe account, we can't store the webhook secret in env file. so, we're placing the webhook secret key of each stripe account in a table.

I would like to get the secret key from database instead of this config file.

Is it possible to listen to multiple stripe account's webhook?

Any help will be appreciated.

答:
I am not sure if this is a good approach but you can:

Send meta data in the checkout which gets posted to the web hook

Get the raw json posted by the web hook before you use the web hook key to validate that the post was from Stripe. Stripe.Net contains a parse method and a construct method. Parse does not require the key. Construct uses the key to validate the post was from Stripe.

So with Stripe.net:

```<code>string endpointSecret;

// get the json posted
var json = await new
StreamReader(HttpContext.Request.Body).ReadToEndAsync();

// convert the json into a stripe event object
var objStripeEvent = EventUtility.ParseEvent(json);
if (objStripeEvent.Type == Events.CheckoutSessionCompleted)
{
   // get the session object and see if it contains the Meta data we passed
   // in at checkout
   var session = objStripeEvent.Data.Object as Session;
   var met = session.Metadata;
   if (met.ContainsKey("FranchiseGuid"))
   {
       // if the meta data contains the franchise guid get the correct
       // wh secret from the DB
       var FranchiseGuid= new Guid(met["FranchiseGuid"]);
       endpointSecret = _repo.GetWebHookSecret(FranchiseGuid);

    }
 }
</code>```

// Then you can go on to use the Construct method to validate the post with the correct key for the Stripe account where the web hook is based.

```<code>try
{
  // check if was from Stripe
  var stripeEvent = EventUtility.ConstructEvent(
  json,
  Request.Headers["Stripe-Signature"],
  endpointSecret);

  ---- etc
</code>```

I've requested help on this from Stripe support but they have promised to get back to me. I'll test out the above to see if it works. I don't think it's ideal though because if a hacker were able to get a valid franchise guid they could possibly fake posts and spam the endpoint. It would not be easy to guess a guid and these id's are not available in any way publicly. Plus https is used. But it still makes me nervous because the franchise guid would be one of a dozen or more. Not like a booking guid which is generated and sent once for the booking that is marked as paid. The franchise guid would be sent every time a payment was made for that franchise.

I think what I may do is use the booking guid since this is randomly generated for every booking. I can join to the franchise table from the booking and get the web hook secret.

We'll see if Stripe come back with something useful.

Body:
I am not sure if this is a good approach but you can:

Send meta data in the checkout which gets posted to the web hook

Get the raw json posted by the web hook before you use the web hook key to validate that the post was from Stripe. Stripe.Net contains a parse method and a construct method. Parse does not require the key. Construct uses the key to validate the post was from Stripe.

So with Stripe.net:

string endpointSecret;

// get the json posted
var json = await new
StreamReader(HttpContext.Request.Body).ReadToEndAsync();

// convert the json into a stripe event object
var objStripeEvent = EventUtility.ParseEvent(json);
if (objStripeEvent.Type == Events.CheckoutSessionCompleted)
{
   // get the session object and see if it contains the Meta data we passed
   // in at checkout
   var session = objStripeEvent.Data.Object as Session;
   var met = session.Metadata;
   if (met.ContainsKey("FranchiseGuid"))
   {
       // if the meta data contains the franchise guid get the correct
       // wh secret from the DB
       var FranchiseGuid= new Guid(met["FranchiseGuid"]);
       endpointSecret = _repo.GetWebHookSecret(FranchiseGuid);

    }
 }

// Then you can go on to use the Construct method to validate the post with the correct key for the Stripe account where the web hook is based.

try
{
  // check if was from Stripe
  var stripeEvent = EventUtility.ConstructEvent(
  json,
  Request.Headers["Stripe-Signature"],
  endpointSecret);

  ---- etc

I've requested help on this from Stripe support but they have promised to get back to me. I'll test out the above to see if it works. I don't think it's ideal though because if a hacker were able to get a valid franchise guid they could possibly fake posts and spam the endpoint. It would not be easy to guess a guid and these id's are not available in any way publicly. Plus https is used. But it still makes me nervous because the franchise guid would be one of a dozen or more. Not like a booking guid which is generated and sent once for the booking that is marked as paid. The franchise guid would be sent every time a payment was made for that franchise.

I think what I may do is use the booking guid since this is randomly generated for every booking. I can join to the franchise table from the booking and get the web hook secret.

We'll see if Stripe come back with something useful.


来源: stackexchange

问:
Funnel plot in Pandas
Is there a way to create a funnel plot in Python using Pandas? The documentation does not seem to have something relevant. </p>

答:
#I am new to Python; I figured it out, did the code below, and it worked.
#Doing a simple funnel plot with data from a csv file
import pandas as pd
import plotly.express as px
df=pd.read_csv("C:\Users\User\Desktop\file_name.csv")# path and file
df= df.sort_values('scores', ascending= False)# True or False for type of sorting
print(df.head(5))# preview data
fig = px.funnel(df['category_column'].values, df['column_with_float'].values,color='red')
fig.show()</p>

ContentLicense: CC BY-SA 3.0

Title: Funnel plot in Pandas

ContentLicense: CC BY-SA 4.0


问:
Definition of struct template value in constructor / member function
I'm working with a Pascal library that uses UCSD Strings. I created this template struct for making working with them easier:

```<code>template <std::size_t N>
struct DString {
    unsigned Reference, Size = N;
    char String[N];
};
#define MAKE_STRING(X) DString<sizeof(X)>{ 0x0FFFFFFFF, sizeof(X) - 1, X}

auto foo = MAKE_STRING("Foo");
</code>```

I know it does not cover WideChar cases but the library does neither in the first place so I'm safe in that regard.

Anyway, my problem is that I don't want to use a macro and instead would like to create a constructor. So I was wondering if does C++ offers a possibility of implementing something like this pseudocode:

```<code>template <std::size_t N>
struct DString {
    unsigned Reference, Size = N;
    char String[N];
    DString<sizeof(s)>(const char* s, unsigned r = 0x0FFFFFFFF):
        String(s), Reference(r) {}
};

auto foo = DString("Foo");
</code>```

Of course, it does not need to be a "constructor". It is just an example.

I also tried this:

```<code>template <std::size_t N>
struct DString {
    unsigned Reference, Size = N;
    char String[N];

    inline static DString build(const char* X) {
        return DString<sizeof(X)>{ 0x0FFFFFFFF, sizeof(X) - 1, X};
    }
};

auto foo = DString::build("Foo");
</code>```

But that in itself represents another issue. Because now I cannot reference the static function from DString without doing DString< size >::build(...);.

What can I do in this case?

答:
If you can use at least C++17... using a delegate constructor and CTAD...

You can add in DString an additional template constructor (maybe private), otherwise you can't initialize, directly, a char[] with a char const *

```<code>template <std::size_t ... Is>
DString (std::index_sequence<Is...>, char const * s, unsigned r)
  : Reference{r}, Size{N}, String{ s[Is]... }
{ }
</code>```

Next you have to call the new constructor from the old one

```<code>DString (char const * s, unsigned r = 0x0FFFFFFFFu):
  DString(std::make_index_sequence<N>{}, s, r)
  { }
</code>```

Last, you have to add an explicit deduction guide (given that you want a DString<3> from a char const [4]

```<code>template <std::size_t N>
DString (char const (&)[N], unsigned = 0u) -> DString<N-1u>;
</code>```

and the automatic deduction works.

The following is a full compiling example

```<code>#include <utility>
#include <iostream>

template <std::size_t N>
struct DString {
  private:
    template <std::size_t ... Is>
    DString (std::index_sequence<Is...>, char const * s, unsigned r)
      : Reference{r}, Size{N}, String{ s[Is]... }
    { }

  public:
    unsigned Reference, Size = N;
    char String[N];

    DString (char const * s, unsigned r = 0x0FFFFFFFFu):
      DString(std::make_index_sequence<N>{}, s, r)
      { }

};

template <std::size_t N>
DString (char const (&)[N], unsigned = 0u) -> DString<N-1u>;

int main()
{
  auto foo = DString{"Foo"};
}
</code>```

Body:
I'm working with a Pascal library that uses UCSD Strings. I created this template struct for making working with them easier:

template <std::size_t N>
struct DString {
    unsigned Reference, Size = N;
    char String[N];
};
#define MAKE_STRING(X) DString<sizeof(X)>{ 0x0FFFFFFFF, sizeof(X) - 1, X}

auto foo = MAKE_STRING("Foo");

I know it does not cover WideChar cases but the library does neither in the first place so I'm safe in that regard.

Anyway, my problem is that I don't want to use a macro and instead would like to create a constructor. So I was wondering if does C++ offers a possibility of implementing something like this pseudocode:

template <std::size_t N>
struct DString {
    unsigned Reference, Size = N;
    char String[N];
    DString<sizeof(s)>(const char* s, unsigned r = 0x0FFFFFFFF):
        String(s), Reference(r) {}
};

auto foo = DString("Foo");

Of course, it does not need to be a "constructor". It is just an example.

I also tried this:

template <std::size_t N>
struct DString {
    unsigned Reference, Size = N;
    char String[N];

    inline static DString build(const char* X) {
        return DString<sizeof(X)>{ 0x0FFFFFFFF, sizeof(X) - 1, X};
    }
};

auto foo = DString::build("Foo");

But that in itself represents another issue. Because now I cannot reference the static function from DString without doing DString< size >::build(...);.

What can I do in this case?

Body:
If you can use at least C++17... using a delegate constructor and CTAD...

You can add in DString an additional template constructor (maybe private), otherwise you can't initialize, directly, a char[] with a char const *

template <std::size_t ... Is>
DString (std::index_sequence<Is...>, char const * s, unsigned r)
  : Reference{r}, Size{N}, String{ s[Is]... }
{ }

Next you have to call the new constructor from the old one

DString (char const * s, unsigned r = 0x0FFFFFFFFu):
  DString(std::make_index_sequence<N>{}, s, r)
  { }

Last, you have to add an explicit deduction guide (given that you want a DString<3> from a char const [4]

template <std::size_t N>
DString (char const (&)[N], unsigned = 0u) -> DString<N-1u>;

and the automatic deduction works.

The following is a full compiling example

#include <utility>
#include <iostream>

template <std::size_t N>
struct DString {
  private:
    template <std::size_t ... Is>
    DString (std::index_sequence<Is...>, char const * s, unsigned r)
      : Reference{r}, Size{N}, String{ s[Is]... }
    { }

  public:
    unsigned Reference, Size = N;
    char String[N];

    DString (char const * s, unsigned r = 0x0FFFFFFFFu):
      DString(std::make_index_sequence<N>{}, s, r)
      { }

};

template <std::size_t N>
DString (char const (&)[N], unsigned = 0u) -> DString<N-1u>;

int main()
{
  auto foo = DString{"Foo"};
}


问:
IBM MQ for Apple Silicon
Is there a solution to make this docker image https://hub.docker.com/r/ibmcom/mq run on Apple M1 chips? For Intel chips, I was able to run this image by:

```<code>docker run -e LICENSE=accept -e MQ_QMGR_NAME=QM1 -p 1414:1414 -p 9443:9443 ibmcom/mq
</code>```

Is there a custom build or an official IBM plan to create an Apple M1 compatible version of this image?

答:
I don't have an M1 mac, so I can't test it but according to this, it says you can try adding --platform linux/amd64.

If that doesn't work then you'll have to build your own (you can base it off the Dockerfile they provided in their GitHub repo.  The ones from the official Dockerhub only supports amd64 and s390x architectures.

Title: IBM MQ for Apple Silicon

Body:
Is there a solution to make this docker image https://hub.docker.com/r/ibmcom/mq run on Apple M1 chips? For Intel chips, I was able to run this image by:

docker run -e LICENSE=accept -e MQ_QMGR_NAME=QM1 -p 1414:1414 -p 9443:9443 ibmcom/mq

Is there a custom build or an official IBM plan to create an Apple M1 compatible version of this image?


问:
Reconnecting remote Jupyter Notebook and get current cell output
I'm currently training a neural network on a remote server, using jupyter notebook. I set it up with the following:

tmux

jupyter-notebook --no-browser --port=5000

connecting to jupyter notebook with a browser and executing the cell for the training (output was fine when I watched for the first 10 minutes)

detach tmux (ctrl-b, d) and closing the browser tab

Now, when I reconnect to the jupyter notebook in the browser, I don't see the current output of the training cell, only the output that I saw when I was watching the first 10 minutes of training.

I tried to find a solution for this and, I think, there are some git issues for this certain problem but they are old and I couldn't figure out if this issue was solved or not.

edit// to make my intentions more clear, since I found some threads on StackOverflow that are addressing this problem: I don't want to wait for the training to complete, as I might want to kill the training before it finishes, when it absolutely doesn't go they way I would expect it to go. So some sort of 'live' output or at least regular output would be nice.

答:
This is a long-running missing feature in jupyter notebooks. I use a near-identical setup: my notebook runs inside a tmux session in a remote server, and I use it locally with ssh tunneling.

Before doing any work, I run the following snippet in the first cell:

```<code>import sys
import logging

nblog = open("nb.log", "a+")
sys.stdout.echo = nblog
sys.stderr.echo = nblog

get_ipython().log.handlers[0].stream = nblog
get_ipython().log.setLevel(logging.INFO)

%autosave 5
</code>```

Now let's say, I run a cell that will take a while to complete (like a training run). Something like:

```<code>import time

def train(num_epochs):
    for epoch in range(num_epochs):
        time.sleep(1)
        print(f"Completed epoch {epoch}")

train(1000)
</code>```

Now while train(1000) is running, after the first 10 seconds, I want to do something else and close the browser, and also disconnect from my remote connection.

(Note the modified short autosave duration; I added that as I often forget to save the notebook before closing the browser tab.)

After 500 seconds have passed, I can reconnect to the remote server and open the notebook in my browser. My logs of this cell will have stopped printing after "Completed epoch 9", i.e. when I disconnected. However, the kernel will still actually be running train in the backend, and it will also show "busy".

We can now just simply open up the file nb.log and we'll find all the logs, including the ones after we closed the browser and connection. We can keep refreshing the nb.log file at our leisure and new logs will keep coming up, till the kernel finishes running train().

Now if we want to stop train() before it's done, we can just press the Interrupt button in jupyter. The kernel will be freed and we can run other stuff (And a Keyboard Interrupt error message will also show up in your nb.log file). All our precomputed notebook variables and imported libraries are still there, as the kernel wasn't actually disconnected.

Although this isn't a very sophisticated solution, I find it quite easy to implement

Body:
This is a long-running missing feature in jupyter notebooks. I use a near-identical setup: my notebook runs inside a tmux session in a remote server, and I use it locally with ssh tunneling.

Before doing any work, I run the following snippet in the first cell:

import sys
import logging

nblog = open("nb.log", "a+")
sys.stdout.echo = nblog
sys.stderr.echo = nblog

get_ipython().log.handlers[0].stream = nblog
get_ipython().log.setLevel(logging.INFO)

%autosave 5

Now let's say, I run a cell that will take a while to complete (like a training run). Something like:

import time

def train(num_epochs):
    for epoch in range(num_epochs):
        time.sleep(1)
        print(f"Completed epoch {epoch}")

train(1000)

Now while train(1000) is running, after the first 10 seconds, I want to do something else and close the browser, and also disconnect from my remote connection.

(Note the modified short autosave duration; I added that as I often forget to save the notebook before closing the browser tab.)

After 500 seconds have passed, I can reconnect to the remote server and open the notebook in my browser. My logs of this cell will have stopped printing after "Completed epoch 9", i.e. when I disconnected. However, the kernel will still actually be running train in the backend, and it will also show "busy".

We can now just simply open up the file nb.log and we'll find all the logs, including the ones after we closed the browser and connection. We can keep refreshing the nb.log file at our leisure and new logs will keep coming up, till the kernel finishes running train().

Now if we want to stop train() before it's done, we can just press the Interrupt button in jupyter. The kernel will be freed and we can run other stuff (And a Keyboard Interrupt error message will also show up in your nb.log file). All our precomputed notebook variables and imported libraries are still there, as the kernel wasn't actually disconnected.

Although this isn't a very sophisticated solution, I find it quite easy to implement


问:
How to flush all of the cached contents of Docker memcached?
How to flush all of the cached contents of Docker container memcached from command line without restarting memcached?</p>

答:
Try to use the following (also works on alpine docker image):</p>
```<code>docker exec -it $DOCKER_CONTAINER_ID sh -c "echo flush_all | nc localhost 11211"
</code>```

Body:
Try to use the following (also works on alpine docker image):

docker exec -it $DOCKER_CONTAINER_ID sh -c "echo flush_all | nc localhost 11211"


问:
Team Making using Python?
I am running a tournament for 16 people, and each tournament, every person earns a certain number of points. These points are earned from 8 different games.

I need to make four teams of four, and their averages and standard deviations should ideally be as close together as possible (to make the fairest teams). I have already done this using a binpacking library. However, I have read that the knapsack problem is often better than binpacking at picking teams.

Ideally, I would be able to select one of the 8 games to balance points off of and obtain fair teams from that; right now I am just using overall points.

If anybody knows of any libraries or functions I can borrow to complete this task, please let me know. Additionally, if there are ways I can further optimize my code, please tell– I am still a beginner. My code is below.

```<code>import numpy as np

levels = np.genfromtxt('points.txt', dtype = 'float')
players = np.genfromtxt('players.txt', dtype = 'str')
playerLevels = zip(players, levels)
playerLevelsList = list(playerLevels)

averageLevels = sum(levels)/len(levels)
print('Average points are', averageLevels)

bins = binpacking.to_constant_bin_number(playerLevelsList, 4, 1)

a, b, c, d = [ [individualArray] for individualArray in bins]

a = a[0]
b = b[0]
c = c[0]
d = d[0]
a1 = a[1]
b1 = b[1]
c1 = c[1]
d1 = d[1]

team1 = list(zip(*a))
team2 = list(zip(*b))
team3 = list(zip(*c))
team4 = list(zip(*d))

points1 = sum(team1[1])/4
points2 = sum(team2[1])/4
points3 = sum(team3[1])/4
points4 = sum(team4[1])/4

stdev1 = np.std(team1[1])
stdev2 = np.std(team2[1])
stdev3 = np.std(team3[1])
stdev4 = np.std(team4[1])

print('Team 1 is', team1[0])
print('Team 2 is', team2[0])
print('Team 3 is', team3[0])
print('Team 4 is', team4[0])
print('\n-----Stats-----')
print('Team 1 Average is', points1, 'with a standard deviation of', stdev1)
print('Team 2 Average is', points2, 'with a standard deviation of', stdev2)
print('Team 3 Average is', points3, 'with a standard deviation of', stdev3)
print('Team 4 Average is', points4, 'with a standard deviation of', stdev4)```
```

答:
This may be a start to your answer.  This was interesting and I had some time to kill.  I was curious just how many unique team combinations are possible.  Using an online combinations and permutations calculator I found out there are only 1820 unique teams possible when selecting 4 from 16 when order is not important.  Using Python I generated a list of possible unique teams.

```<code>import matplotlib.pyplot as plt
import itertools as it

team_score_total=[]

teams = []
players=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

for i in it.combinations(players, 4):
    teams.append(list(i))

# only 1,820 unique team possibilities
print(len(teams))

#check if there are duplicate players before adding to league
def CanAddTeamLeague(team, league):
    for t in league:
        for i in t:
            if i in team:
                return False
    return True;

#check if there are duplicate leagues before adding to list
def CanAddLeagueToList(league, league_list):
    for lg_list in league_list:
        count=0
        for t1 in lg_list:
            for t2 in league:
                if t1 == t2:
                    count+=1
                    if count ==4:
                        return False
    return True;

unique_league_list = []
for i in range(len(teams)):
    league = []
    league.append(teams[i])
    for t in teams:
        if CanAddTeamLeague(t,league):
            if len(league) < 4:
                league.append(t)
        if len(league) == 4:
            if CanAddLeagueToList(league,unique_league_list):
                unique_league_list.append(league)

print(len(unique_league_list))
for l in unique_league_list:
    print(l)

# for i in teams:
#     print(i)

# for t in teams:
#     team_score_total.append(scores[t[0]]+scores[t[1]]+scores[t[2]]+scores[t[3]])

# fig, ax = plt.subplots(figsize=(20, 12))
# plt.plot(range(len(teams)),team_score_total)
</code>```

This got me to wondering just how many truly unique leagues of 4 teams are possible.  I think the answer is 1715.  I switched to Java to figure this out and it took 24 seconds on my machine for the code to eliminate duplicate possibilities.  I don't think I have the math skills to calculate that with combinations/permutations (but somebody does).  Having said that, 1715 is not a huge number to deal with for brute force methods and I don't think it would take much time to calculate the stats for each team.

Here is the final piece.  I put this in another cell so you don't have to recalculate the time consuming part every time.

```<code>import numpy as np
scores=[7,11,20,21,22,12,13,14,15,16,23,18,19,17,24,10]

league_score_list = []
for league in unique_league_list:
    league_score=[]

    for team in league:
        team_score=0
        for ts in range(4):
            team_score += scores[team[ts]]
        league_score.append(team_score)
    league_score_list.append(league_score)

std_list=[]
for l in league_score_list:
    std_list.append(np.std(l))

sorted_list = np.argsort(std_list)
print(league_score_list[sorted_list[0]])
print(unique_league_list[sorted_list[0]])
</code>```

Title: Team Making using Python?

Body:
I am running a tournament for 16 people, and each tournament, every person earns a certain number of points. These points are earned from 8 different games.

I need to make four teams of four, and their averages and standard deviations should ideally be as close together as possible (to make the fairest teams). I have already done this using a binpacking library. However, I have read that the knapsack problem is often better than binpacking at picking teams.

Ideally, I would be able to select one of the 8 games to balance points off of and obtain fair teams from that; right now I am just using overall points.

If anybody knows of any libraries or functions I can borrow to complete this task, please let me know. Additionally, if there are ways I can further optimize my code, please tell– I am still a beginner. My code is below.

import numpy as np

levels = np.genfromtxt('points.txt', dtype = 'float')
players = np.genfromtxt('players.txt', dtype = 'str')
playerLevels = zip(players, levels)
playerLevelsList = list(playerLevels)

averageLevels = sum(levels)/len(levels)
print('Average points are', averageLevels)

bins = binpacking.to_constant_bin_number(playerLevelsList, 4, 1)

a, b, c, d = [ [individualArray] for individualArray in bins]

a = a[0]
b = b[0]
c = c[0]
d = d[0]
a1 = a[1]
b1 = b[1]
c1 = c[1]
d1 = d[1]

team1 = list(zip(*a))
team2 = list(zip(*b))
team3 = list(zip(*c))
team4 = list(zip(*d))

points1 = sum(team1[1])/4
points2 = sum(team2[1])/4
points3 = sum(team3[1])/4
points4 = sum(team4[1])/4

stdev1 = np.std(team1[1])
stdev2 = np.std(team2[1])
stdev3 = np.std(team3[1])
stdev4 = np.std(team4[1])

print('Team 1 is', team1[0])
print('Team 2 is', team2[0])
print('Team 3 is', team3[0])
print('Team 4 is', team4[0])
print('\n-----Stats-----')
print('Team 1 Average is', points1, 'with a standard deviation of', stdev1)
print('Team 2 Average is', points2, 'with a standard deviation of', stdev2)
print('Team 3 Average is', points3, 'with a standard deviation of', stdev3)
print('Team 4 Average is', points4, 'with a standard deviation of', stdev4)```

Body:
This may be a start to your answer.  This was interesting and I had some time to kill.  I was curious just how many unique team combinations are possible.  Using an online combinations and permutations calculator I found out there are only 1820 unique teams possible when selecting 4 from 16 when order is not important.  Using Python I generated a list of possible unique teams.

import matplotlib.pyplot as plt
import itertools as it

team_score_total=[]

teams = []
players=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

for i in it.combinations(players, 4):
    teams.append(list(i))

# only 1,820 unique team possibilities
print(len(teams))

#check if there are duplicate players before adding to league
def CanAddTeamLeague(team, league):
    for t in league:
        for i in t:
            if i in team:
                return False
    return True;

#check if there are duplicate leagues before adding to list
def CanAddLeagueToList(league, league_list):
    for lg_list in league_list:
        count=0
        for t1 in lg_list:
            for t2 in league:
                if t1 == t2:
                    count+=1
                    if count ==4:
                        return False
    return True;

unique_league_list = []
for i in range(len(teams)):
    league = []
    league.append(teams[i])
    for t in teams:
        if CanAddTeamLeague(t,league):
            if len(league) < 4:
                league.append(t)
        if len(league) == 4:
            if CanAddLeagueToList(league,unique_league_list):
                unique_league_list.append(league)

print(len(unique_league_list))
for l in unique_league_list:
    print(l)

# for i in teams:
#     print(i)

# for t in teams:
#     team_score_total.append(scores[t[0]]+scores[t[1]]+scores[t[2]]+scores[t[3]])

# fig, ax = plt.subplots(figsize=(20, 12))
# plt.plot(range(len(teams)),team_score_total)

This got me to wondering just how many truly unique leagues of 4 teams are possible.  I think the answer is 1715.  I switched to Java to figure this out and it took 24 seconds on my machine for the code to eliminate duplicate possibilities.  I don't think I have the math skills to calculate that with combinations/permutations (but somebody does).  Having said that, 1715 is not a huge number to deal with for brute force methods and I don't think it would take much time to calculate the stats for each team.

Here is the final piece.  I put this in another cell so you don't have to recalculate the time consuming part every time.

import numpy as np
scores=[7,11,20,21,22,12,13,14,15,16,23,18,19,17,24,10]

league_score_list = []
for league in unique_league_list:
    league_score=[]

    for team in league:
        team_score=0
        for ts in range(4):
            team_score += scores[team[ts]]
        league_score.append(team_score)
    league_score_list.append(league_score)

std_list=[]
for l in league_score_list:
    std_list.append(np.std(l))

sorted_list = np.argsort(std_list)
print(league_score_list[sorted_list[0]])
print(unique_league_list[sorted_list[0]])


问:
trying to translate a math formula into python
I'm rather new to python I'm writing this program that calculates the falling time of a box using this simple formula:

h-0.5gT^2 = 0

h = 100

g = 9.8

T = ?

Where T is the time it takes (4.5 sec) On paper, I can easily solve for T but I'm not sure how to translate this into python I don't know if there's a formula that can give me the value of T with the inputs I already have or what

答:
import math
T = math.sqrt(h / (0.5 * g))
```


问:
Combining rows that share one variable but differ in others in R (Geographic map data)
I'm working in R and have data on station names and coordinates (as well as the number of trips to respective stations). There are approximately 1,600 distinct station names, but some stations have many rows with slight variations in coordinates associated with them, resulting in thousands of rows showing with the same station with slightly different coordinates,(and only one trip taken when there are in fact many trips to that station).

I've attached a picture of the data to hopefully help convey my issue.screenshot of data frame in R

My end goal is to create a map visualization (which requires the coordinates data), and within that visual I want to display the number of trips to each distinct station. To do that accurately it seems I should create a data frame that has all the distinct station names along with only one set of coordinates for each station.

I'm just having a hard time figuring out how to do that. I already have a data frame with just the distinct station names, but I need one set of coordinates for each station to properly make the map visualization.

My apologies for not being able to ask more clearly, but any help would be greatly appreciated.

```<code>dput(head(popular_starting_routes))
structure(list(member_casual = c("casual", "casual", "casual",
"casual", "casual", "casual"), start_station_name = c("Streeter Dr & Grand Ave",
"Theater on the Lake", "Millennium Park", "Michigan Ave & Oak St",
"Lake Shore Dr & Monroe St", "Wells St & Concord Ln"), start_lat = c(41.892278,
41.926277, 41.8810317, 41.90096039, 41.880958, 41.912133), start_lng = c(-87.612043,
-87.630834, -87.62408432, -87.62377664, -87.616743, -87.634656
), number_of_rides = c(54377L, 17621L, 17004L, 16928L, 16853L,
13941L), average_duration = c(40.9590884013462, 35.1187673798309,
40.4876038971222, 36.4537137681159, 44.4814147827291, 21.9252014441814
)), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA,
-6L), groups = structure(list(member_casual = c("casual", "casual",
"casual", "casual", "casual", "casual"), start_station_name = c("Lake Shore Dr & Monroe St",
"Michigan Ave & Oak St", "Millennium Park", "Streeter Dr & Grand Ave",
"Theater on the Lake", "Wells St & Concord Ln"), start_lat = c(41.880958,
41.90096039, 41.8810317, 41.892278, 41.926277, 41.912133), .rows = structure(list(
    5L, 4L, 3L, 1L, 2L, 6L), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -6L), .drop = TRUE))
</code>```

答:
Try this:</p>
```<code>library(dplyr)
df <- top_50000_popular_ending_routes %>% dplyr::select(end_station_name, end_lat, end_lng) %>% group_by(end_station_name) %>% slice_head(n=1)

</code>```

Body:
I'm working in R and have data on station names and coordinates (as well as the number of trips to respective stations). There are approximately 1,600 distinct station names, but some stations have many rows with slight variations in coordinates associated with them, resulting in thousands of rows showing with the same station with slightly different coordinates,(and only one trip taken when there are in fact many trips to that station).

I've attached a picture of the data to hopefully help convey my issue.screenshot of data frame in R

My end goal is to create a map visualization (which requires the coordinates data), and within that visual I want to display the number of trips to each distinct station. To do that accurately it seems I should create a data frame that has all the distinct station names along with only one set of coordinates for each station.

I'm just having a hard time figuring out how to do that. I already have a data frame with just the distinct station names, but I need one set of coordinates for each station to properly make the map visualization.

My apologies for not being able to ask more clearly, but any help would be greatly appreciated.

dput(head(popular_starting_routes))
structure(list(member_casual = c("casual", "casual", "casual",
"casual", "casual", "casual"), start_station_name = c("Streeter Dr & Grand Ave",
"Theater on the Lake", "Millennium Park", "Michigan Ave & Oak St",
"Lake Shore Dr & Monroe St", "Wells St & Concord Ln"), start_lat = c(41.892278,
41.926277, 41.8810317, 41.90096039, 41.880958, 41.912133), start_lng = c(-87.612043,
-87.630834, -87.62408432, -87.62377664, -87.616743, -87.634656
), number_of_rides = c(54377L, 17621L, 17004L, 16928L, 16853L,
13941L), average_duration = c(40.9590884013462, 35.1187673798309,
40.4876038971222, 36.4537137681159, 44.4814147827291, 21.9252014441814
)), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA,
-6L), groups = structure(list(member_casual = c("casual", "casual",
"casual", "casual", "casual", "casual"), start_station_name = c("Lake Shore Dr & Monroe St",
"Michigan Ave & Oak St", "Millennium Park", "Streeter Dr & Grand Ave",
"Theater on the Lake", "Wells St & Concord Ln"), start_lat = c(41.880958,
41.90096039, 41.8810317, 41.892278, 41.926277, 41.912133), .rows = structure(list(
    5L, 4L, 3L, 1L, 2L, 6L), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -6L), .drop = TRUE))

Body:
Try this:

library(dplyr)
df <- top_50000_popular_ending_routes %>% dplyr::select(end_station_name, end_lat, end_lng) %>% group_by(end_station_name) %>% slice_head(n=1)


答:
You could do something like this:

This will give you the most common end_lat and end_Ing per station.

```<code>library(dplyr)

df %>%
  group_by(end_station_name) %>%
  count(end_station_name, end_lat, end_Ing, sort = TRUE) %>%
  slice_max(n)
</code>```
```<code>  end_station_name  end_lat end_Ing     n
  <chr>               <dbl>   <dbl> <int>
1 Adler Planetarium    41.9   -87.6     5
</code>```

data:

```<code>df <- structure(list(member_casual = c("casual", "casual", "casual",
"casual", "casual", "casual", "casual", "casual", "casual", "casual",
"casual", "casual", "casual", "casual", "casual", "casual", "casual",
"casual", "casual", "casual", "casual", "casual", "casual", "casual",
"casual", "casual", "casual", "casual", "casual", "casual"),
    end_station_name = c("Adler Planetarium", "Adler Planetarium",
    "Adler Planetarium", "Adler Planetarium", "Adler Planetarium",
    "Adler Planetarium", "Adler Planetarium", "Adler Planetarium",
    "Adler Planetarium", "Adler Planetarium", "Adler Planetarium",
    "Adler Planetarium", "Adler Planetarium", "Adler Planetarium",
    "Adler Planetarium", "Adler Planetarium", "Adler Planetarium",
    "Adler Planetarium", "Adler Planetarium", "Adler Planetarium",
    "Adler Planetarium", "Adler Planetarium", "Adler Planetarium",
    "Adler Planetarium", "Adler Planetarium", "Adler Planetarium",
    "Adler Planetarium", "Adler Planetarium", "Adler Planetarium",
    "Adler Planetarium"), end_lat = c(41.86607, 41.86607, 41.86607,
    41.86607, 41.86607, 41.86607, 41.86607, 41.86607, 41.86607,
    41.86607, 41.86607, 41.86607, 41.86608, 41.86608, 41.86608,
    41.86608, 41.86608, 41.86608, 41.86608, 41.86608, 41.86608,
    41.86608, 41.86608, 41.86608, 41.86608, 41.86608, 41.86608,
    41.86608, 41.86608, 41.86608), end_Ing = c(-87.60737, -87.60738,
    -87.60738, -87.60742, -87.60743, -87.60731, -87.60739, -87.60738,
    -87.60736, -87.6074, -87.60738, -87.60738, -87.60726, -87.60734,
    -87.60732, -87.60736, -87.60734, -87.6074, -87.60736, -87.60732,
    -87.60732, -87.60617, -87.60742, -87.60734, -87.60737, -87.60736,
    -87.60735, -87.60744, -87.60727, -87.60734), number_of_rides = c(1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L),
    average_duration = c(28.866667, 5, 34.55, 9.766667, 28.883333,
    19.65, 24.883333, 23.533333, 51.183333, 46.983333, 38.366667,
    1.066667, 27.483333, 15.783333, 56.25, 19.016667, 1.083333,
    9.683333, 32, 13.95, 32.25, 31.116667, 12.783333, 55.3, 10.733333,
    1.45, 59.066667, 51.883333, 49.666667, 113.033333)), class = "data.frame", row.names = c(NA,
-30L))
</code>```

Title: Combining rows that share one variable but differ in others in R (Geographic map data)

Body:
You could do something like this:

This will give you the most common end_lat and end_Ing per station.

library(dplyr)

df %>%
  group_by(end_station_name) %>%
  count(end_station_name, end_lat, end_Ing, sort = TRUE) %>%
  slice_max(n)

  end_station_name  end_lat end_Ing     n
  <chr>               <dbl>   <dbl> <int>
1 Adler Planetarium    41.9   -87.6     5

data:

df <- structure(list(member_casual = c("casual", "casual", "casual",
"casual", "casual", "casual", "casual", "casual", "casual", "casual",
"casual", "casual", "casual", "casual", "casual", "casual", "casual",
"casual", "casual", "casual", "casual", "casual", "casual", "casual",
"casual", "casual", "casual", "casual", "casual", "casual"),
    end_station_name = c("Adler Planetarium", "Adler Planetarium",
    "Adler Planetarium", "Adler Planetarium", "Adler Planetarium",
    "Adler Planetarium", "Adler Planetarium", "Adler Planetarium",
    "Adler Planetarium", "Adler Planetarium", "Adler Planetarium",
    "Adler Planetarium", "Adler Planetarium", "Adler Planetarium",
    "Adler Planetarium", "Adler Planetarium", "Adler Planetarium",
    "Adler Planetarium", "Adler Planetarium", "Adler Planetarium",
    "Adler Planetarium", "Adler Planetarium", "Adler Planetarium",
    "Adler Planetarium", "Adler Planetarium", "Adler Planetarium",
    "Adler Planetarium", "Adler Planetarium", "Adler Planetarium",
    "Adler Planetarium"), end_lat = c(41.86607, 41.86607, 41.86607,
    41.86607, 41.86607, 41.86607, 41.86607, 41.86607, 41.86607,
    41.86607, 41.86607, 41.86607, 41.86608, 41.86608, 41.86608,
    41.86608, 41.86608, 41.86608, 41.86608, 41.86608, 41.86608,
    41.86608, 41.86608, 41.86608, 41.86608, 41.86608, 41.86608,
    41.86608, 41.86608, 41.86608), end_Ing = c(-87.60737, -87.60738,
    -87.60738, -87.60742, -87.60743, -87.60731, -87.60739, -87.60738,
    -87.60736, -87.6074, -87.60738, -87.60738, -87.60726, -87.60734,
    -87.60732, -87.60736, -87.60734, -87.6074, -87.60736, -87.60732,
    -87.60732, -87.60617, -87.60742, -87.60734, -87.60737, -87.60736,
    -87.60735, -87.60744, -87.60727, -87.60734), number_of_rides = c(1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L),
    average_duration = c(28.866667, 5, 34.55, 9.766667, 28.883333,
    19.65, 24.883333, 23.533333, 51.183333, 46.983333, 38.366667,
    1.066667, 27.483333, 15.783333, 56.25, 19.016667, 1.083333,
    9.683333, 32, 13.95, 32.25, 31.116667, 12.783333, 55.3, 10.733333,
    1.45, 59.066667, 51.883333, 49.666667, 113.033333)), class = "data.frame", row.names = c(NA,
-30L))


问:
Basic question about parsing html using bs4 in python
I have a probably simple question about bs4 that I can't seem to figure out.

And for reference I am self-taught and am troubleshooting my way through learning python.

So essentially a chunk of a bigger project I'm working on requires me to scrape a website to get the most up to date rate of a 1 month T-bill. I was able to get 99% of it down, but one aspect of it I'm stuck on.

Essentially this data only updates mon-fri. And running this code say at 8 am before the site has been updated for the day or on the weekend returns an error. When using a date that has been updated I am able to get the exact data I need.

So I have set variables d1, d2 and d3 as today, yesterday, and two day's ago. I want to use my soup.find to search for today, and if none search for yesterday, and then two days ago.

In my code if I use text=d3, for example, I get a value returned.

Here's what I have right now, would really appreciate some help!

```<code>from bs4 import BeautifulSoup
import requests
from datetime import date
import datetime

today = date.today()
d1 = today.strftime("%B %d, %Y")
ndays1 = datetime.timedelta(days = 1)
d2 = (today-ndays1).strftime("%B %d, %Y")
ndays2 = datetime.timedelta(days = 2)
d3 = (today-ndays2).strftime("%B %d, %Y")
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/71.0.3578.98 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5',
    'DNT': '1',  # Do Not Track Request Header
    'Connection': 'close'
}

url_rfr = "https://ycharts.com/indicators/1_month_treasury_rate"

response = requests.get(url_rfr, headers=headers, timeout=5).text
soup = BeautifulSoup(response, 'html.parser')

div = soup.find("td", text=d1 or d2 or d3).find_next_sibling("td").text.strip()

r = (float(div[:-1]))

print(r)
</code>```

答:
So, I changed the text in find(...) to "Last Value" and also added latest_period scrape for completeness

```<code>import datetime
from datetime import date

import requests
from bs4 import BeautifulSoup

today = date.today()
d1 = today.strftime("%B %d, %Y")
ndays1 = datetime.timedelta(days=1)
d2 = (today - ndays1).strftime("%B %d, %Y")
ndays2 = datetime.timedelta(days=2)
d3 = (today - ndays2).strftime("%B %d, %Y")

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/71.0.3578.98 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5',
    'DNT': '1',  # Do Not Track Request Header
    'Connection': 'close'
}

url_rfr = "https://ycharts.com/indicators/1_month_treasury_rate"

response = requests.get(url_rfr, headers=headers, timeout=5).text

soup = BeautifulSoup(response, 'html.parser')
latest_period = soup.find("td", text="Latest Period").find_next_sibling("td").text.strip()
value = soup.find("td", text="Last Value").find_next_sibling("td").text.strip()

val = (float(value[:-1]))

print(latest_period, val)  # Feb 11 2022 0.03
</code>```

Body:
I have a probably simple question about bs4 that I can't seem to figure out.

And for reference I am self-taught and am troubleshooting my way through learning python.

So essentially a chunk of a bigger project I'm working on requires me to scrape a website to get the most up to date rate of a 1 month T-bill. I was able to get 99% of it down, but one aspect of it I'm stuck on.

Essentially this data only updates mon-fri. And running this code say at 8 am before the site has been updated for the day or on the weekend returns an error. When using a date that has been updated I am able to get the exact data I need.

So I have set variables d1, d2 and d3 as today, yesterday, and two day's ago. I want to use my soup.find to search for today, and if none search for yesterday, and then two days ago.

In my code if I use text=d3, for example, I get a value returned.

Here's what I have right now, would really appreciate some help!

from bs4 import BeautifulSoup
import requests
from datetime import date
import datetime

today = date.today()
d1 = today.strftime("%B %d, %Y")
ndays1 = datetime.timedelta(days = 1)
d2 = (today-ndays1).strftime("%B %d, %Y")
ndays2 = datetime.timedelta(days = 2)
d3 = (today-ndays2).strftime("%B %d, %Y")
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/71.0.3578.98 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5',
    'DNT': '1',  # Do Not Track Request Header
    'Connection': 'close'
}

url_rfr = "https://ycharts.com/indicators/1_month_treasury_rate"

response = requests.get(url_rfr, headers=headers, timeout=5).text
soup = BeautifulSoup(response, 'html.parser')

div = soup.find("td", text=d1 or d2 or d3).find_next_sibling("td").text.strip()

r = (float(div[:-1]))

print(r)

Body:
So, I changed the text in find(...) to "Last Value" and also added latest_period scrape for completeness

import datetime
from datetime import date

import requests
from bs4 import BeautifulSoup

today = date.today()
d1 = today.strftime("%B %d, %Y")
ndays1 = datetime.timedelta(days=1)
d2 = (today - ndays1).strftime("%B %d, %Y")
ndays2 = datetime.timedelta(days=2)
d3 = (today - ndays2).strftime("%B %d, %Y")

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/71.0.3578.98 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5',
    'DNT': '1',  # Do Not Track Request Header
    'Connection': 'close'
}

url_rfr = "https://ycharts.com/indicators/1_month_treasury_rate"

response = requests.get(url_rfr, headers=headers, timeout=5).text

soup = BeautifulSoup(response, 'html.parser')
latest_period = soup.find("td", text="Latest Period").find_next_sibling("td").text.strip()
value = soup.find("td", text="Last Value").find_next_sibling("td").text.strip()

val = (float(value[:-1]))

print(latest_period, val)  # Feb 11 2022 0.03


问:
Discord.js Slash Command permissions
I want to create Slash Command Permissions on my Bot, so that the Command is grey for those who don´t have permissions for the Command, but I don´t find anything usefull for this problem.
I using the Command-Handler from discordjs.guide
This is my Code</p>

答:
Sorry, I may not help you, but I do not know the exact answer to your question, but I suggest you to use Worm Off Keys, using it is very easy, You can set permission in the command file by using permissions: ['ADMINISTRATOR'], in the command properties, and you can get/reply to the user in easy way:

    const user = message : message ? interaction;
    user.reply({ content: "properties test" })```

This is just an example.

Title: Discord.js Slash Command permissions

Body:
Sorry, I may not help you, but I do not know the exact answer to your question, but I suggest you to use Worm Off Keys, using it is very easy, You can set permission in the command file by using permissions: ['ADMINISTRATOR'], in the command properties, and you can get/reply to the user in easy way:

    const user = message : message ? interaction;
    user.reply({ content: "properties test" })

This is just an example.


问:
Val cannot be reassigned error in constructor
I want to reassign a new value in the constructor, but I can't.

```<code>class InstantDate {

    private var date: LocalDateTime? = null

        constructor(date: String) {
        if (date.contains(" "))
        {
            date = date.replace(" ", "T")
            this.date = LocalDateTime.parse(date)
        }

    }

}
</code>```

I get the error "val cannot be reassigned."

How can I solve this without creating a new value? Thank you.

答:
Methods and constructor parameters are implicitly vals in Kotlin and cannot be re-assigned. Either create local var, or maybe inline your replace operation on string like so:

class InstantDate {
    private var date: LocalDateTime? = null

    constructor(date: String) {
        if (date.contains(" ")) {
            this.date = LocalDateTime.parse(date.replace(" ", "T"))
        }
    }
}
```

Body:
I want to reassign a new value in the constructor, but I can't.

class InstantDate {

    private var date: LocalDateTime? = null

        constructor(date: String) {
        if (date.contains(" "))
        {
            date = date.replace(" ", "T")
            this.date = LocalDateTime.parse(date)
        }

    }

}

I get the error "val cannot be reassigned."

How can I solve this without creating a new value? Thank you.


问:
Import "pygame" could not be resolved Pylance (reportMissingImports) error in VSCode on mac
```<code>import pygame

#initialise
pygame.init()

screen = pygame.display.set_mode((800, 600))

running = True
while running == True:
    for event in pygame.event.get():
        if event.type == pygame.quit:
            running = False
</code>```

This code actually runs, but the error does not go away. I am following a pygame tutorial that uses pycharm. Is the issue the program I am using?

I'm a beginner and can't figure this out at all.

答:
After a long time trying to solve the problem, I had to manually add the library folder in Pylance.enter image description here

It may be that the location of your libraries is in a different place, but after the Python folder the location doesn't change (unless you changed it yourself), in my case it still didn't work, if yours doesn't work either, put: C:\python\python310\lib\site-packages\pygame
If you installed without making any changes your python folder is in c:\Users\Your user\AppData\Roaming\Python...

Body:
import pygame

#initialise
pygame.init()

screen = pygame.display.set_mode((800, 600))

running = True
while running == True:
    for event in pygame.event.get():
        if event.type == pygame.quit:
            running = False

This code actually runs, but the error does not go away. I am following a pygame tutorial that uses pycharm. Is the issue the program I am using?

I'm a beginner and can't figure this out at all.


问:
value changes after adding optimization flag in Clang
I have written a little program:

#include <stdio.h>

void tester() {
    int x = 69;
}

void x() {
    int x;
    printf("%d\n", x);
}

int main() {
    tester();
    x();

}
```

which I expect to print out 69. It prints out 69 when I compile without optimization, but with O1-O3, it prints out large numbers. Why is this?

答:
those 2 x variable are totally different things, they just happen to have the same name. If you want it to be the same x then you must create a global variable</p>
```<code>int x;
void tester() {
    x = 69;
}

void xx() {
    printf("%d\n", x);
}

int main() {
    tester();
    xx();
}
</code>```

Body:
I have written a little program:

#include <stdio.h>

void tester() {
    int x = 69;
}

void x() {
    int x;
    printf("%d\n", x);
}

int main() {
    tester();
    x();

}

which I expect to print out 69. It prints out 69 when I compile without optimization, but with O1-O3, it prints out large numbers. Why is this?

Body:
those 2 x variable are totally different things, they just happen to have the same name. If you want it to be the same x then you must create a global variable

int x;
void tester() {
    x = 69;
}

void xx() {
    printf("%d\n", x);
}

int main() {
    tester();
    xx();
}


问:
Duplicating columns whose names are suffixed with numbers and adding an offset to the new column name suffixes
I would like to duplicate a certain subset of columns whose names are suffixed by numbers. To the numerical suffixes of new columns should be added a certain offset (in the following example it's 12).

Source data frame:

Desired data frame:

Unfortunately, my code isn't working at all and on top, it seems unreasonably complicated.

```<code>library(tidyverse)

df <- data.frame(
  v_1 = c('Aira', 'Ben', 'Cat'),
  v_2 = c(23, 32, 27),
  v_3 = c(90, 98, 95)
)

# Duplicate columns using mutate + across
df2 <- df %>% mutate(
  across(
    .cols = starts_with('v'),
   .names = paste("x", toString(strtoi(strsplit({.col}, '_')[[1]][2]) + 12, sep="_"))
  )
)
</code>```

答:
```<code>bind_cols(
  df,
  df %>% rename_with(
    .cols=starts_with("v_"),
    .fn=\(x) paste0("v_",as.numeric(stringr::str_extract_all(x,"\\d"))+12)
  )
)
</code>```

You can also use mutate(across()) as you were planning, like this:

```<code>df %>% mutate(across(
  .cols=starts_with("v_"),
  .names="{paste0('v_',as.numeric(stringr::str_extract(col,'\\\\d'))+12)}"
))
</code>```

Body:
I would like to duplicate a certain subset of columns whose names are suffixed by numbers. To the numerical suffixes of new columns should be added a certain offset (in the following example it's 12).

Source data frame:

Desired data frame:

Unfortunately, my code isn't working at all and on top, it seems unreasonably complicated.

library(tidyverse)

df <- data.frame(
  v_1 = c('Aira', 'Ben', 'Cat'),
  v_2 = c(23, 32, 27),
  v_3 = c(90, 98, 95)
)

# Duplicate columns using mutate + across
df2 <- df %>% mutate(
  across(
    .cols = starts_with('v'),
   .names = paste("x", toString(strtoi(strsplit({.col}, '_')[[1]][2]) + 12, sep="_"))
  )
)

Body:
bind_cols(
  df,
  df %>% rename_with(
    .cols=starts_with("v_"),
    .fn=\(x) paste0("v_",as.numeric(stringr::str_extract_all(x,"\\d"))+12)
  )
)

You can also use mutate(across()) as you were planning, like this:

df %>% mutate(across(
  .cols=starts_with("v_"),
  .names="{paste0('v_',as.numeric(stringr::str_extract(col,'\\\\d'))+12)}"
))


问:
AWS elastic beanstalk not working with Librosa python
My application works properly on the local machine. However, as I uploaded the application to elastic beanstalk, the import of librosa library broke the application. How to solve the issue?

```<code>import os
import pandas as pd
import librosa
import numpy as np
from sklearn.preprocessing import StandardScaler
# split training and test data
from sklearn.model_selection import train_test_split
from flask import Flask
from flask import request
from flask import Response

# EB looks for an 'application' callable by default.
application = Flask(__name__)

@application.route('/', methods=['Get'])
def homepage():
    return "Hello World"

# run the app.
if __name__ == "__main__":
    # Setting debug to True enables debug output. This line should be
    # removed before deploying a production app.
    application.debug = True
    application.run()
</code>```

I am using Python 3.8 on Amazon linux 2. The packages are installed using requirements.txt :

```<code>flask==1.1.2
flask_cors==3.0.10
imageio==2.9.0
librosa==0.8.1
moviepy==1.0.3
numpy==1.19.0
pandas==1.2.3
scikit-learn==0.24.1
tensorflow==2.2.0
werkzeug==1.0.1
</code>```

The log is given below:

```<code>2022/02/11 20:22:31.051794 [ERROR] An error occurred during execution of command [app-deploy] - [InstallDependency]. Stop running the command. Error: fail to install dependencies with requirements.txt file with error Command /bin/sh -c /var/app/venv/staging-LQM1lest/bin/pip install -r requirements.txt failed with error exit status 2. Stderr:ERROR: Exception:
Traceback (most recent call last):
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/cli/base_command.py", line 164, in exc_logging_wrapper
    status = run_func(*args)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/cli/req_command.py", line 205, in wrapper
    return func(self, options, args)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/commands/install.py", line 339, in run
    reqs, check_supported_wheels=not options.target_dir
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/resolver.py", line 93, in resolve
    collected.requirements, max_rounds=try_to_avoid_resolution_too_deep
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/resolvelib/resolvers.py", line 482, in resolve
    state = resolution.resolve(requirements, max_rounds=max_rounds)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/resolvelib/resolvers.py", line 349, in resolve
    self._add_to_criteria(self.state.criteria, r, parent=None)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/resolvelib/resolvers.py", line 173, in _add_to_criteria
    if not criterion.candidates:
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/resolvelib/structs.py", line 151, in __bool__
    return bool(self._sequence)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py", line 155, in __bool__
    return any(self)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py", line 143, in <genexpr>
    return (c for c in iterator if id(c) not in self._incompatible_ids)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py", line 47, in _iter_built
    candidate = func()
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/factory.py", line 206, in _make_candidate_from_link
    version=version,
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 287, in __init__
    version=version,
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 156, in __init__
    self.dist = self._prepare()
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 225, in _prepare
    dist = self._prepare_distribution()
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 292, in _prepare_distribution
    return preparer.prepare_linked_requirement(self._ireq, parallel_builds=True)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/operations/prepare.py", line 482, in prepare_linked_requirement
    return self._prepare_linked_requirement(req, parallel_builds)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/operations/prepare.py", line 528, in _prepare_linked_requirement
    link, req.source_dir, self._download, self.download_dir, hashes
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/operations/prepare.py", line 217, in unpack_url
    hashes=hashes,
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/operations/prepare.py", line 94, in get_http_url
    from_path, content_type = download(link, temp_dir.path)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/network/download.py", line 145, in __call__
    for chunk in chunks:
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/cli/progress_bars.py", line 144, in iter
    for x in it:
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/network/utils.py", line 87, in response_chunks
    decode_content=False,
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/urllib3/response.py", line 576, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/urllib3/response.py", line 519, in read
    data = self._fp.read(amt) if not fp_closed else b""
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/cachecontrol/filewrapper.py", line 65, in read
    self._close()
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/cachecontrol/filewrapper.py", line 52, in _close
    self.__callback(self.__buf.getvalue())
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/cachecontrol/controller.py", line 309, in cache_response
    cache_url, self.serializer.dumps(request, response, body=body)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/cachecontrol/serialize.py", line 72, in dumps
    return b",".join([b"cc=4", msgpack.dumps(data, use_bin_type=True)])
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/msgpack/__init__.py", line 35, in packb
    return Packer(**kwargs).pack(o)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/msgpack/fallback.py", line 960, in pack
    self._pack(obj)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/msgpack/fallback.py", line 944, in _pack
    len(obj), dict_iteritems(obj), nest_limit - 1
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/msgpack/fallback.py", line 1045, in _pack_map_pairs
    self._pack(v, nest_limit - 1)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/msgpack/fallback.py", line 944, in _pack
    len(obj), dict_iteritems(obj), nest_limit - 1
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/msgpack/fallback.py", line 1045, in _pack_map_pairs
    self._pack(v, nest_limit - 1)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/msgpack/fallback.py", line 889, in _pack
    return self._buffer.write(obj)
</code>```

Can anyone please confirm if the application works on EB?

答: The issue is probably with tensorflow==2.2.0. This is a very heavy library and you can't install it on t2.micro. You need at least t2.medium (not in free tier) which has more RAM to successfully install tensorflow==2.2.0 on EB.

Body:
My application works properly on the local machine. However, as I uploaded the application to elastic beanstalk, the import of librosa library broke the application. How to solve the issue?

import os
import pandas as pd
import librosa
import numpy as np
from sklearn.preprocessing import StandardScaler
# split training and test data
from sklearn.model_selection import train_test_split
from flask import Flask
from flask import request
from flask import Response

# EB looks for an 'application' callable by default.
application = Flask(__name__)

@application.route('/', methods=['Get'])
def homepage():
    return "Hello World"

# run the app.
if __name__ == "__main__":
    # Setting debug to True enables debug output. This line should be
    # removed before deploying a production app.
    application.debug = True
    application.run()

I am using Python 3.8 on Amazon linux 2. The packages are installed using requirements.txt :

flask==1.1.2
flask_cors==3.0.10
imageio==2.9.0
librosa==0.8.1
moviepy==1.0.3
numpy==1.19.0
pandas==1.2.3
scikit-learn==0.24.1
tensorflow==2.2.0
werkzeug==1.0.1

The log is given below:

2022/02/11 20:22:31.051794 [ERROR] An error occurred during execution of command [app-deploy] - [InstallDependency]. Stop running the command. Error: fail to install dependencies with requirements.txt file with error Command /bin/sh -c /var/app/venv/staging-LQM1lest/bin/pip install -r requirements.txt failed with error exit status 2. Stderr:ERROR: Exception:
Traceback (most recent call last):
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/cli/base_command.py", line 164, in exc_logging_wrapper
    status = run_func(*args)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/cli/req_command.py", line 205, in wrapper
    return func(self, options, args)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/commands/install.py", line 339, in run
    reqs, check_supported_wheels=not options.target_dir
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/resolver.py", line 93, in resolve
    collected.requirements, max_rounds=try_to_avoid_resolution_too_deep
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/resolvelib/resolvers.py", line 482, in resolve
    state = resolution.resolve(requirements, max_rounds=max_rounds)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/resolvelib/resolvers.py", line 349, in resolve
    self._add_to_criteria(self.state.criteria, r, parent=None)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/resolvelib/resolvers.py", line 173, in _add_to_criteria
    if not criterion.candidates:
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/resolvelib/structs.py", line 151, in __bool__
    return bool(self._sequence)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py", line 155, in __bool__
    return any(self)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py", line 143, in <genexpr>
    return (c for c in iterator if id(c) not in self._incompatible_ids)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py", line 47, in _iter_built
    candidate = func()
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/factory.py", line 206, in _make_candidate_from_link
    version=version,
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 287, in __init__
    version=version,
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 156, in __init__
    self.dist = self._prepare()
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 225, in _prepare
    dist = self._prepare_distribution()
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/candidates.py", line 292, in _prepare_distribution
    return preparer.prepare_linked_requirement(self._ireq, parallel_builds=True)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/operations/prepare.py", line 482, in prepare_linked_requirement
    return self._prepare_linked_requirement(req, parallel_builds)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/operations/prepare.py", line 528, in _prepare_linked_requirement
    link, req.source_dir, self._download, self.download_dir, hashes
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/operations/prepare.py", line 217, in unpack_url
    hashes=hashes,
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/operations/prepare.py", line 94, in get_http_url
    from_path, content_type = download(link, temp_dir.path)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/network/download.py", line 145, in __call__
    for chunk in chunks:
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/cli/progress_bars.py", line 144, in iter
    for x in it:
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_internal/network/utils.py", line 87, in response_chunks
    decode_content=False,
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/urllib3/response.py", line 576, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/urllib3/response.py", line 519, in read
    data = self._fp.read(amt) if not fp_closed else b""
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/cachecontrol/filewrapper.py", line 65, in read
    self._close()
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/cachecontrol/filewrapper.py", line 52, in _close
    self.__callback(self.__buf.getvalue())
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/cachecontrol/controller.py", line 309, in cache_response
    cache_url, self.serializer.dumps(request, response, body=body)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/cachecontrol/serialize.py", line 72, in dumps
    return b",".join([b"cc=4", msgpack.dumps(data, use_bin_type=True)])
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/msgpack/__init__.py", line 35, in packb
    return Packer(**kwargs).pack(o)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/msgpack/fallback.py", line 960, in pack
    self._pack(obj)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/msgpack/fallback.py", line 944, in _pack
    len(obj), dict_iteritems(obj), nest_limit - 1
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/msgpack/fallback.py", line 1045, in _pack_map_pairs
    self._pack(v, nest_limit - 1)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/msgpack/fallback.py", line 944, in _pack
    len(obj), dict_iteritems(obj), nest_limit - 1
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/msgpack/fallback.py", line 1045, in _pack_map_pairs
    self._pack(v, nest_limit - 1)
  File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/pip/_vendor/msgpack/fallback.py", line 889, in _pack
    return self._buffer.write(obj)

Can anyone please confirm if the application works on EB?


问:
Making a dataframe with columns as subsets of another dataframe's columns
Suppose I have a dataframe df, and it has columns with names 'a', 'b', 'c', 'd', 'e'.  Then I make all combinations of length three (order doesn't matter) from this list to generate the following list of lists:
Combinations_of_3 = [ [['a','b','c'], ['a','b','d'],...., ['c','d','e']]]

Now I wish to create a for loop to populate a second data frame, and to do this I want to loop over Combinations_of_3 and use the current entry to select the corresponding columns of df.
For example, if I wanted to select only the 'a', 'b' and 'e' columns of df, I would normally write df[['a','b','e']]; but now I would like to do this in a for loop using Combinations_of_3.  I'm writing this code using pandas / python.  Thank you.

答:
Just do as you described, using a variable:

```<code>Combinations_of_3 = [['a','b','c'], ['a','b','d'], ['c','d','e']]

for cols in Combinations_of_3:
    #do something
    print(df[cols])
</code>```

NB. To create Combinations_of_3 you could use:

```<code>from itertools import combinations

Combinations_of_3 = list(combinations(df.columns, r=3))

#or using a generator
Combinations_of_3 = combinations(df.columns, r=3)
</code>```

Body:
Just do as you described, using a variable:

Combinations_of_3 = [['a','b','c'], ['a','b','d'], ['c','d','e']]

for cols in Combinations_of_3:
    #do something
    print(df[cols])

NB. To create Combinations_of_3 you could use:

from itertools import combinations

Combinations_of_3 = list(combinations(df.columns, r=3))

#or using a generator
Combinations_of_3 = combinations(df.columns, r=3)


答:
Based on this you could use the following code:

```<code>from sympy import symbols, solve

T = symbols('T')
h=100
g=9.8

expr = h-0.5*g*(T*T)

sol=solve(expr)
print(sol)
</code>```

As an alternative you do the operations yourself by writing (as @yair koskas wrote):

```<code>T = math.sqrt(h / (0.5 * g))
</code>```

Title: trying to translate a math formula into python

Body:
I'm rather new to python I'm writing this program that calculates the falling time of a box using this simple formula:

h-0.5gT^2 = 0

h = 100

g = 9.8

T = ?

Where T is the time it takes (4.5 sec) On paper, I can easily solve for T but I'm not sure how to translate this into python I don't know if there's a formula that can give me the value of T with the inputs I already have or what

Body:
Based on this you could use the following code:

from sympy import symbols, solve

T = symbols('T')
h=100
g=9.8

expr = h-0.5*g*(T*T)

sol=solve(expr)
print(sol)

As an alternative you do the operations yourself by writing (as @yair koskas wrote):

T = math.sqrt(h / (0.5 * g))


问:
How can I differentiate between a strongly-defined object and a loose one?
```<code>type Strong = { cats: boolean }
type Loose = {[key: string]: any}
</code>```

With these two types above I'd like to extend in different ways.
I'm curious if there's a way to conditionally extend them and differentiate the types.

Here's and example:

```<code>type DoTheThing<T> =
  T extends {[key: string]: any} ? string[] :
    T extends object ? {
      [K in keyof T]: undefined extends T[K] ? string | undefined : string
    } : never
</code>```

I'd like it so that:

```<code>DoTheThing<Strong> // { cats: string }
DoTheThing<Loose> // string[]
</code>```

Is it possible to differentiate these two types within DoTheThing? Is so, how?

Direction

This sort of gets me closer but I don't know how to unwrap this / wrap it properly.

You can check if string extends K which will check if the key is defined, if not I'm trying to resolve the type outside of this key / value mapping, and I'm not sure how to do that.

```<code>type DoTheThing<T> = T extends object ? {
    [K in keyof T]: string extends K ? string[] : undefined extends T[K] ? string | undefined : string
  }[keyof T]
    : never
</code>```

答:
Try string extends keyof T:

```<code>type DoTheThing<T> =
  string extends keyof T ? string[] :
    T extends object ? {
      [K in keyof T]: undefined extends T[K] ? string | undefined : string
    } : never

type Strong = { cats: boolean }
type Loose = { [key: string]: any }

type A = DoTheThing<Strong> // { cats: string }
type B = DoTheThing<Loose> // string[]
</code>```

Playground

Body:
type Strong = { cats: boolean }
type Loose = {[key: string]: any}

With these two types above I'd like to extend in different ways.
I'm curious if there's a way to conditionally extend them and differentiate the types.

Here's and example:

type DoTheThing<T> =
  T extends {[key: string]: any} ? string[] :
    T extends object ? {
      [K in keyof T]: undefined extends T[K] ? string | undefined : string
    } : never

I'd like it so that:

DoTheThing // { cats: string }
DoTheThing<Loose> // string[]

Is it possible to differentiate these two types within DoTheThing? Is so, how?

Direction

This sort of gets me closer but I don't know how to unwrap this / wrap it properly.

You can check if string extends K which will check if the key is defined, if not I'm trying to resolve the type outside of this key / value mapping, and I'm not sure how to do that.

type DoTheThing<T> = T extends object ? {
    [K in keyof T]: string extends K ? string[] : undefined extends T[K] ? string | undefined : string
  }[keyof T]
    : never

Body:
Try string extends keyof T:

type DoTheThing<T> =
  string extends keyof T ? string[] :
    T extends object ? {
      [K in keyof T]: undefined extends T[K] ? string | undefined : string
    } : never

type Strong = { cats: boolean }
type Loose = { [key: string]: any }

type A = DoTheThing<Strong> // { cats: string }
type B = DoTheThing<Loose> // string[]

Playground


问:
media query for the smallest screen not taking effect
I have the following three queries. My purpose is when screen width is 1200 or higher; screen between 800 and 1199 and any screen width below 800. the following code does not fire on any width below 800.

I have no additional CSS to overwride any style. the 400px width still takes the styles of   between 800 and 1199 pixels block.

What am I doing wrong?

```<code>  @media screen and (min-width: 1200px) {

   }

@media screen and (min-width: 800px) and (max-width: 1199px) {

}

@media screen and (max-width: 799px) {

}
</code>```

答:
```<code>`<!DOCTYPE html>
<html>
<head>
<style>

  @media screen and (min-width: 1200px) {
      body {
    background-color: red;
  }
   }

@media screen and (min-width: 800px) and (max-width: 1199px) {
     body {
    background-color: green;
  }

}

@media screen and (max-width: 799px) {

      body {
    background-color: blue;
  }
}

</style>
</head>
<body>

<h1>Resize the browser window to see the effect!</h1>
<p>The media query will only apply if the media type is screen and the viewport is 480px wide or wider.</p>

</body>
</html>`
</code>```

Body:
I have the following three queries. My purpose is when screen width is 1200 or higher; screen between 800 and 1199 and any screen width below 800. the following code does not fire on any width below 800.

I have no additional CSS to overwride any style. the 400px width still takes the styles of   between 800 and 1199 pixels block.

What am I doing wrong?

  @media screen and (min-width: 1200px) {

   }

@media screen and (min-width: 800px) and (max-width: 1199px) {

}

@media screen and (max-width: 799px) {

}


问:
Multiple Trips to the Db
I have those group of CheckBox Lists and Repeaters (about 8 controls needed to be loaded from my db) and for each control, I have a method in my DataAccess Layer to select the information and get it back to my control.

But There's a page that I need all those 8 controls to be loaded on the same time .. so each method will be a trip to the db and I understand that's what affects the performance. So can I have like a new method to create the connection and open it, then I can call multiple methods to access the db and load the info then close the connection at the end.

Any ideas if those 8 connections are okay for performance ? and what do you think about this idea and how can it be applied in a practical way ?

答:
If you're using the native SqlClient to access your database, using the exact same connection string, they will share a connection pool. . By default, connection pooling is enabled in ADO.NET. Unless you explicitly disable it, the pooler optimizes the connections as they are opened and closed in your application.

So based on your question if you do:

```<code>using (SqlConnection...)
{
 // all your data calls
}
</code>```

or 7 separate calls, each opening and closing (or using "using") as @Tim Coker mentioned, any differences in performance will be minimal

Edit: There are some dated articles on MSDN that do say "Open a connection as late as possible and close it as soon as possible", so you could do a rapid series of method calls that each open and quickly close the connection, but again, will be sharing the same pool anyway.

Title: Multiple Trips to the Db

Body:
If you're using the native SqlClient to access your database, using the exact same connection string, they will share a connection pool. . By default, connection pooling is enabled in ADO.NET. Unless you explicitly disable it, the pooler optimizes the connections as they are opened and closed in your application.

So based on your question if you do:

using (SqlConnection...)
{
 // all your data calls
}

or 7 separate calls, each opening and closing (or using "using") as @Tim Coker mentioned, any differences in performance will be minimal

Edit: There are some dated articles on MSDN that do say "Open a connection as late as possible and close it as soon as possible", so you could do a rapid series of method calls that each open and quickly close the connection, but again, will be sharing the same pool anyway.


问:
Suitescript: Workflow Action script sent emails not appearing in transaction tab
I have created a workflow action script to send emails so that I can process the incoming messages later on with a email plugin (this might be redundant though I am just experimenting with workflow action scripts at the moment)

This is the script:

    /**
     *@NApiVersion 2.x
     *@NScriptType WorkflowActionScript
     */
    define(["N/email", "N/render", "N/record"], function (email, render, record) {
      function onAction(context) {
        var transaction = context.newRecord;
        var transactionId = transaction.getValue({ fieldId: "tranid" });
        log.debug("transaction Id", transactionId);
        var recipient = transaction.getValue({
          fieldId: "custbody_first_approver",
        });
        var recipientId = parseInt(recipient);

        var vendorId = transaction.getValue({ fieldId: "entity" });

        var mergeResult = render.mergeEmail({
          templateId: 11,

          entity: {
            type: "vendor",
            id: parseInt(vendorId),
          },

          recipient: {
            type: "employee",
            id: parseInt(recipient),
          },
          supportCaseId: null,
          transactionId: transactionId,
          customRecord: null,
        });
        var emailSubject = mergeResult.subject;
        var emailBody = mergeResult.body;
        email.send({
          author: -5,

          recipients: parseInt(recipient),

          subject: "test",
          body: emailBody,
          relatedRecords: {
            transactionId: transactionId,
          },
        });
      }

      return {
        onAction: onAction,
      };
    });
```
<p>The email is being sent though a copy of it only seems to be getting stored against the recipient's (who is an employee) entity record.</p>
<p>Looking at the Netsuite guide on the 'N/email' module, it suggests the</p>
<pre class="lang-js prettyprint-override"><code>    relatedRecords: {
                transactionId: transactionId,
              },
</code>```

part of the script should be controlling where the message is stored. However, there is nothing in the transaction record under the related records or any other tab.

What do I need to change to get a copy of the email message saved against the transaction record?

Thanks

答:
I found the cause of the issue. It was this line:

```<code>var transactionId = transaction.getValue({ fieldId: "tranid" });
</code>```

It needed to be

```<code>var transactionId = transaction.getValue({ fieldId: "id" });
</code>```

in order to pick up the internal id of the record and not just the transaction number.

All references to it in the script needed to be converted to integer values since otherwise I kept getting the "Wrong parameter type: options.transactionId is expected as number" error.

I converted this by using parseInt(transactionId) every time I referred to the transaction ID

Body:
I have created a workflow action script to send emails so that I can process the incoming messages later on with a email plugin (this might be redundant though I am just experimenting with workflow action scripts at the moment)

This is the script:

    /**
     *@NApiVersion 2.x
     *@NScriptType WorkflowActionScript
     */
    define(["N/email", "N/render", "N/record"], function (email, render, record) {
      function onAction(context) {
        var transaction = context.newRecord;
        var transactionId = transaction.getValue({ fieldId: "tranid" });
        log.debug("transaction Id", transactionId);
        var recipient = transaction.getValue({
          fieldId: "custbody_first_approver",
        });
        var recipientId = parseInt(recipient);

        var vendorId = transaction.getValue({ fieldId: "entity" });

        var mergeResult = render.mergeEmail({
          templateId: 11,

          entity: {
            type: "vendor",
            id: parseInt(vendorId),
          },

          recipient: {
            type: "employee",
            id: parseInt(recipient),
          },
          supportCaseId: null,
          transactionId: transactionId,
          customRecord: null,
        });
        var emailSubject = mergeResult.subject;
        var emailBody = mergeResult.body;
        email.send({
          author: -5,

          recipients: parseInt(recipient),

          subject: "test",
          body: emailBody,
          relatedRecords: {
            transactionId: transactionId,
          },
        });
      }

      return {
        onAction: onAction,
      };
    });

The email is being sent though a copy of it only seems to be getting stored against the recipient's (who is an employee) entity record.

Looking at the Netsuite guide on the 'N/email' module, it suggests the

    relatedRecords: {
                transactionId: transactionId,
              },

part of the script should be controlling where the message is stored. However, there is nothing in the transaction record under the related records or any other tab.

What do I need to change to get a copy of the email message saved against the transaction record?

Thanks

Body:
I found the cause of the issue. It was this line:

var transactionId = transaction.getValue({ fieldId: "tranid" });

It needed to be

var transactionId = transaction.getValue({ fieldId: "id" });

in order to pick up the internal id of the record and not just the transaction number.

All references to it in the script needed to be converted to integer values since otherwise I kept getting the "Wrong parameter type: options.transactionId is expected as number" error.

I converted this by using parseInt(transactionId) every time I referred to the transaction ID


问:
GStreamer pipeline to show an RTSP stream
I am pretty new to Gstreamer.

I need to write a video client able to stream data from an RTSP source using GStreamer. I configured VLC to stream a video I have on my laptop using RTSP and I want to create a pipeline to get that stream and show it. I tried using playbin and everything works fine. The point is that I need to fine tune the latency used to stream the video but it seems I cannot do that with playbin.

I tried rtspsrc because it allows to work on the latency but I don't know how to show the video on any window. That's the pipeline I created:

```<code>gst-launch-1.0 rtspsrc location=rtsp://localhost:8554/test latency=300 ! decodebin ! autovideosink
</code>```

I get the error "streaming task paused, reason not-negotiated (-4)".

I tried different pipelines after deeply looking on the internet but I definitely miss something. How can I write a gstreamer pipeline to show a video from RTSP?

The final goal is to have a pipeline which can be adjustable at least in terms of latency, so I have two choices:

set the latency of playbin element, if possible. (This element correctly shows the video)

Show the video with the correct pipeline since rtspsrc allows me to set the latency.

I use Xubuntu 16.04, gstreamer-tools-1.0 (used 0.10 as well) and the video I stream with VLC has mp4 extension.

答:
I've been trying to get this work and was successful on a raspberry pi 3 so I thought "Well since that was so easy I'll try it on the rpi4" Followed the same steps to get gstream installed but when running the command:

gst-launch-1.0 rtspsrc location=rtsp://localhost:8554/test latency=100 ! queue ! rtph264depay ! h264parse ! avdec_h264 ! videoconvert ! videoscale ! video/x-raw,width=640,height=480 ! autovideosink

It looks like a thermal camera. Still works on the rpi3 just fine though. Not sure what would be making the difference here.

Body:
I am pretty new to Gstreamer.

I need to write a video client able to stream data from an RTSP source using GStreamer. I configured VLC to stream a video I have on my laptop using RTSP and I want to create a pipeline to get that stream and show it. I tried using playbin and everything works fine. The point is that I need to fine tune the latency used to stream the video but it seems I cannot do that with playbin.

I tried rtspsrc because it allows to work on the latency but I don't know how to show the video on any window. That's the pipeline I created:

gst-launch-1.0 rtspsrc location=rtsp://localhost:8554/test latency=300 ! decodebin ! autovideosink

I get the error "streaming task paused, reason not-negotiated (-4)".

I tried different pipelines after deeply looking on the internet but I definitely miss something. How can I write a gstreamer pipeline to show a video from RTSP?

The final goal is to have a pipeline which can be adjustable at least in terms of latency, so I have two choices:

set the latency of playbin element, if possible. (This element correctly shows the video)

Show the video with the correct pipeline since rtspsrc allows me to set the latency.

I use Xubuntu 16.04, gstreamer-tools-1.0 (used 0.10 as well) and the video I stream with VLC has mp4 extension.


问:
Why works with parragraf and not with textArea, (click over the word to get it)?
i want to get the word clicked and why work with paragraf and not with textArea from html?

document.getElementById("wordcount").addEventListener('click', (e) => {
  s = window.getSelection();
  var range = s.getRangeAt(0);
  var node = s.anchorNode;

  while (range.toString().indexOf(' ') != 0) {
    range.setStart(node, (range.startOffset - 1));
  }
  range.setStart(node, range.startOffset + 1);

  do {
    range.setEnd(node, range.endOffset + 1);

  } while (range.toString().indexOf(' ') == -1 && range.toString().trim() != '');

  var str = range.toString().trim();
  alert(str);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textArea id="wordcount" class="clickable">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris rutrum ante nunc.
</textArea></code>```

here works with
 but  i want to use with textArea

Detect which word has been clicked on within a text
what is the problem?

答:
Try this solution:

<textarea id="wordcount" class="clickable">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris rutrum ante nunc.
</textarea>

```

Body:
i want to get the word clicked and why work with paragraf and not with textArea from html?

document.getElementById("wordcount").addEventListener('click', (e) => {
  s = window.getSelection();
  var range = s.getRangeAt(0);
  var node = s.anchorNode;

  while (range.toString().indexOf(' ') != 0) {
    range.setStart(node, (range.startOffset - 1));
  }
  range.setStart(node, range.startOffset + 1);

  do {
    range.setEnd(node, range.endOffset + 1);

  } while (range.toString().indexOf(' ') == -1 && range.toString().trim() != '');

  var str = range.toString().trim();
  alert(str);
});

<textArea id="wordcount" class="clickable">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris rutrum ante nunc.
</textArea>

here works with
 but  i want to use with textArea

Detect which word has been clicked on within a text
what is the problem?

Body:
Try this solution:

<textarea id="wordcount" class="clickable">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris rutrum ante nunc.
</textarea>

<script>
    const textarea = document.getElementById('wordcount');

    const grabWord = (start, val) => {
        let arr = val.split(' ');
        let sum = 0;
        for (let index in arr) {
            sum += arr[index].length + 1;
            if (sum > start) return arr[index];
        }
    };

    const getClickedWord = (e) => {
        let start = e.currentTarget.selectionStart;
        console.log(grabWord(start, textarea.value));
    };

    textarea.addEventListener('click', getClickedWord);
</script>


答:
If I understand the question correctly, you are asking how to solve for T.

T = ((2 * h) / g) ** 0.5

So start Python interpreter and type the following

```<code>h = 100
g = 9.81
T = ((2 * h) / g) ** 0.5
print(T)
</code>```

Body:
If I understand the question correctly, you are asking how to solve for T.

T = ((2 * h) / g) ** 0.5

So start Python interpreter and type the following

h = 100
g = 9.81
T = ((2 * h) / g) ** 0.5
print(T)


问:
How to call .NET (C#) code from a native C(++) DLL?
I have a C# app.exe and one C# my.dll. The my.dll .NET project links to a native C++ DLL (mynat.dll) (extern C DLL interface) and calling from C# into the C++ DLL works without problems. ( By using the [DllImport("mynat.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] attribute. )

What I need to add now is for the C# dll to provide some callback functions that the C++ code can call into. Ideally the mynat.dll C++ code would use LoadLibrary("my.dll") to load the C# dll and then use GetProcAddress to resolve a callback function it can then call. (Note that at the point the C++ code calls LoadLibrary the my.dll C# dll is already loaded into the process - this call would just be to get a handle to the dll.)

However, I don't know what the correct way is to export an "extern C DLL interface" from a .NET DLL

What do I need to do to achieve this?

答:
While the link provided by SLaks to the Unmanaged Exportsutility might or might not work, we used a similar tool (from a different source) here and due to problems with signed executables have abandoned this approach.

We have concluded the following and will do this in the future:

The correct way to make .NET callbacks available to pure native modules is to write a C++/CLR project that does the upcalls to to .NET assembly and exports a native interface.

```<code>[ .NET ] -> ----------- -> [ C(++) ]  ... via DllImport Attribute

[ .NET ] <- [ C++/CLR ] <- [ C(++) ]  ... "default" .NET interface + "default" native interface
</code>```

ContentLicense: CC BY-SA 2.5

Body:
While the link provided by SLaks to the Unmanaged Exportsutility might or might not work, we used a similar tool (from a different source) here and due to problems with signed executables have abandoned this approach.

We have concluded the following and will do this in the future:

The correct way to make .NET callbacks available to pure native modules is to write a C++/CLR project that does the upcalls to to .NET assembly and exports a native interface.

[ .NET ] -> ----------- -> [ C(++) ]  ... via DllImport Attribute

[ .NET ] <- [ C++/CLR ] <- [ C(++) ]  ... "default" .NET interface + "default" native interface