问:
How exactly does //= require bootstrap/dist/css/bootstrap work?
I have this in my application.scss, but I don't understand how it works:

```<code>//= require bootstrap/dist/css/bootstrap
</code>```

What I do know:

Without it, the application doesn't get the boostrap styling added to the .css file.

I know require includes the css file that goes by the name of the argument in application's css.

I know it's conventional for these 'require' calls to be commented out, but I have no idea why, it's not a convention I've not seen anywhere else.

I've searched my entire application for directories similar to bootstrap/dist/css/bootstrap to figure out where the bootstrap css is coming from. But a search of the entire app doesn't reveal such directories (nor any files called bootstrap.css or bootstrap.scss).

The app I'm working on uses sprockets and webpacker. I think this syntax is unique to sprockets, although I'm not sure.

So TL;DR I understand what this line does, but could someone explain how //= require bootstrap/dist/css/bootstrap is working to get that css into the application?

答:
Just to add to @mechincov's answer. I still couldn't work out where this bootstrap file was actually coming from (since there was no bootstrap directory in my app, and definitely no file located at bootstrap/dist/css/bootstrap.css - none that I could find, anyway.

But I (sort of) figured out where it was coming from. I believe it's coming into the app via yarn.lock, which contains this:

```<code>bootstrap@^4.5.2:
  version "4.6.1"
  resolved "https://registry.yarnpkg.com/bootstrap/-/bootstrap-4.6.1.tgz#bc25380c2c14192374e8dec07cf01b2742d222a2"
  integrity sha512-0dj+VgI9Ecom+rvvpNZ4MUZJz8dcX7WCX+eTID9+/8HgOkv3dsRzi8BGeZJCQU6flWQVYxwTQnEZFrmJSEO7og==
</code>```

package.json also contains a reference to bootstrap (and associated libraries jQuery and popper), so perhaps that's where it originates:

```<code>  "dependencies": {
    "@rails/actioncable": "^6.0.0",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "5.4.3",
    "bootstrap": "^4.5.2",
    "jquery": "^3.5.1",
    "popper.js": "^1.16.1"
  }
</code>```

Body:
I have this in my application.scss, but I don't understand how it works:

//= require bootstrap/dist/css/bootstrap

What I do know:

Without it, the application doesn't get the boostrap styling added to the .css file.

I know require includes the css file that goes by the name of the argument in application's css.

I know it's conventional for these 'require' calls to be commented out, but I have no idea why, it's not a convention I've not seen anywhere else.

I've searched my entire application for directories similar to bootstrap/dist/css/bootstrap to figure out where the bootstrap css is coming from. But a search of the entire app doesn't reveal such directories (nor any files called bootstrap.css or bootstrap.scss).

The app I'm working on uses sprockets and webpacker. I think this syntax is unique to sprockets, although I'm not sure.

So TL;DR I understand what this line does, but could someone explain how //= require bootstrap/dist/css/bootstrap is working to get that css into the application?

Body:
Just to add to @mechincov's answer. I still couldn't work out where this bootstrap file was actually coming from (since there was no bootstrap directory in my app, and definitely no file located at bootstrap/dist/css/bootstrap.css - none that I could find, anyway.

But I (sort of) figured out where it was coming from. I believe it's coming into the app via yarn.lock, which contains this:

bootstrap@^4.5.2:
  version "4.6.1"
  resolved "https://registry.yarnpkg.com/bootstrap/-/bootstrap-4.6.1.tgz#bc25380c2c14192374e8dec07cf01b2742d222a2"
  integrity sha512-0dj+VgI9Ecom+rvvpNZ4MUZJz8dcX7WCX+eTID9+/8HgOkv3dsRzi8BGeZJCQU6flWQVYxwTQnEZFrmJSEO7og==

package.json also contains a reference to bootstrap (and associated libraries jQuery and popper), so perhaps that's where it originates:

  "dependencies": {
    "@rails/actioncable": "^6.0.0",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "5.4.3",
    "bootstrap": "^4.5.2",
    "jquery": "^3.5.1",
    "popper.js": "^1.16.1"
  }


来源: stackexchange

问:
Git branching strategy - losing changes on merge
We've got a branching strategy with develop, release, and master branches.  Features/bugs branch off of release.
When complete, they merge into develop for QA testing.  Once QA passes, they merge (directly from the feature/bug branch) into release for release regression testing.  Release merges to master after final regression testing.  Hotfixes branch off master, merge back into master.

With all that said, we are sometimes losing changes in release and QA when merging branches in.  Developers are merging from release into their branches prior to merging into QA and release, but never merging in from QA.

Are there any conceptual issues with this strategy?  Any potential reasons why we may be losing those changes?

答:
Your strategy is sound, and has a name: gitworkflow, which allows to merge only the feature branch you want/need in QA or release (instead of merging everything from QA to release)

But that does not account for any "lost changes": that would be caused by merge conflict resolution which somehow keep one change and override another concurrent change.

Developers are merging from release into their branches

That is the only flaw I can see. No merge is ever made from release or master. Those are branches you merge to, not from.

The best practice is to rebase a dev branch on top of their intended merge target (QA or release), and then merge them.

ContentLicense: CC BY-SA 4.0


问:
How can I make a saving code faster? -MatLab
I'm running a short code to open one by one a list of files and saving back only one of the variables contained in the files. The process seems to me much slower than I expected and getting slower with time, I don't fully understand why and how I could make it run faster. I always struggle with optimization. I'd appreciate if you have suggestions.

The code is the following (the ... substitute the actual path just for example):

```<code>main_dir=dir(strcat('\\storage2-...\Raw\DAQ5\'));

filename={};
for m=7:size(main_dir,1)
    m
    second_dir=dir([main_dir(m).folder '\' main_dir(m).name '\*.mat']);
    for mm=1:numel(second_dir)
        filename{end+1}=[second_dir(mm).folder '\' second_dir(mm).name];
        for mmm=1:numel(filename)
            namefile=sprintf(second_dir(mm,1).name);
            load(string(filename(1,mmm)));
            save(['\\storage2-...\DAQ5\Ch1_',namefile(end-18:end-4),'.mat'], 'Ch_1_y')
        end
    end
end
</code>```

The original file is about 17 MB and once the single variable is saved it is about 6 MB in size.

答:
The Matlab load function takes an optional additional argument to specify just a selected variable to read from the input file.

```<code>s = load('path/to/file.mat', 'Ch_1_y');
</code>```

That way you don't have to spend time loading in all the other variables from those input .mat files that you're just going to immediately throw away.

And using save to save MAT-files over SMB shares can be slow. You might want to call save to write it to a temporary local file first, and then copy the completed file to the final destination. Sounds like more I/O, but it can actually be a net win, depending on your particular system and network. Measure it both ways to see if it's a win in your particular situation.

Body:
I'm running a short code to open one by one a list of files and saving back only one of the variables contained in the files. The process seems to me much slower than I expected and getting slower with time, I don't fully understand why and how I could make it run faster. I always struggle with optimization. I'd appreciate if you have suggestions.

The code is the following (the ... substitute the actual path just for example):

main_dir=dir(strcat('\\storage2-...\Raw\DAQ5\'));

filename={};
for m=7:size(main_dir,1)
    m
    second_dir=dir([main_dir(m).folder '\' main_dir(m).name '\*.mat']);
    for mm=1:numel(second_dir)
        filename{end+1}=[second_dir(mm).folder '\' second_dir(mm).name];
        for mmm=1:numel(filename)
            namefile=sprintf(second_dir(mm,1).name);
            load(string(filename(1,mmm)));
            save(['\\storage2-...\DAQ5\Ch1_',namefile(end-18:end-4),'.mat'], 'Ch_1_y')
        end
    end
end

The original file is about 17 MB and once the single variable is saved it is about 6 MB in size.

Body:
The Matlab load function takes an optional additional argument to specify just a selected variable to read from the input file.

s = load('path/to/file.mat', 'Ch_1_y');

That way you don't have to spend time loading in all the other variables from those input .mat files that you're just going to immediately throw away.

And using save to save MAT-files over SMB shares can be slow. You might want to call save to write it to a temporary local file first, and then copy the completed file to the final destination. Sounds like more I/O, but it can actually be a net win, depending on your particular system and network. Measure it both ways to see if it's a win in your particular situation.


问:
turn several line function into a one liner list format
I am learning and I am trying to make this code nicer and learn more in pythonic way! I wanna turn this code into a one line code inside list (list comprehension). e.g., [here goes the new implementation]</p>
```<code>def main():
    inp = input()
    x = []
    x_tm = ''
    for i in range( 0, len(inp)):
        if inp[i] == ',':
            x.append(x_tm)
            x_tm = ""
            continue
        if inp[i] ==" ":
            continue
        x_tm += inp[i]
    x.append(inp)

</code>```

答:
Your function reads a line, then computes something from it without printing, returning, or any other kind of "output". Hence here's an equivalent one liner:</p>
```<code>main = input
</code>```

Body:
I am learning and I am trying to make this code nicer and learn more in pythonic way! I wanna turn this code into a one line code inside list (list comprehension). e.g., [here goes the new implementation]

def main():
    inp = input()
    x = []
    x_tm = ''
    for i in range( 0, len(inp)):
        if inp[i] == ',':
            x.append(x_tm)
            x_tm = ""
            continue
        if inp[i] ==" ":
            continue
        x_tm += inp[i]
    x.append(inp)

Body:
Your function reads a line, then computes something from it without printing, returning, or any other kind of "output". Hence here's an equivalent one liner:

main = input


问:
Sum two columns to a third one of DataGridView. How?
How can I sum the values of two dataGridView columns and store the result in a third column for each row ? </p>

答: Do what ever the calculations you want in the dataSource and bind it after calculating values.</p>

ContentLicense: CC BY-SA 3.0


问:
How to do forward fill as a PL/PGSQL function
I am trying to create a pl/pgsql equivalent to the pandas 'ffill' function. The function should forward fill null values. In the example I can do a forward fill but I get errors when I try to create a function from my procedure. The function seems to reflect exactly the procedure but I get a syntax error at the portion ... as $1.

Why? What should I be reading to clarify?

```<code>-- Forward fill experiment
DROP TABLE IF EXISTS example;
create temporary table example(id int, str text, val integer);
insert into example values
(1, 'a', null),
(1, null, 1),
(2, 'b', 2),
(2,null ,null );

select * from example

select (case
            when str is null
            then lag(str,1) over (order by id)
            else str
            end) as str,
            (case
            when val is null
            then lag(val,1) over (order by id)
            else val
            end) as val
from example

-- Forward fill function
create or replace function ffill(text, text, text) -- takes column to fill, the table, and the ordering column
returns text as $$
    begin
        select (case
            when $1 is null
            then lag($1 ,1) over (order by $3)
            else $1
            end) as $1
        from $2;
    end;
$$ LANGUAGE plpgsql;
</code>```

Update 1:   I did some additional experimenting taking a different approach.  The code is below.  It uses the same example table as above.

```<code>CREATE OR REPLACE FUNCTION GapFillInternal(
    s anyelement,
    v anyelement) RETURNS anyelement AS
$$
declare
    temp alias for $0 ;
begin
    RAISE NOTICE 's= %, v= %', s, v;
    if v is null and s notnull then
        temp := s;
    elsif s is null and v notnull then
        temp := v;
    elsif s notnull and v notnull then
        temp := v;
    else
        temp := null;
    end if;
    RAISE NOTICE 'temp= %', temp;
    return temp;
END;
$$ LANGUAGE PLPGSQL;

CREATE AGGREGATE GapFill(anyelement) (
  SFUNC=GapFillInternal,
  STYPE=anyelement
);

select id, str, val, GapFill(val) OVER (ORDER by id) as valx
from example;
</code>```

The resulting table is this:

I don't understand where the '1' in the first row of valx column comes from. From the raise notice output it should be Null and that seems a correct expectation from the CREATE AGGREGATE docs.

答:
Correct call

Seems like your displayed query is incorrect, and the test case is just too reduced to show it.

Assuming you want to "forward fill" partitioned by id, you'll have to say so:

SELECT row_num, id
     , str, gap_fill(str) OVER w AS strx
     , val, gap_fill(val) OVER w AS valx
FROM   example
WINDOW w AS (PARTITION BY id ORDER BY row_num);  -- !
```
<p>The <code>WINDOW</code> clause is just a syntactical convenience to avoid spelling out the same window frame repeatedly. The important part is the added <code>PARTITION</code> clause.</p>
<h3>Simpler function</h3>
<p>Much simpler, actually:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE OR REPLACE FUNCTION gap_fill_internal(s anyelement, v anyelement)
  RETURNS anyelement
  LANGUAGE plpgsql AS
$func$
BEGIN
RETURN COALESCE(v, s);  -- that's all!
END
$func$;

CREATE AGGREGATE gap_fill(anyelement) (
  SFUNC = gap_fill_internal,
  STYPE = anyelement
);
</code>```

Slightly faster in a quick test.

Standard SQL

Without custom function:

SELECT row_num, id
     , str, first_value(str) OVER (PARTITION BY id, ct_str ORDER BY row_num) AS strx
     , val, first_value(val) OVER (PARTITION BY id, ct_val ORDER BY row_num) AS valx
FROM (
   SELECT *, count(str) OVER w AS ct_str, count(val) OVER w AS ct_val
   FROM   example
   WINDOW w AS (PARTITION BY id ORDER BY row_num)
   ) sub;
```

The query becomes more complex with a subquery. Performance is similar. Slightly slower in a quick test.

More explanation in these related answers:

Carry over long sequence of missing values with Postgres

Retrieve last known value for each column of a row

SQL group table by "leading rows" without pl/sql

db<>fiddle here - showing all with extended test case

Body:
I am trying to create a pl/pgsql equivalent to the pandas 'ffill' function. The function should forward fill null values. In the example I can do a forward fill but I get errors when I try to create a function from my procedure. The function seems to reflect exactly the procedure but I get a syntax error at the portion ... as $1.

Why? What should I be reading to clarify?

-- Forward fill experiment
DROP TABLE IF EXISTS example;
create temporary table example(id int, str text, val integer);
insert into example values
(1, 'a', null),
(1, null, 1),
(2, 'b', 2),
(2,null ,null );

select * from example

select (case
            when str is null
            then lag(str,1) over (order by id)
            else str
            end) as str,
            (case
            when val is null
            then lag(val,1) over (order by id)
            else val
            end) as val
from example

-- Forward fill function
create or replace function ffill(text, text, text) -- takes column to fill, the table, and the ordering column
returns text as $$
    begin
        select (case
            when $1 is null
            then lag($1 ,1) over (order by $3)
            else $1
            end) as $1
        from $2;
    end;
$$ LANGUAGE plpgsql;

Update 1:   I did some additional experimenting taking a different approach.  The code is below.  It uses the same example table as above.

CREATE OR REPLACE FUNCTION GapFillInternal(
    s anyelement,
    v anyelement) RETURNS anyelement AS
$$
declare
    temp alias for $0 ;
begin
    RAISE NOTICE 's= %, v= %', s, v;
    if v is null and s notnull then
        temp := s;
    elsif s is null and v notnull then
        temp := v;
    elsif s notnull and v notnull then
        temp := v;
    else
        temp := null;
    end if;
    RAISE NOTICE 'temp= %', temp;
    return temp;
END;
$$ LANGUAGE PLPGSQL;

CREATE AGGREGATE GapFill(anyelement) (
  SFUNC=GapFillInternal,
  STYPE=anyelement
);

select id, str, val, GapFill(val) OVER (ORDER by id) as valx
from example;

The resulting table is this:

I don't understand where the '1' in the first row of valx column comes from. From the raise notice output it should be Null and that seems a correct expectation from the CREATE AGGREGATE docs.

Body:
Correct call

Seems like your displayed query is incorrect, and the test case is just too reduced to show it.

Assuming you want to "forward fill" partitioned by id, you'll have to say so:

SELECT row_num, id
     , str, gap_fill(str) OVER w AS strx
     , val, gap_fill(val) OVER w AS valx
FROM   example
WINDOW w AS (PARTITION BY id ORDER BY row_num);  -- !

The WINDOW clause is just a syntactical convenience to avoid spelling out the same window frame repeatedly. The important part is the added PARTITION clause.

Simpler function

Much simpler, actually:

CREATE OR REPLACE FUNCTION gap_fill_internal(s anyelement, v anyelement)
  RETURNS anyelement
  LANGUAGE plpgsql AS
$func$
BEGIN
RETURN COALESCE(v, s);  -- that's all!
END
$func$;

CREATE AGGREGATE gap_fill(anyelement) (
  SFUNC = gap_fill_internal,
  STYPE = anyelement
);

Slightly faster in a quick test.

Standard SQL

Without custom function:

SELECT row_num, id
     , str, first_value(str) OVER (PARTITION BY id, ct_str ORDER BY row_num) AS strx
     , val, first_value(val) OVER (PARTITION BY id, ct_val ORDER BY row_num) AS valx
FROM (
   SELECT *, count(str) OVER w AS ct_str, count(val) OVER w AS ct_val
   FROM   example
   WINDOW w AS (PARTITION BY id ORDER BY row_num)
   ) sub;

The query becomes more complex with a subquery. Performance is similar. Slightly slower in a quick test.

More explanation in these related answers:

Carry over long sequence of missing values with Postgres

Retrieve last known value for each column of a row

SQL group table by "leading rows" without pl/sql

db<>fiddle here - showing all with extended test case


问:
Why and when to add element to the end of singly linked list?
Is there any reason to add element to the end of a singly linked list instead of adding to the beginning? Adding to the end you have to traverse the whole list every time so the bigger the list gets the more time it takes to add a new item.</p>

答: Yes. For example, if you're keeping the list sorted, you might need to insert your new node at any point, including at the end.</p>


问:
How to store fixed length strings inside a std::vector
I want to mimic a structure:

```<code>char [][40] = { "Stack", "Overflow", "Exchange", "Network" };
</code>```

using a std::vector, so I can populate it at runtime and dynamically change the size of the vector, but keeping the member elements located inside fixed size blocks.

Static initialization is not my question - I can do that using boost::assign or other tricks.

答:
Parapura's answer is correct, but you will be storing the pointers to the strings. If the original character array falls out of scope you will lose the information posted. If this vector is used elsewhere, it should allocate (and deallocate!) it's own memory. This can be done when the input is taken.

Here's a sample program that does that.

```<code>#include <vector>
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using std::vector;

int main()
{
    int numEntries = 4;
    const int strlen = 40;

    // Parapura's correct answer, but let's expand this further
    vector<char*> strvec;
    char* input = 0;
    int i;

    cout << "Enter four names." << endl;
    for (i=0; i<numEntries; i++)
    {
        // Allocate some memory to store in the vector
        input = new char[strlen];
        cout << "Name: ";
        cin.get(input, strlen);
        cin.ignore(strlen, '\n');

        // Push the populated memory into the vector.
        // Now we can let 'input' fall out of scope.
        strvec.push_back(input);
    }
    cout << endl;

    /* -- cool code here! -- */

    cout << "List of names." << endl;
    for (i=0; i<numEntries; i++)
    {
        cout << strvec[i] << endl;
    }

    /* -- more cool code! -- */

    // don't forget to clean up!
    for (i=0; i<numEntries; i++)
    {
        delete[] strvec[i];
    }

    return 0;
}
</code>```

Body:
I want to mimic a structure:

char [][40] = { "Stack", "Overflow", "Exchange", "Network" };

using a std::vector, so I can populate it at runtime and dynamically change the size of the vector, but keeping the member elements located inside fixed size blocks.

Static initialization is not my question - I can do that using boost::assign or other tricks.

Body:
Parapura's answer is correct, but you will be storing the pointers to the strings. If the original character array falls out of scope you will lose the information posted. If this vector is used elsewhere, it should allocate (and deallocate!) it's own memory. This can be done when the input is taken.

Here's a sample program that does that.

#include <vector>
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using std::vector;

int main()
{
    int numEntries = 4;
    const int strlen = 40;

    // Parapura's correct answer, but let's expand this further
    vector<char*> strvec;
    char* input = 0;
    int i;

    cout << "Enter four names." << endl;
    for (i=0; i<numEntries; i++)
    {
        // Allocate some memory to store in the vector
        input = new char[strlen];
        cout << "Name: ";
        cin.get(input, strlen);
        cin.ignore(strlen, '\n');

        // Push the populated memory into the vector.
        // Now we can let 'input' fall out of scope.
        strvec.push_back(input);
    }
    cout << endl;

    /* -- cool code here! -- */

    cout << "List of names." << endl;
    for (i=0; i<numEntries; i++)
    {
        cout << strvec[i] << endl;
    }

    /* -- more cool code! -- */

    // don't forget to clean up!
    for (i=0; i<numEntries; i++)
    {
        delete[] strvec[i];
    }

    return 0;
}


问:
How to configure proxy in emulators in new versions of Android Studio?

Problem Description

I need to configure the proxy manually in my emulator through Android Studio. From the official Android documentation, it is suggested that this change can be made in the "settings" tab of the emulator's extended controls. The problem is that it seems to me that this documentation is outdated, as this setting is no longer displayed in the "settings" tab of the Android Studio emulators' extended controls.

Documentation

My Android Studio

My version of Android Studio

```<code>Android Studio Bumblebee | 2021.1.1
Build #AI-211.7628.21.2111.8092744, built on January 19, 2022
Runtime version: 11.0.11+9-b60-7590822 amd64
VM: OpenJDK 64-Bit Server VM by Oracle Corporation
Windows 10 10.0
GC: G1 Young Generation, G1 Old Generation
Memory: 1280M
Cores: 8
Registry: external.system.auto.import.disabled=true
Non-Bundled Plugins: com.wakatime.intellij.plugin (13.1.10), wu.seal.tool.jsontokotlin (3.7.2), org.jetbrains.kotlin (211-1.6.10-release-923-AS7442.40), com.developerphil.adbidea (1.6.4), org.jetbrains.compose.desktop.ide (1.0.0), ru.adelf.idea.dotenv (2021.2), org.intellij.plugins.markdown (211.7142.37)
</code>```

答:
After a while trying to find solutions to this problem, I saw that an emulator running outside android studio provides these options. To run a standalone Android Studio emulator see the official documentation or simply enter the command:

```<code>emulator -avd <avd_name>
</code>```

In my case I'm using an avd named PIXEL 4 API 30, so the command will be emulator -avd PIXEL_4_API_30. If you are on Windows you may have problems running this command so I suggest you see this.

Edit

The solution proposed by @Inliner also solves this problem.

Body:
Problem Description

I need to configure the proxy manually in my emulator through Android Studio. From the official Android documentation, it is suggested that this change can be made in the "settings" tab of the emulator's extended controls. The problem is that it seems to me that this documentation is outdated, as this setting is no longer displayed in the "settings" tab of the Android Studio emulators' extended controls.

Documentation

My Android Studio

My version of Android Studio

Android Studio Bumblebee | 2021.1.1
Build #AI-211.7628.21.2111.8092744, built on January 19, 2022
Runtime version: 11.0.11+9-b60-7590822 amd64
VM: OpenJDK 64-Bit Server VM by Oracle Corporation
Windows 10 10.0
GC: G1 Young Generation, G1 Old Generation
Memory: 1280M
Cores: 8
Registry: external.system.auto.import.disabled=true
Non-Bundled Plugins: com.wakatime.intellij.plugin (13.1.10), wu.seal.tool.jsontokotlin (3.7.2), org.jetbrains.kotlin (211-1.6.10-release-923-AS7442.40), com.developerphil.adbidea (1.6.4), org.jetbrains.compose.desktop.ide (1.0.0), ru.adelf.idea.dotenv (2021.2), org.intellij.plugins.markdown (211.7142.37)

Body:
After a while trying to find solutions to this problem, I saw that an emulator running outside android studio provides these options. To run a standalone Android Studio emulator see the official documentation or simply enter the command:

emulator -avd <avd_name>

In my case I'm using an avd named PIXEL 4 API 30, so the command will be emulator -avd PIXEL_4_API_30. If you are on Windows you may have problems running this command so I suggest you see this.

Edit

The solution proposed by @Inliner also solves this problem.


问:
Python 3, find nearest timedate value
I hope to find help here, I am new to python and I want to extract time from 2 different nc file with different time structures.
The first nc file stored time and date information as:

```<code>year: 2009
month: 10
day: 12
hour: 20
minute: 10
second: 4.0
</code>```

and the second nc file time and date is in "unix epoch time" format for n event (i.e, this nc file contains several timedate information in float64 time(n_event))

What I want to do is to find nearest time from the second nc file to the first nc file time.

I have tried this code for the first nc file:

```<code>    #time
hour=(nc.__dict__['hour'])
minute=(nc.__dict__['minute'])
second=(nc.__dict__['second'])
    #time= hour,minute,second
time= str(hour)+':'+str(minute)+':'+str(second)

    #date
year_nc=(nc.__dict__['year'])
month_nc=(nc.__dict__['month'])
day_nc=(nc.__dict__['day'])
date_nc= year_nc,month_nc,day_nc
#solved-not used

date_nc_arr = np.array(date_nc)
time_nc_arr = np.array(time)

time_nc_arr
date_nc_arr

full_date_nc_arr=[date_nc_arr,time_nc_arr]
full_date_nc_arr
</code>```

and I get

```<code>[array([2009,   10,   12], dtype=int32), array('20:10:4.0', dtype='<U9')]
</code>```

and for the second nc file I did:

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

import datetime
from netCDF4 import Dataset,num2date

t_unit = nc2.variables['time'].units # get unit
t_cal = nc2.variables['time'].calendar
tvalue = num2date(timess,units = t_unit,calendar = t_cal)
str_time = [i.strftime("%Y-%m-%d %H:%M:%S") for i in tvalue]

str_time = list(map(lambda x: datetime.datetime.strptime(x,  "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d %I:%M:%S"), str_time))
print(str_time)
</code>```

and the output is something like: (I just paste some of the time here)

```<code>['2009-10-12 09:19:25', '2009-10-12 09:24:15', '2009-10-12 09:25:03', '2009-10-12 09:26:37', '2009-10-12 09:31:48', '2009-10-12 09:36:13', '2009-10-12 09:40:46', '2009-10-12 09:41:28', '2009-10-12 09:42:13', '2009-10-12 09:46:14', '2009-10-12 09:47:18', '2009-10-12 09:54:58', '2009-10-12 10:03:07', '2009-10-12 10:09:10', '2009-10-12 10:14:54', '2009-10-12 10:15:34', '2009-10-12 10:16:49', '2009-10-12 10:18:29', '2009-10-12 10:18:59', '2009-10-12 10:20:13', '2009-10-12 10:26:12', '2009-10-12 10:26:14', '2009-10-12 10:32:02', '2009-10-12 10:34:28', '2009-10-12 10:34:42', '2009-10-12 10:35:34', '2009-10-12 10:36:30', '2009-10-12 10:40:35', '2009-10-12 10:47:22', '2009-10-12 10:56:07', '2009-10-12 10:57:02', '2009-10-12 10:59:33', '2009-10-12 11:00:26', '2009-10-12 11:14:17', '2009-10-12 11:14:55', '2009-10-12 11:21:07', '2009-10-12 11:27:10', '2009-10-12 11:27:39', '2009-10-12 11:36:08', '2009-10-12 11:36:58', '2009-10-12 11:40:28', '2009-10-12 11:42:02', '2009-10-12 11:46:35', '2009-10-12 11:48:31', '2009-10-12 11:50:13', '2009-10-12 11:52:06']
</code>```

but when I try to find the nearest timedate value of the first nc file to the second nc file:

```<code>def find_nearest(array, value):
    array = np.asarray(array)
    idx = (np.abs(array - value)).argmin()
    return array[idx]

array = str_time
value = full_date_nc_arr

print(find_nearest(array, value))
</code>```

I get several different errors like:

ValueError: operands could not be broadcast together with shapes (463,) (6,)

I will really appreciate it if anyone can give me a solution or better approach to solve this problem.

答:
If you have date/time data, then use a datetime object.

```<code>from datetime import datetime
t1 = datetime(
    nc.year, nc.month, nc.day,
    nc.hour, nc.minute, nc.second
)
</code>```

That's all it takes.  If you really do have a Unit time_t value, that's

```<code>t2 = datetime.fromtimestamp( epoch )
</code>```

Now you have datetime objects you can compare directly.  I'm not sure numpy is really required for this, although it does understand datetime values.

Title: Python 3, find nearest timedate value

Body:
I hope to find help here, I am new to python and I want to extract time from 2 different nc file with different time structures.
The first nc file stored time and date information as:

year: 2009
month: 10
day: 12
hour: 20
minute: 10
second: 4.0

and the second nc file time and date is in "unix epoch time" format for n event (i.e, this nc file contains several timedate information in float64 time(n_event))

What I want to do is to find nearest time from the second nc file to the first nc file time.

I have tried this code for the first nc file:

    #time
hour=(nc.__dict__['hour'])
minute=(nc.__dict__['minute'])
second=(nc.__dict__['second'])
    #time= hour,minute,second
time= str(hour)+':'+str(minute)+':'+str(second)

    #date
year_nc=(nc.__dict__['year'])
month_nc=(nc.__dict__['month'])
day_nc=(nc.__dict__['day'])
date_nc= year_nc,month_nc,day_nc
#solved-not used

date_nc_arr = np.array(date_nc)
time_nc_arr = np.array(time)

time_nc_arr
date_nc_arr

full_date_nc_arr=[date_nc_arr,time_nc_arr]
full_date_nc_arr

and I get

[array([2009,   10,   12], dtype=int32), array('20:10:4.0', dtype='<U9')]

and for the second nc file I did:

from datetime import datetime
import datetime

import datetime
from netCDF4 import Dataset,num2date

t_unit = nc2.variables['time'].units # get unit
t_cal = nc2.variables['time'].calendar
tvalue = num2date(timess,units = t_unit,calendar = t_cal)
str_time = [i.strftime("%Y-%m-%d %H:%M:%S") for i in tvalue]

str_time = list(map(lambda x: datetime.datetime.strptime(x,  "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d %I:%M:%S"), str_time))
print(str_time)

and the output is something like: (I just paste some of the time here)

['2009-10-12 09:19:25', '2009-10-12 09:24:15', '2009-10-12 09:25:03', '2009-10-12 09:26:37', '2009-10-12 09:31:48', '2009-10-12 09:36:13', '2009-10-12 09:40:46', '2009-10-12 09:41:28', '2009-10-12 09:42:13', '2009-10-12 09:46:14', '2009-10-12 09:47:18', '2009-10-12 09:54:58', '2009-10-12 10:03:07', '2009-10-12 10:09:10', '2009-10-12 10:14:54', '2009-10-12 10:15:34', '2009-10-12 10:16:49', '2009-10-12 10:18:29', '2009-10-12 10:18:59', '2009-10-12 10:20:13', '2009-10-12 10:26:12', '2009-10-12 10:26:14', '2009-10-12 10:32:02', '2009-10-12 10:34:28', '2009-10-12 10:34:42', '2009-10-12 10:35:34', '2009-10-12 10:36:30', '2009-10-12 10:40:35', '2009-10-12 10:47:22', '2009-10-12 10:56:07', '2009-10-12 10:57:02', '2009-10-12 10:59:33', '2009-10-12 11:00:26', '2009-10-12 11:14:17', '2009-10-12 11:14:55', '2009-10-12 11:21:07', '2009-10-12 11:27:10', '2009-10-12 11:27:39', '2009-10-12 11:36:08', '2009-10-12 11:36:58', '2009-10-12 11:40:28', '2009-10-12 11:42:02', '2009-10-12 11:46:35', '2009-10-12 11:48:31', '2009-10-12 11:50:13', '2009-10-12 11:52:06']

but when I try to find the nearest timedate value of the first nc file to the second nc file:

def find_nearest(array, value):
    array = np.asarray(array)
    idx = (np.abs(array - value)).argmin()
    return array[idx]

array = str_time
value = full_date_nc_arr

print(find_nearest(array, value))

I get several different errors like:

ValueError: operands could not be broadcast together with shapes (463,) (6,)

I will really appreciate it if anyone can give me a solution or better approach to solve this problem.

Body:
If you have date/time data, then use a datetime object.

from datetime import datetime
t1 = datetime(
    nc.year, nc.month, nc.day,
    nc.hour, nc.minute, nc.second
)

That's all it takes.  If you really do have a Unit time_t value, that's

t2 = datetime.fromtimestamp( epoch )

Now you have datetime objects you can compare directly.  I'm not sure numpy is really required for this, although it does understand datetime values.


问:
how to call a Function from another Dart file
i have this funtion which handles my Date and Time picker widget ...Code bellow...

```<code>Future selectDayAndTimeL(BuildContext context) async {
    DateTime? selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2021),
        lastDate: DateTime(2030),
        builder: (BuildContext context, Widget? child) => child!);

    TimeOfDay? selectedTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );

    if (selectedDay != null && selectedTime != null) {
      //a little check
    }
    setState(() {
      selectedDateAndTime = DateTime(
        selectedDay!.year,
        selectedDay!.month,
        selectedDay!.day,
        selectedTime!.hour,
        selectedTime!.minute,
      );
      // _selectedDate = _selectedDay;
    });
    // print('...');
  }
</code>```

initially it was inside my add new task class/dart file "Stateful Widget", and everything was working fine but now i want to also use that function on the Home screen when a button is pressed.

Then i checked a StackOverflow question on how to call a function from another dart file which the solution required that i keep the Function on a different dart file then call it from there like this Example

```<code>void launchWebView () {
  print("1234");
}
</code>```

when i did i was getting an error which i lookedup and it was because of the "setState" in my function so i needed to put it inside a Stateful widget,

```<code>import 'package:flutter/material.dart';

class SelectDateAndTime extends StatefulWidget {
  @override
  _SelectDateAndTimeState createState() => _SelectDateAndTimeState();
}

class _SelectDateAndTimeState extends State<SelectDateAndTime> {

  DateTime? _selectedDate;
// DateTime _selectedDate;
  DateTime? selectedDateAndTime;

  Future selectDayAndTimeL(BuildContext context) async {
    DateTime? selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2021),
        lastDate: DateTime(2030),
        builder: (BuildContext context, Widget? child) => child!);

    TimeOfDay? selectedTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );

    if (selectedDay != null && selectedTime != null) {
      //a little check
    }
    setState(() {
      selectedDateAndTime = DateTime(
        selectedDay!.year,
        selectedDay!.month,
        selectedDay!.day,
        selectedTime!.hour,
        selectedTime!.minute,
      );
      // _selectedDate = _selectedDay;
    });
    // print('...');
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    throw UnimplementedError();
  }
}
</code>```

And that was the only difference from my code with the example i followed and i was still getting an error when i tried calling the funtion, and i have checked all the quetions related to clling functions from another dart file / class and none of them had SetState so their solution didn't work for me

This is the error i got when i called just the Function Name

Bellow s the error i got when i tried to call

```<code>onPressed: () => selectedDateAndTime!.selectDayAndTimeL(),
</code>```

what should i do from here?

答:
setState tells a stateful widget to re-render based on the changed data. In your case you are changing selectedDateAndTime and re-building the Widget with updated data.

If you want to update/rebuild a widget from a "remote" function you need to use a callback.

Future selectDayAndTimeL(BuildContext context,Function(DateTime time) onDateTimeSelected)  async {
    DateTime? selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2021),
        lastDate: DateTime(2030),
        builder: (BuildContext context, Widget? child) => child!);

    TimeOfDay? selectedTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );

    if (selectedDay != null && selectedTime != null) {
      //a little check
    }
    // call the callback here with your calculated data
    onDateTimeSelected(
      DateTime(
        selectedDay!.year,
        selectedDay!.month,
        selectedDay!.day,
        selectedTime!.hour,
        selectedTime!.minute,
      ),
    );
  }
```
<p>Then in the StatefulWidget where you call this function:</p>
<pre class="lang-dart prettyprint-override"><code>selectDayAndTimeL(BuildContext context,(time) {
  setState(() {
    selectedDateAndTime = time;
  });
});
</code>```

Body:
i have this funtion which handles my Date and Time picker widget ...Code bellow...

Future selectDayAndTimeL(BuildContext context) async {
    DateTime? selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2021),
        lastDate: DateTime(2030),
        builder: (BuildContext context, Widget? child) => child!);

    TimeOfDay? selectedTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );

    if (selectedDay != null && selectedTime != null) {
      //a little check
    }
    setState(() {
      selectedDateAndTime = DateTime(
        selectedDay!.year,
        selectedDay!.month,
        selectedDay!.day,
        selectedTime!.hour,
        selectedTime!.minute,
      );
      // _selectedDate = _selectedDay;
    });
    // print('...');
  }

initially it was inside my add new task class/dart file "Stateful Widget", and everything was working fine but now i want to also use that function on the Home screen when a button is pressed.

Then i checked a StackOverflow question on how to call a function from another dart file which the solution required that i keep the Function on a different dart file then call it from there like this Example

void launchWebView () {
  print("1234");
}

when i did i was getting an error which i lookedup and it was because of the "setState" in my function so i needed to put it inside a Stateful widget,

import 'package:flutter/material.dart';

class SelectDateAndTime extends StatefulWidget {
  @override
  _SelectDateAndTimeState createState() => _SelectDateAndTimeState();
}

class _SelectDateAndTimeState extends State<SelectDateAndTime> {

  DateTime? _selectedDate;
// DateTime _selectedDate;
  DateTime? selectedDateAndTime;

  Future selectDayAndTimeL(BuildContext context) async {
    DateTime? selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2021),
        lastDate: DateTime(2030),
        builder: (BuildContext context, Widget? child) => child!);

    TimeOfDay? selectedTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );

    if (selectedDay != null && selectedTime != null) {
      //a little check
    }
    setState(() {
      selectedDateAndTime = DateTime(
        selectedDay!.year,
        selectedDay!.month,
        selectedDay!.day,
        selectedTime!.hour,
        selectedTime!.minute,
      );
      // _selectedDate = _selectedDay;
    });
    // print('...');
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    throw UnimplementedError();
  }
}

