问:
How to append the first zero's of HEX to the BIN string?
I am trying to implement a bits extractor for CAN bus data in Excel. I struggle with the algorithm part therefore this is mainly independent from Excel/openpyxl.

I have a table with the ID being stored in column B and the binary code per time step in column F. I want to parse through the binary numbers and extract the parts which contains the signals' value. One ID can have one or more signals. Depending on the ID, I want to go through all the rows and convert the binary to decimal (as shown below). The IDs contain either 3, 4, 5, 6, 7 or 8 bytes, which is defined for each ID (example below: 2E has 8bytes, 4A has 5bytes).

Input:

```<code>A  B  C D  E            F            G   H  .. M
.. 2E .... 0000000000000AA4..
...4A ...  02478304B..
</code>```

Organized Input:
    A  B  C D  E            F            G   H  .. M
    .. 2E .... 00 00 00 00 00 00 0A A4..
    ...4A ...  00 24 78 30 4B..

Current Output:

```<code>A B  C D E     F   G    H  .. M
..2E .... ...  101010100100
..4A .......   100100011110000011000001001011
</code>```

Wanted Output:

```<code>A B  C D E     F   G    H  .. M
..2E .... ...  0000000000000000000000000000000000000000000000000000101010100100
..4A .......   100100011110000011000001001011
</code>```

QUESTION:
Since in the beginning of the measurement, most of the values are set to zero (in HEX, in column E), the BIN does not include them and the signals cannot be extracted correctly. I do not know how to do this in the convertHEXtoBIN() function (see below).
The HEX value in column E is a string from which I did successfully convert to BIN but the zero's in the beginning were not included into the BIN code. Those zero's in the end are included.

