问:
Architecture: Multiple websites. One codebase. Custom code
Okay. I am currently building an php application (platform) which will be deployed multiple times, only with different configurations. The application consists of a backend and frontend. Through the backend, we are able to configure which modules are active, what there settings are and how the platform looks like.

We expect that customers will start asking for specific functionality on their platform. This means that there platform will be different then the other ones. But, we maintain one codebase.

What's the best way to solve this? Since we keep on fixing bugs and developing new features, it should be easy to take care of all the platforms. We have a script which we use to deploy our platform updates to all our platforms.

Should we convert all our functionality into plugins so every platform can be updated manually if they want? So if a customer wants something differently then the original plugin, we duplicate the plugin and create their own customer-plugin? But is the code easily to maintain then if we ever decide to update the plugin?

Or should we write exceptions in the code for every customer?

Should we have separate files which override the base files for every platform with custom code?

What's the best way to go?

答:
The big trick will be balancing the diverging needs of customers without ending up with a massively complex system that is impossible to maintain. Here's a few approaches you should consider:

Dependency Inversion: there's lot of material on this subject, basically it's a way of structuring a system so that different parts within it depend on concepts rather than concrete implementations.  This will allow you to swap those implementations for different customers.  It can be used for everything from deep business logic and algorithms to data-providers to UI widgets.  I'm not sure where the best place is to start with DI (and I come from a .Net background not a PHP one) so here's the Wikipedia entry as a start.