And that was the only difference from my code with the example i followed and i was still getting an error when i tried calling the funtion, and i have checked all the quetions related to clling functions from another dart file / class and none of them had SetState so their solution didn't work for me

This is the error i got when i called just the Function Name

Bellow s the error i got when i tried to call

onPressed: () => selectedDateAndTime!.selectDayAndTimeL(),

what should i do from here?

Body:
setState tells a stateful widget to re-render based on the changed data. In your case you are changing selectedDateAndTime and re-building the Widget with updated data.

If you want to update/rebuild a widget from a "remote" function you need to use a callback.

Future selectDayAndTimeL(BuildContext context,Function(DateTime time) onDateTimeSelected)  async {
    DateTime? selectedDay = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2021),
        lastDate: DateTime(2030),
        builder: (BuildContext context, Widget? child) => child!);

    TimeOfDay? selectedTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );

    if (selectedDay != null && selectedTime != null) {
      //a little check
    }
    // call the callback here with your calculated data
    onDateTimeSelected(
      DateTime(
        selectedDay!.year,
        selectedDay!.month,
        selectedDay!.day,
        selectedTime!.hour,
        selectedTime!.minute,
      ),
    );
  }

Then in the StatefulWidget where you call this function:

selectDayAndTimeL(BuildContext context,(time) {
  setState(() {
    selectedDateAndTime = time;
  });
});