Approach:
In the function below, I would add an if-clause to catch the first zero's the cell.value contains a zero until the first HEX code != 0 shows up and then these zero's are then appended the eightfold (8 times a zero if two zero's show up, 4 times if one zero shows up) and put before binary code res. Another solution might be to let the convertHEXtoBIN() function to include zero's (instead of neglecting them) but I don't know whether this is even possible...

Do you have an idea how to implement this?

The code so far:

```<code>import openpyxl
from openpyxl import Workbook

theFile = openpyxl.load_workbook('Adapted_T013.xlsx')
allSheetNames = theFile.sheetnames
print("All sheet names {} " .format(theFile.sheetnames))
sheet = theFile.active
def convertHEXtoBIN():
    max_row_var = sheet.max_row+1
    for row in sheet.iter_rows(min_row=1, max_row=max_row_var,values_only = True):
        for cell in sheet["E"]:
            if cell.value is not None:
                inputHEX = str(cell.value)
                res = "{0:08b}".format(int(inputHEX,16))
                sheet.cell(row=cell.row, column=6).value = res
        break
</code>```

答:
You need 8 characters of binary for every 2 characters of hex.

That is an easy calculation and you can let python do the padding for you.

```<code>inputHEX = str(cell.value)
res = "{value:0{width}b}".format(value=int(inputHEX, 16), width=len(inputHEX) * 4)
sheet.cell(row=cell.row, column=6).value = res
</code>```

Apart from that, I think you would get more answers if you would ask simple questions like "how to keep leading zeros when converting hex to binary" or something like that.
The layout of your Excel, the fact that this is CAN-data and so on does not really matter.

Body:
I am trying to implement a bits extractor for CAN bus data in Excel. I struggle with the algorithm part therefore this is mainly independent from Excel/openpyxl.

I have a table with the ID being stored in column B and the binary code per time step in column F. I want to parse through the binary numbers and extract the parts which contains the signals' value. One ID can have one or more signals. Depending on the ID, I want to go through all the rows and convert the binary to decimal (as shown below). The IDs contain either 3, 4, 5, 6, 7 or 8 bytes, which is defined for each ID (example below: 2E has 8bytes, 4A has 5bytes).

Input:

A  B  C D  E            F            G   H  .. M
.. 2E .... 0000000000000AA4..
...4A ...  02478304B..

Organized Input:
    A  B  C D  E            F            G   H  .. M
    .. 2E .... 00 00 00 00 00 00 0A A4..
    ...4A ...  00 24 78 30 4B..

Current Output:

A B  C D E     F   G    H  .. M
..2E .... ...  101010100100
..4A .......   100100011110000011000001001011

Wanted Output:

A B  C D E     F   G    H  .. M
..2E .... ...  0000000000000000000000000000000000000000000000000000101010100100
..4A .......   100100011110000011000001001011

QUESTION:
Since in the beginning of the measurement, most of the values are set to zero (in HEX, in column E), the BIN does not include them and the signals cannot be extracted correctly. I do not know how to do this in the convertHEXtoBIN() function (see below).
The HEX value in column E is a string from which I did successfully convert to BIN but the zero's in the beginning were not included into the BIN code. Those zero's in the end are included.

Approach:
In the function below, I would add an if-clause to catch the first zero's the cell.value contains a zero until the first HEX code != 0 shows up and then these zero's are then appended the eightfold (8 times a zero if two zero's show up, 4 times if one zero shows up) and put before binary code res. Another solution might be to let the convertHEXtoBIN() function to include zero's (instead of neglecting them) but I don't know whether this is even possible...

Do you have an idea how to implement this?

The code so far:

import openpyxl
from openpyxl import Workbook

theFile = openpyxl.load_workbook('Adapted_T013.xlsx')
allSheetNames = theFile.sheetnames
print("All sheet names {} " .format(theFile.sheetnames))
sheet = theFile.active
def convertHEXtoBIN():
    max_row_var = sheet.max_row+1
    for row in sheet.iter_rows(min_row=1, max_row=max_row_var,values_only = True):
        for cell in sheet["E"]:
            if cell.value is not None:
                inputHEX = str(cell.value)
                res = "{0:08b}".format(int(inputHEX,16))
                sheet.cell(row=cell.row, column=6).value = res
        break

Body:
You need 8 characters of binary for every 2 characters of hex.

That is an easy calculation and you can let python do the padding for you.

inputHEX = str(cell.value)
res = "{value:0{width}b}".format(value=int(inputHEX, 16), width=len(inputHEX) * 4)
sheet.cell(row=cell.row, column=6).value = res

Apart from that, I think you would get more answers if you would ask simple questions like "how to keep leading zeros when converting hex to binary" or something like that.
The layout of your Excel, the fact that this is CAN-data and so on does not really matter.


来源: stackexchange

问:
node.js 13 - import is not working properly
$ node --version
v13.8.0

Let's create three files:

```<code>// package.json
{
  "type": "module"
}

// foobar.js
function foo() { console.log('foo') }
export default {foo}

// index.js
import Foo from './foobar.js';
Foo.foo();
</code>```

Run index.js

```<code>$ node index.js
(node:22768) ExperimentalWarning: The ESM module loader is experimental.
foo
</code>```

All working.

And now changing './foobar.js'; to './foobar';

```<code>// index.js
import Foo from './foobar';
Foo.foo();
</code>```

And we get an error!

```<code>(node:22946) ExperimentalWarning: The ESM module loader is experimental.
internal/modules/esm/resolve.js:58
  let url = moduleWrapResolve(specifier, parentURL);
            ^
Error: Cannot find module /foobar imported from /index.js
</code>```

There is no other files in directory.

Why does it happens?
Why import without extension doesn't work?

UPDATE:
https://nodejs.org/api/esm.html

package.json "type" field

Files ending with .js or lacking any extension will be loaded as ES  modules when the nearest parent package.json file contains a top-level field "type" with a value of "module".

So './foobar' must work.

UPDATE 2:

I believe what the documentation call "extensionless files" are literaly files without extensions, not files imported without extensions.

For example, if you import your file with import Foo from './foobar';, and you file is called foobar without the .js extension, it will work fine.

Thanks to @Seblor

答:
Looking at the documentation, in the category Differences Between ES Modules and CommonJS, and more precisely at the "Mandatory file extensions" section, it says that the .js  file extension must be present to make the import work :

A file extension must be provided when using the import keyword. Directory indexes (e.g. './startup/index.js') must also be fully specified.

This behavior matches how import behaves in browser environments, assuming a typically configured server.

I am not sure why your last question is about the import without extention not working anymore. I guess you have been working at some point with a transpiler like babel that will resolve the files without the extensions.

Edit :

I believe what the documentation call "extensionless files" are literaly files without extensions, not files imported without extensions.

For example, if you import your file with import Foo from './foobar';, and you file is called foobar without the .js extension, it will work fine.

ContentLicense: CC BY-SA 4.0

Body:
$ node --version
v13.8.0

Let's create three files:

// package.json
{
  "type": "module"
}

// foobar.js
function foo() { console.log('foo') }
export default {foo}

// index.js
import Foo from './foobar.js';
Foo.foo();

Run index.js

$ node index.js
(node:22768) ExperimentalWarning: The ESM module loader is experimental.
foo

All working.

And now changing './foobar.js'; to './foobar';

// index.js
import Foo from './foobar';
Foo.foo();

And we get an error!

(node:22946) ExperimentalWarning: The ESM module loader is experimental.
internal/modules/esm/resolve.js:58
  let url = moduleWrapResolve(specifier, parentURL);
            ^
Error: Cannot find module /foobar imported from /index.js

There is no other files in directory.

Why does it happens?
Why import without extension doesn't work?

UPDATE:
https://nodejs.org/api/esm.html

package.json "type" field

Files ending with .js or lacking any extension will be loaded as ES  modules when the nearest parent package.json file contains a top-level field "type" with a value of "module".

So './foobar' must work.

UPDATE 2:

I believe what the documentation call "extensionless files" are literaly files without extensions, not files imported without extensions.

For example, if you import your file with import Foo from './foobar';, and you file is called foobar without the .js extension, it will work fine.

Thanks to @Seblor


问:
How to add caffe to anaconda on windows?
I'm trying to use Caffe in Anaconda3 on windows, but when I try to import caffe in iPython, it shows this error:

ImportError: No module named caffe

I tried to add a new system variable named PYTHONPATH which looks like this:

```<code>C:\Users\Hadi\Anaconda3;C:\Projects\caffe\python\caffe;C:\Projects\caffe\python
</code>```

It still shows the same error. I would appreciate if anyone mentioned what am I missing here?

答:
caffe doesn't have support for windows as it have for others. After trying many things, i am able to import caffe. The best solution i find is the git link https://github.com/Microsoft/caffe .

Create a virtual environment in Anaconda, python = 3.7 and then follow the instructions.

You would have to make changes CommonSettings.props as mentioned in the documentation for CUDA and cuDNN if you would be using it with CPU only.

clone repository to the location and copy caffe folder to .\anaconda3\envs\env_caffe\Lib\site-packages location as stated in the documentation .

and finally un the following commands from elevated command prompt:

conda install --yes numpy scipy matplotlib scikit-image pip
pip install protobuf.

Read the instruction carefully and then proceed.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to use Caffe in Anaconda3 on windows, but when I try to import caffe in iPython, it shows this error:

ImportError: No module named caffe

I tried to add a new system variable named PYTHONPATH which looks like this:

C:\Users\Hadi\Anaconda3;C:\Projects\caffe\python\caffe;C:\Projects\caffe\python

It still shows the same error. I would appreciate if anyone mentioned what am I missing here?


问:
How to delete/detect any emoji as a whole from a string in Flutter?
I would like to simulate a keyboard backspace delete event from a string in Flutter (or Dart). Something like:

String str = "hello你们"
myBackspace(str) // will return "hello你们"
myBackspace(str) // will return "hello你们"
myBackspace(str) // will return "hello你们"
myBackspace(str) // will return "hello你"
myBackspace(str) // will return "hello"
myBackspace(str) // will return "hello"
myBackspace(str) // will return "hell"
```

答:
if someone need simple solution to remove emojies from string try this.   </p>

```<code>String str = "hello你们"İ
    final RegExp REGEX_EMOJI = RegExp(r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])');
    if(str.contains(REGEX_EMOJI)){
       str = str.replaceAll(REGEX_EMOJI,'');
     }
</code>```

Body:
if someone need simple solution to remove emojies from string try this.

String str = "hello你们"İ
    final RegExp REGEX_EMOJI = RegExp(r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])');
    if(str.contains(REGEX_EMOJI)){
       str = str.replaceAll(REGEX_EMOJI,'');
     }


问:
How to get which date is on particular saturday or sunday of a month
Can I find the date of a day that is on which dates the saturdays and sundays of a specific month fall
For e.g Consider the month of JANUARY-2017. The following dates are weekends

```<code>7/1/2017 - Saturday

14/1/2017 - Saturday

21/1/2017 - Saturday

28/1/2017 - Saturday
</code>```

```<code>1/1/2017 - Sunday

8/1/2017 - Sunday

15/1/2017 - Sunday

22/1/2017 - Sunday

29/1/2017 - Sunday
</code>```

I want SQL query for this such that when I give Month and Year as input it should give me all the above dates (only dates of saturday and sunday) as output

答:
I will do some major changes above code
we are get the all sundays and saturdays in year</p>

```<code>SELECT TRUNC(dt, 'yyyy') + LEVEL - 1 AS mdate
,to_char(TRUNC(dt, 'yyyy') + LEVEL - 1,'DY' ) as m_day
FROM
(select to_date('2020-01','YYYY-MM') as dt from dual) --this is where you can put year/month
where to_char(TRUNC(dt, 'yyyy') + LEVEL - 1,'DY' ) in ('SAT','SUN')
CONNECT BY TRUNC(TRUNC(dt, 'yyyy') + LEVEL - 1, 'yyyy') = TRUNC(dt, 'yyyy')
</code>```

Body:
Can I find the date of a day that is on which dates the saturdays and sundays of a specific month fall
For e.g Consider the month of JANUARY-2017. The following dates are weekends

7/1/2017 - Saturday

14/1/2017 - Saturday

21/1/2017 - Saturday

28/1/2017 - Saturday

1/1/2017 - Sunday

8/1/2017 - Sunday

15/1/2017 - Sunday

22/1/2017 - Sunday

29/1/2017 - Sunday

I want SQL query for this such that when I give Month and Year as input it should give me all the above dates (only dates of saturday and sunday) as output

Body:
I will do some major changes above code
we are get the all sundays and saturdays in year

SELECT TRUNC(dt, 'yyyy') + LEVEL - 1 AS mdate
,to_char(TRUNC(dt, 'yyyy') + LEVEL - 1,'DY' ) as m_day
FROM
(select to_date('2020-01','YYYY-MM') as dt from dual) --this is where you can put year/month
where to_char(TRUNC(dt, 'yyyy') + LEVEL - 1,'DY' ) in ('SAT','SUN')
CONNECT BY TRUNC(TRUNC(dt, 'yyyy') + LEVEL - 1, 'yyyy') = TRUNC(dt, 'yyyy')


问:
Why can't I push change to this up-to-date Git subtree?
I have a git subtree module called "gempak-tables" in subdirectory "gempak/tables":

```<code>$ git config -l | grep -i gempak
remote.gempak-tables.url=git@github.com:Unidata/GEMPAK-Tables.git
remote.gempak-tables.fetch=+refs/heads/*:refs/remotes/gempak-tables/*
$
</code>```

I can't push changes to the subtree module to GitHub, however:

```<code>$ git subtree push --prefix=gempak/tables gempak-tables master
git push using:  gempak-tables master
X11 forwarding request failed on channel 0
To git@github.com:Unidata/GEMPAK-Tables.git
 ! [rejected]        89d8f94d010e6677f146608674cf7408eecb4a61 -> master (non-fast-forward)
error: failed to push some refs to 'git@github.com:Unidata/GEMPAK-Tables.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Merge the remote changes (e.g. 'git pull')
hint: before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
$
</code>```

even though the subtree module appears to be up-to-date:

```<code>$ git subtree pull --prefix=gempak/tables gempak-tables master
X11 forwarding request failed on channel 0
From github.com:Unidata/GEMPAK-Tables
 * branch            master     -> FETCH_HEAD
Already up-to-date.
$
</code>```

My git(1) version:

```<code>$ git --version
git version 1.8.3.1
</code>```

I'm a subtree novice. Please help.

答:
The answer is most probably given already by Git subtree - subtree up-to-date but can't push

I found the answer on this blog comment https://coderwall.com/p/ssxp5q

If you come across the Updates were rejected because the tip of your current branch is behind. Merge the remote changes (e.g. 'git pull') problem when you're pushing (due to whatever reason, esp screwing about with git history) then you'll need to nest git commands so that you can force a push to heroku. e.g, given the above example:

git push heroku `git subtree split --prefix pythonapp master`:master --force

Body:
I have a git subtree module called "gempak-tables" in subdirectory "gempak/tables":

$ git config -l | grep -i gempak
remote.gempak-tables.url=git@github.com:Unidata/GEMPAK-Tables.git
remote.gempak-tables.fetch=+refs/heads/*:refs/remotes/gempak-tables/*
$

I can't push changes to the subtree module to GitHub, however:

$ git subtree push --prefix=gempak/tables gempak-tables master
git push using:  gempak-tables master
X11 forwarding request failed on channel 0
To git@github.com:Unidata/GEMPAK-Tables.git
 ! [rejected]        89d8f94d010e6677f146608674cf7408eecb4a61 -> master (non-fast-forward)
error: failed to push some refs to 'git@github.com:Unidata/GEMPAK-Tables.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Merge the remote changes (e.g. 'git pull')
hint: before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
$

even though the subtree module appears to be up-to-date:

$ git subtree pull --prefix=gempak/tables gempak-tables master
X11 forwarding request failed on channel 0
From github.com:Unidata/GEMPAK-Tables
 * branch            master     -> FETCH_HEAD
Already up-to-date.
$

My git(1) version:

$ git --version
git version 1.8.3.1

I'm a subtree novice. Please help.


问:
Selenide profiler in TestNG
I have problem to generate profiler report(with TestNG) in my TC.

As it is written on selenide.org page, I add following :

```<code>@Listeners(TextReport.class)
@Report
public class GoogleTest {
   ...
}
</code>```

Test is correctly running, but I do not see the profiler report.

Do you have any idea, how can I fix it and see the report?

答:
You should have slf4j in your classpath.

Add testCompile 'org.slf4j:slf4j-simple:1.7.30' to your gradle.build .

Or in maven:

```<code><dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.30</version>
    <scope>test</scope>
</dependency>
</code>```

Title: Selenide profiler in TestNG

Body:
I have problem to generate profiler report(with TestNG) in my TC.

As it is written on selenide.org page, I add following :

@Listeners(TextReport.class)
@Report
public class GoogleTest {
   ...
}

Test is correctly running, but I do not see the profiler report.

Do you have any idea, how can I fix it and see the report?

Body:
You should have slf4j in your classpath.

Add testCompile 'org.slf4j:slf4j-simple:1.7.30' to your gradle.build .

Or in maven:

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.30</version>
    <scope>test</scope>
</dependency>


问:
is there any method in python to replace nan in dataframe by string without effect blank cell
I have dataframe with values Na, blank and others. I want to replace Na with noted  (string value)
I want to transform from here to here without changing blank cell.

I already tried

```<code>df['A']=df['A'].replace(regex=['NaN'], value='needed')
</code>```

and

```<code>df['A'].replace(regex=['NA'], value='noted
</code>```

答:
You can use fillna():

```<code>df['A'].fillna('noted')
</code>```

Alternatively, if NA is a string and not np.nan then you can use replace():

```<code>df['A'].replace(['NA'], 'noted')
</code>```

Body:
I have dataframe with values Na, blank and others. I want to replace Na with noted  (string value)
I want to transform from here to here without changing blank cell.

I already tried

df['A']=df['A'].replace(regex=['NaN'], value='needed')

and

df['A'].replace(regex=['NA'], value='noted

Body:
You can use fillna():

df['A'].fillna('noted')

Alternatively, if NA is a string and not np.nan then you can use replace():

df['A'].replace(['NA'], 'noted')


问:
Is it possible to write a read-only property of an enumerator?
Suppose I have a class Seat with an enumerator of type SeatType with the enum values Window, Aisle, and Middle as follows:

```<code>public enum SeatType
{
Window,
Aisle,
Middle
}
</code>```

Is it possible to use an enumerator like a property? I was attempting to make a way to assign a seat object's SeatType usable based on reading another variable as follows, but I am unsure this is the right way to return a seat type SeatType based upon a given seat letter _seatLetter. I was attempting to make it so that if the _seatLetter instance variable of an object is a certain character then the object's enumerator is either Window, Aisle, or Middle.

```<code>public enum Type
{
  get
  {
    if (_seatLetter == 'A' or _seatLetter == 'F')
    {
      return SeatType.Window;
    }
    else if (_seatLetter == 'C' or _seatLetter == 'D')
    {
      return SeatType.Aisle;
    }
    else
    {
      return SeatType.Middle;
    }
  }
}
</code>```

答:
You can use many approaches depending on your starting situation, that we don't know.

This is a possible approach:

```<code>class Program
{
    static void Main(string[] args)
    {
        Seat seat = new Seat('A');
    }
}

public class Seat
{
    public SeatType Type { get; set; }

    public Seat(char seatLetter)
    {
        SetSeatType(seatLetter);
    }

    public void SetSeatType(char seatLetter)
    {
        switch (seatLetter)
        {
            case 'A':
            case 'F':
                Type = SeatType.Window;
                break;
            case 'C':
            case 'D':
                Type = SeatType.Aisle;
                break;
            default:
                Type = SeatType.Middle;
                break;
        }
    }
}

public enum SeatType
{
    Window,
    Aisle,
    Middle
}
</code>```

Body:
Suppose I have a class Seat with an enumerator of type SeatType with the enum values Window, Aisle, and Middle as follows:

public enum SeatType
{
Window,
Aisle,
Middle
}

Is it possible to use an enumerator like a property? I was attempting to make a way to assign a seat object's SeatType usable based on reading another variable as follows, but I am unsure this is the right way to return a seat type SeatType based upon a given seat letter _seatLetter. I was attempting to make it so that if the _seatLetter instance variable of an object is a certain character then the object's enumerator is either Window, Aisle, or Middle.

public enum Type
{
  get
  {
    if (_seatLetter == 'A' or _seatLetter == 'F')
    {
      return SeatType.Window;
    }
    else if (_seatLetter == 'C' or _seatLetter == 'D')
    {
      return SeatType.Aisle;
    }
    else
    {
      return SeatType.Middle;
    }
  }
}

Body:
You can use many approaches depending on your starting situation, that we don't know.

This is a possible approach:

class Program
{
    static void Main(string[] args)
    {
        Seat seat = new Seat('A');
    }
}

public class Seat
{
    public SeatType Type { get; set; }

    public Seat(char seatLetter)
    {
        SetSeatType(seatLetter);
    }

    public void SetSeatType(char seatLetter)
    {
        switch (seatLetter)
        {
            case 'A':
            case 'F':
                Type = SeatType.Window;
                break;
            case 'C':
            case 'D':
                Type = SeatType.Aisle;
                break;
            default:
                Type = SeatType.Middle;
                break;
        }
    }
}

public enum SeatType
{
    Window,
    Aisle,
    Middle
}


问:
Skipping the first column while renaming column using for loop in python
The ask is simple, for renaming multiple dataframe's with a single code I have written the below but when I am using the code the column which contains the primary key is also getting renamed what I want my code to do is to skip the first column and rename the rest.

Codes have been provided below for better understanding of what I am trying to achieve:

```<code>import pandas as pd

USA = pd.read_excel(r"C:\Users\Rage\Desktop\usa.xlsx")
BRA = pd.read_excel(r"C:\Users\Rage\Desktop\usa.xlsx")
CAN = pd.read_excel(r"C:\Users\Rage\Desktop\usa.xlsx")

df_dict = {"USA":USA, "BRA":BRA, "CAN":CAN}

for name, df in df_dict.items():
        df.columns = df.columns + "_" + name
</code>```

Which gives me the below output:

```<code>Primary Key_CAN local stat_CAN  valid stat_CAN  valid date_CAN
123                Approved        completed      2018-02-02
554                Restrict        pending        2020-06-05
789                Declined        pending        2016-08-07
</code>```

Which is perfect but with one problem I want the loop to skip the first column that is "Primary key"
Making my expected output to be below:

```<code>Primary Key   local stat_CAN      valid stat_CAN valid date_CAN
123                Approved        completed      2018-02-02
554                Restrict        pending        2020-06-05
789                Declined        pending        2016-08-07
</code>```

答:
You should split the columns index in 2 sublists and only change the second one:

```<code>df.columns = [df.columns[0]] + (df.columns[1:] + '_' + 'CAN').tolist()
</code>```

Body:
The ask is simple, for renaming multiple dataframe's with a single code I have written the below but when I am using the code the column which contains the primary key is also getting renamed what I want my code to do is to skip the first column and rename the rest.

Codes have been provided below for better understanding of what I am trying to achieve:

import pandas as pd

USA = pd.read_excel(r"C:\Users\Rage\Desktop\usa.xlsx")
BRA = pd.read_excel(r"C:\Users\Rage\Desktop\usa.xlsx")
CAN = pd.read_excel(r"C:\Users\Rage\Desktop\usa.xlsx")

df_dict = {"USA":USA, "BRA":BRA, "CAN":CAN}

for name, df in df_dict.items():
        df.columns = df.columns + "_" + name

Which gives me the below output:

Primary Key_CAN local stat_CAN  valid stat_CAN  valid date_CAN
123                Approved        completed      2018-02-02
554                Restrict        pending        2020-06-05
789                Declined        pending        2016-08-07

Which is perfect but with one problem I want the loop to skip the first column that is "Primary key"
Making my expected output to be below:

Primary Key   local stat_CAN      valid stat_CAN valid date_CAN
123                Approved        completed      2018-02-02
554                Restrict        pending        2020-06-05
789                Declined        pending        2016-08-07

Body:
You should split the columns index in 2 sublists and only change the second one:

df.columns = [df.columns[0]] + (df.columns[1:] + '_' + 'CAN').tolist()


问:
Is it possible to refresh a View Component in an ASP.NET Core 2.1 Razor page?
Is it possible to refresh a View Component in an ASP.NET Core 2.1 Razor page?

I discovered that this is possible in ASP.NET MVC using AJAX—see solutions at Viewcomponent alternative for ajax refresh and ViewComponents are not async. But what about ASP.NET Core?

One solution I found is basically to have a controller returning the View Component, and then using AJAX to do the refresh.

This is example is borrowed from ViewComponents are not async

~/HelloWorldViewComponent.cs

```<code>public class HelloWorldViewComponent : ViewComponent
{
    public IViewComponentResult Invoke()
    {
        var model = new string[]
        {
            "Hello", "from", "the", "view", "component."
        };

        return View("Default", model);
    }
}
</code>```

~/HomeController.cs (I cannot get this part working in razor pages)

```<code>public class HomeController : Controller
{
    public IActionResult GetHelloWorld()
    {
        return ViewComponent("HelloWorld");
    }
}
</code>```

~/Views/Shared/Components/HelloWorld/Default.cshtml

```<code>@model string[]
<ul>
    @foreach(var item in Model)
    {
        <li>@item</li>
    }
</ul>
</code>```

~/wwwroot/index.html

```<code><body>
<script src="js/jquery.min.js"></script>
<script>
    $.get("home/GetHelloWorld", function(data) {
        $("body").html(data);
    });
</script>
</body>
</code>```

My problem is that I cannot get a controller working together with Razor Pages, I cannot figure out if that's even possible.

答:
To do this within the RazorPage ensure that the handler method follows the convention OGet[MyMethodName] and this should resolve your routing issue

```<code>public class HomeController : Controller
{
    public IActionResult OnGetHelloWorld()
    {
        return ViewComponent("HelloWorld");
    }
}
</code>```

And modify the get request to make use of the handler

```<code><body>
<script src="js/jquery.min.js"></script>
<script>
    $.get(window.location.href.split('?')[0] + "?handler=HelloWorld", function(data) {
        $("body").html(data);
    });
</script>
</body>
</code>```

Various example are available at https://learn.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-3.1&tabs=visual-studio

Body:
Is it possible to refresh a View Component in an ASP.NET Core 2.1 Razor page?

I discovered that this is possible in ASP.NET MVC using AJAX—see solutions at Viewcomponent alternative for ajax refresh and ViewComponents are not async. But what about ASP.NET Core?

One solution I found is basically to have a controller returning the View Component, and then using AJAX to do the refresh.

This is example is borrowed from ViewComponents are not async

~/HelloWorldViewComponent.cs

public class HelloWorldViewComponent : ViewComponent
{
    public IViewComponentResult Invoke()
    {
        var model = new string[]
        {
            "Hello", "from", "the", "view", "component."
        };

        return View("Default", model);
    }
}

~/HomeController.cs (I cannot get this part working in razor pages)

public class HomeController : Controller
{
    public IActionResult GetHelloWorld()
    {
        return ViewComponent("HelloWorld");
    }
}

~/Views/Shared/Components/HelloWorld/Default.cshtml

@model string[]

    @foreach(var item in Model)
    {

@item

    }

~/wwwroot/index.html

My problem is that I cannot get a controller working together with Razor Pages, I cannot figure out if that's even possible.

Body:
To do this within the RazorPage ensure that the handler method follows the convention OGet[MyMethodName] and this should resolve your routing issue

public class HomeController : Controller
{
    public IActionResult OnGetHelloWorld()
    {
        return ViewComponent("HelloWorld");
    }
}

And modify the get request to make use of the handler

<body>
<script src="js/jquery.min.js"></script>
<script>
    $.get(window.location.href.split('?')[0] + "?handler=HelloWorld", function(data) {
        $("body").html(data);
    });
</script>
</body>

Various example are available at https://learn.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-3.1&tabs=visual-studio


问:
2D conditional calculation
I have a spreadsheet with list of Products sold over time, with each product having it's class (I'd prefer if classes would be unlimited, but I can also live with predefined classes) and status active/inactive.
I need an arrayformula for H5 to fill the yellow area (only active products). I've tried with combination of MMULT and Arrayformula, but no luck, maybe someone can help me out.</p>

答:
You need

an array formula to apply the criteria to all rows

if statements to verify either the checkboxes are checked

to sum over several columns with the same class

This is how you can do it:

Type into H5

=ARRAYFORMULA(if(AND(C$3=true; C$2="Class A");C5:C8;0)+if(AND(D$3=true; D$2="Class A");D5:D8;0)+if(AND(E$3=true; E$2="Class A");E5:E8;0)+if(AND(F$3=true; F$2="Class A");F5:F8;0))

and into I5

=ARRAYFORMULA(if(AND(C$3=true; C$2="Class B");C5:C8;0)+if(AND(D$3=true; D$2="Class B");D5:D8;0)+if(AND(E$3=true; E$2="Class B");E5:E8;0)+if(AND(F$3=true; F$2="Class B");F5:F8;0))

Title: 2D conditional calculation


问:
Create a TypeScript project in Visual Studio Community 2019
Is there a way to create a TypeScript project in Visual Studio Community 2019?

All the tutorial I see are from previous version of Visual Studio--with its corresponding old version of the "New project" form. However, on 2019 I can't seem to find the option, even after adding the TypeScript components on the Visual Studio Installer.

答:
You need to install the Project template manually.

https://marketplace.visualstudio.com/items?itemName=Rich-Newman.TypeScriptHTMLApplicationTemplate&ssr=false#overview


问:
How to force a web browser NOT to cache images

Background

I am writing and using a very simple CGI-based (Perl) content management tool for two pro-bono websites. It provides the website administrator with HTML forms for events where they fill the fields (date, place, title, description, links, etc.) and save it. On that form I allow the administrator to upload an image related to the event. On the HTML page displaying the form, I am also showing a preview of the picture uploaded (HTML img tag).

The Problem

The problem happens when the administrator wants to change the picture. He would just have to hit the "browse" button, pick a new picture and press ok. And this works fine.

Once the image is uploaded, my back-end CGI handles the upload and reloads the form properly.

The problem is that the image shown does not get refreshed. The old image is still shown, even though the database holds the right image. I have narrowed it down to the fact that the IMAGE IS CACHED in the web browser. If the administrator hits the RELOAD button in Firefox/Explorer/Safari, everything gets refreshed fine and the new image just appears.

My Solution - Not Working

I am trying to control the cache by writing a HTTP Expires instruction with a date very far in the past.

```<code>Expires: Mon, 15 Sep 2003 1:00:00 GMT
</code>```

Remember that I am on the administrative side and I don't really care if the pages takes a little longer to load because they are always expired.

But, this does not work either.

Notes

When uploading an image, its filename is not kept in the database. It is renamed as Image.jpg (to simply things out when using it). When replacing the existing image with a new one, the name doesn't change either. Just the content of the image file changes.

The webserver is provided by the hosting service/ISP. It uses Apache.

Question

Is there a way to force the web browser to NOT cache things from this page, not even images?

I am juggling with the option to actually "save the filename" with the database. This way, if the image is changed, the src of the IMG tag will also change. However, this requires a lot of changes throughout the site and I rather not do it if I have a better solution. Also, this will still not work if the new image uploaded has the same name (say the image is photoshopped a bit and re-uploaded).

答:
You must use a unique filename(s). Like this

```<code><img src="cars.png?1287361287" alt="">
</code>```

But this technique means high server usage and bandwidth wastage.
Instead, you should use the version number or date. Example:

```<code><img src="cars.png?2020-02-18" alt="">
</code>```

But you want it to never serve image from cache. For this, if the page does not use page cache, it is possible with PHP or server side.

```<code><img src="cars.png?<?php echo time();?>" alt="">
</code>```

However, it is still not effective. Reason: Browser cache ...
The last but most effective method is Native JAVASCRIPT. This simple code finds all images with a "NO-CACHE" class and makes the images almost unique. Put this between script tags.

```<code>var items = document.querySelectorAll("img.NO-CACHE");
for (var i = items.length; i--;) {
    var img = items[i];
    img.src = img.src + '?' + Date.now();
}
</code>```

USAGE

```<code><img class="NO-CACHE" src="https://upload.wikimedia.org/wikipedia/commons/6/6a/JavaScript-logo.png" alt="">
</code>```

RESULT(s) Like This

```<code>https://example.com/image.png?1582018163634
</code>```

OwnerDisplayName: philibertperusse

Body:
Background

I am writing and using a very simple CGI-based (Perl) content management tool for two pro-bono websites. It provides the website administrator with HTML forms for events where they fill the fields (date, place, title, description, links, etc.) and save it. On that form I allow the administrator to upload an image related to the event. On the HTML page displaying the form, I am also showing a preview of the picture uploaded (HTML img tag).

The Problem

The problem happens when the administrator wants to change the picture. He would just have to hit the "browse" button, pick a new picture and press ok. And this works fine.

Once the image is uploaded, my back-end CGI handles the upload and reloads the form properly.

The problem is that the image shown does not get refreshed. The old image is still shown, even though the database holds the right image. I have narrowed it down to the fact that the IMAGE IS CACHED in the web browser. If the administrator hits the RELOAD button in Firefox/Explorer/Safari, everything gets refreshed fine and the new image just appears.

My Solution - Not Working

I am trying to control the cache by writing a HTTP Expires instruction with a date very far in the past.

Expires: Mon, 15 Sep 2003 1:00:00 GMT

Remember that I am on the administrative side and I don't really care if the pages takes a little longer to load because they are always expired.

But, this does not work either.

Notes

When uploading an image, its filename is not kept in the database. It is renamed as Image.jpg (to simply things out when using it). When replacing the existing image with a new one, the name doesn't change either. Just the content of the image file changes.

The webserver is provided by the hosting service/ISP. It uses Apache.

Question

Is there a way to force the web browser to NOT cache things from this page, not even images?

I am juggling with the option to actually "save the filename" with the database. This way, if the image is changed, the src of the IMG tag will also change. However, this requires a lot of changes throughout the site and I rather not do it if I have a better solution. Also, this will still not work if the new image uploaded has the same name (say the image is photoshopped a bit and re-uploaded).

LastEditorDisplayName: jjnguy

Body:
You must use a unique filename(s). Like this

<img src="cars.png?1287361287" alt="">

But this technique means high server usage and bandwidth wastage.
Instead, you should use the version number or date. Example:

<img src="cars.png?2020-02-18" alt="">

But you want it to never serve image from cache. For this, if the page does not use page cache, it is possible with PHP or server side.

<img src="cars.png?<?php echo time();?>" alt="">

However, it is still not effective. Reason: Browser cache ...
The last but most effective method is Native JAVASCRIPT. This simple code finds all images with a "NO-CACHE" class and makes the images almost unique. Put this between script tags.

var items = document.querySelectorAll("img.NO-CACHE");
for (var i = items.length; i--;) {
    var img = items[i];
    img.src = img.src + '?' + Date.now();
}

USAGE

<img class="NO-CACHE" src="https://upload.wikimedia.org/wikipedia/commons/6/6a/JavaScript-logo.png" alt="">

RESULT(s) Like This

https://example.com/image.png?1582018163634


问:
how to loop an array and get only the value of a particular index
I am building a dynamic table where i want only 3 values from my json to display and make one a link which when clicked on, the rest displays. Below is my code kindly assist please.

```<code>var myInvestment =[
    {
      "investmentNo":"00032",
      "amount":"70000",
      "status": "Expired",
      "repayAmt":"70500",
      "description": "Official",
      "maturityDate":"2020-10-31"
  },

{
     "investmentNo":"00034",
     "amount":"5000",
     "status": "Current",
     "repayAmt":"6000",
     "description": "School fees",
     "maturityDate":"2022-03-31"
 }
]

var investmentTable = document.querySelector("#investmentTable");
        if(myInvestment.length>0){
var col = []; // define an empty array
            for (var i = 0; i < myInvestment.length; i++) {
                for (var key in myInvestment[i]) {
                    if (col.indexOf(key) === -1) {
                        col.push(key);
                    }
                }
            }

            // CREATE TABLE HEAD .
            var tHead = document.createElement("tHead");
            // CREATE ROW FOR TABLE HEAD .
            var hRow = document.createElement("tr");
            // ADD COLUMN HEADER TO ROW OF TABLE HEAD.
            tHead.appendChild(hRow);
            investmentTable.appendChild(tHead);
            // CREATE TABLE BODY .
            var tBody = document.createElement("tbody");
            // ADD COLUMN HEADER TO ROW OF TABLE HEAD.
            for (var i = 0; i < myInvestment.length; i++) {
                    var bRow = document.createElement("tr");
                    // CREATE ROW FOR EACH RECORD .
                        var td = document.createElement("td");
                        td.innerHTML = i+1;
                        bRow.appendChild(td);

                    for (var j = 0; j < 3; j++) {
                        var td = document.createElement("td");
                        if (j==0) {
                            td.innerHTML = '<a href="#" onclick = "return invModalView('+i+')">'+myInvestment[i][col[j]]+ '</a>';
                          bRow.appendChild(td);
                        }else{
                        td.innerHTML = myInvestment[i][col[j]];
                        bRow.appendChild(td);
                         }if (j==2) {
                        td.innerHTML = '<div class="badge">'+myInvestment[i][col[j]]+ '</div>';
                        if (td.textContent=="Current") {
                            td.innerHTML = '<div class="badge badge-success">'+myInvestment[i][col[j]]+ '</div>';
                        } else {
                                  td.innerHTML = '<div class="badge badge-danger">'+myInvestment[i][col[j]]+ '</div>';
                            }

                        }
                    tBody.appendChild(bRow)
                    }
            investmentTable.appendChild(tBody);
            }
}
</code>```

This is my modal function that will display the second table

```<code>function invModalView(k,myInvestment){
        var modal = document.getElementById("modal-block-normal");
        modal.style.display = "block";
        var investNo = document.getElementById("investNo");
        var investmentTableModal = document.querySelector("#investmentTableModal");

        myInvestment
  .forEach((item, i) => {

    var row = investmentTable.insertRow();

    row.insertCell(0).innerHTML = item.repayAmt;
    row.insertCell(1).innerHTML = item.description;
    row.insertCell(2).innerHTML = item.maturityDate;
  });
}
}

HTML
<table class="table table-bordered table-striped table-vcenter  table-responsive" id="investmentTableModal">

                                <thead id="invtableHead">
                                    <tr >

                                        <th class="d-sm-table-cell" style="width: 30%;">Repayment Amount</th>
                                        <td id="repayAmt"></td>
                                    </tr>
                                    <tr>
                                        <th class="d-sm-table-cell" style="width: 30%;">Description</th>
                                        <td id="description"></td>
                                    </tr>
                                    <tr>
                                        <th class="d-sm-table-cell" style="width: 30%;">Maturity Date</th>
<td id = "matureDate"></td>
                                    </tr>
</table>
</code>```

i want when a user clicks on myInvestment.investmentNo[0], only the repaymentamt, description and maturityDate of myInvestment[0] will show

答:
```<code> function setSession(key,value){
    window.localStorage.setItem(key, value);
}

function getSession(key){
    return window.localStorage.getItem(key)
;
}

function unsetSession(key){
    window.localStorage.removeItem(key)
;
}
////// Investment page scripts //////
function investmentData(){

      var InvData = getSession("InvData");
      var myInvestment = JSON.parse(InvData);
var investmentTable = document.querySelector("#investmentTable");
        if(myInvestment.investments.length>0){
var col = []; // define an empty array
            for (var i = 0; i < myInvestment.investments.length; i++) {
                for (var key in myInvestment.investments[i]) {
                    if (col.indexOf(key) === -1) {
                        col.push(key);
                    }
                }
            }

            // CREATE TABLE HEAD .
            var tHead = document.querySelector("#tableHead");
            // CREATE ROW FOR TABLE HEAD .
            var hRow = document.querySelector("#tableRow");
            // ADD COLUMN HEADER TO ROW OF TABLE HEAD.
            tHead.appendChild(hRow);
            investmentTable.appendChild(tHead);
            // CREATE TABLE BODY .
            var tBody = document.createElement("tbody");
            // ADD COLUMN HEADER TO ROW OF TABLE HEAD.
            for (var i = 0; i < myInvestment.investments.length; i++) {
                    var bRow = document.createElement("tr");
                    // CREATE ROW FOR EACH RECORD .
                        var td = document.createElement("td");
                        td.innerHTML = i+1;
                        bRow.appendChild(td);

                    for (var j = 0; j < 3; j++) {
                        var td = document.createElement("td");
                        if (j==0) {
                          td.innerHTML = '<a href="#" onclick = "return invModalView('+i+')">'+myInvestment.investments[i][col[j]]+ '</a>';
                          bRow.appendChild(td);
                        }else{
                        td.innerHTML = myInvestment.investments[i][col[j]];
                        bRow.appendChild(td);
                       }if (j==2) {
                      td.innerHTML = '<div class="badge">'+myInvestment.investments[i][col[j]]+ '</div>';
                      if (td.textContent=="Current") {
                        td.innerHTML = '<div class="badge badge-success">'+myInvestment.investments[i][col[j]]+ '</div>';
                      } else {
                  td.innerHTML = '<div class="badge badge-danger">'+myInvestment.investments[i][col[j]]+ '</div>';
              }

                      }
                    tBody.appendChild(bRow)
                }
            investmentTable.appendChild(tBody);
      }
}
}

function invModalView(k){
     $('#investmentTableModal').empty();
        var myInv = JSON.parse(getSession("InvData"));
        var modal = document.getElementById("modal-block-normal");
        modal.style.display = "block";
        var investmentTableModal = document.querySelector("#investmentTableModal");
            // CREATE TABLE BODY .
            var tBody = document.createElement("tbody");

            // // ADD COLUMN HEADER TO ROW OF TABLE HEAD.

            // // Investment No
              var bRow = document.createElement("tr");
              var th = document.createElement("th");
              th.innerHTML = "Investment No";
              var td2 = document.createElement("td");
              td2.style.width = "30%";
              th.style.width = "30%";
              td2.innerHTML = myInv.investments[k].investmentNo;
                        bRow.appendChild(th);
                        bRow.appendChild(td2);
              tBody.appendChild(bRow);
              investmentTableModal.appendChild(tBody)

            // Investment duration
            var tBody = document.createElement("tbody");
                  var bRow = document.createElement("tr");
              var th = document.createElement("th");
              th.innerHTML = "Duration";
              var td2 = document.createElement("td");
              td2.innerHTML = myInv.investments[k].duration;
                        bRow.appendChild(th);
                        bRow.appendChild(td2);
              tBody.appendChild(bRow)
              investmentTableModal.appendChild(tBody);

              // investment start date
            var tBody = document.createElement("tbody");
                  var bRow = document.createElement("tr");
              var th = document.createElement("th");
              th.innerHTML = "startDate";
              var td2 = document.createElement("td");
              td2.innerHTML = myInv.investments[k].startDate;
                        bRow.appendChild(th);
                        bRow.appendChild(td2);
              tBody.appendChild(bRow)
              investmentTableModal.appendChild(tBody);

              // investment yield
            var tBody = document.createElement("tbody");
                  var bRow = document.createElement("tr");
              var th = document.createElement("th");
              th.innerHTML = "Yield";
              var td2 = document.createElement("td");
              td2.innerHTML = myInv.investments[k].yield;
                        bRow.appendChild(th);
                        bRow.appendChild(td2);
              tBody.appendChild(bRow)
              investmentTableModal.appendChild(tBody);

              // investment repayment Amount
            var tBody = document.createElement("tbody");
                  var bRow = document.createElement("tr");
              var th = document.createElement("th");
              th.innerHTML = "Repayment Amount";
              var td2 = document.createElement("td");
              td2.innerHTML = myInv.investments[k].repayAmt;
                        bRow.appendChild(th);
                        bRow.appendChild(td2);
              tBody.appendChild(bRow)
              investmentTableModal.appendChild(tBody);

              // investment description
            var tBody = document.createElement("tbody");
                  var bRow = document.createElement("tr");
              var th = document.createElement("th");
              th.innerHTML = "Description";
              var td2 = document.createElement("td");
              td2.innerHTML = myInv.investments[k].description;
                        bRow.appendChild(th);
                        bRow.appendChild(td2);
              tBody.appendChild(bRow)
              investmentTableModal.appendChild(tBody);

              // investment maturityDate
            var tBody = document.createElement("tbody");
                  var bRow = document.createElement("tr");
              var th = document.createElement("th");
              th.innerHTML = "MaturityDate";
              var td2 = document.createElement("td");
              td2.innerHTML = myInv.investments[k].maturityDate;
                        bRow.appendChild(th);
                        bRow.appendChild(td2);
              tBody.appendChild(bRow)
              investmentTableModal.appendChild(tBody);

}

////// Create Localstorage for MyInvestment ////
var myInvestment =  '{"investments":[{"investmentNo":"00032","amount":"70000","status": "Expired","duration": "2","startDate": "2020-02-02","yield": "2.60","repayAmt":"70500","description": "Official","maturityDate":"2020-10-31"},{"investmentNo":"00033","amount":"40000","status": "Current","duration": "3","startDate": "2019-01-05","yield": "12.0","repayAmt":"42000","description": "Personal","maturityDate":"2020-12-31"},{"investmentNo":"00034","amount":"5000","status": "Current","duration": "4","startDate": "5-04-2008","yield": "20.0","repayAmt":"6000","description": "School fees","maturityDate":"2022-03-31"}]}'

setSession("InvData",myInvestment);
</code>```

I later succeeded in getting this. i think it would be nice to share for someone out there who might need it.

Body:
I am building a dynamic table where i want only 3 values from my json to display and make one a link which when clicked on, the rest displays. Below is my code kindly assist please.

var myInvestment =[
    {
      "investmentNo":"00032",
      "amount":"70000",
      "status": "Expired",
      "repayAmt":"70500",
      "description": "Official",
      "maturityDate":"2020-10-31"
  },

{
     "investmentNo":"00034",
     "amount":"5000",
     "status": "Current",
     "repayAmt":"6000",
     "description": "School fees",
     "maturityDate":"2022-03-31"
 }
]

var investmentTable = document.querySelector("#investmentTable");
        if(myInvestment.length>0){
var col = []; // define an empty array
            for (var i = 0; i < myInvestment.length; i++) {
                for (var key in myInvestment[i]) {
                    if (col.indexOf(key) === -1) {
                        col.push(key);
                    }
                }
            }

            // CREATE TABLE HEAD .
            var tHead = document.createElement("tHead");
            // CREATE ROW FOR TABLE HEAD .
            var hRow = document.createElement("tr");
            // ADD COLUMN HEADER TO ROW OF TABLE HEAD.
            tHead.appendChild(hRow);
            investmentTable.appendChild(tHead);
            // CREATE TABLE BODY .
            var tBody = document.createElement("tbody");
            // ADD COLUMN HEADER TO ROW OF TABLE HEAD.
            for (var i = 0; i < myInvestment.length; i++) {
                    var bRow = document.createElement("tr");
                    // CREATE ROW FOR EACH RECORD .
                        var td = document.createElement("td");
                        td.innerHTML = i+1;
                        bRow.appendChild(td);

                    for (var j = 0; j < 3; j++) {
                        var td = document.createElement("td");
                        if (j==0) {
                            td.innerHTML = ''+myInvestment[i][col[j]]+ '';
                          bRow.appendChild(td);
                        }else{
                        td.innerHTML = myInvestment[i][col[j]];
                        bRow.appendChild(td);
                         }if (j==2) {
                        td.innerHTML = '
'+myInvestment[i][col[j]]+ '
';
                        if (td.textContent=="Current") {
                            td.innerHTML = '
'+myInvestment[i][col[j]]+ '
';
                        } else {
                                  td.innerHTML = '
'+myInvestment[i][col[j]]+ '
';
                            }

                        }
                    tBody.appendChild(bRow)
                    }
            investmentTable.appendChild(tBody);
            }
}

This is my modal function that will display the second table

function invModalView(k,myInvestment){
        var modal = document.getElementById("modal-block-normal");
        modal.style.display = "block";
        var investNo = document.getElementById("investNo");
        var investmentTableModal = document.querySelector("#investmentTableModal");

        myInvestment
  .forEach((item, i) => {

    var row = investmentTable.insertRow();

    row.insertCell(0).innerHTML = item.repayAmt;
    row.insertCell(1).innerHTML = item.description;
    row.insertCell(2).innerHTML = item.maturityDate;
  });
}
}

HTML

                                        Repayment Amount

                                        Description

                                        Maturity Date

i want when a user clicks on myInvestment.investmentNo[0], only the repaymentamt, description and maturityDate of myInvestment[0] will show

Body:
 function setSession(key,value){
    window.localStorage.setItem(key, value);
}

function getSession(key){
    return window.localStorage.getItem(key)
;
}

function unsetSession(key){
    window.localStorage.removeItem(key)
;
}
////// Investment page scripts //////
function investmentData(){

      var InvData = getSession("InvData");
      var myInvestment = JSON.parse(InvData);
var investmentTable = document.querySelector("#investmentTable");
        if(myInvestment.investments.length>0){
var col = []; // define an empty array
            for (var i = 0; i < myInvestment.investments.length; i++) {
                for (var key in myInvestment.investments[i]) {
                    if (col.indexOf(key) === -1) {
                        col.push(key);
                    }
                }
            }

            // CREATE TABLE HEAD .
            var tHead = document.querySelector("#tableHead");
            // CREATE ROW FOR TABLE HEAD .
            var hRow = document.querySelector("#tableRow");
            // ADD COLUMN HEADER TO ROW OF TABLE HEAD.
            tHead.appendChild(hRow);
            investmentTable.appendChild(tHead);
            // CREATE TABLE BODY .
            var tBody = document.createElement("tbody");
            // ADD COLUMN HEADER TO ROW OF TABLE HEAD.
            for (var i = 0; i < myInvestment.investments.length; i++) {
                    var bRow = document.createElement("tr");
                    // CREATE ROW FOR EACH RECORD .
                        var td = document.createElement("td");
                        td.innerHTML = i+1;
                        bRow.appendChild(td);

                    for (var j = 0; j < 3; j++) {
                        var td = document.createElement("td");
                        if (j==0) {
                          td.innerHTML = '<a href="#" onclick = "return invModalView('+i+')">'+myInvestment.investments[i][col[j]]+ '</a>';
                          bRow.appendChild(td);
                        }else{
                        td.innerHTML = myInvestment.investments[i][col[j]];
                        bRow.appendChild(td);
                       }if (j==2) {
                      td.innerHTML = '<div class="badge">'+myInvestment.investments[i][col[j]]+ '</div>';
                      if (td.textContent=="Current") {
                        td.innerHTML = '<div class="badge badge-success">'+myInvestment.investments[i][col[j]]+ '</div>';
                      } else {
                  td.innerHTML = '<div class="badge badge-danger">'+myInvestment.investments[i][col[j]]+ '</div>';
              }

                      }
                    tBody.appendChild(bRow)
                }
            investmentTable.appendChild(tBody);
      }
}
}

function invModalView(k){
     $('#investmentTableModal').empty();
        var myInv = JSON.parse(getSession("InvData"));
        var modal = document.getElementById("modal-block-normal");
        modal.style.display = "block";
        var investmentTableModal = document.querySelector("#investmentTableModal");
            // CREATE TABLE BODY .
            var tBody = document.createElement("tbody");

            // // ADD COLUMN HEADER TO ROW OF TABLE HEAD.

            // // Investment No
              var bRow = document.createElement("tr");
              var th = document.createElement("th");
              th.innerHTML = "Investment No";
              var td2 = document.createElement("td");
              td2.style.width = "30%";
              th.style.width = "30%";
              td2.innerHTML = myInv.investments[k].investmentNo;
                        bRow.appendChild(th);
                        bRow.appendChild(td2);
              tBody.appendChild(bRow);
              investmentTableModal.appendChild(tBody)

            // Investment duration
            var tBody = document.createElement("tbody");
                  var bRow = document.createElement("tr");
              var th = document.createElement("th");
              th.innerHTML = "Duration";
              var td2 = document.createElement("td");
              td2.innerHTML = myInv.investments[k].duration;
                        bRow.appendChild(th);
                        bRow.appendChild(td2);
              tBody.appendChild(bRow)
              investmentTableModal.appendChild(tBody);

              // investment start date
            var tBody = document.createElement("tbody");
                  var bRow = document.createElement("tr");
              var th = document.createElement("th");
              th.innerHTML = "startDate";
              var td2 = document.createElement("td");
              td2.innerHTML = myInv.investments[k].startDate;
                        bRow.appendChild(th);
                        bRow.appendChild(td2);
              tBody.appendChild(bRow)
              investmentTableModal.appendChild(tBody);

              // investment yield
            var tBody = document.createElement("tbody");
                  var bRow = document.createElement("tr");
              var th = document.createElement("th");
              th.innerHTML = "Yield";
              var td2 = document.createElement("td");
              td2.innerHTML = myInv.investments[k].yield;
                        bRow.appendChild(th);
                        bRow.appendChild(td2);
              tBody.appendChild(bRow)
              investmentTableModal.appendChild(tBody);

              // investment repayment Amount
            var tBody = document.createElement("tbody");
                  var bRow = document.createElement("tr");
              var th = document.createElement("th");
              th.innerHTML = "Repayment Amount";
              var td2 = document.createElement("td");
              td2.innerHTML = myInv.investments[k].repayAmt;
                        bRow.appendChild(th);
                        bRow.appendChild(td2);
              tBody.appendChild(bRow)
              investmentTableModal.appendChild(tBody);

              // investment description
            var tBody = document.createElement("tbody");
                  var bRow = document.createElement("tr");
              var th = document.createElement("th");
              th.innerHTML = "Description";
              var td2 = document.createElement("td");
              td2.innerHTML = myInv.investments[k].description;
                        bRow.appendChild(th);
                        bRow.appendChild(td2);
              tBody.appendChild(bRow)
              investmentTableModal.appendChild(tBody);

              // investment maturityDate
            var tBody = document.createElement("tbody");
                  var bRow = document.createElement("tr");
              var th = document.createElement("th");
              th.innerHTML = "MaturityDate";
              var td2 = document.createElement("td");
              td2.innerHTML = myInv.investments[k].maturityDate;
                        bRow.appendChild(th);
                        bRow.appendChild(td2);
              tBody.appendChild(bRow)
              investmentTableModal.appendChild(tBody);

}

////// Create Localstorage for MyInvestment ////
var myInvestment =  '{"investments":[{"investmentNo":"00032","amount":"70000","status": "Expired","duration": "2","startDate": "2020-02-02","yield": "2.60","repayAmt":"70500","description": "Official","maturityDate":"2020-10-31"},{"investmentNo":"00033","amount":"40000","status": "Current","duration": "3","startDate": "2019-01-05","yield": "12.0","repayAmt":"42000","description": "Personal","maturityDate":"2020-12-31"},{"investmentNo":"00034","amount":"5000","status": "Current","duration": "4","startDate": "5-04-2008","yield": "20.0","repayAmt":"6000","description": "School fees","maturityDate":"2022-03-31"}]}'

setSession("InvData",myInvestment);

I later succeeded in getting this. i think it would be nice to share for someone out there who might need it.


问:
How to run multiple select query at once in sequelize using single await
Have to run both codes at a single time. Don't want to wait and then fire next query but wait for both query execution complete.</p>

```<code>products = await Product.findAll()
.then(data => {
  return data;
})
.catch(error => {
  //
});

variationProducts = await VariationProduct.findAll()
.then(data => {
  return data;
})
.catch(error => {
  //
});
</code>```

答:
You may choose

```<code>const [ productsPromise, variationProductsPromise ] = await Promise.all([Product.findAll(), VariationProduct.findAll()]);
</code>```

OR

```<code>const [ productsPromise, variationProductsPromise ] = await { Product.findAll(), VariationProduct.findAll()}
</code>```

Body:
Have to run both codes at a single time. Don't want to wait and then fire next query but wait for both query execution complete.

products = await Product.findAll()
.then(data => {
  return data;
})
.catch(error => {
  //
});

variationProducts = await VariationProduct.findAll()
.then(data => {
  return data;
})
.catch(error => {
  //
});

Body:
You may choose

const [ productsPromise, variationProductsPromise ] = await Promise.all([Product.findAll(), VariationProduct.findAll()]);

OR

const [ productsPromise, variationProductsPromise ] = await { Product.findAll(), VariationProduct.findAll()}


问:
Access file directory path with Streamreader in local computer
I should save file by request get
The request  contain file name and URL to file for content,
I have WebApi that run in server,
I want to set taht URL of file be from local computer and not from server,
But the WebApi run in server so if I set to take directory path it take path of server,
How can I set that take directory path from local computer where I run the URL?

My Code:

```<code>     [HttpGet("SetConfiguration")]
     public IActionResult SetConfiguration(string fileName, string url)
     {

        if (System.IO.File.Exists(@"D:/" + fileName + @".json"))
         {
             Logger._logger.Debug("File " + fileName + " already exists");
             return BadRequest("File " + fileName + " already exists");
         }
         else
         {
             string content = "";
             using (StreamReader sr = new StreamReader(url))
             {
                 try
                 {
                     content = sr.ReadToEnd();
                 }
                 catch
                 {
                     Logger._logger.Debug("File is not a valid json ");
                     return BadRequest("File is not a valid json ");
                 }
             }
             using (StreamWriter fileStream = new StreamWriter(@"D:/" + fileName + @".json", false))
             {
                 try
                 {
                     fileStream.WriteLine(content);

                 }
                 catch
                 {
                     Logger._logger.Debug("content is not a valid json ");
                     return BadRequest("content is not a valid json ");
                 }
             }
             return Ok("file " + fileName + " saved");
         }
     }
</code>```

答:
If I understand correctly, you want to save the file on the server from the client?

What you need to do is send the file from the client to the server (for example, if it's an image you can send it in base64 in POST) or use/create an uploader component to upload the file to your server (for example - by chunk of data).

If your client is written in javascript, Here's a nice plugin for uploading files.

Body:
I should save file by request get
The request  contain file name and URL to file for content,
I have WebApi that run in server,
I want to set taht URL of file be from local computer and not from server,
But the WebApi run in server so if I set to take directory path it take path of server,
How can I set that take directory path from local computer where I run the URL?

My Code:

     [HttpGet("SetConfiguration")]
     public IActionResult SetConfiguration(string fileName, string url)
     {

        if (System.IO.File.Exists(@"D:/" + fileName + @".json"))
         {
             Logger._logger.Debug("File " + fileName + " already exists");
             return BadRequest("File " + fileName + " already exists");
         }
         else
         {
             string content = "";
             using (StreamReader sr = new StreamReader(url))
             {
                 try
                 {
                     content = sr.ReadToEnd();
                 }
                 catch
                 {
                     Logger._logger.Debug("File is not a valid json ");
                     return BadRequest("File is not a valid json ");
                 }
             }
             using (StreamWriter fileStream = new StreamWriter(@"D:/" + fileName + @".json", false))
             {
                 try
                 {
                     fileStream.WriteLine(content);

                 }
                 catch
                 {
                     Logger._logger.Debug("content is not a valid json ");
                     return BadRequest("content is not a valid json ");
                 }
             }
             return Ok("file " + fileName + " saved");
         }
     }


问:
Google Sheets 50 million cell count work around
Is there a way to get around the 50 million cell count rule? Can this be done by using 2 separate workbooks?

We have a lead tracking system that we have built in a Google Sheets workbook and with the way our leads get updated we have already hit the 50mil record count in Google Sheets over the past 3 months. Deleting the data is not an option as we have to analyze weekly monthly quarterly and yearly stats.

I am pretty sure IMPORTRANGE would still hit the 50mil cell count limit.

Is there a way around this limit?

Update:

So a way to combat the cell limit is to totally delete all columns and rows that you do not use and are empty. Trimming the sheets down to just what you have filled in rows and columns.

Apparently if the cell has no data in it it still counts against your cell count despite it being empty.

This is not a solution per say but it is a way to make sure empty cells are not counting against your cell count.

答:
Answer:

There is no way around this. According to the Google File Size documentation[1], the limits on a Spreadsheet are:

Up to 5 million cells or 18,278 columns (column ZZZ) for spreadsheets that are created in or converted to Google Sheets.

Things I Tested:

Starting in 2019 it became possible to edit Office files natively in G Suite[2] so I thought I'd give it a test. According to the specifications and limits page for Microsoft Office Excel[3]:

Total number of rows and columns on a worksheet: 1,048,576 rows by 16,384 columns

Which totals 17,179,869,184 cells.

As Spreadsheets that are created on Google Drive have the Google Drive limit, I created an Excel workbook on my local machine, with the maximum number of possible cells and uploaded it to Drive to see if it could be edited natively. Unfortunately, while the file uploaded successfully, attempting to open the file resulted in the following page:

More Information, Workarounds & Similar Services:

Honestly if you need more than 5 million cells in a Spreadsheet (or even 50 million!) then you're not using the right tool for the job. With this much data, you're likely better off using a database or a cloud data warehouse such as Google BigQuery[4] or Cloud SQL[5]

That being said, if Google Sheets/Spreadsheet workbooks really is the only way forward for you, the only thing I can recommend you doing is creating multiple Sheets files, separated into a more appropriate timeframe - each Sheet containing data for just a month. This will take a bit more time to set up (though you can use Apps Script for data migration between the Sheets), but in the long run will mean you will be able to use your data more effectively, and any data processing you need to do will complete within the Apps Script Quotas[6].

References:

Google Drive Help - Files you can store in Google Drive

G Suite Updates - "Office editing makes it easier to work with Office files in Docs, Sheets and Slides."

Excel specifications and limits

Google BigQuery

Google Cloud SQL

Google Apps Script - Quotas for Google Services


问:
Using database of main website for multiple subdirectories
**I have a Wordpress website. I need to create subdirectories.

Purpose of subdirectories: I need to redirect the users into subdirectories based on their geo.

```<code>For example:

example.com – my website
example.com/uk – redirect users from UK.
example.com/usa – redirect users from USA
</code>```

I have 6 pages and some posts on the main website and I need all these pages and posts in the subdirectories too with small changes in content.

Can I create all the sub-directories with a single database. Or it is mandatory to have a single database for all subdirectories.

**

答:
From what I know, any database will hold specific data.

eg: if you saved I am a cat in a table and it loads on yourdomain.com then created a page home.php, the page will always load with I am a cat.

With this in mind, if you copy home.php and create a new page house.php the call will still be to the same table 'I am a cat' the content will not change. any changes would affect everyone. (same as sub-directories with pages in there)

What you can do is change the language using one of several tools and plugins but the content will always be the same.

Haven, explained that, what else you could do is create other pages and load them separately.

Consider this thread with a similar request and solution.
Wordpress - Display variable content based on variable in URL

Let me know if it helps. It will be interesting to learn how this was solved.

Body:
**I have a Wordpress website. I need to create subdirectories.

Purpose of subdirectories: I need to redirect the users into subdirectories based on their geo.

For example:

example.com – my website
example.com/uk – redirect users from UK.
example.com/usa – redirect users from USA

I have 6 pages and some posts on the main website and I need all these pages and posts in the subdirectories too with small changes in content.

Can I create all the sub-directories with a single database. Or it is mandatory to have a single database for all subdirectories.

**


问:
Cannot use use ref or out parameter for anonymous methods
```<code>    static BackgroundWorker worker;
    static void Main(string[] args)
    {
      worker = new BackgroundWorker();
      worker.DoWork += worker_DoWork;
      worker.RunWorkerAsync();
      Console.ReadLine();
    }
    static void worker_DoWork(object sender,DoWorkEventArgs e)
    {
      string strClientId = "2211"; Authenticate(ref strClientId);
    }
    static void Authenticate(ref string strClientId)
    {
       Timer timer = new Timer(500);
       //Error in this line
       //Cannot use ref or out parameter 'strClientId' inside an anonymous method,lambda expression or query expression
       timer.Elapsed += (sender, e) => Authenticates_Timer(sender, e,ref strClientId);
       //timer.Elapsed += Authenticates_Timer();
       timer.Start();
    }
    static void Authenticates_Timer(object sender, ElapsedEventArgs e, ref string strClientId)
    {
      //want to use variable here
      strClientId = "";
    }
</code>```

if there is a way i can use ref variable while passing
parameter to event Cannot use ref or out parameter 'strClientId'
inside an anonymous method,lambda expression or query
expression.I know this is repeated question but i am unable to
figure out how to solve this have refered different posts and
posted question in codeproject too but no one is responding any
help is appreciated

答:
As simple as that:</p>

```<code>static void Authenticate(ref string strClientId)
{
       Timer timer = new Timer(500);
       var strClientIdVar = strClientId;
       timer.Elapsed += (sender, e) => Authenticates_Timer(sender, e,ref strClientIdVar);
       timer.Start();
}
</code>```

Body:
    static BackgroundWorker worker;
    static void Main(string[] args)
    {
      worker = new BackgroundWorker();
      worker.DoWork += worker_DoWork;
      worker.RunWorkerAsync();
      Console.ReadLine();
    }
    static void worker_DoWork(object sender,DoWorkEventArgs e)
    {
      string strClientId = "2211"; Authenticate(ref strClientId);
    }
    static void Authenticate(ref string strClientId)
    {
       Timer timer = new Timer(500);
       //Error in this line
       //Cannot use ref or out parameter 'strClientId' inside an anonymous method,lambda expression or query expression
       timer.Elapsed += (sender, e) => Authenticates_Timer(sender, e,ref strClientId);
       //timer.Elapsed += Authenticates_Timer();
       timer.Start();
    }
    static void Authenticates_Timer(object sender, ElapsedEventArgs e, ref string strClientId)
    {
      //want to use variable here
      strClientId = "";
    }

if there is a way i can use ref variable while passing
parameter to event Cannot use ref or out parameter 'strClientId'
inside an anonymous method,lambda expression or query
expression.I know this is repeated question but i am unable to
figure out how to solve this have refered different posts and
posted question in codeproject too but no one is responding any
help is appreciated

Body:
As simple as that:

static void Authenticate(ref string strClientId)
{
       Timer timer = new Timer(500);
       var strClientIdVar = strClientId;
       timer.Elapsed += (sender, e) => Authenticates_Timer(sender, e,ref strClientIdVar);
       timer.Start();
}


问:
pivot_wider issue "Values in `values_from` are not uniquely identified; output will contain list-cols"
My data looks like this:

```<code># A tibble: 6 x 4
  name          val time          x1
  <chr>       <dbl> <date>     <dbl>
1 C Farolillo     7 2016-04-20  51.5
2 C Farolillo     3 2016-04-21  56.3
3 C Farolillo     7 2016-04-22  56.3
4 C Farolillo    13 2016-04-23  57.9
5 C Farolillo     7 2016-04-24  58.7
6 C Farolillo     9 2016-04-25  59.0
</code>```

I am trying to use the pivot_wider function to expand out the data based on the name column. I use the following code:

```<code>yy <- d %>%
  pivot_wider(., names_from = name, values_from = val)
</code>```

Which gives me the following warning message:

```<code>Warning message:
Values in `val` are not uniquely identified; output will contain list-cols.
* Use `values_fn = list(val = list)` to suppress this warning.
* Use `values_fn = list(val = length)` to identify where the duplicates arise
* Use `values_fn = list(val = summary_fun)` to summarise duplicates
</code>```

The output looks like:

```<code>       time       x1        out1    out2
    2016-04-20  51.50000    <dbl>   <dbl>
2   2016-04-21  56.34615    <dbl>   <dbl>
3   2016-04-22  56.30000    <dbl>   <dbl>
4   2016-04-23  57.85714    <dbl>   <dbl>
5   2016-04-24  58.70968    <dbl>   <dbl>
6   2016-04-25  58.96774    <dbl>   <dbl>
</code>```

I know that here mentions the issue and to resolve it they suggest using summary statistics. However I have time series data and thus do not want to use summary statistics since each day has a single value (and not multiple values).

I know the problem is because the val column has duplicates (i.e. in the above example 7 occurs 3 times.

Any suggestions on how to pivot_wider and overcome this issue?

Data:

```<code>    d <- structure(list(name = c("C Farolillo", "C Farolillo", "C Farolillo",
"C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo",
"C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo",
"C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo",
"C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo",
"C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo",
"C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo",
"C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo",
"C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo",
"C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo",
"C Farolillo", "C Farolillo", "C Farolillo", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica"), val = c(7, 3, 7, 13, 7,
9, 20, 19, 4, 5, 5, 2, 6, 6, 16, 13, 7, 6, 3, 3, 6, 10, 5, 3,
5, 3, 4, 4, 10, 11, 4, 13, 8, 2, 8, 10, 3, 10, 14, 4, 2, 4, 6,
6, 8, 8, 3, 3, 13, 10, 13, 32, 25, 31, 34, 26, 33, 35, 43, 22,
22, 21, 10, 33, 33, 48, 47, 27, 23, 11, 13, 25, 31, 20, 16, 10,
9, 23, 11, 23, 26, 16, 34, 17, 4, 24, 21, 10, 26, 32, 10, 5,
9, 19, 14, 27, 27, 10, 8, 28, 32, 25), time = structure(c(16911,
16912, 16913, 16914, 16915, 16916, 16917, 16918, 16919, 16920,
16921, 16922, 16923, 16923, 16924, 16925, 16926, 16927, 16928,
16929, 16930, 16931, 16932, 16933, 16934, 16935, 16936, 16937,
16938, 16939, 16940, 16941, 16942, 16943, 16944, 16945, 16946,
16947, 16948, 16949, 16950, 16951, 16952, 16953, 16954, 16955,
16956, 16957, 16958, 16959, 16960, 16911, 16912, 16913, 16914,
16915, 16916, 16917, 16918, 16919, 16920, 16921, 16922, 16923,
16923, 16924, 16925, 16926, 16927, 16928, 16929, 16930, 16931,
16932, 16933, 16934, 16935, 16936, 16937, 16938, 16939, 16940,
16941, 16942, 16943, 16944, 16945, 16946, 16947, 16948, 16949,
16950, 16951, 16952, 16953, 16954, 16955, 16956, 16957, 16958,
16959, 16960), class = "Date"), x1 = c(51.5, 56.3461538461538,
56.3, 57.8571428571429, 58.7096774193548, 58.9677419354839, 64.4615384615385,
61.9310344827586, 60.3214285714286, 59.4137931034483, 59.5806451612903,
57.3448275862069, 64.0333333333333, 64.0333333333333, 70.15625,
71.3636363636364, 62.8125, 56.4375, 56.4516129032258, 51.741935483871,
52.84375, 53.09375, 52.969696969697, 54, 54.3870967741936, 60.3870967741936,
64.4516129032258, 66.2903225806452, 68.2333333333333, 69.7741935483871,
70.5806451612903, 73.8275862068966, 72.8181818181818, 64.6764705882353,
64.4838709677419, 68.7741935483871, 62.1764705882353, 68.969696969697,
70.1935483870968, 59.6774193548387, 59.9677419354839, 63.125,
67.5882352941177, 71.4705882352941, 73.8529411764706, 76.1935483870968,
72.6451612903226, 76.0645161290323, 76.4193548387097, 81.7741935483871,
85.0645161290323, 51.5, 56.3461538461538, 56.3, 57.8571428571429,
58.7096774193548, 58.9677419354839, 64.4615384615385, 61.9310344827586,
60.3214285714286, 59.4137931034483, 59.5806451612903, 57.3448275862069,
64.0333333333333, 64.0333333333333, 70.15625, 71.3636363636364,
62.8125, 56.4375, 56.4516129032258, 51.741935483871, 52.84375,
53.09375, 52.969696969697, 54, 54.3870967741936, 60.3870967741936,
64.4516129032258, 66.2903225806452, 68.2333333333333, 69.7741935483871,
70.5806451612903, 73.8275862068966, 72.8181818181818, 64.6764705882353,
64.4838709677419, 68.7741935483871, 62.1764705882353, 68.969696969697,
70.1935483870968, 59.6774193548387, 59.9677419354839, 63.125,
67.5882352941177, 71.4705882352941, 73.8529411764706, 76.1935483870968,
72.6451612903226, 76.0645161290323, 76.4193548387097, 81.7741935483871,
85.0645161290323)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-102L))
</code>```

答:
The problem is caused by the fact that the data that you want to spread / pivot wider has duplicate identifiers.  While both suggestions above, i.e. creating a unique artifical id from row numbers with mutate(row = row_number()) , or filtering only distinct rows will allow you to pivot wider, but they change the structure of your table, which is likely to have an logical, organizational problem that will come out next time you try to join anything to it.

It is a much better practice to use the id_cols parameter explicity, to see that you actually want to have to be unique after pivotting wide, and if you are running into problems, re-organize the original table first. Of course, you may find reason for filtering to distinct rows, or adding a new ID, most likely you will want to avoid the duplication earlier in your code.

Body:
My data looks like this:

# A tibble: 6 x 4
  name          val time          x1
  <chr>       <dbl> <date>     <dbl>
1 C Farolillo     7 2016-04-20  51.5
2 C Farolillo     3 2016-04-21  56.3
3 C Farolillo     7 2016-04-22  56.3
4 C Farolillo    13 2016-04-23  57.9
5 C Farolillo     7 2016-04-24  58.7
6 C Farolillo     9 2016-04-25  59.0

I am trying to use the pivot_wider function to expand out the data based on the name column. I use the following code:

yy <- d %>%
  pivot_wider(., names_from = name, values_from = val)

Which gives me the following warning message:

Warning message:
Values in `val` are not uniquely identified; output will contain list-cols.
* Use `values_fn = list(val = list)` to suppress this warning.
* Use `values_fn = list(val = length)` to identify where the duplicates arise
* Use `values_fn = list(val = summary_fun)` to summarise duplicates

The output looks like:

       time       x1        out1    out2
    2016-04-20  51.50000    <dbl>   <dbl>
2   2016-04-21  56.34615    <dbl>   <dbl>
3   2016-04-22  56.30000    <dbl>   <dbl>
4   2016-04-23  57.85714    <dbl>   <dbl>
5   2016-04-24  58.70968    <dbl>   <dbl>
6   2016-04-25  58.96774    <dbl>   <dbl>

I know that here mentions the issue and to resolve it they suggest using summary statistics. However I have time series data and thus do not want to use summary statistics since each day has a single value (and not multiple values).

I know the problem is because the val column has duplicates (i.e. in the above example 7 occurs 3 times.

Any suggestions on how to pivot_wider and overcome this issue?

Data:

    d <- structure(list(name = c("C Farolillo", "C Farolillo", "C Farolillo",
"C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo",
"C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo",
"C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo",
"C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo",
"C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo",
"C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo",
"C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo",
"C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo",
"C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo", "C Farolillo",
"C Farolillo", "C Farolillo", "C Farolillo", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica", "Plaza Eliptica",
"Plaza Eliptica", "Plaza Eliptica"), val = c(7, 3, 7, 13, 7,
9, 20, 19, 4, 5, 5, 2, 6, 6, 16, 13, 7, 6, 3, 3, 6, 10, 5, 3,
5, 3, 4, 4, 10, 11, 4, 13, 8, 2, 8, 10, 3, 10, 14, 4, 2, 4, 6,
6, 8, 8, 3, 3, 13, 10, 13, 32, 25, 31, 34, 26, 33, 35, 43, 22,
22, 21, 10, 33, 33, 48, 47, 27, 23, 11, 13, 25, 31, 20, 16, 10,
9, 23, 11, 23, 26, 16, 34, 17, 4, 24, 21, 10, 26, 32, 10, 5,
9, 19, 14, 27, 27, 10, 8, 28, 32, 25), time = structure(c(16911,
16912, 16913, 16914, 16915, 16916, 16917, 16918, 16919, 16920,
16921, 16922, 16923, 16923, 16924, 16925, 16926, 16927, 16928,
16929, 16930, 16931, 16932, 16933, 16934, 16935, 16936, 16937,
16938, 16939, 16940, 16941, 16942, 16943, 16944, 16945, 16946,
16947, 16948, 16949, 16950, 16951, 16952, 16953, 16954, 16955,
16956, 16957, 16958, 16959, 16960, 16911, 16912, 16913, 16914,
16915, 16916, 16917, 16918, 16919, 16920, 16921, 16922, 16923,
16923, 16924, 16925, 16926, 16927, 16928, 16929, 16930, 16931,
16932, 16933, 16934, 16935, 16936, 16937, 16938, 16939, 16940,
16941, 16942, 16943, 16944, 16945, 16946, 16947, 16948, 16949,
16950, 16951, 16952, 16953, 16954, 16955, 16956, 16957, 16958,
16959, 16960), class = "Date"), x1 = c(51.5, 56.3461538461538,
56.3, 57.8571428571429, 58.7096774193548, 58.9677419354839, 64.4615384615385,
61.9310344827586, 60.3214285714286, 59.4137931034483, 59.5806451612903,
57.3448275862069, 64.0333333333333, 64.0333333333333, 70.15625,
71.3636363636364, 62.8125, 56.4375, 56.4516129032258, 51.741935483871,
52.84375, 53.09375, 52.969696969697, 54, 54.3870967741936, 60.3870967741936,
64.4516129032258, 66.2903225806452, 68.2333333333333, 69.7741935483871,
70.5806451612903, 73.8275862068966, 72.8181818181818, 64.6764705882353,
64.4838709677419, 68.7741935483871, 62.1764705882353, 68.969696969697,
70.1935483870968, 59.6774193548387, 59.9677419354839, 63.125,
67.5882352941177, 71.4705882352941, 73.8529411764706, 76.1935483870968,
72.6451612903226, 76.0645161290323, 76.4193548387097, 81.7741935483871,
85.0645161290323, 51.5, 56.3461538461538, 56.3, 57.8571428571429,
58.7096774193548, 58.9677419354839, 64.4615384615385, 61.9310344827586,
60.3214285714286, 59.4137931034483, 59.5806451612903, 57.3448275862069,
64.0333333333333, 64.0333333333333, 70.15625, 71.3636363636364,
62.8125, 56.4375, 56.4516129032258, 51.741935483871, 52.84375,
53.09375, 52.969696969697, 54, 54.3870967741936, 60.3870967741936,
64.4516129032258, 66.2903225806452, 68.2333333333333, 69.7741935483871,
70.5806451612903, 73.8275862068966, 72.8181818181818, 64.6764705882353,
64.4838709677419, 68.7741935483871, 62.1764705882353, 68.969696969697,
70.1935483870968, 59.6774193548387, 59.9677419354839, 63.125,
67.5882352941177, 71.4705882352941, 73.8529411764706, 76.1935483870968,
72.6451612903226, 76.0645161290323, 76.4193548387097, 81.7741935483871,
85.0645161290323)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-102L))


问:
How do you overwrite items in a list?
How do you overwrite items in a list?

I tried this, but it didn't work.

```<code>numbs = [5, 10, 15, 20, 25]
i = 0
for numb in numbs:
    numbs[i] = (numb+5)
    i+=i+1
</code>```

答:
try this:

```<code>numbs = [5, 10, 15, 20, 25]
i = 0
for numb in numbs:
    numbs[i] += 5
    i += 1
print(numbs)
</code>```

The output i got from it was: [10, 15, 20, 25, 30]

Title: How do you overwrite items in a list?

Body:
How do you overwrite items in a list?

I tried this, but it didn't work.

numbs = [5, 10, 15, 20, 25]
i = 0
for numb in numbs:
    numbs[i] = (numb+5)
    i+=i+1

Body:
try this:

numbs = [5, 10, 15, 20, 25]
i = 0
for numb in numbs:
    numbs[i] += 5
    i += 1
print(numbs)

The output i got from it was: [10, 15, 20, 25, 30]