Identify the sorts of things users will want to change and isolate those things into things which can easily be swapped out using DI or some other practical approach.  Having done that try very hard not to introduce variations into the framework code-base (the core that basically "hosts" the swappable bits.

Keep the dependency tree as clean as possible.

Start with a PoC / Prototype.  Building frameworks is very hard.  Your first attempt might work ok but your second and third attempts will be better; experience counts for a lot.

Put some effort into making the system easy to test, both during development and after deployment.  With all the moving parts you will want good diagnostics to help you isolate issues and help with integration.

Edit: Finally, if you're not already aware of them, there are existing PHP frameworks that you might be able to use or simply borrow approaches from - the PHP Open Source community is fairly strong.  Check out the Zend Framework.


来源: stackexchange

问:
Github action for `yarn build` fails with missing React component
I have a React app that builds correctly locally with yarn build. I have the following job in my config for Github Actions to deploy the app to S3:

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
    - name: Checkout
      uses: actions/checkout@v1

    - name: Configure AWS Credentials
      uses: aws-actions/configure-aws-credentials@v1
      with:
        aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
        aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
        aws-region: us-east-2

    - name: Install dependencies
      run: yarn install

    - name: Build
      run: yarn build

    - name: Deploy static site to S3 bucket
      run: aws s3 sync build/ s3://my-s3-bucket --delete
```

<p>The Build phase is failing with this error:</p>
```Module not found: Error: Can't resolve './components/Layout' in '/home/runner/work/storefront-app/storefront-app/src'
```

This module does exist under the src/components/ directory, so I'm not sure why it can't be found. I'm exporting it with export default Layout;

答:
So I found that the issue was with filenames and Git.

Locally, all my files were named correctly: Nav.js, Layout.js, etc. On Github, they were downcased: layout.js. Git never picked up the change to the filename, and so the build on GH could not find ./components/Layout. Deleting the files and re-committing them solved the problem.

ContentLicense: CC BY-SA 4.0

Body:
I have a React app that builds correctly locally with yarn build. I have the following job in my config for Github Actions to deploy the app to S3:

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
    - name: Checkout
      uses: actions/checkout@v1

    - name: Configure AWS Credentials
      uses: aws-actions/configure-aws-credentials@v1
      with:
        aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
        aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
        aws-region: us-east-2

    - name: Install dependencies
      run: yarn install

    - name: Build
      run: yarn build

    - name: Deploy static site to S3 bucket
      run: aws s3 sync build/ s3://my-s3-bucket --delete

The Build phase is failing with this error:

Module not found: Error: Can't resolve './components/Layout' in '/home/runner/work/storefront-app/storefront-app/src'

This module does exist under the src/components/ directory, so I'm not sure why it can't be found. I'm exporting it with export default Layout;


问:
Spring integration SFTP - issue with filters and number of messages emits
I started using spring integration SFTP and I have some questions.

Filters not working. I have example configuration:

Sftp.inboundAdapter(ftpFileSessionFactory())
                .preserveTimestamp(true)
                .deleteRemoteFiles(false)
                .remoteDirectory(integrationProperties.getRemoteDirectory())
                .filter(sftpFileListFilter()) // doesn't work
                .patternFilter("*.xlsx") // doesn't work
```
<p>And my ChainFileListFilter:</p>
<pre class="lang-java prettyprint-override"><code>private ChainFileListFilter<ChannelSftp.LsEntry> sftpFileListFilter() {
        ChainFileListFilter<ChannelSftp.LsEntry> chainFileListFilter = new ChainFileListFilter<>();
        chainFileListFilter.addFilter(new SftpPersistentAcceptOnceFileListFilter(metadataStore(), "INT"));
        chainFileListFilter.addFilter(new SftpSimplePatternFileListFilter("*.xlsx"));
        return chainFileListFilter;
    }
</code>```

If I understand correctly, only the XLSX file should be saved in the local directory. If yes it doesn't work with this configuration. Am I doing something wrong or misunderstood this?

How I can configure SFTP that each downloaded file emit message? I see in the doc two params max-messages-per-poll and max-fetch-size, but I don't know how to set it up so that every file emits a message. I would like to sync files once every 24 hours and produce batch job queue. Maybe there is a workaround?

Is there built-in filter which allow me fetch only files with changed content? The best solution would be to check the checksums of the files.

I will be grateful for your help and explanations.

答:
You cannot combine filter() and patternFilter(). Only one of them can be used: the last one overrides whatever you used before. In other words: or filter() or patternFilter() - not both. By default the logic is like this:

```<code>public SftpInboundChannelAdapterSpec patternFilter(String pattern) {
    return filter(composeFilters(new SftpSimplePatternFileListFilter(pattern)));
}

private CompositeFileListFilter<ChannelSftp.LsEntry> composeFilters(FileListFilter<ChannelSftp.LsEntry>
        fileListFilter) {
    CompositeFileListFilter<ChannelSftp.LsEntry> compositeFileListFilter = new CompositeFileListFilter<>();
    compositeFileListFilter.addFilters(fileListFilter,
            new SftpPersistentAcceptOnceFileListFilter(new SimpleMetadataStore(), "sftpMessageSource"));
    return compositeFileListFilter;
}
</code>```

So, technically you don't need your custom one, if you don't use external persistent MetadataStore. But if you do, think about flipping SftpSimplePatternFileListFilter with SftpPersistentAcceptOnceFileListFilter. Since it is better to check for the pattern before storing the file into MetadataStore.

It is the fact that every synched remote file, passed those filters, is stored into local dir and the message for that local file is emitted immediately when the poller does a request.

The maxFetchSize plays the role when we load remote files into a local dir. The maxMessagesPerPoll is used from the poller, but those are already built from the local files. The message is emitted per local file, not as a batch for all of them. That's not what messaging is designed for.

Please, share more info what does not work with files. The SftpPersistentAcceptOnceFileListFilter checks not only file name, but also mtime of the file. So, that it not about any checksum, but more last  modified timestamp of the file.

Body:
I started using spring integration SFTP and I have some questions.

Filters not working. I have example configuration:

Sftp.inboundAdapter(ftpFileSessionFactory())
                .preserveTimestamp(true)
                .deleteRemoteFiles(false)
                .remoteDirectory(integrationProperties.getRemoteDirectory())
                .filter(sftpFileListFilter()) // doesn't work
                .patternFilter("*.xlsx") // doesn't work

And my ChainFileListFilter:

private ChainFileListFilter<ChannelSftp.LsEntry> sftpFileListFilter() {
        ChainFileListFilter<ChannelSftp.LsEntry> chainFileListFilter = new ChainFileListFilter<>();
        chainFileListFilter.addFilter(new SftpPersistentAcceptOnceFileListFilter(metadataStore(), "INT"));
        chainFileListFilter.addFilter(new SftpSimplePatternFileListFilter("*.xlsx"));
        return chainFileListFilter;
    }

If I understand correctly, only the XLSX file should be saved in the local directory. If yes it doesn't work with this configuration. Am I doing something wrong or misunderstood this?

How I can configure SFTP that each downloaded file emit message? I see in the doc two params max-messages-per-poll and max-fetch-size, but I don't know how to set it up so that every file emits a message. I would like to sync files once every 24 hours and produce batch job queue. Maybe there is a workaround?

Is there built-in filter which allow me fetch only files with changed content? The best solution would be to check the checksums of the files.

I will be grateful for your help and explanations.

Body:
You cannot combine filter() and patternFilter(). Only one of them can be used: the last one overrides whatever you used before. In other words: or filter() or patternFilter() - not both. By default the logic is like this:

public SftpInboundChannelAdapterSpec patternFilter(String pattern) {
    return filter(composeFilters(new SftpSimplePatternFileListFilter(pattern)));
}

private CompositeFileListFilter<ChannelSftp.LsEntry> composeFilters(FileListFilter<ChannelSftp.LsEntry>
        fileListFilter) {
    CompositeFileListFilter<ChannelSftp.LsEntry> compositeFileListFilter = new CompositeFileListFilter<>();
    compositeFileListFilter.addFilters(fileListFilter,
            new SftpPersistentAcceptOnceFileListFilter(new SimpleMetadataStore(), "sftpMessageSource"));
    return compositeFileListFilter;
}

So, technically you don't need your custom one, if you don't use external persistent MetadataStore. But if you do, think about flipping SftpSimplePatternFileListFilter with SftpPersistentAcceptOnceFileListFilter. Since it is better to check for the pattern before storing the file into MetadataStore.

It is the fact that every synched remote file, passed those filters, is stored into local dir and the message for that local file is emitted immediately when the poller does a request.

The maxFetchSize plays the role when we load remote files into a local dir. The maxMessagesPerPoll is used from the poller, but those are already built from the local files. The message is emitted per local file, not as a batch for all of them. That's not what messaging is designed for.

Please, share more info what does not work with files. The SftpPersistentAcceptOnceFileListFilter checks not only file name, but also mtime of the file. So, that it not about any checksum, but more last  modified timestamp of the file.


问:
Prolog database with automatic retraction on backtracking
Are there any Prolog implementations supporting retractable database? I mean a database that automatically retract a fact inserted by assert() predicate call when the prolog engine backtracks through this predicate call? In other words, I'd want an "automatic" implicit retraction on backtracking.

Something similar may be expressed as

```<code>my_assert(Fact):- assert(Fact).
my_assert(Fact):- retract(Fact), fail.
</code>```

but that wouldn't work properly while backtracking through cutting (!)

Or this goal may be achieved in some manner using "tabled" flavours of Prolog?

答:
In SWI-Prolog, backtrackable assert can be implemented with the built-in predicate undo/1:

```<code>b_assertz(Term) :-
    assertz(Term, Ref),
    undo(erase(Ref)).
</code>```

Example without cut:

```<code>?- between(1,2,X), b_assertz(p(X)), between(3,4,Y), b_assertz(p(Y)), listing(p).
:- dynamic p/1.

p(1).
p(3).

X = 1,
Y = 3 ;
:- dynamic p/1.

p(1).
p(4).

X = 1,
Y = 4 ;
:- dynamic p/1.

p(2).
p(3).

X = 2,
Y = 3 ;
:- dynamic p/1.

p(2).
p(4).

X = 2,
Y = 4.

?- p(X).
false.
</code>```

Example with cut:

```<code>?- between(1,2,X), b_assertz(p(X)), !, between(3,4,Y), b_assertz(p(Y)), listing(p).
:- dynamic p/1.

p(1).
p(3).

X = 1,
Y = 3 ;
:- dynamic p/1.

p(1).
p(4).

X = 1,
Y = 4.

?- p(X).
false.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Are there any Prolog implementations supporting retractable database? I mean a database that automatically retract a fact inserted by assert() predicate call when the prolog engine backtracks through this predicate call? In other words, I'd want an "automatic" implicit retraction on backtracking.

Something similar may be expressed as

my_assert(Fact):- assert(Fact).
my_assert(Fact):- retract(Fact), fail.

but that wouldn't work properly while backtracking through cutting (!)

Or this goal may be achieved in some manner using "tabled" flavours of Prolog?

Body:
In SWI-Prolog, backtrackable assert can be implemented with the built-in predicate undo/1:

b_assertz(Term) :-
    assertz(Term, Ref),
    undo(erase(Ref)).

Example without cut:

?- between(1,2,X), b_assertz(p(X)), between(3,4,Y), b_assertz(p(Y)), listing(p).
:- dynamic p/1.

p(1).
p(3).

X = 1,
Y = 3 ;
:- dynamic p/1.

p(1).
p(4).

X = 1,
Y = 4 ;
:- dynamic p/1.

p(2).
p(3).

X = 2,
Y = 3 ;
:- dynamic p/1.

p(2).
p(4).

X = 2,
Y = 4.

?- p(X).
false.

Example with cut:

?- between(1,2,X), b_assertz(p(X)), !, between(3,4,Y), b_assertz(p(Y)), listing(p).
:- dynamic p/1.

p(1).
p(3).

X = 1,
Y = 3 ;
:- dynamic p/1.

p(1).
p(4).

X = 1,
Y = 4.

?- p(X).
false.


Title: How to make a python program that calculates a result for each row of the input table?

Body:
I am trying to make a Python program that will calculate a result based on a formula, given factors and an input dataframe.

I have a number of cars (N_cars) on a given length of the road (l) and their average speed (v):

input_columns = ['l', 'N_cars', 'v']
input_data = [[3.5, 1000, 100], [5.7, 500, 110],
              [10, 367, 110], [11.1, 1800, 95],
              [2.8, 960, 105], [4.7, 800, 120],
              [10.4, 103, 111], [20.1, 1950, 115]]

input_df = pd.DataFrame(input_data, columns=input_columns)
input_df

      l  N_cars    v
0   3.5    1000  100
1   5.7     500  110
2  10.0     367  110
3  11.1    1800   95
4   2.8     960  105
5   4.7     800  120
6  10.4     103  111
7  20.1    1950  115

I also know the factors needed for the formula for each category of car, and I know the percentage of each category. I also have different options for each category (3 options that I have here are just an example, there are many more options).

factors_columns = ['category', 'category %', 'option', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
factors_data = [['A', 58, 'opt_1', 0.000011, 0.23521, 0.93847, 0.39458, 0.00817, 0.24566, 0.0010, 0],
                ['A', 58, 'opt_2', 0.000011, 0.23521, 0.93145, 0.39458, 0.00467, 0.24566, 0.0010, 0],
                ['A', 58, 'opt_3', 0.000011, 0.23521, 0.93145, 0.39458, 0.00467, 0.24566, 0.0010, 0],
                ['B', 22, 'opt_1', 0.002452, 0.48327, 0.83773, 0.92852, 0.00871, 0.29568, 0.0009, 0.02],
                ['B', 22, 'opt_2', 0.002899, 0.49327, 0.83773, 0.92852, 0.00871, 0.30468, 0.0009, 0.02],
                ['B', 22, 'opt_3', 0.002452, 0.48327, 0.83773, 0.92852, 0.00771, 0.29568, 0.0119, 0.01],
                ['C', 17, 'opt_1', 0.082583, 0.39493, 0.02462, 0.82714, 0.00918, 0.28572, 0.0012, 0],
                ['C', 17, 'opt_2', 0.072587, 0.35493, 0.02852, 0.82723, 0.00912, 0.29572, 0.0018, 0],
                ['C', 17, 'opt_3', 0.082583, 0.39493, 0.02852, 0.82714, 0.00962, 0.28572, 0.0012, 0.01],
                ['D', 3, 'opt_1', 0.018327, 0.32342, 0.82529, 0.92752, 0.00988, 0.21958, 0.0016, 0],
                ['D', 3, 'opt_2', 0.014427, 0.32342, 0.82729, 0.92752, 0.00968, 0.22558, 0.0026, 0],
                ['D', 3, 'opt_3', 0.018327, 0.32342, 0.82729, 0.94452, 0.00988, 0.21258, 0.0016, 0]]

factors_df = pd.DataFrame(factors_data, columns=factors_columns)
factors_df

   category  category % option         a        b        c        d        e        f       g     h
0         A          58  opt_1  0.000011  0.23521  0.93847  0.39458  0.00817  0.24566  0.0010  0.00
1         A          58  opt_2  0.000011  0.23521  0.93145  0.39458  0.00467  0.24566  0.0010  0.00
2         A          58  opt_3  0.000011  0.23521  0.93145  0.39458  0.00467  0.24566  0.0010  0.00
3         B          22  opt_1  0.002452  0.48327  0.83773  0.92852  0.00871  0.29568  0.0009  0.02
4         B          22  opt_2  0.002899  0.49327  0.83773  0.92852  0.00871  0.30468  0.0009  0.02
5         B          22  opt_3  0.002452  0.48327  0.83773  0.92852  0.00771  0.29568  0.0119  0.01
6         C          17  opt_1  0.082583  0.39493  0.02462  0.82714  0.00918  0.28572  0.0012  0.00
7         C          17  opt_2  0.072587  0.35493  0.02852  0.82723  0.00912  0.29572  0.0018  0.00
8         C          17  opt_3  0.082583  0.39493  0.02852  0.82714  0.00962  0.28572  0.0012  0.01
9         D           3  opt_1  0.018327  0.32342  0.82529  0.92752  0.00988  0.21958  0.0016  0.00
10        D           3  opt_2  0.014427  0.32342  0.82729  0.92752  0.00968  0.22558  0.0026  0.00
11        D           3  opt_3  0.018327  0.32342  0.82729  0.94452  0.00988  0.21258  0.0016  0.00

For each option (opt_1, opt_2, opt_3), I have to calculate the result based on this formula (factors are taken from the factors table, but v is coming from the input table):

formula = ( (a*v*v) + (b*v) + c + (d/v) )  /  ( (e*v*v) + (f*v) + g) * (1 - h)
result = l * N_cars * formula

However, I have to take into account the percentage of each category of car. For each row of the input_df I have to perform the calculations three times, once for each of the three options. For example, for the index 0 of input_df, I have N_cars=1000, v=100 and l=3.5, the output should be something like this:

# for opt_1:
result = 3.5 * 1000 * ((58% of category A {formula for index 0 of factors_df}) +
                       (22% of category B {formula for index 3 of factors_df) +
                       (17% of category C {formula for index 6 of factors_df}) +
                       (3% of category D {formula for index 9 of factors_df}) )

# for opt_2:
result = 3.5 * 1000 * ((58% of category A {formula for index 1 of factors_df}) +
                       (22% of category B {formula for index 4 of factors_df) +
                       (17% of category C {formula for index 7 of factors_df}) +
                       (3% of category D {formula for index 10 of factors_df}) )

# for opt_3:
result = 3.5 * 1000 * ((58% of category A {formula for index 2 of factors_df}) +
                       (22% of category B {formula for index 5 of factors_df) +
                       (17% of category C {formula for index 8 of factors_df}) +
                       (3% of category D {formula for index 11 of factors_df}) )

So, as an output, for each of the rows in input_df, I should have three results, one for each of the three options.

I can do the calculation manually for each step, but what I am having troubles with is to make a loop that does it automatically for each input row and all 3 options and then passes to the next input row and so on until the last input row.

Body:
Solution

Not sure what your expected results are, but I believe this does what you're asking for:

def formula(g, *, l, N_cars, v):
    x = (1 - g.h) * (g.a * v*v + g.b*v + g.c + g.d/v) / (g.e * v*v + g.f*v + g.g)
    return N_cars * l * (x * g.pct / 100).sum()

groups = factors_df.rename(columns={"category %": "pct"}).groupby("option")
result = input_df.apply(lambda r: groups.apply(lambda g: formula(g, **r)), axis=1)

Output:

In [5]: input_df.join(result)
Out[5]:
      l  N_cars    v         opt_1         opt_2         opt_3
0   3.5    1000  100   5411.685077   5115.048256   5500.985916
1   5.7     500  110   4425.339734   4169.893681   4483.595803
2  10.0     367  110   5698.595376   5369.652565   5773.612841
3  11.1    1800   95  30820.717985  29180.106606  31384.785443
4   2.8     960  105   4165.270216   3930.726187   4226.877893
5   4.7     800  120   5860.057879   5506.509637   5919.496692
6  10.4     103  111   1663.960420   1567.455541   1685.339848
7  20.1    1950  115  60976.735053  57375.300546  61685.075902

Explanation

The first step is to group factors_df by option. Just to show what that looks like:

In [6]: groups.apply(print)
  category  pct option         a        b  ...        d        e        f       g     h
0        A   58  opt_1  0.000011  0.23521  ...  0.39458  0.00817  0.24566  0.0010  0.00
3        B   22  opt_1  0.002452  0.48327  ...  0.92852  0.00871  0.29568  0.0009  0.02
6        C   17  opt_1  0.082583  0.39493  ...  0.82714  0.00918  0.28572  0.0012  0.00
9        D    3  opt_1  0.018327  0.32342  ...  0.92752  0.00988  0.21958  0.0016  0.00

[4 rows x 11 columns]
   category  pct option         a        b  ...        d        e        f       g     h
1         A   58  opt_2  0.000011  0.23521  ...  0.39458  0.00467  0.24566  0.0010  0.00
4         B   22  opt_2  0.002899  0.49327  ...  0.92852  0.00871  0.30468  0.0009  0.02
7         C   17  opt_2  0.072587  0.35493  ...  0.82723  0.00912  0.29572  0.0018  0.00
10        D    3  opt_2  0.014427  0.32342  ...  0.92752  0.00968  0.22558  0.0026  0.00

[4 rows x 11 columns]
   category  pct option         a        b  ...        d        e        f       g     h
2         A   58  opt_3  0.000011  0.23521  ...  0.39458  0.00467  0.24566  0.0010  0.00
5         B   22  opt_3  0.002452  0.48327  ...  0.92852  0.00771  0.29568  0.0119  0.01
8         C   17  opt_3  0.082583  0.39493  ...  0.82714  0.00962  0.28572  0.0012  0.01
11        D    3  opt_3  0.018327  0.32342  ...  0.94452  0.00988  0.21258  0.0016  0.00

Note that I renamed the category % to pct. This isn't necessary, but made accessing that column in the formula() function a bit cleaner (g.pct vs g["category %"]).

The next step was to implement formula() in such a way as to accept a group from factors_df as an argument:

def formula(g, *, l, N_cars, v):
    x = (1 - g.h) * (g.a * v*v + g.b*v + g.c + g.d/v) / (g.e * v*v + g.f*v + g.g)
    return N_cars * l * (x * g.pct / 100).sum()

In the function signature, g is a group from factors_df, then the keyword-only arguments l, N_cars, and v, which will come from a single row of input_df at a time.

Each of the three groups shown above will be entered into the formula() function one at a time, in their entirety. For example, during one call to formula(), the g argument will hold all of this data:

  category  pct option         a        b  ...        d        e        f       g     h
0        A   58  opt_1  0.000011  0.23521  ...  0.39458  0.00817  0.24566  0.0010  0.00
3        B   22  opt_1  0.002452  0.48327  ...  0.92852  0.00871  0.29568  0.0009  0.02
6        C   17  opt_1  0.082583  0.39493  ...  0.82714  0.00918  0.28572  0.0012  0.00
9        D    3  opt_1  0.018327  0.32342  ...  0.92752  0.00988  0.21958  0.0016  0.00

When the formula uses something like g.e, it's accessing the entire e column, and is taking advantage of vectorization to perform the arithmetic calculations on the entire column at the same time. When the dust settles, x will be a Series where each item in the series will be the result of the formula for each of the four categories of car. Here's an example:

0    0.231242
3    0.619018
6    7.188941
9    1.792376

Notice the indices? Those correspond to category A, B, C, and D from factors_df, respectively.

From there, we need to call formula() on each row of input_df, using the axis argument of pd.DataFrame.apply():

input_df.apply(lambda r: groups.apply(lambda g: formula(g, **r)), axis=1)

The lambda r is an anonymous function object being passed to apply, being applied over axis 1, meaning that r will be a single row from input_df at a time, for example:

In [13]: input_df.apply(print, axis=1)
l            3.5
N_cars    1000.0
v          100.0
Name: 0, dtype: float64
.
.
.

Now, on each row-wise apply, we're also applying the formula() function on the groups groupby object with lambda g: formula(g, **r). The **r unpacks the row from input_df as keyword arguments, which helps to ensure that the values for v, l, and N_cars aren't misused in the formula (no need to worry about which order they're passed into the formula() function).


问:
convert times like these 1h30m/13h30m/1d5m into seconds
```<code>time_convert = {"s":1, "m":60, "h":3600,"d":86400}
converted = int(time[0]) * time_convert[time[-1]]
</code>```

That code above only converts the first first number to the corresponding converted time so 12h would come back as 3600 instead of 43200, so that way no other times would work for what I'm trying to do.
I'm wanting to convert any time the user says into seconds so, 1h5m,15h40m,1d55m ect

答:
A regex based approach could work well:

total = 0
time_convert = {"s": 1, "m": 60, "h": 3600, "d": 86400}
for quantity, unit in re.findall("(\d+)([dhm])", "1h30m"):
    total += time_convert[unit] * int(quantity)
print(total)

>>> 5400

```

re.findall returns all matches in a given string. We're matching for a number that's 1 or more digits long (\d+), then we're matching for one of d, h, or m. These first and second groups correspond to the quantity and the unit.

Body:
time_convert = {"s":1, "m":60, "h":3600,"d":86400}
converted = int(time[0]) * time_convert[time[-1]]

That code above only converts the first first number to the corresponding converted time so 12h would come back as 3600 instead of 43200, so that way no other times would work for what I'm trying to do.
I'm wanting to convert any time the user says into seconds so, 1h5m,15h40m,1d55m ect

Body:
A regex based approach could work well:

total = 0
time_convert = {"s": 1, "m": 60, "h": 3600, "d": 86400}
for quantity, unit in re.findall("(\d+)([dhm])", "1h30m"):
    total += time_convert[unit] * int(quantity)
print(total)

>>> 5400

re.findall returns all matches in a given string. We're matching for a number that's 1 or more digits long (\d+), then we're matching for one of d, h, or m. These first and second groups correspond to the quantity and the unit.


问:
Java SQL connection, select query
I created this method, but when i try to call the method it returns a null pointer exception. Can anybody tell me what's wrong? help me please</p>

```<code>public Talent SearchTalentQuery(int talentID){
    String SearchTalentString = "SELECT * FROM TALENT WHERE TALENTID = "+talentID+";";
    Talent talent=null;
    try{
        //error in select query
        if(getOracleXEConnection()!=null){

            Statement statement = conn.createStatement();
            ResultSet rs = statement.executeQuery(SearchTalentString);
                   while( rs.next()){
                   talent.setTalentName(rs.getString("talentname"));
                   talent.setTalentFocus(rs.getString("maintalentfocus"));
                   talent.setTalentNationality((rs.getString("nationality")));
                   talent.setTalentGroup(rs.getString("talentgroup"));
                   talent.setTalentHiredate(rs.getString("hiredate"));
                   talent.setTalentAge(Integer.parseInt(rs.getString("age")));
                   talent.setTalentID(Integer.parseInt(rs.getString("talentid")));
                   }

            rs.close();
            statement.close();
            conn.close();

            return talent;
        }
        else{
            return null;
        }
    }
    catch(SQLException | NumberFormatException e){
        e.printStackTrace();
    }
    return null;
</code>```

答:
Example</p>
```<code>   public void Insert(){
            try {
                Statement sta = conn.createStatement();
                Statement consulta = conn.createStatement();
                String query = "SELECT * FROM coches";
                System.out.println("Fecha de entrada");
                String fe = scanner.next();
                System.out.println("Fecha de salida");
                String fs = scanner.next();

                ResultSet rs = consulta.executeQuery(query);
                int i = 1;
                while (rs.next()) {
                    System.out.println(i + "," + rs.getString("matricula") + "," + rs.getString("marca") + "," + rs.getString("modelo"));
                    i++;
                }
                System.out.println("Selecciona el numero del coche");
                int n = scanner.nextInt();
                rs.absolute(n);

                sta.executeUpdate("INSERT INTO reparaciones (fecha_entrada,fecha_salida,coche) VALUES ('"+ fe + "', '" + fs + "', '" + rs.getString("matricula") + "');");

                System.out.println("Reparación insertada, indica los materiales usados");

                String nombre = "";

                do{
                    System.out.println("-------------------------------------------------");
                    System.out.println("Nombre :");
                    scanner.nextLine();
                    nombre = scanner.nextLine();
                    if(!nombre.equals("")){
                        System.out.println("Cantidad :");
                        int cant = scanner.nextInt();
                        System.out.println("Precio :");
                        int prec = scanner.nextInt();
                        sta.executeUpdate("INSERT INTO materiales (nombre,cantidad,precio,reparacion) VALUES ('"+ nombre + "', '" + cant + "', '" + prec +  "', '" + n + "');");
                    }
               }
               while(!nombre.equals(""));
                sta.close();
                rs.close();
                consulta.close();
            } catch (SQLException ex) {
                System.out.println("ERROR:al hacer un Insert");
                ex.printStackTrace();
            }
        }
        public void Delete(){
            try {
                Statement baja = conn.createStatement();
                Statement consulta = conn.createStatement();
                String query = "SELECT * FROM materiales";
                ResultSet rs = consulta.executeQuery(query);
                int i = 1;
                while (rs.next()) {
                    System.out.println(rs.getInt("id") + "," + rs.getString("nombre"));
                    i++;
                }
                System.out.println("Elige una opcion");
                int opc = scanner.nextInt();

                String query2 = "SELECT reparacion FROM materiales WHERE id = " + opc;
                ResultSet rs2 = consulta.executeQuery(query2);
                if(rs2.next()){
                  if(rs2.getInt("reparacion")!=0){
                    System.out.println("No es posible darlo de baja");
                  }
                  else{
                    String queryBaja = "DELETE FROM materiales WHERE id ='" + opc +"'";
                    baja.executeUpdate(queryBaja);
                    System.out.println("Eliminado con exito");
                  }
                }

                baja.close();
                consulta.close();
                rs.close();
                rs2.close();
            } catch (SQLException ex) {
                System.out.println("ERROR:al hacer un delete");
                ex.printStackTrace();
            }
        }
</code>```

Title: Java SQL connection, select query

Body:
I created this method, but when i try to call the method it returns a null pointer exception. Can anybody tell me what's wrong? help me please

public Talent SearchTalentQuery(int talentID){
    String SearchTalentString = "SELECT * FROM TALENT WHERE TALENTID = "+talentID+";";
    Talent talent=null;
    try{
        //error in select query
        if(getOracleXEConnection()!=null){

            Statement statement = conn.createStatement();
            ResultSet rs = statement.executeQuery(SearchTalentString);
                   while( rs.next()){
                   talent.setTalentName(rs.getString("talentname"));
                   talent.setTalentFocus(rs.getString("maintalentfocus"));
                   talent.setTalentNationality((rs.getString("nationality")));
                   talent.setTalentGroup(rs.getString("talentgroup"));
                   talent.setTalentHiredate(rs.getString("hiredate"));
                   talent.setTalentAge(Integer.parseInt(rs.getString("age")));
                   talent.setTalentID(Integer.parseInt(rs.getString("talentid")));
                   }

            rs.close();
            statement.close();
            conn.close();

            return talent;
        }
        else{
            return null;
        }
    }
    catch(SQLException | NumberFormatException e){
        e.printStackTrace();
    }
    return null;

Body:
Example

   public void Insert(){
            try {
                Statement sta = conn.createStatement();
                Statement consulta = conn.createStatement();
                String query = "SELECT * FROM coches";
                System.out.println("Fecha de entrada");
                String fe = scanner.next();
                System.out.println("Fecha de salida");
                String fs = scanner.next();

                ResultSet rs = consulta.executeQuery(query);
                int i = 1;
                while (rs.next()) {
                    System.out.println(i + "," + rs.getString("matricula") + "," + rs.getString("marca") + "," + rs.getString("modelo"));
                    i++;
                }
                System.out.println("Selecciona el numero del coche");
                int n = scanner.nextInt();
                rs.absolute(n);

                sta.executeUpdate("INSERT INTO reparaciones (fecha_entrada,fecha_salida,coche) VALUES ('"+ fe + "', '" + fs + "', '" + rs.getString("matricula") + "');");

                System.out.println("Reparación insertada, indica los materiales usados");

                String nombre = "";

                do{
                    System.out.println("-------------------------------------------------");
                    System.out.println("Nombre :");
                    scanner.nextLine();
                    nombre = scanner.nextLine();
                    if(!nombre.equals("")){
                        System.out.println("Cantidad :");
                        int cant = scanner.nextInt();
                        System.out.println("Precio :");
                        int prec = scanner.nextInt();
                        sta.executeUpdate("INSERT INTO materiales (nombre,cantidad,precio,reparacion) VALUES ('"+ nombre + "', '" + cant + "', '" + prec +  "', '" + n + "');");
                    }
               }
               while(!nombre.equals(""));
                sta.close();
                rs.close();
                consulta.close();
            } catch (SQLException ex) {
                System.out.println("ERROR:al hacer un Insert");
                ex.printStackTrace();
            }
        }
        public void Delete(){
            try {
                Statement baja = conn.createStatement();
                Statement consulta = conn.createStatement();
                String query = "SELECT * FROM materiales";
                ResultSet rs = consulta.executeQuery(query);
                int i = 1;
                while (rs.next()) {
                    System.out.println(rs.getInt("id") + "," + rs.getString("nombre"));
                    i++;
                }
                System.out.println("Elige una opcion");
                int opc = scanner.nextInt();

                String query2 = "SELECT reparacion FROM materiales WHERE id = " + opc;
                ResultSet rs2 = consulta.executeQuery(query2);
                if(rs2.next()){
                  if(rs2.getInt("reparacion")!=0){
                    System.out.println("No es posible darlo de baja");
                  }
                  else{
                    String queryBaja = "DELETE FROM materiales WHERE id ='" + opc +"'";
                    baja.executeUpdate(queryBaja);
                    System.out.println("Eliminado con exito");
                  }
                }

                baja.close();
                consulta.close();
                rs.close();
                rs2.close();
            } catch (SQLException ex) {
                System.out.println("ERROR:al hacer un delete");
                ex.printStackTrace();
            }
        }


问:
In Visual Studio Code for Windows, the Git branch doesn't show and can't create a branch
So I've been using Visual Studio Code (VS Code) for a while and working on my project with Git and had no problem.  I was able to clone the git repository to a work space then I would see the "master" at the bottom left corner showing that I cloned a master branch and am working on the master branch.  Then Normally I can click on it and select "Create new branch" and create my own branch such as "off_master".

I don't know why, but since little over a week ago, when I clone a git repository, it downloads the files, but I don't see the the word "master" at the bottom left of VS Code.  And when I click on "Create new branch" and give a name, I get a general git error:

```<code>Git: Failed to execute git
</code>```

and I see these in the git log:

```<code>> git rev-parse --show-toplevel
> git checkout -q -b off_Master
> git rev-parse --show-toplevel
</code>```

I have no idea why it's starting to do this.
So I've uninstalled VS Code, deleted this directory which seem to have all the VS Code settings:

```<code>C:\Users\<myId>\AppData\Roaming\Code\
</code>```

I've then reinstalled VS Code with latest and same thing happens.

When I issue git status from the directory which contains .git directory, I get an output like this:

```<code>On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working tree clean
</code>```

So it looks like I am using the master branch, but VS Code is not showing.
And somehow I cannot create a new branch from VS Code.

I also tried a command like git config --list and it does have correct user.name, user.email, and remote.origin.url and these which look OK:

```<code>remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
branch.master.remote=origin
branch.master.merge=refs/heads/master
</code>```

I am not very familiar with git, thus I use VS Code to drive the git, so it's very critical that I get this back to working state...

Any idea why this might be happening?

Only thing that makes me bit suspicious is that I was doing some stuff with Angular JS and upgraded NodeJS to do some stuff, but I wouldn't think these will have any impact to VS Code and git.

One other thing is that even if I removed that "Code" directory, when I reinstalled VS Code, it seemed to have all the extensions that I had installed previously, so it seems not everything was cleaned up.. How can I clean up everything so that it will look as if I am installing VS Code brand new?  Perhaps doing this and reinstalling might help?

答:
Steps to reproduce :

Access the "Source Control" tab on the left side of VSCode

Click on the "three small dots" next to the refresh button

Go to "Pull, Push"

Click on the "Fetch" option

Enjoy

If you would like to know more about creating a new branch and switch between branches : Switch between branches in VSCode

Body:
So I've been using Visual Studio Code (VS Code) for a while and working on my project with Git and had no problem.  I was able to clone the git repository to a work space then I would see the "master" at the bottom left corner showing that I cloned a master branch and am working on the master branch.  Then Normally I can click on it and select "Create new branch" and create my own branch such as "off_master".

I don't know why, but since little over a week ago, when I clone a git repository, it downloads the files, but I don't see the the word "master" at the bottom left of VS Code.  And when I click on "Create new branch" and give a name, I get a general git error:

Git: Failed to execute git

and I see these in the git log:

> git rev-parse --show-toplevel
> git checkout -q -b off_Master
> git rev-parse --show-toplevel

I have no idea why it's starting to do this.
So I've uninstalled VS Code, deleted this directory which seem to have all the VS Code settings:

C:\Users\<myId>\AppData\Roaming\Code\

I've then reinstalled VS Code with latest and same thing happens.

When I issue git status from the directory which contains .git directory, I get an output like this:

On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working tree clean

So it looks like I am using the master branch, but VS Code is not showing.
And somehow I cannot create a new branch from VS Code.

I also tried a command like git config --list and it does have correct user.name, user.email, and remote.origin.url and these which look OK:

remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
branch.master.remote=origin
branch.master.merge=refs/heads/master

I am not very familiar with git, thus I use VS Code to drive the git, so it's very critical that I get this back to working state...

Any idea why this might be happening?

Only thing that makes me bit suspicious is that I was doing some stuff with Angular JS and upgraded NodeJS to do some stuff, but I wouldn't think these will have any impact to VS Code and git.

One other thing is that even if I removed that "Code" directory, when I reinstalled VS Code, it seemed to have all the extensions that I had installed previously, so it seems not everything was cleaned up.. How can I clean up everything so that it will look as if I am installing VS Code brand new?  Perhaps doing this and reinstalling might help?


问:
Is there a way to expand a JFileChooser directory without a mouse
Using a JFileChooser, I can select a directory by double clicking the directory (going down a level) with my mouse.  Is there a way to select a directory without the mouse?  For example, is there a key binding to go down a directory level or do I have to somehow add a key listener to the  JFileChooser? </p>

答:
You should be able to use tab to move between the different parts of the chooser, and then use the arrow keys to change which directory is highlighted, and then press Enter to change the directory to the highlighted one.

I have tested the following example code on my machine (Vista/JDK 1.6) and it works as I would expect:

```<code>import javax.swing.*;
public class test {
  public static void main(String[] args) {
      (new JFileChooser("")).showOpenDialog(new JFrame());
      System.out.println("OK!");
   }
}
</code>```

If your project is not responding similiarly in your JFileChooser, I would debug as follows:

Create test.java with only the code necessary to pop up a chooser.

If the test app differently than within your app, its something in your code causing it to fail, such as UI skinning code, keyboard listeners, etc. Modify the example, one change at a time to closer replicate your settings for your chooser in your app and see if you can pinpoint where it breaks.

If even a basic test app doesn't work right, it is probably something about your setup, such as a bug in your JDK version, your OS, etc. Troubleshoot your setup.

Body:
You should be able to use tab to move between the different parts of the chooser, and then use the arrow keys to change which directory is highlighted, and then press Enter to change the directory to the highlighted one.

I have tested the following example code on my machine (Vista/JDK 1.6) and it works as I would expect:

import javax.swing.*;
public class test {
  public static void main(String[] args) {
      (new JFileChooser("")).showOpenDialog(new JFrame());
      System.out.println("OK!");
   }
}

If your project is not responding similiarly in your JFileChooser, I would debug as follows:

Create test.java with only the code necessary to pop up a chooser.

If the test app differently than within your app, its something in your code causing it to fail, such as UI skinning code, keyboard listeners, etc. Modify the example, one change at a time to closer replicate your settings for your chooser in your app and see if you can pinpoint where it breaks.

If even a basic test app doesn't work right, it is probably something about your setup, such as a bug in your JDK version, your OS, etc. Troubleshoot your setup.


问:
How to delete spacing after row is complete in c++?
I have been working on a project. I am limited to using a few libraries so any additional library would not be helpful. So far my project works, but I am noticing an extra space after the last row is completed. How do I fix this extra spacing issue? please help! There's a space at the bottom... and this only seems to happen when the last row is full and no date is carried over.</p>
```<code>// Extracted..
#include <iostream>

         if (day >= 9)
         {
            std::cout << day;
         }
         else
         {
          std::cout << day << " ";
         }
         if (day != days_per)
         {
          std::cout << " ";
         }
         }
</code>```

答:
I think this will fix it:

That's the block dealing with the last day of the week (Saturday).

Print it always.

If it is the last day of the month, don't do anything else.

Otherwise: 1) print a newline, and 2) if the next day has 1 digit (current day < 9), print a space.

[Demo]

      if (++count > 6)
      {
         count = 0;
         std::cout << day;
         if (day != days_per)
         {
            std::cout << '\n';
            if (day < 9)
            {
                std::cout << " ";
            }
         }
      }

```

Body:
I have been working on a project. I am limited to using a few libraries so any additional library would not be helpful. So far my project works, but I am noticing an extra space after the last row is completed. How do I fix this extra spacing issue? please help! There's a space at the bottom... and this only seems to happen when the last row is full and no date is carried over.

// Extracted..
#include <iostream>

         if (day >= 9)
         {
            std::cout << day;
         }
         else
         {
          std::cout << day << " ";
         }
         if (day != days_per)
         {
          std::cout << " ";
         }
         }


问:
Get a specific text value from an HTML table using python and selenium
This website (https://egov.uscis.gov/processing-times/) shows the processing time for different immigration applications for different service centers.
There are two drop-down menus; first is the Form (immigration application), and second is the service center. Once you select a value from these two menus and hit the "Get processing time" button, a table will be displayed which shows the details for different immigration categories/types (you have to scroll down a bit to be able to see the table)(the table has three column titles: "Estimated time range", "Form type", "Receipt date for a case inquiry").
I want to use selenium with python to automate printing out the current range for processing time for form I-765 in Texas Service Center for the category of "Based on a pending I-485 adjustment application [(c)(9)]", which is the sixth row in the table.

As of 2/5/2022, I want my code to print out a text as: "11.5 Months to 13.5 Months".

Here is my attempt so far, but it only prints an empty string.

It opens the website, selects the right Form and then the right service center, and hits the button. But it fails to fetch the text I want from the table.

What if I want to print out all the text values in the 6th row?

```<code> from selenium import webdriver
 from selenium.webdriver.support.ui import Select
 import time

 browser = webdriver.Chrome('C:\ChromeDriver\chromedriver')
 browser.get('https://egov.uscis.gov/processing-times/')

 form_menu = browser.find_element_by_id('selectForm')
 select_form_menu = Select(form_menu)
 select_form = select_form_menu.select_by_visible_text('I-765 | Application for Employment Authorization')

 time.sleep(2)

 office_menu = browser.find_element_by_id('officeOrCenter')
 select_office_menu = Select(office_menu)
 select_office = select_office_menu.select_by_visible_text('Texas Service Center')

 time.sleep(2)

 search_btn = browser.find_element_by_id('getProcTimes')
 search_btn.click()

 time.sleep(2)

 table = browser.find_element_by_id('resultList')
 items = table.find_elements_by_id('est') #here I am trying to return a list of all the values in the first column.

 print(items[5].text) #my value of interest is the 6th element in the list (6th row in the table).
</code>```

答:
If I change

```<code>print(items[5].text)
</code>```

to

```<code>print(items[5].get_attribute("innerText"))
</code>```

I get the result I want.

Body:
This website (https://egov.uscis.gov/processing-times/) shows the processing time for different immigration applications for different service centers.
There are two drop-down menus; first is the Form (immigration application), and second is the service center. Once you select a value from these two menus and hit the "Get processing time" button, a table will be displayed which shows the details for different immigration categories/types (you have to scroll down a bit to be able to see the table)(the table has three column titles: "Estimated time range", "Form type", "Receipt date for a case inquiry").
I want to use selenium with python to automate printing out the current range for processing time for form I-765 in Texas Service Center for the category of "Based on a pending I-485 adjustment application [(c)(9)]", which is the sixth row in the table.

As of 2/5/2022, I want my code to print out a text as: "11.5 Months to 13.5 Months".

Here is my attempt so far, but it only prints an empty string.

It opens the website, selects the right Form and then the right service center, and hits the button. But it fails to fetch the text I want from the table.

What if I want to print out all the text values in the 6th row?

 from selenium import webdriver
 from selenium.webdriver.support.ui import Select
 import time

 browser = webdriver.Chrome('C:\ChromeDriver\chromedriver')
 browser.get('https://egov.uscis.gov/processing-times/')

 form_menu = browser.find_element_by_id('selectForm')
 select_form_menu = Select(form_menu)
 select_form = select_form_menu.select_by_visible_text('I-765 | Application for Employment Authorization')

 time.sleep(2)

 office_menu = browser.find_element_by_id('officeOrCenter')
 select_office_menu = Select(office_menu)
 select_office = select_office_menu.select_by_visible_text('Texas Service Center')

 time.sleep(2)

 search_btn = browser.find_element_by_id('getProcTimes')
 search_btn.click()

 time.sleep(2)

 table = browser.find_element_by_id('resultList')
 items = table.find_elements_by_id('est') #here I am trying to return a list of all the values in the first column.

 print(items[5].text) #my value of interest is the 6th element in the list (6th row in the table).

Body:
If I change

print(items[5].text)

to

print(items[5].get_attribute("innerText"))

I get the result I want.


问:
Access function in class A from non related class B using object of class A

Possible Duplicate:

  Call function of class ONE from class TWO without extend?

why this does not work?

```<code>    class A {
        function one() {
            echo "Class A";
        }
    }

    class B {
        function two() {
            echo "Class B";
            $a->one();
        }
    }

    $a = new A;
    $b = new B;

    $b->two();
</code>```

答:
$a is not accessable in Class B in your example. Please read Variable Scope

Try:

```<code>class A {
    public function one() {
        echo "Class A";
    }
}

class B {
    public function two() {
        echo "Class B";
        $a = new A;
        $a->one();
    }
}

$b = new B;
$b->two();
</code>```

Body:
Possible Duplicate:

  Call function of class ONE from class TWO without extend?

why this does not work?

    class A {
        function one() {
            echo "Class A";
        }
    }

    class B {
        function two() {
            echo "Class B";
            $a->one();
        }
    }

    $a = new A;
    $b = new B;

    $b->two();

Body:
$a is not accessable in Class B in your example. Please read Variable Scope

Try:

class A {
    public function one() {
        echo "Class A";
    }
}

class B {
    public function two() {
        echo "Class B";
        $a = new A;
        $a->one();
    }
}

$b = new B;
$b->two();


问:
Codeigniter attendance Module Looping result
Hello I have been following a tutorial to help me with an attendance module I am making in Codeigniter.

I have events and in each event you can take attendance.

In my events View File, I am loading another View file called attendance.php.

The events view file shows all the event details with the attendance form embeded at the bottom.

The attendance form pulls in all the users who are registered and provides 2 radio buttons to mark whether the user has attended the event or not.

This is the HTML I have got so far:

```<code><section class="content">
   <div class="row" >
      <div class="col-md-12">
      <h3>Event Attendance</h3>
      <?php echo form_open() ?>
        <div class="table-responsive">
            <table class="table table-bordered table-striped dataTable">
                <thead>
                <tr class="">
                    <th>Number</th>
                    <th>User ID</th>
                    <th>Name</th>
                    <th>Attendance</th>
                </tr>
                </thead>
                <tbody id="tbody_events">

                <?php
                    $emp = $this->db->query("SELECT * FROM `aauth_users`");
                    $result = $emp->result();
                    settype($sl, "integer");

                    foreach($result as $row):
                        $sl++;

                ?>
                <tr>
                    <td><?php echo $sl ?></td>
                    <td><?php echo $row->id ?>
                    <input type="hidden" name="emid[]" value="<?php echo $row->id ?>">
                    </td>
                    <td><?php echo $row->full_name ?></td>
                    <td>
                        <input type="radio" value="1" name="<?php echo $sl?>"> Present
                        <input type="radio" value="0" name="<?php echo $sl?>"> Absent
                    </td>
                </tr>
                    <?php endforeach ?>
                <tr>
                    <td colspan="4">
                    <input type="submit" name="submit" value="Submit Attendance" class="btn btn-success">
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
        <?php echo form_close() ?>
      </div>
    </div>
</section>
</code>```

The PHP Code I have

```<code><?php

if (isset($_POST['submit'])) {

    $attid = $this->input->post('emid');
    $date = date("d-m-Y");
    $time = date("h:s:i A");
    $eventid = $events->id;
    $tm = count($attid);
    for($i=0;$i<$tm;$i++) {

        $at = $i+1;
        $attended = $_POST[$at];

        $attr = array(
            "user_id" => $attid[$i],
            "attended" => $attended,
            "attendance_date" => $date,
            "attendance_time" => $time,
            "event_id" => $eventid,
        );

    }

}

?>
</code>```

The Problem
The problem I am having is everything is working great and I can take the attendance. I am seeing the results go into the database.

Every time I submit the attendance it is duplicating the attendance records. So currently I have 3 users registered. So on the events page down in the attendance table, it shows 3 users in each table row. Each have radio buttons to say 'present' or 'absent'. I submit the form and in the database I will have 6 entries. 2 from each user stating their attendance when I only need to show 1 entry for each user.

Any help would be deeply appreciated.

答: Please verify your database to see if you've utilised the enum data type. Now that I've removed the enum, everything is operating fine.</p>

Body:
Hello I have been following a tutorial to help me with an attendance module I am making in Codeigniter.

I have events and in each event you can take attendance.

In my events View File, I am loading another View file called attendance.php.

The events view file shows all the event details with the attendance form embeded at the bottom.

The attendance form pulls in all the users who are registered and provides 2 radio buttons to mark whether the user has attended the event or not.

This is the HTML I have got so far:

Event Attendance

      <?php echo form_open() ?>

                    Number
                    User ID
                    Name
                    Attendance

                <?php
                    $emp = $this->db->query("SELECT * FROM `aauth_users`");
                    $result = $emp->result();
                    settype($sl, "integer");

                    foreach($result as $row):
                        $sl++;

                ?>

                    <?php echo $sl ?>
                    <?php echo $row->id ?>
                    <input type="hidden" name="emid[]" value="<?php echo $row->id ?>">

                    <?php echo $row->full_name ?>

                        <input type="radio" value="1" name="<?php echo $sl?>"> Present
                        <input type="radio" value="0" name="<?php echo $sl?>"> Absent

                    <?php endforeach ?>

                    <input type="submit" name="submit" value="Submit Attendance" class="btn btn-success">

        <?php echo form_close() ?>

The PHP Code I have

<?php

if (isset($_POST['submit'])) {

    $attid = $this->input->post('emid');
    $date = date("d-m-Y");
    $time = date("h:s:i A");
    $eventid = $events->id;
    $tm = count($attid);
    for($i=0;$i<$tm;$i++) {

        $at = $i+1;
        $attended = $_POST[$at];

        $attr = array(
            "user_id" => $attid[$i],
            "attended" => $attended,
            "attendance_date" => $date,
            "attendance_time" => $time,
            "event_id" => $eventid,
        );

    }

}

?>

The Problem
The problem I am having is everything is working great and I can take the attendance. I am seeing the results go into the database.

Every time I submit the attendance it is duplicating the attendance records. So currently I have 3 users registered. So on the events page down in the attendance table, it shows 3 users in each table row. Each have radio buttons to say 'present' or 'absent'. I submit the form and in the database I will have 6 entries. 2 from each user stating their attendance when I only need to show 1 entry for each user.

Any help would be deeply appreciated.


问:
Need to automate Sending Telegram Messages for the next 14 Days
I have a Telegram Group that I recreate every 2 weeks. I then have a list of messages & media that need to be sent at certain times in the next 2 weeks. I am using Telegram's "Schedule Message" that I set up on the first Sunday evening. I am looking for a way to automate this whereby I have a sheet that has the details & it can be read & posted into the group... Something like this

06/02/2022 8:00pm "Message1...."

07/02/2022 9:00am Pic1

07/02/2022 10:00am Pic2

07/02/2022 10:30am "Message2....."

Any ideas how I can automate this? Instead of doing this every 2 weeks manually.

答:
use telethon! it's as easy as doing:

pip install telethon

https://docs.telethon.dev/en/stable/modules/client.html#telethon.client.messages.MessageMethods.send_message here you can find the part about scheduling :)


问:
How do I print something only when a given parameter does not equal an empty string
I am trying to print out different options which are parameters to my function, however, i want my code not to print anything if that specific parameter is an empty string.
The code I have till now:

```<code>def ask_question(question, option1, option2, option3, option4):
#print the question onto the screen as well as numbered options
print(question)
print("1 ", option1)
print("2 ", option2)
print("3 ", option3)
print("4 ", option4)

#store answer under user_response
user_response = input("Your answer: ")

return user_response
</code>```

This prints

How are you

good

bad

when parameters are:
("How are you", "good", "bad","","")

but I would like it to print:

How are you

good

bad

without including any options with an empty string

Any help on what I should do?

答:
You would be better off passing in a list of possible responses, along the lines of:

def ask_question(question, options):
    print(question)

    number = 0
    for option in options:
        number += 1
        print(f"   {number:2}. {option}")

    while True:
        try:
            answer = int(input("Your answer: "))
            if 1 <= answer <= number:
                return answer
            print(f"Input out of range, try again.")
        except Exception as exc:
            print(f"Input error, try again: {exc}.")

response = ask_question("How are you?", ["Good", "Bad"])
```

That way, you can cater for any number of possibilities, including checking input for validity as shown.

Body:
I am trying to print out different options which are parameters to my function, however, i want my code not to print anything if that specific parameter is an empty string.
The code I have till now:

def ask_question(question, option1, option2, option3, option4):
#print the question onto the screen as well as numbered options
print(question)
print("1 ", option1)
print("2 ", option2)
print("3 ", option3)
print("4 ", option4)

#store answer under user_response
user_response = input("Your answer: ")

return user_response

This prints

How are you

good

bad

when parameters are:
("How are you", "good", "bad","","")

but I would like it to print:

How are you

good

bad

without including any options with an empty string

Any help on what I should do?

Body:
You would be better off passing in a list of possible responses, along the lines of:

def ask_question(question, options):
    print(question)

    number = 0
    for option in options:
        number += 1
        print(f"   {number:2}. {option}")

    while True:
        try:
            answer = int(input("Your answer: "))
            if 1 <= answer <= number:
                return answer
            print(f"Input out of range, try again.")
        except Exception as exc:
            print(f"Input error, try again: {exc}.")

response = ask_question("How are you?", ["Good", "Bad"])

That way, you can cater for any number of possibilities, including checking input for validity as shown.


Title: Icon display with different color on Iphone and on other devices

Body:
i have a problem with some icon color displaying on Iphone.
Here the html code :

<button type="submit" aria-label="Start Searching">
   <i className={`icon-search`} aria-hidden="true" />
</button>

Here the svg of the icon :

<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
<title>Search</title>
<g id="icomoon-ignore">
</g>
<path fill="#666" d="M637.117 637.117c81.229-81.229 81.229-212.928 0-294.157s-212.928-81.228-294.157 0c-81.228 81.229-81.228 212.928 0 294.157s212.928 81.229 294.157 0zM653.322 687.229c-100.573 83.475-250.045 78.086-344.302-16.17-99.974-99.974-99.974-262.067 0-362.040 99.975-99.974 262.065-99.974 362.039 0 94.256 94.258 99.648 243.73 16.17 344.302 0.272 0.25 0.538 0.502 0.8 0.765l90.509 90.512c9.373 9.373 9.373 24.566 0 33.939s-24.566 9.373-33.939 0l-90.512-90.509c-0.262-0.262-0.515-0.531-0.765-0.8z"></path>
</svg>

The icon color is correctly displayed ( that to say dark gray ) on Android or any desktop ( including Safari ) but he is fully white on Iphone ( Iphone 8, IOS 15.1 )

Does any one have a solution ?

Body:
As @A Haworth pointed out: it might be ralated to some css rule in your global css.

Browser specific default styles

Since your icon already contains a hard coded fill attribute, my suspicion is your icon is colored white due to a safari default button style.

You could try to disable default button styling by applying an appearance: none rule.

button {
  font-size: 2em;
  display: block;
  width: 100%;
}

button svg {
  display: inline-block;
  height: 1em;
}

.btn-default {
  appearance: none;
  background: #fff;
  border: 1px solid #000;
}

.btn-default-use {
  color: #666;
}

button svg {
  display: inline-block;
  width: 1em;
}

.svgAssetHiddden {
  position: absolute;
  width: 0;
  height: 0;
  overflow: hidden;
}

<p>button</p>
<button type="submit" aria-label="Start Searching">
  <svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
    <title>Search</title>
    <path fill="#666" d="M637.117 637.117c81.229-81.229 81.229-212.928 0-294.157s-212.928-81.228-294.157 0c-81.228 81.229-81.228 212.928 0 294.157s212.928 81.229 294.157 0zM653.322 687.229c-100.573 83.475-250.045 78.086-344.302-16.17-99.974-99.974-99.974-262.067 0-362.040 99.975-99.974 262.065-99.974 362.039 0 94.256 94.258 99.648 243.73 16.17 344.302 0.272 0.25 0.538 0.502 0.8 0.765l90.509 90.512c9.373 9.373 9.373 24.566 0 33.939s-24.566 9.373-33.939 0l-90.512-90.509c-0.262-0.262-0.515-0.531-0.765-0.8z"></path>
  </svg>
</button>

<p>button appearance none</p>
<button class="btn-default" type="submit" aria-label="Start Searching">
  <svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
    <title>Search</title>
    <path fill="#666" d="M637.117 637.117c81.229-81.229 81.229-212.928 0-294.157s-212.928-81.228-294.157 0c-81.228 81.229-81.228 212.928 0 294.157s212.928 81.229 294.157 0zM653.322 687.229c-100.573 83.475-250.045 78.086-344.302-16.17-99.974-99.974-99.974-262.067 0-362.040 99.975-99.974 262.065-99.974 362.039 0 94.256 94.258 99.648 243.73 16.17 344.302 0.272 0.25 0.538 0.502 0.8 0.765l90.509 90.512c9.373 9.373 9.373 24.566 0 33.939s-24.566 9.373-33.939 0l-90.512-90.509c-0.262-0.262-0.515-0.531-0.765-0.8z"></path>
  </svg>
</button>

<p>button use</p>
<button class="btn-default btn-default-use" type="submit" aria-label="Start Searching">
  <svg viewBox="0 0 1024 1024">
    <use href="#searchIcon" />
  </svg>
</button>

<svg class="svgAssetHiddden" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" aria-hidden="true">
  <symbol id="searchIcon" fill="currentColor">
    <path d="M637.117 637.117c81.229-81.229 81.229-212.928 0-294.157s-212.928-81.228-294.157 0c-81.228 81.229-81.228 212.928 0 294.157s212.928 81.229 294.157 0zM653.322 687.229c-100.573 83.475-250.045 78.086-344.302-16.17-99.974-99.974-99.974-262.067 0-362.040 99.975-99.974 262.065-99.974 362.039 0 94.256 94.258 99.648 243.73 16.17 344.302 0.272 0.25 0.538 0.502 0.8 0.765l90.509 90.512c9.373 9.373 9.373 24.566 0 33.939s-24.566 9.373-33.939 0l-90.512-90.509c-0.262-0.262-0.515-0.531-0.765-0.8z" />
  </symbol>
</svg>

Eventually, it might also be related to a Dark mode setting overriding your original fill to ensure a sufficient contrast.


问:
Python Iteration using while loops and a timer
I am trying to run my program with a timer so that it will stop after 10 seconds but having problems with my iterating through it, so far I've tried using 2 while loops and a while loop within a for loop but have not come right. The program essentially makes shapes fall from top to bottom of the screen but I want it to stop after 10 seconds.</p>
```<code>def main():
    star = pygame.Rect(75, 0, WIDTH, HEIGHT)
    triangle = pygame.Rect(575, 0, WIDTH, HEIGHT)
    rectangle = pygame.Rect(175, 0, WIDTH, HEIGHT)
    square = pygame.Rect(275, 0, WIDTH, HEIGHT)
    hexagon = pygame.Rect(375, 0, WIDTH, HEIGHT)
    circle = pygame.Rect(475, 0, WIDTH, HEIGHT)

    clock = pygame.time.Clock()
    for i in range (10,0,-1):
        time.sleep(1)
        run = True
        while run:
            if star.y > HEIGHT:
                star.y = -1
            elif triangle.y > HEIGHT:
                triangle.y = -1
            elif rectangle.y > HEIGHT:
                rectangle.y = -1
            elif square.y > HEIGHT:
                square.y = -1
            elif hexagon.y > HEIGHT:
                hexagon.y = -1
            elif circle.y > HEIGHT:
                circle.y = -1

    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
           run = False
    star.y += 2
    triangle.y += 2
    rectangle.y += 2
    square.y += 2
    hexagon.y += 2
    circle.y += 2
    draw_window_one(star, triangle, rectangle, square, hexagon, circle)

    pygame.quit()

    if __name__ == "__main__":
        main()
</code>```

答:
if you want to stop after 10 seconds, consider a comparison

from datetime import datetime, timedelta
import sys
import time

start = datetime.now()

while datetime.now() - start < timedelta(seconds=10):
    # your thing
    sys.stdout.write("\r")
    sys.stdout.write(f"{datetime.now() - start}")

```

Body:
I am trying to run my program with a timer so that it will stop after 10 seconds but having problems with my iterating through it, so far I've tried using 2 while loops and a while loop within a for loop but have not come right. The program essentially makes shapes fall from top to bottom of the screen but I want it to stop after 10 seconds.

def main():
    star = pygame.Rect(75, 0, WIDTH, HEIGHT)
    triangle = pygame.Rect(575, 0, WIDTH, HEIGHT)
    rectangle = pygame.Rect(175, 0, WIDTH, HEIGHT)
    square = pygame.Rect(275, 0, WIDTH, HEIGHT)
    hexagon = pygame.Rect(375, 0, WIDTH, HEIGHT)
    circle = pygame.Rect(475, 0, WIDTH, HEIGHT)

    clock = pygame.time.Clock()
    for i in range (10,0,-1):
        time.sleep(1)
        run = True
        while run:
            if star.y > HEIGHT:
                star.y = -1
            elif triangle.y > HEIGHT:
                triangle.y = -1
            elif rectangle.y > HEIGHT:
                rectangle.y = -1
            elif square.y > HEIGHT:
                square.y = -1
            elif hexagon.y > HEIGHT:
                hexagon.y = -1
            elif circle.y > HEIGHT:
                circle.y = -1

    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
           run = False
    star.y += 2
    triangle.y += 2
    rectangle.y += 2
    square.y += 2
    hexagon.y += 2
    circle.y += 2
    draw_window_one(star, triangle, rectangle, square, hexagon, circle)

    pygame.quit()

    if __name__ == "__main__":
        main()


问:
perform patch request using trestclient component which contains json object in request
I'm trying to call trestClient component in talend.
But trestClient is failing with error message of "javax.ws.rs.WebApplicationException: HTTP 415 Unsupported Media Type".

i'm trying to pass json request to trestclient component.
Job

Error

Request

From textracJson component ,extracting recordiD and json object to pass to trestClient component.

答: The issue is caused by the tExtractJSONField component. You want to pass JSON into your tRestClient component, but tExtractJSON reads your JSON from the previous tWriteJSONField component converts it back to a Talend data flow. Remove this component and connect tWriteJSONField to tRestClient directly and connect your schema accordingly (check the input schema in tRestClient to see they're connected and have the right data types). To ensure this, best is to use a tMap with output string and map the JSON as a string to that column.


问:
Custom protocol handler in chrome
How do i set up a custom protocol handler in chrome? Something like:

myprotocol://testfile

I would need this to send a request to http://example.com?query=testfile, then send the httpresponse to my extension.

答:
Chrome 13 now supports the navigator.registerProtocolHandler API. For example,

```<code>navigator.registerProtocolHandler(
    'web+custom', 'http://example.com/rph?q=%s', 'My App');
</code>```

Note that your protocol name has to start with web+, with a few exceptions for common ones (like mailto, etc). For more details, see: http://updates.html5rocks.com/2011/06/Registering-a-custom-protocol-handler

Title: Custom protocol handler in chrome

Body:
Chrome 13 now supports the navigator.registerProtocolHandler API. For example,

navigator.registerProtocolHandler(
    'web+custom', 'http://example.com/rph?q=%s', 'My App');

Note that your protocol name has to start with web+, with a few exceptions for common ones (like mailto, etc). For more details, see: http://updates.html5rocks.com/2011/06/Registering-a-custom-protocol-handler


答:
Instead of separate option params it may be better to just have one options param that takes a list. Then you can do this:</p>
```<code>def ask_question(question, options:list):
    #print the question onto the screen as well as numbered options
    print(question)
    for e, option in enumerate(options,1):
        print(f'{e}) {option}')

    #store answer under user_response
    user_response = input("Your answer: ")

    return user_response
</code>```

Title: How do I print something only when a given parameter does not equal an empty string

Body:
Instead of separate option params it may be better to just have one options param that takes a list. Then you can do this:

def ask_question(question, options:list):
    #print the question onto the screen as well as numbered options
    print(question)
    for e, option in enumerate(options,1):
        print(f'{e}) {option}')

    #store answer under user_response
    user_response = input("Your answer: ")

    return user_response


问:
ChartJs Get date from dropdown and then refresh Charts
I have a dashboard right now that produces graphs and data from the database based on the current year. I am trying to add a dropdownlist of years and then have the graphs in the dashboard change on the year select. I have 2 areas that have to change and I am having issues with getting the variable for the year in the URL. I dont want to post the whole script because it is lengthy. My dropdown works fine, I just cannot use the variable in the string.

This is how it is currently setup:
Inside a  $(document).ready(function () { }

```<code>    SalesByMonth()

    var Year = new Date().getFullYear()

    $('#year').change(function () {
        Year = document.getElementById("year").value;
        $("#year").val(" ");
        console.log(Year);
    });

    function SalesByMonth() {
        var Year = new Date().getFullYear()
        $.ajax({
            url: '@Url.Action("GetChartData", "Dashboard", new { Year = "Year" })',
</code>```

The variable "Year" is not seen by the function. Even if I put it in the function SalesByMonth

答:
After doing some searching I figured out what works.
First in my CHTML page I had to put this:

```<code>@{ var dates = DateTime.Now.Year.ToString(); }
</code>```

Because I could not get the JavaScript getFullYear() to work at all. It was always null. No matter how I tried to do it. Then I got my variable like this with the select function right below it:

```<code>   var currentYear = @dates;

    $('#year').change(function () {
        currentYear = document.getElementById("year").value;
        $("#year").val(" ");
        console.log(currentYear);
        SalesByMonth();
        Revenue();
    });
</code>```

Here is my selectlist:

```<code><div class="form-group sol-container">
   @Html.DropDownList("Year", null, new { @class = "sol-container-selection", id = "year" })
</div>
</code>```

Then in my ajax url I had to do this:

```<code>url: '@Url.Action("GetChartData", "Dashboard", new { Year = "year" })'.replace('year', currentYear),
</code>```

The call to SalesByMonth and Revenue functions in the .change function refreshes the charts with the current year.

And just to complete this to have the full code, here is my controller for the dropdown list.

```<code> AccountingEntities acct = new AccountingEntities();
 var list = acct.Transaction.Select(s => s.TransactionDate.Year).Distinct().OrderByDescending(s => s).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() });
 ViewBag.Year = list.Select(x => new SelectListItem
                                 {
                                    Value = x.Text,
                                    Text = x.Text
                                 }).ToList();
</code>```

Body:
I have a dashboard right now that produces graphs and data from the database based on the current year. I am trying to add a dropdownlist of years and then have the graphs in the dashboard change on the year select. I have 2 areas that have to change and I am having issues with getting the variable for the year in the URL. I dont want to post the whole script because it is lengthy. My dropdown works fine, I just cannot use the variable in the string.

This is how it is currently setup:
Inside a  $(document).ready(function () { }

    SalesByMonth()

    var Year = new Date().getFullYear()

    $('#year').change(function () {
        Year = document.getElementById("year").value;
        $("#year").val(" ");
        console.log(Year);
    });

    function SalesByMonth() {
        var Year = new Date().getFullYear()
        $.ajax({
            url: '@Url.Action("GetChartData", "Dashboard", new { Year = "Year" })',

The variable "Year" is not seen by the function. Even if I put it in the function SalesByMonth

Body:
After doing some searching I figured out what works.
First in my CHTML page I had to put this:

@{ var dates = DateTime.Now.Year.ToString(); }

Because I could not get the JavaScript getFullYear() to work at all. It was always null. No matter how I tried to do it. Then I got my variable like this with the select function right below it:

   var currentYear = @dates;

    $('#year').change(function () {
        currentYear = document.getElementById("year").value;
        $("#year").val(" ");
        console.log(currentYear);
        SalesByMonth();
        Revenue();
    });

Here is my selectlist:

<div class="form-group sol-container">
   @Html.DropDownList("Year", null, new { @class = "sol-container-selection", id = "year" })
</div>

Then in my ajax url I had to do this:

url: '@Url.Action("GetChartData", "Dashboard", new { Year = "year" })'.replace('year', currentYear),

The call to SalesByMonth and Revenue functions in the .change function refreshes the charts with the current year.

And just to complete this to have the full code, here is my controller for the dropdown list.

 AccountingEntities acct = new AccountingEntities();
 var list = acct.Transaction.Select(s => s.TransactionDate.Year).Distinct().OrderByDescending(s => s).Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() });
 ViewBag.Year = list.Select(x => new SelectListItem
                                 {
                                    Value = x.Text,
                                    Text = x.Text
                                 }).ToList();


问:
How can I build Maven dependencies from Ant Java classpath?
Using Maven Ant Tasks, I see lots of examples that build Ant classpath from Maven dependencies, but what about the other way round?

I have a carefully tuned Ant project that builds the Java task classpath from all the jars in my lib directory. How can I use Maven-Ant-tasks to use my classpath to build Maven dependencies?

I would rather not do each jar file individually (my last resort).
Is there a better way?

答: If you're working on converting from Ant to Maven, just bite the bullet and write out your <dependencies> section to match your ant classpath. You only have to do it once, and you'll thank yourself many times over.


问:
manipulating lists in python
Take three integers as input.

N1=123

N2=456

N3=789

Generate 4 digit password i.e. WXYZ.

Where

W is maximum digit of all the input numbers

X is the minimum of 100th position of all input numbers

Y is the minimum of 10th position of all input numbers

Z is the minimum of 1st position of all input numbers

Example:

N1=123

N2=456

N3=789

Password=WXYZ

W=maximum of 1,2,3,4,5,6,7,8,9 is 9

X= minimum of 1,4,7 is 1

Y=minimum of 2,5,8 is 2

Z=minimum of 3,6,9 is 3

4 digit password generated from given numbers is 9123

```<code>def add(x):
    a = []
    i = 2
    while x > 0:
        a[i] = x % 10
        x /= 10
        i -= 1
    return a

def password(x1, x2, x3):
    i = 0
    p = 0
    n = []

    n.append(add(x1))
    n.append(add(x2))
    n.append(add(x3))
    p = max(n) * 1000

    m = []
    for j in range(0, 9, 3):
        m.append(n[j])
    p += min(m) * 100

    m = []
    for j in range(1, 9, 3):
        m.append(n[j])
    p += min(m) * 10

    m = []
    for j in range(2, 9, 3):
        m.append(n[j])
    p += min(m)

    return p

print("Enter three numbers: ")
n1 = int(input())
n2 = int(input())
n3 = int(input())
print("Generated password: ", password(n1, n2, n3))

</code>```

I initially wrote this code in Java and it worked perfectly. I am trying to write it in Python and am getting this error. I'm new to Pythons so I'm not sure what I'm doing wrong. Please advice on how to correct my code.

a[i] = x % 10

IndexError: list assignment index out of range

p = max(n) * 1000

'>' not supported between instances of 'list' and 'int'

答:
Your function could be implemented as follows:

```<code>def password(n1='123', n2='456', n3='789'):
    w = max(map(int, n1 + n2 + n3))
    x = min(map(int, n1[0] + n2[0] + n3[0]))
    y = min(map(int, n1[1] + n2[1] + n3[1]))
    z = min(map(int, n1[2] + n2[2] + n3[2]))
    return f"{w}{x}{y}{z}"

print(password())
</code>```

Out:

```<code>9123
</code>```

Title: manipulating lists in python

Body:
Take three integers as input.

N1=123

N2=456

N3=789

Generate 4 digit password i.e. WXYZ.

Where

W is maximum digit of all the input numbers

X is the minimum of 100th position of all input numbers

Y is the minimum of 10th position of all input numbers

Z is the minimum of 1st position of all input numbers

Example:

N1=123

N2=456

N3=789

Password=WXYZ

W=maximum of 1,2,3,4,5,6,7,8,9 is 9

X= minimum of 1,4,7 is 1

Y=minimum of 2,5,8 is 2

Z=minimum of 3,6,9 is 3

4 digit password generated from given numbers is 9123

def add(x):
    a = []
    i = 2
    while x > 0:
        a[i] = x % 10
        x /= 10
        i -= 1
    return a

def password(x1, x2, x3):
    i = 0
    p = 0
    n = []

    n.append(add(x1))
    n.append(add(x2))
    n.append(add(x3))
    p = max(n) * 1000

    m = []
    for j in range(0, 9, 3):
        m.append(n[j])
    p += min(m) * 100

    m = []
    for j in range(1, 9, 3):
        m.append(n[j])
    p += min(m) * 10

    m = []
    for j in range(2, 9, 3):
        m.append(n[j])
    p += min(m)

    return p

print("Enter three numbers: ")
n1 = int(input())
n2 = int(input())
n3 = int(input())
print("Generated password: ", password(n1, n2, n3))

I initially wrote this code in Java and it worked perfectly. I am trying to write it in Python and am getting this error. I'm new to Pythons so I'm not sure what I'm doing wrong. Please advice on how to correct my code.

a[i] = x % 10

IndexError: list assignment index out of range

p = max(n) * 1000

'>' not supported between instances of 'list' and 'int'

Body:
Your function could be implemented as follows:

def password(n1='123', n2='456', n3='789'):
    w = max(map(int, n1 + n2 + n3))
    x = min(map(int, n1[0] + n2[0] + n3[0]))
    y = min(map(int, n1[1] + n2[1] + n3[1]))
    z = min(map(int, n1[2] + n2[2] + n3[2]))
    return f"{w}{x}{y}{z}"

print(password())

Out:

9123


问:
Cannot Draw Canvas Image On Image's Load
I have a canvas and I wish to draw an icon on it. I'm aware you have to wait for the image to load before attempting to draw the image however nothing I've tried has worked.

I've attempted to use the full image URL (protocol, domain, and path), I've moved everything around, nothing has worked.

I've been Googling around for the better part of an hour and pretty much every solution involves making sure that the image loads first.

Here are a couple of snippets of what I have.

const image = new Image()
image.addEventListener('load', _ => {
    addImage(canvas, image, coords)
})
image.src = '/images/image-location.svg'
```
<pre class="lang-js prettyprint-override"><code>function addImage(canvas, image, coords) {
    const ctx = canvas.getContext('2d')
    ctx.save()
    ctx.drawImage(image, 0, 0, image.width, image.height, ...coords, 50, 50)
    ctx.restore()
}
</code>```

I threw a console.log within the event listener just to make sure it was firing and it does indeed fire. I even logged inside addImage and it definitely gets that far.

What is the solution to this?

答: I figured out the issue I was having here. I needed to add width/height attributes to the SVG element I was using as an image.

Body:
I have a canvas and I wish to draw an icon on it. I'm aware you have to wait for the image to load before attempting to draw the image however nothing I've tried has worked.

I've attempted to use the full image URL (protocol, domain, and path), I've moved everything around, nothing has worked.

I've been Googling around for the better part of an hour and pretty much every solution involves making sure that the image loads first.

Here are a couple of snippets of what I have.

const image = new Image()
image.addEventListener('load', _ => {
    addImage(canvas, image, coords)
})
image.src = '/images/image-location.svg'

function addImage(canvas, image, coords) {
    const ctx = canvas.getContext('2d')
    ctx.save()
    ctx.drawImage(image, 0, 0, image.width, image.height, ...coords, 50, 50)
    ctx.restore()
}

I threw a console.log within the event listener just to make sure it was firing and it does indeed fire. I even logged inside addImage and it definitely gets that far.

What is the solution to this?


答:
Here's an approach that might be considered more "Pythonic".

```<code>def digits(x):
    return list(map(int,str(x)))

def password(*args):
    n = list(map(digits,args))
    first = max([max(lst) for lst in n])
    lasts = [min(col) for col in zip(*n)]
    return str(first)+''.join(map(str,lasts))
</code>```

Example application: password(123,456,789) yields '9123'.

Title: manipulating lists in python

Body:
Here's an approach that might be considered more "Pythonic".

def digits(x):
    return list(map(int,str(x)))

def password(*args):
    n = list(map(digits,args))
    first = max([max(lst) for lst in n])
    lasts = [min(col) for col in zip(*n)]
    return str(first)+''.join(map(str,lasts))

Example application: password(123,456,789) yields '9123'.


问:
I get "_CastError (Null check operator used on a null value)" while trying to run the Flutter application
I am using the following code inside the onInit() method of my GetXController auth controller:

```<code>  Future<bool> autoLogin() async {
    final SharedPreferences? prefs = await SharedPreferences.getInstance();
    if (prefs == null ||   !prefs.containsKey('userData') ) {
      return false;
    } else {
      _isAuth.value = true;
    }
    final Map<String, Object> extractedUserData = Map<String, Object>.from(
        json.decode(prefs.getString('userData') as String));
    final expiryDate =
        DateTime.parse(extractedUserData['expiryDate'] as String);

    if (expiryDate.isBefore(DateTime.now())) {
      return false;
    }
    _token = extractedUserData['token'] as String;
    _userId = extractedUserData['userId'] as String;
    _expiryDate = expiryDate;
    _autoLogout();
    return true;
  }
</code>```

What I am trying to do is to check and see if there is any preferences stored in the storage from previous login and use it to log the user in if it is still valid. But I get the following error message when I try to run the application:

```<code>_CastError (Null check operator used on a null value)
</code>```

And the error comes from the following line of code:

```<code>final SharedPreferences? prefs = await SharedPreferences.getInstance();
</code>```

答: Try removing null checker and comparison of prefs == null

Body:
I am using the following code inside the onInit() method of my GetXController auth controller:

  Future<bool> autoLogin() async {
    final SharedPreferences? prefs = await SharedPreferences.getInstance();
    if (prefs == null ||   !prefs.containsKey('userData') ) {
      return false;
    } else {
      _isAuth.value = true;
    }
    final Map<String, Object> extractedUserData = Map<String, Object>.from(
        json.decode(prefs.getString('userData') as String));
    final expiryDate =
        DateTime.parse(extractedUserData['expiryDate'] as String);

    if (expiryDate.isBefore(DateTime.now())) {
      return false;
    }
    _token = extractedUserData['token'] as String;
    _userId = extractedUserData['userId'] as String;
    _expiryDate = expiryDate;
    _autoLogout();
    return true;
  }

What I am trying to do is to check and see if there is any preferences stored in the storage from previous login and use it to log the user in if it is still valid. But I get the following error message when I try to run the application:

_CastError (Null check operator used on a null value)

And the error comes from the following line of code:

final SharedPreferences? prefs = await SharedPreferences.getInstance();


问:
SimpleExoPlayer.Builder(this).build() deprecated
I'm using Exoplayer in my app and initializing exoplayer as

```<code>player = SimpleExoPlayer.Builder(this).build()
</code>```

But Android Studio is giving me warning as it is deprecated. When I get to the lower version of Exoplayer 2.15.1, then warning goes off. But in latest version 2.16.0, it is giving deprecation warning. How can we initialize exoplayer now with the latest version?

答:
In 2.16.1 do as following.

```<code>ExoPlayer player = new ExoPlayer.Builder(context).build();
</code>```

Pls see : https://exoplayer.dev/hello-world.html

Body:
I'm using Exoplayer in my app and initializing exoplayer as

player = SimpleExoPlayer.Builder(this).build()

But Android Studio is giving me warning as it is deprecated. When I get to the lower version of Exoplayer 2.15.1, then warning goes off. But in latest version 2.16.0, it is giving deprecation warning. How can we initialize exoplayer now with the latest version?

Body:
In 2.16.1 do as following.

ExoPlayer player = new ExoPlayer.Builder(context).build();

Pls see : https://exoplayer.dev/hello-world.html


问:
How do i display devise sign_up page error messages?
I have a problem that whenever iam trying to sign_up and leave all input fields empty i don't get any errors like "password can't be empty"..
but after refreshing the page and resubmit the same data i get the errors displayed on the page.. in short in order to display sign_up errors i have to refresh the sign_up page a couple of times .. how can i solve this issue? ..

Notice : i make sure that i have this line: <%= render "devise/shared/error_messages", resource: resource %> , in "views/devise/registrations/new.html.erb" file.

The devise shared error partial contains the following code:

```<code><% if resource.errors.any? %>

<%= I18n.t("errors.messages.not_saved",
count: resource.errors.count,
resource: resource.class.model_name.human.downcase)
%>
    <% resource.errors.full_messages.each do |message| %>
    <%= message %>
    <% end %>

<% end %>
</code>```

The form after being submitted there is no error messages displayed to me, but after refreshing the page a couple of times it redirects me to (/users), with the error messages displayed to me...so i have to refresh the page a couple of times to see the error messages..

答:
The solution for me:

I just changed one line of devise registration create action.

This is the creat method of devise registration controller:

```<code>  def create
    build_resource(sign_up_params)

    resource.save
    yield resource if block_given?
    if resource.persisted?
      if resource.active_for_authentication?
        set_flash_message! :notice, :signed_up
        sign_up(resource_name, resource)
        respond_with resource, location: after_sign_up_path_for(resource)
      else
        set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}"
        expire_data_after_sign_in!
        respond_with resource, location: after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource
      set_minimum_password_length
      respond_with resource
    end
  end
</code>```

I changed the last line respond_with resource to be render :new, status: 422

And this is the create action with the modification that I have made.

```<code>  def create
    build_resource(sign_up_params)

    resource.save
    yield resource if block_given?
    if resource.persisted?
      if resource.active_for_authentication?
        set_flash_message! :notice, :signed_up
        sign_up(resource_name, resource)
        respond_with resource, location: after_sign_up_path_for(resource)
      else
        set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}"
        expire_data_after_sign_in!
        respond_with resource, location: after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource
      set_minimum_password_length
      render :new, status: 422
    end
  end
</code>```

Body:
I have a problem that whenever iam trying to sign_up and leave all input fields empty i don't get any errors like "password can't be empty"..
but after refreshing the page and resubmit the same data i get the errors displayed on the page.. in short in order to display sign_up errors i have to refresh the sign_up page a couple of times .. how can i solve this issue? ..

Notice : i make sure that i have this line: <%= render "devise/shared/error_messages", resource: resource %> , in "views/devise/registrations/new.html.erb" file.

The devise shared error partial contains the following code:

<% if resource.errors.any? %>

<%= I18n.t("errors.messages.not_saved",
count: resource.errors.count,
resource: resource.class.model_name.human.downcase)
%>
    <% resource.errors.full_messages.each do |message| %>
    <%= message %>
    <% end %>

<% end %>

The form after being submitted there is no error messages displayed to me, but after refreshing the page a couple of times it redirects me to (/users), with the error messages displayed to me...so i have to refresh the page a couple of times to see the error messages..

Body:
The solution for me:

I just changed one line of devise registration create action.

This is the creat method of devise registration controller:

  def create
    build_resource(sign_up_params)

    resource.save
    yield resource if block_given?
    if resource.persisted?
      if resource.active_for_authentication?
        set_flash_message! :notice, :signed_up
        sign_up(resource_name, resource)
        respond_with resource, location: after_sign_up_path_for(resource)
      else
        set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}"
        expire_data_after_sign_in!
        respond_with resource, location: after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource
      set_minimum_password_length
      respond_with resource
    end
  end

I changed the last line respond_with resource to be render :new, status: 422

And this is the create action with the modification that I have made.

  def create
    build_resource(sign_up_params)

    resource.save
    yield resource if block_given?
    if resource.persisted?
      if resource.active_for_authentication?
        set_flash_message! :notice, :signed_up
        sign_up(resource_name, resource)
        respond_with resource, location: after_sign_up_path_for(resource)
      else
        set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}"
        expire_data_after_sign_in!
        respond_with resource, location: after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource
      set_minimum_password_length
      render :new, status: 422
    end
  end