问:
Golang - Sending API POST Request - Not enough arguments error
The following code attempts to send a POST API request with a payload that is in RequestDetails.FormData. When I run main.go function, then I get the following errors.

```<code>go run main.go
# command-line-arguments
./main.go:53:17: not enough arguments in call to http.HandleFunc
./main.go:53:33: not enough arguments in call to reqDetails.Send
        have ()
        want (http.ResponseWriter, *http.Request)
./main.go:53:33: reqDetails.Send() used as value
</code>```

The code is available below. Anybody knows what I could do wrong here? Thanks a lot for your help.

```<code>//main.go

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)

// RequestDetails contains input data for Send
type RequestDetails struct {
    EndPoint string
    FormType string
    FormData map[string]string
}

// Send sends API POST request to an endpoint
func (rd RequestDetails) Send(w http.ResponseWriter, r *http.Request) {

    json_data, err := json.Marshal(rd.FormData)

    if err != nil {
        log.Fatal(err)
    }

    resp, err := http.Post(rd.EndPoint, rd.FormType, bytes.NewBuffer(json_data))

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(resp)

}

func main() {
    m := map[string]string{
        "AuthParamOne":   "AP0000001",
        "AuthParamTwo":   "AP0000002",
        "AuthParamThree": "AP0000003",
    }

    reqDetails := RequestDetails{
        EndPoint: "https://httpbin.org/post",
        FormType: "application/json",
        FormData: m,
    }

    http.HandleFunc(reqDetails.Send())
}
</code>```

答:
you have to use HandleFunc in following below:

```<code>func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
</code>```

for code above follow this:

```<code>http.HandleFunc("/test",reqDetails.Send) //-> add reference instead of calling 'reqDetails.Send()'
</code>```

reference: https://pkg.go.dev/net/http#HandleFunc

please vote up :)

Body:
The following code attempts to send a POST API request with a payload that is in RequestDetails.FormData. When I run main.go function, then I get the following errors.

go run main.go
# command-line-arguments
./main.go:53:17: not enough arguments in call to http.HandleFunc
./main.go:53:33: not enough arguments in call to reqDetails.Send
        have ()
        want (http.ResponseWriter, *http.Request)
./main.go:53:33: reqDetails.Send() used as value

The code is available below. Anybody knows what I could do wrong here? Thanks a lot for your help.

//main.go

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)

// RequestDetails contains input data for Send
type RequestDetails struct {
    EndPoint string
    FormType string
    FormData map[string]string
}

// Send sends API POST request to an endpoint
func (rd RequestDetails) Send(w http.ResponseWriter, r *http.Request) {

    json_data, err := json.Marshal(rd.FormData)

    if err != nil {
        log.Fatal(err)
    }

    resp, err := http.Post(rd.EndPoint, rd.FormType, bytes.NewBuffer(json_data))

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(resp)

}

func main() {
    m := map[string]string{
        "AuthParamOne":   "AP0000001",
        "AuthParamTwo":   "AP0000002",
        "AuthParamThree": "AP0000003",
    }

    reqDetails := RequestDetails{
        EndPoint: "https://httpbin.org/post",
        FormType: "application/json",
        FormData: m,
    }

    http.HandleFunc(reqDetails.Send())
}

Body:
you have to use HandleFunc in following below:

func HandleFunc(pattern string, handler func(ResponseWriter, *Request))

for code above follow this:

http.HandleFunc("/test",reqDetails.Send) //-> add reference instead of calling 'reqDetails.Send()'

reference: https://pkg.go.dev/net/http#HandleFunc

please vote up :)


问:
[Flutter]: notifyListeners not working from other screens or popups
I am using the provider libarary for my state management and everything works fine up until this point. However, I have noticed that when calling notifyListeners from another screen (or a popup like showModalBottomSheet) my UI will not be notified.

The method I am using in the provider looks something like this and adds an item to a ListView:

```<code>void addEntry(http.Response response) {
  Group group = Group.fromJson(jsonDecode(response.body));
  groups.add(group);
  notifyListeners();
}
</code>```

As for the UI the entire Screen is wrapped in a Consumer. Calling this method from a button in the screen works fine and the list is updated. Calling this method from a popup created with showModalBottomSheet does not update the UI.

How do I ensure the UI is notified of the changes?

Update #1:

I have a button that calls showModalBottomSheet like this:

```<code>showModalBottomSheet<void>(
  ...
  context: context,
  builder: (context) {
    return Padding(
      padding: MediaQuery.of(context).viewInsets,
      child: AddWidget(model: Provider.of<GroupsProvider>(context)),
    );
  },
);
</code>```

So it creates a popup with a separate widget. That separate widget in turn does this when another button is pressed:

```<code>widget.model.createGroup(name, icon);
</code>```

This method eventually calls addEntry. As I said this works perfectly fine without a popup but does not work at all in the popup :/

答:
Pop-ups like bottomsheets are most likely opened from the root navigator and hence provides a different context and if your provider is not created above the root Navigator i.e above the MaterialApp, it will cause this issue.
The context that is coming from the builder of the showModalBottomSheet is not where your Provider is created.
There are 2 solutions I can think of:

Just before calling the showModalBottomSheet , you can create a reference to the Provider and then pass that to the AddWidget.

```<code>var provider = Provider.of<GroupsProvider>(context, listen:false);

showModalBottomSheet<void>(
  ...
  context: context,
  builder: (context) {
    return Padding(
      padding: MediaQuery.of(context).viewInsets,
      child: AddWidget(model: provider),
    );
  },
);

</code>```

Use the ChangeNotifierProvider.value and wrap the widget in the builder with it.

```<code>showModalBottomSheet<void>(
  ...
  context: context,
  builder: (_) {
    return ChangeNotifierProvider.value(
          value: Provider.of<GroupsProvider>(context, listen:false),
         builder: (context, _) =>
                Padding(
      padding: MediaQuery.of(context).viewInsets,
      child: AddWidget(model: Provider.of<GroupsProvider>(context)),
    );
       );
  },
);

</code>```

(2) ensures that the widget tree below it will have access to the same Provider instance. For new screens, you can do :

```<code>Navigator.push(
  context,
  MaterialPageRoute(
   builder: (_) => ChangeNotifierProvider.value(...),
   ),
);
</code>```

Looking at the widget inspector in debug mode will help you understand better

Body:
I am using the provider libarary for my state management and everything works fine up until this point. However, I have noticed that when calling notifyListeners from another screen (or a popup like showModalBottomSheet) my UI will not be notified.

The method I am using in the provider looks something like this and adds an item to a ListView:

void addEntry(http.Response response) {
  Group group = Group.fromJson(jsonDecode(response.body));
  groups.add(group);
  notifyListeners();
}

As for the UI the entire Screen is wrapped in a Consumer. Calling this method from a button in the screen works fine and the list is updated. Calling this method from a popup created with showModalBottomSheet does not update the UI.

How do I ensure the UI is notified of the changes?

Update #1:

I have a button that calls showModalBottomSheet like this:

showModalBottomSheet<void>(
  ...
  context: context,
  builder: (context) {
    return Padding(
      padding: MediaQuery.of(context).viewInsets,
      child: AddWidget(model: Provider.of<GroupsProvider>(context)),
    );
  },
);

So it creates a popup with a separate widget. That separate widget in turn does this when another button is pressed:

widget.model.createGroup(name, icon);

This method eventually calls addEntry. As I said this works perfectly fine without a popup but does not work at all in the popup :/

Body:
Pop-ups like bottomsheets are most likely opened from the root navigator and hence provides a different context and if your provider is not created above the root Navigator i.e above the MaterialApp, it will cause this issue.
The context that is coming from the builder of the showModalBottomSheet is not where your Provider is created.
There are 2 solutions I can think of:

Just before calling the showModalBottomSheet , you can create a reference to the Provider and then pass that to the AddWidget.

var provider = Provider.of<GroupsProvider>(context, listen:false);

showModalBottomSheet<void>(
  ...
  context: context,
  builder: (context) {
    return Padding(
      padding: MediaQuery.of(context).viewInsets,
      child: AddWidget(model: provider),
    );
  },
);

Use the ChangeNotifierProvider.value and wrap the widget in the builder with it.

showModalBottomSheet<void>(
  ...
  context: context,
  builder: (_) {
    return ChangeNotifierProvider.value(
          value: Provider.of<GroupsProvider>(context, listen:false),
         builder: (context, _) =>
                Padding(
      padding: MediaQuery.of(context).viewInsets,
      child: AddWidget(model: Provider.of<GroupsProvider>(context)),
    );
       );
  },
);

(2) ensures that the widget tree below it will have access to the same Provider instance. For new screens, you can do :

Navigator.push(
  context,
  MaterialPageRoute(
   builder: (_) => ChangeNotifierProvider.value(...),
   ),
);

Looking at the widget inspector in debug mode will help you understand better


问:
SQL Server 2019 query returns all null values when trying to separate a single column into multiples columns of data
I have a table of data that uses a / as delimiter. I'm trying to separate the single column of data into three columns.

My query is returning the proper number of rows, but all three columns are NULL. Does anything jump off the page as obvious that I've missed?

Here is how the data is stored in the PGroup column:

```<code>Steve/Mouse/Vitamin
Matt/Cat/Soda
Shelly/Dog/Bread
</code>```

I'm hoping to return 3 separate columns: Name, Pet, Food

```<code>DECLARE @delimiter VARCHAR(50)
SET @delimiter='/'

;WITH CTE AS
(
    SELECT
        CAST('' + REPLACE([PGroup], @delimiter, '') + '' AS XML) AS [PXML]
    FROM
        xx123
)
SELECT
    [PXML].value('/M[1]', 'varchar(50)') As [Name],
    [PXML].value('/M[2]', 'varchar(50)') As [Pet],
    [PXML].value('/M[3]', 'varchar(50)') As [Food]
FROM
    CTE
</code>```

答:
Please try the following solution.

Notable points:

CData section protects against XML entities like ampersand and the
like.

XPath expressions were adjusted to use text() for performance
reasons.

SQL

```<code>-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, tokens VARCHAR(1000));
INSERT INTO @tbl (tokens) VALUES
('Steve/Mouse/Vitamin'),
('Matt/Cat/Soda'),
('Shelly/Dog/Bread');
-- DDL and sample data population, end

DECLARE @separator CHAR(1) = '/';

SELECT ID
    , c.value('(/root/r[1]/text())[1]', 'varchar(50)') As [Name]
    , c.value('(/root/r[2]/text())[1]', 'varchar(50)') As [Pet]
    , c.value('(/root/r[3]/text())[1]', 'varchar(50)') As [Food]
FROM @tbl
CROSS APPLY (SELECT TRY_CAST('<root><r><![CDATA[' +
        REPLACE(tokens, @separator, ']]></r><r><![CDATA[') +
        ']]></r></root>' AS XML)) AS t(c);
</code>```

Output

```<code>+----+--------+-------+---------+
| ID |  Name  |  Pet  |  Food   |
+----+--------+-------+---------+
|  1 | Steve  | Mouse | Vitamin |
|  2 | Matt   | Cat   | Soda    |
|  3 | Shelly | Dog   | Bread   |
+----+--------+-------+---------+
</code>```

Body:
I have a table of data that uses a / as delimiter. I'm trying to separate the single column of data into three columns.

My query is returning the proper number of rows, but all three columns are NULL. Does anything jump off the page as obvious that I've missed?

Here is how the data is stored in the PGroup column:

Steve/Mouse/Vitamin
Matt/Cat/Soda
Shelly/Dog/Bread

I'm hoping to return 3 separate columns: Name, Pet, Food

DECLARE @delimiter VARCHAR(50)
SET @delimiter='/'

;WITH CTE AS
(
    SELECT
        CAST('' + REPLACE([PGroup], @delimiter, '') + '' AS XML) AS [PXML]
    FROM
        xx123
)
SELECT
    [PXML].value('/M[1]', 'varchar(50)') As [Name],
    [PXML].value('/M[2]', 'varchar(50)') As [Pet],
    [PXML].value('/M[3]', 'varchar(50)') As [Food]
FROM
    CTE

Body:
Please try the following solution.

Notable points:

CData section protects against XML entities like ampersand and the
like.

XPath expressions were adjusted to use text() for performance
reasons.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, tokens VARCHAR(1000));
INSERT INTO @tbl (tokens) VALUES
('Steve/Mouse/Vitamin'),
('Matt/Cat/Soda'),
('Shelly/Dog/Bread');
-- DDL and sample data population, end

DECLARE @separator CHAR(1) = '/';

SELECT ID
    , c.value('(/root/r[1]/text())[1]', 'varchar(50)') As [Name]
    , c.value('(/root/r[2]/text())[1]', 'varchar(50)') As [Pet]
    , c.value('(/root/r[3]/text())[1]', 'varchar(50)') As [Food]
FROM @tbl
CROSS APPLY (SELECT TRY_CAST('<root><r><![CDATA[' +
        REPLACE(tokens, @separator, ']]></r><r><![CDATA[') +
        ']]></r></root>' AS XML)) AS t(c);

Output

+----+--------+-------+---------+
| ID |  Name  |  Pet  |  Food   |
+----+--------+-------+---------+
|  1 | Steve  | Mouse | Vitamin |
|  2 | Matt   | Cat   | Soda    |
|  3 | Shelly | Dog   | Bread   |
+----+--------+-------+---------+


问:
Can't pass params in URL to react component
I am trying to pass params in the URL to a React component, but doing so gives errors.
These are the errors:

```<code>Uncaught SyntaxError: Unexpected token '<'

epoxy:68 Uncaught ReferenceError: $ is not defined
    at epoxy:68:9
</code>```

Screenshot of error messages:

I get these errors if I navigate to the page http://localhost:3000/project-details/epoxy.

However, if I naviagte to http://localhost:3000/project-details then no errors.

But if I navigate to http://localhost:3000/project-details/ (notice the slash at the end), then I get the same errors again.

Here is the relevant code:
App.js:

```<code>import { React } from 'react';
import AppRoute from '../components/route-components/Approute';

function App() {
  return (
   <AppRoute />
  );
}

export default App;
</code>```

AppRoute.js:

```<code>function AppRoute() {

    return (
        < BrowserRouter >
            < Switch >
                < Route path = '/' exact component = { Home } />
                < Route path = { `/project-details/:id` } component = { SingleProjectPage } />
                < Route path = { `/project-details` } component = { SingleProjectPage } />
                < Route path='*' component = { ErrorPage }/>
            </ Switch>
        </ BrowserRouter>
    )

}
export default AppRoute;
</code>```

SingleProjectPage:

```<code>import React, { useEffect, Fragment } from 'react';

const SingleProjectPage = (props) =>{
    let data = sectionData.sectionTitle.singleProject;
    useEffect(() => {
        console.log(props.match.params.id);
        window.scrollTo(0,0);
    }, [])
    return (
        <Fragment>
            hello
        </Fragment>

    )
}
export default SingleProjectPage;
</code>```

I took over this project and it is already a massive project so I am having a hard time diagnosing the issue. It looks to me like this should just work, I am not seeing any issues. After reading other similar questions, it looks like the code may be trying to use jQuery before it is available to me, but why would the path http://localhost:3000/project-details/ break the app just because of a forward slash at the end?

Any ideas? I can provide more code if needed.

EDIT: it even fails if I change the route to this:

```<code>{/* < Route path = { `/project-details/:id` } component = { SingleProjectPage } />
< Route path = { `/project-details` } component = { SingleProjectPage } />   */}
< Route path = { `/project-details/epoxy` } component = { SingleProjectPage } />
</code>```

Its like I am unable to change that route in any way.

答:
As it turns out, the route works if I only have one forward slash in the path. No idea why. But for example, this will work:

```<code>< Route path = { `/epoxy` } component = { SingleProjectPage } />
</code>```

But this will not:

```<code>< Route path = { `/project/epoxy` } component = { SingleProjectPage } />
</code>```

Just having the extra path /project at the prefix breaks it.

Body:
I am trying to pass params in the URL to a React component, but doing so gives errors.
These are the errors:

Uncaught SyntaxError: Unexpected token '<'

epoxy:68 Uncaught ReferenceError: $ is not defined
    at epoxy:68:9

Screenshot of error messages:

I get these errors if I navigate to the page http://localhost:3000/project-details/epoxy.

However, if I naviagte to http://localhost:3000/project-details then no errors.

But if I navigate to http://localhost:3000/project-details/ (notice the slash at the end), then I get the same errors again.

Here is the relevant code:
App.js:

import { React } from 'react';
import AppRoute from '../components/route-components/Approute';

function App() {
  return (
   <AppRoute />
  );
}

export default App;

AppRoute.js:

function AppRoute() {

    return (
        < BrowserRouter >
            < Switch >
                < Route path = '/' exact component = { Home } />
                < Route path = { `/project-details/:id` } component = { SingleProjectPage } />
                < Route path = { `/project-details` } component = { SingleProjectPage } />
                < Route path='*' component = { ErrorPage }/>
            </ Switch>
        </ BrowserRouter>
    )

}
export default AppRoute;

SingleProjectPage:

import React, { useEffect, Fragment } from 'react';

const SingleProjectPage = (props) =>{
    let data = sectionData.sectionTitle.singleProject;
    useEffect(() => {
        console.log(props.match.params.id);
        window.scrollTo(0,0);
    }, [])
    return (
        <Fragment>
            hello
        </Fragment>

    )
}
export default SingleProjectPage;

I took over this project and it is already a massive project so I am having a hard time diagnosing the issue. It looks to me like this should just work, I am not seeing any issues. After reading other similar questions, it looks like the code may be trying to use jQuery before it is available to me, but why would the path http://localhost:3000/project-details/ break the app just because of a forward slash at the end?

Any ideas? I can provide more code if needed.

EDIT: it even fails if I change the route to this:

{/* < Route path = { `/project-details/:id` } component = { SingleProjectPage } />
< Route path = { `/project-details` } component = { SingleProjectPage } />   */}
< Route path = { `/project-details/epoxy` } component = { SingleProjectPage } />

Its like I am unable to change that route in any way.

Body:
As it turns out, the route works if I only have one forward slash in the path. No idea why. But for example, this will work:

< Route path = { `/epoxy` } component = { SingleProjectPage } />

But this will not:

< Route path = { `/project/epoxy` } component = { SingleProjectPage } />

Just having the extra path /project at the prefix breaks it.


问:
Relative Interface (TYPESCRIPT)
How can I make the state in ISetOpen with relative type of modal in ISetOpen?

Example:

if ISetOpen.modal === 'payModal': ISetOpen.state = IPayModal

if ISetOpen.modal === 'deleteModal': ISetOpen.state = IDeleteModal

```<code>import { createSlice, PayloadAction } from '@reduxjs/toolkit'

interface IPayModal {
  amount: number
  isOpen: boolean
}

interface IDeleteModal {
  id: number
  isOpen: boolean
}

export interface ModalsState {
  payModal: IPayModal
  deleteModal: IDeleteModal
}

const initialState: ModalsState = {
  payModal: {
    amount: 0,
    isOpen: false
  },
  deleteModal: {
    id: 0,
    isOpen: false
  }
}

interface ISetOpen {
  modal: keyof typeof initialState
  state: IPayModal | IDeleteModal
}

export const modalsSlice = createSlice({
  name: 'modals',
  initialState,
  reducers: {
    setOpen: (state, action: PayloadAction<ISetOpen>) => {
      state[action.payload.modal] = action.payload.state
    }
  }
})

export const { setOpen } = modalsSlice.actions

export default modalsSlice.reducer
</code>```

答:
I don't know how much are you attached to this keyof typeof initialState, especially in a case when there will be 3rd or more options there.

You can achieve what you want by converting your interface into union type:

type ISetOpen = {
  modal: 'payModal';
  state: IPayModal;
} | {
  modal: 'deleteModal';
  state: IDeleteModal;
}
```

Title: Relative Interface (TYPESCRIPT)

Body:
How can I make the state in ISetOpen with relative type of modal in ISetOpen?

Example:

if ISetOpen.modal === 'payModal': ISetOpen.state = IPayModal

if ISetOpen.modal === 'deleteModal': ISetOpen.state = IDeleteModal

import { createSlice, PayloadAction } from '@reduxjs/toolkit'

interface IPayModal {
  amount: number
  isOpen: boolean
}

interface IDeleteModal {
  id: number
  isOpen: boolean
}

export interface ModalsState {
  payModal: IPayModal
  deleteModal: IDeleteModal
}

const initialState: ModalsState = {
  payModal: {
    amount: 0,
    isOpen: false
  },
  deleteModal: {
    id: 0,
    isOpen: false
  }
}

interface ISetOpen {
  modal: keyof typeof initialState
  state: IPayModal | IDeleteModal
}

export const modalsSlice = createSlice({
  name: 'modals',
  initialState,
  reducers: {
    setOpen: (state, action: PayloadAction<ISetOpen>) => {
      state[action.payload.modal] = action.payload.state
    }
  }
})

export const { setOpen } = modalsSlice.actions

export default modalsSlice.reducer


问:
iOS taking a screenshot of tableview
So I am creating an iPad app where I need to take a screenshot of a tableview and display it later, similar to iPad safari tabs page. I need to take the screenshot in both orientations without actually changing the orientation. How can I archieve this?</p>

答:
What you are describing is beyond the limits of any "screenshot." You will need to manually generate the images for the table view.  If the view is simple (i.e. some text, separators, etc), you could do this using CoreGraphics or something of the sort to draw the image from scratch.  I maintain an open source class called ANImageBitmapRep which allows for easy pixel-level, and context level image manipulation.  In this case, you will most likely be using core graphics, but here's how you would generate a context in the first place:

```<code>ANImageBitmapRep * irep = [[ANImageBitmapRep alloc] initWithSize:BMPointMake(myWidth, myHeight)];
CGContextRef context = [irep context];
// ...
// use context here to manually generate your "screenshot."
// ...
[irep setNeedsUpdate]; // tell the image bitmap rep to update its image
UIImage * savedImage = [irep image]; // get a UIImage for storing
[irep release]; // free the memory
</code>```

A small tutorial on drawing with CoreGraphics can be found at http://idevhub.com/exploring-iphone-graphics-part-1/.

Title: iOS taking a screenshot of tableview

Body:
What you are describing is beyond the limits of any "screenshot." You will need to manually generate the images for the table view.  If the view is simple (i.e. some text, separators, etc), you could do this using CoreGraphics or something of the sort to draw the image from scratch.  I maintain an open source class called ANImageBitmapRep which allows for easy pixel-level, and context level image manipulation.  In this case, you will most likely be using core graphics, but here's how you would generate a context in the first place:

ANImageBitmapRep * irep = [[ANImageBitmapRep alloc] initWithSize:BMPointMake(myWidth, myHeight)];
CGContextRef context = [irep context];
// ...
// use context here to manually generate your "screenshot."
// ...
[irep setNeedsUpdate]; // tell the image bitmap rep to update its image
UIImage * savedImage = [irep image]; // get a UIImage for storing
[irep release]; // free the memory

A small tutorial on drawing with CoreGraphics can be found at http://idevhub.com/exploring-iphone-graphics-part-1/.


问:
Can a grid item adjust its span based on height?
Is there any way to get a behaviour similar to this shown on drawing?
I mean of course manually we can specify grid-row: span x, but grid-row: span auto seems doesn't work. I need all grid items to be the same size, but when one item has to resize (due to text overflow) i need to set the grid-row: span 2, and when it's getting bigger - respectively higher number.

To acheive something like this I need to write .js or can it be done with css only?
Here is code sandbox

答:
let items = document.querySelectorAll('.item')
items.forEach(item => {
  if(item.scrollHeight>item.clientHeight){
    let itemSpan = Math.round(item.scrollHeight/40) + 1  // (height = 30) + (gap = 10) 40 =>
    item.style.cssText = `--n : ${itemSpan}`
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  width: 200px;
  margin: 15vw auto;
}
.grid {
  width: 100%;
  background-color: chartreuse;
  display: grid;
  justify-items: center;
  grid-template-columns: 1fr 1fr;
  grid-auto-rows: 30px;
  grid-auto-flow: row;
  grid-gap: 10px;
  word-break: break-all;
}

.item {
  background-color: gold;
  min-height: 30px;
  width: 50px;
  padding: 5px;
  grid-row: auto / span var(--n); /* var(--n) is calculated with js */
  box-sizing: border-box;
}</code>```

1

2 Lorem ipsum dolor sit amet consectetur adipisicing

3

4

5 t amet consectetur adipisi

6 lorem

7

8

9 t amet consectetur adipisi

```

Body:
let items = document.querySelectorAll('.item')
items.forEach(item => {
  if(item.scrollHeight>item.clientHeight){
    let itemSpan = Math.round(item.scrollHeight/40) + 1  // (height = 30) + (gap = 10) 40 =>
    item.style.cssText = `--n : ${itemSpan}`
  }
})

.container {
  width: 200px;
  margin: 15vw auto;
}
.grid {
  width: 100%;
  background-color: chartreuse;
  display: grid;
  justify-items: center;
  grid-template-columns: 1fr 1fr;
  grid-auto-rows: 30px;
  grid-auto-flow: row;
  grid-gap: 10px;
  word-break: break-all;
}

.item {
  background-color: gold;
  min-height: 30px;
  width: 50px;
  padding: 5px;
  grid-row: auto / span var(--n); /* var(--n) is calculated with js */
  box-sizing: border-box;
}

<div class="container">
  <div class="grid">
    <div class="item">1</div>
    <div class="item ">2 Lorem ipsum dolor sit amet consectetur adipisicing </div>
    <div class="item">3</div>
    <div class="item">4</div>
    <div class="item">5 t amet consectetur adipisi</div>
    <div class="item">6 lorem</div>
    <div class="item">7</div>
    <div class="item">8</div>
    <div class="item">9 t amet consectetur adipisi </div>
  </div>
</div>


问:
I'm trying to script 6 identical tables/calculators with one easy code
I'm creating some calculators for a mobile game that I play. I'm going to have 6 of the same type of calculator on the same page. Each one should look and operate like so:

const speedupInputs = document.querySelectorAll('input');
const results = document.getElementById('results');
const submit = document.getElementById('submit');

submit.addEventListener('click', function() {
    let total = 0;
    results.textContent = '';
    speedupInputs.forEach((input) => {
        if(input.value != '') {
            if(input.classList.contains('minutes')) {
                total += input.value * input.name;
            } else if (input.classList.contains('hours')) {
                total += (input.value * input.name) * 60;
            } else if (input.classList.contains('days')) {
                total += (input.value * input.name) * 60 * 24;
            }
        }
    })

    results.textContent = toTime(total * 60);

});

function toTime(seconds) {
    const secsPerDay = 86400;
    const secsPerHour = 3600;
    const secsPerMinute = 60;

    var minus   = (this < 0) ? '-' : '';

    var days    = Math.floor(seconds / secsPerDay);
    seconds     = (seconds % secsPerDay);
    var hours   = Math.floor(seconds / secsPerHour);
    seconds     = (seconds % secsPerHour);
    var minutes = Math.floor(seconds / secsPerMinute);
    seconds     = (seconds % secsPerMinute);

    var sDays    = new String(days).padStart(1, '0');
    var sHours   = new String(hours).padStart(2, '0');
    var sMinutes = new String(minutes).padStart(2, '0');

    return `${minus}${sDays}d ${sHours}:${sMinutes}:00`;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table, tr, td {
    border: 1px solid black;
    border-collapse: collapse;
}

table {
    width: 100px;
    margin: 40px;
}

input {
    width: 90%;
    outline: 0;
    border: none;

}

td {
    text-align: center;
}</code>```

  <colgroup>
    <col span="1" style="width: 50%;">
    <col span="1" style="width: 50%;">
  </colgroup>

    Speed-Ups

      1m

      <input type="number" class="minutes" id="1m" name="1" min="0">

      3m

      <input type="number" class="minutes" id="3m" name="3" min="0">

      5m

      <input type="text" class="minutes" id="5m" name="5" min="0">

      10m

      <input type="number" class="minutes" id="10m" name="10" min="0">

      15m

      <input type="number" class="minutes" id="15m" name="15" min="0">

      30m

      <input type="number" class="minutes" id="30m" name="30" min="0">

      45m

      <input type="number" class="minutes" id="45m" name="45" min="0">

      60m

      <input type="number" class="minutes" id="60m" name="60" min="0">

      3h

      <input type="number" class="hours" id="3h" name="3" min="0">

      8h

      <input type="number" class="hours" id="8h" name="8" min="0">

      15h

      <input type="number" class="hours" id="15h" name="15" min="0">

      24h

      <input type="number" class="hours" id="24h" name="24" min="0">

      3d

      <input type="number" id="3d" class="days" name="3" min="0">

      7d

      <input type="number" id="7d" class="days" name="7" min="0">

      30d

      <input type="number" id="30d" class="days" name="30" min="0">

      <button id="submit" class="submitbtn">Submit</button>

```
</div>
</div>
</p>
<p>Because there are 6 and because I'm trying to follow the DRY way of coding, I'm trying to create the least amount of code to do the job of scripting all 6 calculators. I mean, they're all identical si this shouldn't be hard, right?</p>
<p>This is the code that I thought would work. I don't know what the problem is because it isn't throwing any errors in the console. In a nutshell, the code is pretty similar to the first, except I tried to reference all tables via a <code>.forEach</code> function. Also, I read that one way to reference children of an element is to give all of the children a class name and then use <code>parentName.querySelectorAll('className')</code> (hence me trying to use it with <em>table</em> as the "parentName").</p>
```const submitBtns = document.querySelectorAll('.subitbtn');
const tables = document.querySelectorAll('table');
const speedupInputs = document.querySelectorAll('.tableinput');

submitBtns.forEach((btn) => {
    btn.addEventListener('click', myFunction);
});

function myFunction() {
    tables.forEach((table) => {
        const results = table.querySelector('.resultsarea');
        let total = 0;
        results.textContent = '';

        speedupInputs.forEach((input) => {
            if(input.value != '') {
                if(input.classList.contains('minutes')) {
                    total += input.value * input.name;
                } else if (input.classList.contains('hours')) {
                    total += (input.value * input.name) * 60;
                } else if (input.classList.contains('days')) {
                    total += (input.value * input.name) * 60 * 24;
                }
            }
        });
    results.textContent = toTime(total * 60);
    });
};

function toTime(seconds) {
    const secsPerDay = 86400;
    const secsPerHour = 3600;
    const secsPerMinute = 60;

    var minus   = (this < 0) ? '-' : '';

    var days    = Math.floor(seconds / secsPerDay);
    seconds     = (seconds % secsPerDay);
    var hours   = Math.floor(seconds / secsPerHour);
    seconds     = (seconds % secsPerHour);
    var minutes = Math.floor(seconds / secsPerMinute);
    seconds     = (seconds % secsPerMinute);

    var sDays    = new String(days).padStart(1, '0');
    var sHours   = new String(hours).padStart(2, '0');
    var sMinutes = new String(minutes).padStart(2, '0');

    return `${minus}${sDays}d ${sHours}:${sMinutes}:00`;
}
```

So yeah. To reiterate: I want 6 identical versions of these tables/calculators on a page, and I want one simple, easy code to script all 6 of them since they're identical. Thank you.

答:
The first principle in DRY is to use metadata (here units and tabMeta).
then it is to use them to generate the HTML for all 6 tables.

otherwise for the rest of DRY questions, JavaScript allows event delegation (use here to detect the slightest change in value (your submit button is useless).

There are also a whole host of array methods that you should study in detail.

sample code:

const
  twoDgts = t => (t<10) ? `0${t}` : t.toString(10)
, tablesBox = document.querySelector('#tables-box')
, units =
    { minutes : { lib: 'm', val:  1 }
    , hours   : { lib: 'h', val: 60 }
    , days    : { lib: 'd', val:60 * 24 }
    }
, tabMeta =
    [ { base:  1, unit: units.minutes }, { base:  3, unit: units.minutes }
    , { base:  5, unit: units.minutes }, { base: 10, unit: units.minutes }
    , { base: 15, unit: units.minutes }, { base: 30, unit: units.minutes }
    , { base: 45, unit: units.minutes }, { base: 60, unit: units.minutes }
    , { base:  3, unit: units.hours   }, { base:  8, unit: units.hours   }
    , { base: 15, unit: units.hours   }, { base: 24, unit: units.hours   }
    , { base:  3, unit: units.days    }, { base:  7, unit: units.days    }
    , { base: 30, unit: units.days    }
    ];

tabMeta.forEach(({base, unit},i,arr)=>arr[i].value=base * unit.val) // add values

const tables = Array.from({length:6},()=>// IHM generator... ( 6 tables )
  {
  let tableN = tablesBox.appendChild( document.createElement('table'))

  tabMeta.forEach(({base,unit},indx)=>
    {
    let newRow = tableN.insertRow()
    newRow.insertCell().textContent = `${base} ${unit.lib}`
    newRow.insertCell().innerHTML = `<input type="number" min="0" value="0" data-indx="${indx}">`
    })
  tableN.insertRow().innerHTML = '
 	'
  tableN.createTHead().insertRow().innerHTML = 'Spead-Up	'
  return tableN
  })

tablesBox.oninput = e =>
  {
  if (!e.target.matches('input')) return
  MakeSum( e.target.closest('table'))
  }

function MakeSum( refTable )
  {
  let sum =
    [...refTable.querySelectorAll('td input[type=number]')]
    .reduce((sum,inputX)=> sum + (inputX.valueAsNumber * tabMeta[inputX.dataset.indx].value), 0)

  let mins = sum % 60; sum = (sum - mins) / 60
  let hrs  = sum % 24; sum = (sum - hrs) / 24

  refTable.querySelector('tr:last-of-type td').innerHTML =
    `${sum}${units.days.lib}<br>${twoDgts(hrs)}:${twoDgts(mins)}:00`
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  display          : inline-block;
  font             : 14px Arial, Helvetica, sans-serif;
  white-space      : nowrap;
  border-collapse  : separate;
  border-spacing   : 1px;
  background-color : darkblue;
  margin           : 1em .4em;
  }
td, th {
  padding          : .3em .6em;
  background-color : whitesmoke;
  min-width        : 2em;
  }
td {
  text-align       : right;
  }
tr:last-of-type td {
  background-color : #a2e0da;
  text-align       : center;
  }
input[type=number] {
  border     : none;
  text-align : center;
  width      : 5em;
  }</code>```

```

Body:
I'm creating some calculators for a mobile game that I play. I'm going to have 6 of the same type of calculator on the same page. Each one should look and operate like so:

const speedupInputs = document.querySelectorAll('input');
const results = document.getElementById('results');
const submit = document.getElementById('submit');

submit.addEventListener('click', function() {
    let total = 0;
    results.textContent = '';
    speedupInputs.forEach((input) => {
        if(input.value != '') {
            if(input.classList.contains('minutes')) {
                total += input.value * input.name;
            } else if (input.classList.contains('hours')) {
                total += (input.value * input.name) * 60;
            } else if (input.classList.contains('days')) {
                total += (input.value * input.name) * 60 * 24;
            }
        }
    })

    results.textContent = toTime(total * 60);

});

function toTime(seconds) {
    const secsPerDay = 86400;
    const secsPerHour = 3600;
    const secsPerMinute = 60;

    var minus   = (this < 0) ? '-' : '';

    var days    = Math.floor(seconds / secsPerDay);
    seconds     = (seconds % secsPerDay);
    var hours   = Math.floor(seconds / secsPerHour);
    seconds     = (seconds % secsPerHour);
    var minutes = Math.floor(seconds / secsPerMinute);
    seconds     = (seconds % secsPerMinute);

    var sDays    = new String(days).padStart(1, '0');
    var sHours   = new String(hours).padStart(2, '0');
    var sMinutes = new String(minutes).padStart(2, '0');

    return `${minus}${sDays}d ${sHours}:${sMinutes}:00`;
}

table, tr, td {
    border: 1px solid black;
    border-collapse: collapse;
}

table {
    width: 100px;
    margin: 40px;
}

input {
    width: 90%;
    outline: 0;
    border: none;

}

td {
    text-align: center;
}

  <colgroup>
    <col span="1" style="width: 50%;">
    <col span="1" style="width: 50%;">
  </colgroup>

    Speed-Ups

      1m

      <input type="number" class="minutes" id="1m" name="1" min="0">

      3m

      <input type="number" class="minutes" id="3m" name="3" min="0">

      5m

      <input type="text" class="minutes" id="5m" name="5" min="0">

      10m

      <input type="number" class="minutes" id="10m" name="10" min="0">

      15m

      <input type="number" class="minutes" id="15m" name="15" min="0">

      30m

      <input type="number" class="minutes" id="30m" name="30" min="0">

      45m

      <input type="number" class="minutes" id="45m" name="45" min="0">

      60m

      <input type="number" class="minutes" id="60m" name="60" min="0">

      3h

      <input type="number" class="hours" id="3h" name="3" min="0">

      8h

      <input type="number" class="hours" id="8h" name="8" min="0">

      15h

      <input type="number" class="hours" id="15h" name="15" min="0">

      24h

      <input type="number" class="hours" id="24h" name="24" min="0">

      3d

      <input type="number" id="3d" class="days" name="3" min="0">

      7d

      <input type="number" id="7d" class="days" name="7" min="0">

      30d

      <input type="number" id="30d" class="days" name="30" min="0">

      <button id="submit" class="submitbtn">Submit</button>

Because there are 6 and because I'm trying to follow the DRY way of coding, I'm trying to create the least amount of code to do the job of scripting all 6 calculators. I mean, they're all identical si this shouldn't be hard, right?

This is the code that I thought would work. I don't know what the problem is because it isn't throwing any errors in the console. In a nutshell, the code is pretty similar to the first, except I tried to reference all tables via a .forEach function. Also, I read that one way to reference children of an element is to give all of the children a class name and then use parentName.querySelectorAll('className') (hence me trying to use it with table as the "parentName").

const submitBtns = document.querySelectorAll('.subitbtn');
const tables = document.querySelectorAll('table');
const speedupInputs = document.querySelectorAll('.tableinput');

submitBtns.forEach((btn) => {
    btn.addEventListener('click', myFunction);
});

function myFunction() {
    tables.forEach((table) => {
        const results = table.querySelector('.resultsarea');
        let total = 0;
        results.textContent = '';

        speedupInputs.forEach((input) => {
            if(input.value != '') {
                if(input.classList.contains('minutes')) {
                    total += input.value * input.name;
                } else if (input.classList.contains('hours')) {
                    total += (input.value * input.name) * 60;
                } else if (input.classList.contains('days')) {
                    total += (input.value * input.name) * 60 * 24;
                }
            }
        });
    results.textContent = toTime(total * 60);
    });
};

function toTime(seconds) {
    const secsPerDay = 86400;
    const secsPerHour = 3600;
    const secsPerMinute = 60;

    var minus   = (this < 0) ? '-' : '';

    var days    = Math.floor(seconds / secsPerDay);
    seconds     = (seconds % secsPerDay);
    var hours   = Math.floor(seconds / secsPerHour);
    seconds     = (seconds % secsPerHour);
    var minutes = Math.floor(seconds / secsPerMinute);
    seconds     = (seconds % secsPerMinute);

    var sDays    = new String(days).padStart(1, '0');
    var sHours   = new String(hours).padStart(2, '0');
    var sMinutes = new String(minutes).padStart(2, '0');

    return `${minus}${sDays}d ${sHours}:${sMinutes}:00`;
}

So yeah. To reiterate: I want 6 identical versions of these tables/calculators on a page, and I want one simple, easy code to script all 6 of them since they're identical. Thank you.

Body:
The first principle in DRY is to use metadata (here units and tabMeta).
then it is to use them to generate the HTML for all 6 tables.

otherwise for the rest of DRY questions, JavaScript allows event delegation (use here to detect the slightest change in value (your submit button is useless).

There are also a whole host of array methods that you should study in detail.

sample code:

const
  twoDgts = t => (t<10) ? `0${t}` : t.toString(10)
, tablesBox = document.querySelector('#tables-box')
, units =
    { minutes : { lib: 'm', val:  1 }
    , hours   : { lib: 'h', val: 60 }
    , days    : { lib: 'd', val:60 * 24 }
    }
, tabMeta =
    [ { base:  1, unit: units.minutes }, { base:  3, unit: units.minutes }
    , { base:  5, unit: units.minutes }, { base: 10, unit: units.minutes }
    , { base: 15, unit: units.minutes }, { base: 30, unit: units.minutes }
    , { base: 45, unit: units.minutes }, { base: 60, unit: units.minutes }
    , { base:  3, unit: units.hours   }, { base:  8, unit: units.hours   }
    , { base: 15, unit: units.hours   }, { base: 24, unit: units.hours   }
    , { base:  3, unit: units.days    }, { base:  7, unit: units.days    }
    , { base: 30, unit: units.days    }
    ];

tabMeta.forEach(({base, unit},i,arr)=>arr[i].value=base * unit.val) // add values

const tables = Array.from({length:6},()=>// IHM generator... ( 6 tables )
  {
  let tableN = tablesBox.appendChild( document.createElement('table'))

  tabMeta.forEach(({base,unit},indx)=>
    {
    let newRow = tableN.insertRow()
    newRow.insertCell().textContent = `${base} ${unit.lib}`
    newRow.insertCell().innerHTML = `<input type="number" min="0" value="0" data-indx="${indx}">`
    })
  tableN.insertRow().innerHTML = '<td colspan="2">&nbsp;<br>&nbsp;</td>'
  tableN.createTHead().insertRow().innerHTML = '<th colspan="2">Spead-Up</th>'
  return tableN
  })

tablesBox.oninput = e =>
  {
  if (!e.target.matches('input')) return
  MakeSum( e.target.closest('table'))
  }

function MakeSum( refTable )
  {
  let sum =
    [...refTable.querySelectorAll('td input[type=number]')]
    .reduce((sum,inputX)=> sum + (inputX.valueAsNumber * tabMeta[inputX.dataset.indx].value), 0)

  let mins = sum % 60; sum = (sum - mins) / 60
  let hrs  = sum % 24; sum = (sum - hrs) / 24

  refTable.querySelector('tr:last-of-type td').innerHTML =
    `${sum}${units.days.lib}<br>${twoDgts(hrs)}:${twoDgts(mins)}:00`
  }

table {
  display          : inline-block;
  font             : 14px Arial, Helvetica, sans-serif;
  white-space      : nowrap;
  border-collapse  : separate;
  border-spacing   : 1px;
  background-color : darkblue;
  margin           : 1em .4em;
  }
td, th {
  padding          : .3em .6em;
  background-color : whitesmoke;
  min-width        : 2em;
  }
td {
  text-align       : right;
  }
tr:last-of-type td {
  background-color : #a2e0da;
  text-align       : center;
  }
input[type=number] {
  border     : none;
  text-align : center;
  width      : 5em;
  }

<div id="tables-box"></div>


问:
Github Pages can't find Jekyll theme "Minimal Mistakes"
I've made a personal blog with Jakyll on Github Pages, it was working flawlessly with the default theme.

Then I've (locally) installed the theme Minimal Mistakes and worked on it to add some customizations. It works fine locally.

I'm using VS Code on Windows 10.

I then committed and synced the repo but GitHub Pages can't load the new theme apparently. The blog still works with the old one but I've got this error message from GitHUb Pages:

```<code>/usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/theme.rb:84:in `rescue in gemspec': The minimal-mistakes-jekyll theme could not be found. (Jekyll::Errors::MissingDependencyException)
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/theme.rb:81:in `gemspec'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/theme.rb:19:in `root'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/theme.rb:12:in `initialize'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/site.rb:439:in `new'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/site.rb:439:in `configure_theme'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/site.rb:55:in `config='
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/site.rb:23:in `initialize'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/commands/build.rb:30:in `new'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/commands/build.rb:30:in `process'
from /usr/local/bundle/gems/github-pages-223/bin/github-pages:70:in `block (3 levels) in <top (required)>'
from /usr/local/bundle/gems/mercenary-0.3.6/lib/mercenary/command.rb:220:in `block in execute'
from /usr/local/bundle/gems/mercenary-0.3.6/lib/mercenary/command.rb:220:in `each'
from /usr/local/bundle/gems/mercenary-0.3.6/lib/mercenary/command.rb:220:in `execute'
from /usr/local/bundle/gems/mercenary-0.3.6/lib/mercenary/program.rb:42:in `go'
from /usr/local/bundle/gems/mercenary-0.3.6/lib/mercenary.rb:19:in `program'
from /usr/local/bundle/gems/github-pages-223/bin/github-pages:6:in `<top (required)>'
from /usr/local/bundle/bin/github-pages:23:in `load'
from /usr/local/bundle/bin/github-pages:23:in `<main>'
</code>```

/usr/local/lib/ruby/2.7.0/rubygems/dependency.rb:311:in to_specs': Could not find 'minimal-mistakes-jekyll' (>= 0) among 159 total gem(s) (Gem::MissingSpecError) Checked in 'GEM_PATH=/github/home/.gem/ruby/2.7.0:/usr/local/lib/ruby/gems/2.7.0:/usr/local/bundle', execute gem envfor more information from /usr/local/lib/ruby/2.7.0/rubygems/dependency.rb:323:into_spec'
from /usr/local/lib/ruby/2.7.0/rubygems/specification.rb:986:in find_by_name' from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/theme.rb:82:in gemspec'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/theme.rb:19:in root' from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/theme.rb:12:in initialize'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/site.rb:439:in new' from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/site.rb:439:in configure_theme'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/site.rb:55:in config=' from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/site.rb:23:in initialize'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/commands/build.rb:30:in new' from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/commands/build.rb:30:in process'
from /usr/local/bundle/gems/github-pages-223/bin/github-pages:70:in block (3 levels) in <top (required)>' from /usr/local/bundle/gems/mercenary-0.3.6/lib/mercenary/command.rb:220:in block in execute'
from /usr/local/bundle/gems/mercenary-0.3.6/lib/mercenary/command.rb:220:in each' from /usr/local/bundle/gems/mercenary-0.3.6/lib/mercenary/command.rb:220:in execute'
from /usr/local/bundle/gems/mercenary-0.3.6/lib/mercenary/program.rb:42:in go' from /usr/local/bundle/gems/mercenary-0.3.6/lib/mercenary.rb:19:in program'
from /usr/local/bundle/gems/github-pages-223/bin/github-pages:6:in <top (required)>' from /usr/local/bundle/bin/github-pages:23:in load'
from /usr/local/bundle/bin/github-pages:23:in `'
Logging at level: debug
Configuration file: /github/workspace/./_config.yml
Theme: minimal-mistakes-jekyll
github-pages 223 | Error:  The minimal-mistakes-jekyll theme could not be found.

I've originally installed (and developed the whole blog) Ruby 3.0.
I suspect GitHub Pages needs 2.7.0?

You can have a look at my repo here

答:
From what I know, GitHub Pages Jekyll generator is quite limited at what it can do. It doesn't support too much customization, especially not adding new gems. What you actually need to do is to push a static CSS/HTML site into GitHub Pages... generated with Jekyll, BUT for example by GitHub Actions.

All this is counter-intuitive, I know. But the solution is fairly simple.

All you need to do, is to follow the instruction located here: https://github.com/helaili/jekyll-action

The guide tells you, that all you need to do is to create a .github/workflows/pages.yml with the following content:

name: Testing the GitHub Pages publication

on:
  push

jobs:
  jekyll:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2

    # Use GitHub Actions' cache to shorten build times and decrease load on servers
    - uses: actions/cache@v2
      with:
        path: vendor/bundle
        key: ${{ runner.os }}-gems-${{ hashFiles('**/Gemfile') }}
        restore-keys: |
          ${{ runner.os }}-gems-

    # Standard usage
    - uses:  helaili/jekyll-action@v2
      with:
        token: ${{ secrets.GITHUB_TOKEN }}
```

And change the publishing branch to gh-pages afterwards.

Body:
I've made a personal blog with Jakyll on Github Pages, it was working flawlessly with the default theme.

Then I've (locally) installed the theme Minimal Mistakes and worked on it to add some customizations. It works fine locally.

I'm using VS Code on Windows 10.

I then committed and synced the repo but GitHub Pages can't load the new theme apparently. The blog still works with the old one but I've got this error message from GitHUb Pages:

/usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/theme.rb:84:in `rescue in gemspec': The minimal-mistakes-jekyll theme could not be found. (Jekyll::Errors::MissingDependencyException)
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/theme.rb:81:in `gemspec'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/theme.rb:19:in `root'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/theme.rb:12:in `initialize'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/site.rb:439:in `new'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/site.rb:439:in `configure_theme'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/site.rb:55:in `config='
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/site.rb:23:in `initialize'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/commands/build.rb:30:in `new'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/commands/build.rb:30:in `process'
from /usr/local/bundle/gems/github-pages-223/bin/github-pages:70:in `block (3 levels) in <top (required)>'
from /usr/local/bundle/gems/mercenary-0.3.6/lib/mercenary/command.rb:220:in `block in execute'
from /usr/local/bundle/gems/mercenary-0.3.6/lib/mercenary/command.rb:220:in `each'
from /usr/local/bundle/gems/mercenary-0.3.6/lib/mercenary/command.rb:220:in `execute'
from /usr/local/bundle/gems/mercenary-0.3.6/lib/mercenary/program.rb:42:in `go'
from /usr/local/bundle/gems/mercenary-0.3.6/lib/mercenary.rb:19:in `program'
from /usr/local/bundle/gems/github-pages-223/bin/github-pages:6:in `<top (required)>'
from /usr/local/bundle/bin/github-pages:23:in `load'
from /usr/local/bundle/bin/github-pages:23:in `'

/usr/local/lib/ruby/2.7.0/rubygems/dependency.rb:311:in to_specs': Could not find 'minimal-mistakes-jekyll' (>= 0) among 159 total gem(s) (Gem::MissingSpecError) Checked in 'GEM_PATH=/github/home/.gem/ruby/2.7.0:/usr/local/lib/ruby/gems/2.7.0:/usr/local/bundle', execute gem envfor more information from /usr/local/lib/ruby/2.7.0/rubygems/dependency.rb:323:into_spec'
from /usr/local/lib/ruby/2.7.0/rubygems/specification.rb:986:in find_by_name' from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/theme.rb:82:in gemspec'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/theme.rb:19:in root' from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/theme.rb:12:in initialize'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/site.rb:439:in new' from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/site.rb:439:in configure_theme'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/site.rb:55:in config=' from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/site.rb:23:in initialize'
from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/commands/build.rb:30:in new' from /usr/local/bundle/gems/jekyll-3.9.0/lib/jekyll/commands/build.rb:30:in process'
from /usr/local/bundle/gems/github-pages-223/bin/github-pages:70:in block (3 levels) in <top (required)>' from /usr/local/bundle/gems/mercenary-0.3.6/lib/mercenary/command.rb:220:in block in execute'
from /usr/local/bundle/gems/mercenary-0.3.6/lib/mercenary/command.rb:220:in each' from /usr/local/bundle/gems/mercenary-0.3.6/lib/mercenary/command.rb:220:in execute'
from /usr/local/bundle/gems/mercenary-0.3.6/lib/mercenary/program.rb:42:in go' from /usr/local/bundle/gems/mercenary-0.3.6/lib/mercenary.rb:19:in program'
from /usr/local/bundle/gems/github-pages-223/bin/github-pages:6:in <top (required)>' from /usr/local/bundle/bin/github-pages:23:in load'
from /usr/local/bundle/bin/github-pages:23:in `'
Logging at level: debug
Configuration file: /github/workspace/./_config.yml
Theme: minimal-mistakes-jekyll
github-pages 223 | Error:  The minimal-mistakes-jekyll theme could not be found.

I've originally installed (and developed the whole blog) Ruby 3.0.
I suspect GitHub Pages needs 2.7.0?

You can have a look at my repo here

Body:
From what I know, GitHub Pages Jekyll generator is quite limited at what it can do. It doesn't support too much customization, especially not adding new gems. What you actually need to do is to push a static CSS/HTML site into GitHub Pages... generated with Jekyll, BUT for example by GitHub Actions.

All this is counter-intuitive, I know. But the solution is fairly simple.

All you need to do, is to follow the instruction located here: https://github.com/helaili/jekyll-action

The guide tells you, that all you need to do is to create a .github/workflows/pages.yml with the following content:

name: Testing the GitHub Pages publication

on:
  push

jobs:
  jekyll:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2

    # Use GitHub Actions' cache to shorten build times and decrease load on servers
    - uses: actions/cache@v2
      with:
        path: vendor/bundle
        key: ${{ runner.os }}-gems-${{ hashFiles('**/Gemfile') }}
        restore-keys: |
          ${{ runner.os }}-gems-

    # Standard usage
    - uses:  helaili/jekyll-action@v2
      with:
        token: ${{ secrets.GITHUB_TOKEN }}

And change the publishing branch to gh-pages afterwards.