问:
Work item access for non visual-studio users
We're using TFS for source control and are trialling using the TFS work item tracking. I am trying to find out, is it possible for people who don't have visual studio installed to access, create and edit work items via a browser based user interface?

Our technical support team need to be able to use work items. TFS work items won't be suitable for our company if the support team and project managers can't get sufficient access.

I'm not familiar with how the licensing works either. If there is a way for non visual studio users to use TFS work items, will they need a license?

答:
As far as licensing goes, a full-blown TFS user requires a TFS CAL (in addition to the normal Windows Server CAL).

However, for particular types of 'light' users a TFS CAL might not be required (I'm not sure, but I'd think that a Windows Server CAL would still be required).  See http://blogs.msdn.com/bharry/archive/2007/11/23/tfs-licensing-change-for-tfs-2008.aspx for some details.

As always, MS server application licensing requirements are often quite complicated - you will need to do your own research (probably in consultation with MIcrosoft) to determine your actual licensing requirements.

OwnerDisplayName: Scott Langham

LastEditorDisplayName: Scott Langham

OwnerDisplayName: Michael Burr

LastEditorDisplayName: Michael Burr


来源: stackexchange

问:
How can I not show a css drop shadow on ie6?
I want to know if I can ignore my css drop shadow on ie6 without using conditional statements to filter the css.

here is my current css:

```<code>/* Drop shadow */
-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#000000')";
filter: progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#000000');
box-shadow: 0px 10px 15px rgba(0, 0, 0, 0.7);
-moz-box-shadow: 0px 10px 15px rgba(0, 0, 0, 0.7);
-o-box-shadow: 0px 10px 15px rgba(0, 0, 0, 0.7);
-webkit-box-shadow: 0px 10px 15px rgba(0, 0, 0, 0.7);
</code>```

Maybe -ms-filter-ie6: none or something :P along those lines

答:
Adding the following line below your -ms-filter: line should work:

```<code>* html -ms-filter: "progid:DXImageTransform.Microsoft.Shadow(enabled=false)";
</code>```

The * html is read only by IE6. But that is a CSS hack, which is very bad practice. You should use conditionals instead.

ContentLicense: CC BY-SA 3.0

Body:
I want to know if I can ignore my css drop shadow on ie6 without using conditional statements to filter the css.

here is my current css:

/* Drop shadow */
-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#000000')";
filter: progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#000000');
box-shadow: 0px 10px 15px rgba(0, 0, 0, 0.7);
-moz-box-shadow: 0px 10px 15px rgba(0, 0, 0, 0.7);
-o-box-shadow: 0px 10px 15px rgba(0, 0, 0, 0.7);
-webkit-box-shadow: 0px 10px 15px rgba(0, 0, 0, 0.7);

Maybe -ms-filter-ie6: none or something :P along those lines

Body:
Adding the following line below your -ms-filter: line should work:

* html -ms-filter: "progid:DXImageTransform.Microsoft.Shadow(enabled=false)";

The * html is read only by IE6. But that is a CSS hack, which is very bad practice. You should use conditionals instead.


问:
Functions that calculates a filter mask of size NXN and applies it to an input image I using conv2() function in Matlab
I am trying to write a function to create a filter mask of size NXN and then apply it to an image read in. Here is my attempt...

```<code>function Iout = noiseReduction(I, N)
image = imread(I);
figure(3)
subplot(2,1,1), imshow(image), title('Original Image', 'FontSize', 15);

mask = ones(3,3) * N;
Iout = conv2(image, mask);
subplot(2,1,2), imshow(uint8(Iout)), title('Blurred Image', 'FontSize', 15);

end
</code>```

However, when I run the function I don't get any output in Blurred Image I just get a blank square. Can anyone help me figure out what is wrong with this? Any help would be fantastic.

答:
```<code>mask = ones(3,3) * N;
</code>```

This is not a NxN filter, but a 3x3 filter where each element has a value of N.

By convolving with such a filter, you obtain an image with very large values. You later cast this to uint8, clamping all values to 255. Hence the image looks all white.

Instead, define your kernel as:

```<code>mask = ones(N,N) / N^2;
</code>```

Now mask is NxN and sums to 1, meaning that the output will remain in the same range as the input.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to write a function to create a filter mask of size NXN and then apply it to an image read in. Here is my attempt...

function Iout = noiseReduction(I, N)
image = imread(I);
figure(3)
subplot(2,1,1), imshow(image), title('Original Image', 'FontSize', 15);

mask = ones(3,3) * N;
Iout = conv2(image, mask);
subplot(2,1,2), imshow(uint8(Iout)), title('Blurred Image', 'FontSize', 15);

end

However, when I run the function I don't get any output in Blurred Image I just get a blank square. Can anyone help me figure out what is wrong with this? Any help would be fantastic.

Body:
mask = ones(3,3) * N;

This is not a NxN filter, but a 3x3 filter where each element has a value of N.

By convolving with such a filter, you obtain an image with very large values. You later cast this to uint8, clamping all values to 255. Hence the image looks all white.

Instead, define your kernel as:

mask = ones(N,N) / N^2;

Now mask is NxN and sums to 1, meaning that the output will remain in the same range as the input.


问:
Error in Getting newly inserted record through trigger-PLSQL
I am trying to create a trigger on EMP table which will audit insertions in EMP_AUDIT table and send mail to respective empno. The thing I am not getting is to get newly inserted record in CSV attachment that is being generated in v_block_query. I want to get that data basis of :new.FIELD_NAME but it's throwing the error:

ORA-01008: not all variables bound ORA-06512: at
  "SCOTT.EMP_AFTER_INSERT", line 18 ORA-04088: error during execution of
  trigger 'SCOTT.EMP_AFTER_INSERT'

```<code> create or replace TRIGGER emp_after_insert
                              AFTER INSERT
                                   ON emp
                                   FOR EACH ROW
                                DECLARE
        v_block_qry VARCHAR2(3000);
                          v_block_row VARCHAR2(6000);
                        TYPE bl_cur IS REF CURSOR;
                       v_result bl_cur;
                       v_rowcount NUMBER;
                   v_attachment CLOB;
           v_username varchar2(10);
            v_no number(4);
                v_name varchar2(10);
    v_email varchar2(30);
    v_subj varchar2(30);
             BEGIN
          insert into emp_audit(id,name,insertion_date) values(:new.empno,:new.ename,sysdate);
            dbms_output.put_line('inserted'||:new.empno);
               v_attachment := '"COL1", "COL2"' || CHR(13) || CHR(10);
                      v_block_qry := 'SELECT ''"'' || new.empno || ''", "'' || new.ename || ''", "'' || insertion_date ||''"'' AS ROWTXT FROM emp_audit ';
                      OPEN v_result FOR v_block_qry;
                        LOOP
                        v_rowcount := v_result%ROWCOUNT;
                        FETCH v_result INTO v_block_row;
                          EXIT WHEN v_result%NOTFOUND;
                          v_attachment := v_attachment || v_block_row || chr(13) || chr(10);
                        END LOOP;
                      CLOSE v_result;

                       dbms_output.put_line(v_attachment);
     select email into v_email from dept_email where deptno=:new.empno;
     dbms_output.put_line(v_email);
        v_subj:= 'MAIL_SUBJECT ' || TO_CHAR(TRUNC(SYSDATE-1), 'YYYY-MM-DD');
              UTL_MAIL.send_attach_varchar2(sender => 'abc@gmail.com',
              recipients        => v_email,
              subject           => 'mail testing',
              message           =>  'current record',
             mime_type         => 'text/html; charset=us-ascii', -- send html e-mail
             attachment        => v_attachment,
             att_inline        => FALSE,
             att_filename      => 'Change_Report' || TO_CHAR(TRUNC(SYSDATE-1), 'YYYY-MM-DD') || '.csv');

                 END;
</code>```

Please Help. Thanks in advance

答:
v_block_qry := 'SELECT ''"'' || BRANCH_NUMB || ''", "'' || LOAN_CODE || ''", "'' || LOAN_PRODUCT_NUMB || ''"
               , "'' || BRM_NUM || "'', "'' || CURR_CODE || "'', "'' || NAME_DESN || ''", "'' || CNIC_NUMB || ''"
               , "'' || PRINCIPAL_NEW || ''", "'' || AMOUNT_APPLIED_NEW || ''", "'' || ACCT_BASC || ''", "'' || ACCT_SFIX || ''"
               , "'' || DATE_ADDED_NEW || ''", "'' || DATE_DUE_NEW || ''", "'' || B_STATUS || ''", "'' || S_STATUS || ''", "'' || DISB_TOTAL_AMOUNT_NEW || ''"''
               , "'' || OUTSTANDING_PRINCIPAL_NEW || ''", "'' || GROUPBR_NEW || ''", "'' || INSERTED_DATE || ''"''</p>

<p>'
               AS ROWTXT </p>

```<code>           FROM SMFB.LMFLOANSNEW where branch_numb = :new.branch_code;
</code>```

Body:
I am trying to create a trigger on EMP table which will audit insertions in EMP_AUDIT table and send mail to respective empno. The thing I am not getting is to get newly inserted record in CSV attachment that is being generated in v_block_query. I want to get that data basis of :new.FIELD_NAME but it's throwing the error:

ORA-01008: not all variables bound ORA-06512: at
  "SCOTT.EMP_AFTER_INSERT", line 18 ORA-04088: error during execution of
  trigger 'SCOTT.EMP_AFTER_INSERT'

 create or replace TRIGGER emp_after_insert
                              AFTER INSERT
                                   ON emp
                                   FOR EACH ROW
                                DECLARE
        v_block_qry VARCHAR2(3000);
                          v_block_row VARCHAR2(6000);
                        TYPE bl_cur IS REF CURSOR;
                       v_result bl_cur;
                       v_rowcount NUMBER;
                   v_attachment CLOB;
           v_username varchar2(10);
            v_no number(4);
                v_name varchar2(10);
    v_email varchar2(30);
    v_subj varchar2(30);
             BEGIN
          insert into emp_audit(id,name,insertion_date) values(:new.empno,:new.ename,sysdate);
            dbms_output.put_line('inserted'||:new.empno);
               v_attachment := '"COL1", "COL2"' || CHR(13) || CHR(10);
                      v_block_qry := 'SELECT ''"'' || new.empno || ''", "'' || new.ename || ''", "'' || insertion_date ||''"'' AS ROWTXT FROM emp_audit ';
                      OPEN v_result FOR v_block_qry;
                        LOOP
                        v_rowcount := v_result%ROWCOUNT;
                        FETCH v_result INTO v_block_row;
                          EXIT WHEN v_result%NOTFOUND;
                          v_attachment := v_attachment || v_block_row || chr(13) || chr(10);
                        END LOOP;
                      CLOSE v_result;

                       dbms_output.put_line(v_attachment);
     select email into v_email from dept_email where deptno=:new.empno;
     dbms_output.put_line(v_email);
        v_subj:= 'MAIL_SUBJECT ' || TO_CHAR(TRUNC(SYSDATE-1), 'YYYY-MM-DD');
              UTL_MAIL.send_attach_varchar2(sender => 'abc@gmail.com',
              recipients        => v_email,
              subject           => 'mail testing',
              message           =>  'current record',
             mime_type         => 'text/html; charset=us-ascii', -- send html e-mail
             attachment        => v_attachment,
             att_inline        => FALSE,
             att_filename      => 'Change_Report' || TO_CHAR(TRUNC(SYSDATE-1), 'YYYY-MM-DD') || '.csv');

                 END;

Please Help. Thanks in advance

Body:
v_block_qry := 'SELECT ''"'' || BRANCH_NUMB || ''", "'' || LOAN_CODE || ''", "'' || LOAN_PRODUCT_NUMB || ''"
               , "'' || BRM_NUM || "'', "'' || CURR_CODE || "'', "'' || NAME_DESN || ''", "'' || CNIC_NUMB || ''"
               , "'' || PRINCIPAL_NEW || ''", "'' || AMOUNT_APPLIED_NEW || ''", "'' || ACCT_BASC || ''", "'' || ACCT_SFIX || ''"
               , "'' || DATE_ADDED_NEW || ''", "'' || DATE_DUE_NEW || ''", "'' || B_STATUS || ''", "'' || S_STATUS || ''", "'' || DISB_TOTAL_AMOUNT_NEW || ''"''
               , "'' || OUTSTANDING_PRINCIPAL_NEW || ''", "'' || GROUPBR_NEW || ''", "'' || INSERTED_DATE || ''"''

'
               AS ROWTXT

           FROM SMFB.LMFLOANSNEW where branch_numb = :new.branch_code;


问:
Change date format during conversion from xlsx to csv with PHPExcel
I'm converting various xls and xlsx spreadsheets into csv files with PHPExcel.  The original spreadsheet has dates in various formats but I need them to be consistent format in the csv file.

Here are the pertinent parts of the conversion code.

```<code>$filePath = "fromFile.xlsx";
$csvPath = "toFile.csv";

PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);
$reader = PHPExcel_IOFactory::load( $filePath );

$writer = PHPExcel_IOFactory::createWriter( $reader, 'CSV' );
$writer->setDelimiter(",");
$writer->setEnclosure('"');
$writer->setSheetIndex(0);

$writer->save( $csvPath );
</code>```

I'm seeing dates that are formatted like mm/dd/yyyy in the original spreadsheet being converted to mm-dd-yy.  I paged around the documentation and the code looking for where that format is being set but I wasn't able to find a clear answer.

My test file is using excel's default Short Date format of *3/14/2012.
I consistently get "12-20-18" for a date that reads as '12/20/2018' in the excel file.

EDIT:

Proposed duplicate of question answers how to set a format on a specific cell.  In my case the formats are already set, but they are not working properly.

I've discovered that the issue is specific to the "*mm/dd/yyyy" format.  For some reason, this particular format gets changed to mm-dd-yy when written to the csv file.

Excel's Format Cells dialog says "Date formats that begin with an asterisk respond to changes in regional date and time settings that are specified for the operating system."

Is there a more elegant solution than cell by cell search for date fields and overwriting their format?

答:
I was looking for a way to set the format code for all cells that are dates without having to iterate through all the cells. I never found that solution.  Here is what I ended up using. </p>

```<code>$filePath = "fromFile.xlsx";
$csvPath = "toFile.csv";

PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);
$reader = PHPExcel_IOFactory::load( $filePath );

foreach( $reader->getActiveSheet()->getRowIterator(1) as $row ){
    foreach( $row->getCellIterator() as $cell ){
        if( PHPExcel_Shared_Date::isDateTime($cell)){
            $cell->getStyle()->getNumberFormat()->setFormatCode("mm/dd/yyyy" );
        }
    }
}

$writer = PHPExcel_IOFactory::createWriter( $reader, 'CSV' );
$writer->setDelimiter(",");
$writer->setEnclosure('"');
$writer->setSheetIndex(0);

$writer->save( $csvPath );
</code>```

Body:
I'm converting various xls and xlsx spreadsheets into csv files with PHPExcel.  The original spreadsheet has dates in various formats but I need them to be consistent format in the csv file.

Here are the pertinent parts of the conversion code.

$filePath = "fromFile.xlsx";
$csvPath = "toFile.csv";

PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);
$reader = PHPExcel_IOFactory::load( $filePath );

$writer = PHPExcel_IOFactory::createWriter( $reader, 'CSV' );
$writer->setDelimiter(",");
$writer->setEnclosure('"');
$writer->setSheetIndex(0);

$writer->save( $csvPath );

I'm seeing dates that are formatted like mm/dd/yyyy in the original spreadsheet being converted to mm-dd-yy.  I paged around the documentation and the code looking for where that format is being set but I wasn't able to find a clear answer.

My test file is using excel's default Short Date format of *3/14/2012.
I consistently get "12-20-18" for a date that reads as '12/20/2018' in the excel file.

EDIT:

Proposed duplicate of question answers how to set a format on a specific cell.  In my case the formats are already set, but they are not working properly.

I've discovered that the issue is specific to the "*mm/dd/yyyy" format.  For some reason, this particular format gets changed to mm-dd-yy when written to the csv file.

Excel's Format Cells dialog says "Date formats that begin with an asterisk respond to changes in regional date and time settings that are specified for the operating system."

Is there a more elegant solution than cell by cell search for date fields and overwriting their format?

Body:
I was looking for a way to set the format code for all cells that are dates without having to iterate through all the cells. I never found that solution.  Here is what I ended up using.

$filePath = "fromFile.xlsx";
$csvPath = "toFile.csv";

PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);
$reader = PHPExcel_IOFactory::load( $filePath );

foreach( $reader->getActiveSheet()->getRowIterator(1) as $row ){
    foreach( $row->getCellIterator() as $cell ){
        if( PHPExcel_Shared_Date::isDateTime($cell)){
            $cell->getStyle()->getNumberFormat()->setFormatCode("mm/dd/yyyy" );
        }
    }
}

$writer = PHPExcel_IOFactory::createWriter( $reader, 'CSV' );
$writer->setDelimiter(",");
$writer->setEnclosure('"');
$writer->setSheetIndex(0);

$writer->save( $csvPath );


问:
Bigger value without greater than or less than operators
this is just for fun.

Can you give me a way to determine the greater value of two numbers? You can use other operators except greater than or less than operator.

Use any tool you like (programming language, pencil paper, etc.).
And another thing you cannot do the following:

int main()
{
    int num1, num2;
    cin >> num1 >> num2;

    if( (num1-num2) + abs(num1-num2) )
        cout << num1 << " is bigger" << endl;
    else
        cout << num2 << " is bigger" << endl;
    return 0;
}
```

答:
SSE 4.1 solution

#include <smmintrin.h>
#include <iostream>

using namespace std;

int main()
{
    int num1, num2, test;
    __m128i v1, v2, vcmp;

    cin >> num1 >> num2;
    v1 = _mm_set1_epi32(num1);
    v2 = _mm_set1_epi32(num2);
    vcmp = _mm_cmpgt_epi32(v1, v2);
    test = _mm_testz_si128(vcmp, vcmp);
    if (test == 0)
    {
        cout << "num1 is bigger" << endl;
    }
    else
    {
        cout << "num2 is bigger" << endl;
    }
    return 0;
}

$ g++ -Wall -msse4.1 cmpgt.cpp -o cmpgt
$ ./cmpgt
-10 10
num2 is bigger
$ ./cmpgt
10 -10
num1 is bigger
```


问:
How to calculate a time between two times with one day off?
I have a Do Not Disturb system that mutes the sounds of my android app if the current time is in Do not disturb range time.
It works fine if I use a range time just between a day, but I dont know how to write it with one day off, For example at 11:00 pm to 1:00 am of the next day.

This is method that I used for detecting DND time:

```<code>private boolean isInDNDTime() {
    Calendar now = Calendar.getInstance();
    Calendar startTime = Calendar.getInstance();
    Calendar endTime = Calendar.getInstance();
    MyDate myDate = new MyDate(new Date());

    if (isDNDTwoDays()) {
        startTime.setTime(myDate.getYesterday().toDate());
        startTime.set(Calendar.HOUR_OF_DAY, getDNDStartHourTime());
        startTime.set(Calendar.MINUTE, getDNDStartMinuteTime());

        endTime.setTime(myDate.getTomorrow().toDate());
        endTime.set(Calendar.HOUR_OF_DAY, getDNDEndHourTime());
        endTime.set(Calendar.MINUTE, getDNDEndMinuteTime());

    } else {
        startTime.set(Calendar.HOUR_OF_DAY, getDNDStartHourTime());
        startTime.set(Calendar.MINUTE, getDNDStartMinuteTime());

        endTime.set(Calendar.HOUR_OF_DAY, getDNDEndHourTime());
        endTime.set(Calendar.MINUTE, getDNDEndMinuteTime());
    }

    return now.after(startTime) && now.before(endTime);
}
</code>```

答:
There is a modern API for tasks like this, it is called java.time and is available from Java 8. The following example illustrates how to do that with a few lines of code:

```<code>public static void main(String[] args) {
    // create sample data
    LocalDateTime start = LocalDateTime.of(2020, 2, 19, 12, 30);
    LocalDateTime timeInDND = LocalDateTime.now();
    LocalDateTime end = LocalDateTime.of(2020, 2, 21, 12, 30);

    // just check if the time is equal to start or end or is between them
    if (timeInDND.equals(start) || timeInDND.equals(end)
            || (timeInDND.isAfter(start) && timeInDND.isBefore(end))) {
        System.out.println(timeInDND.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
                + " is in the DND period");
    } else {
        System.err.println(timeInDND.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
                + " is not in the DND period");
    }
}
</code>```

Unfortunately, your support of Android API levels below 26 requires an external library, the ThreeTen Android Backport because java.time is available from API level 26. You can check another question about how to use the ThreeTenABP.

Body:
I have a Do Not Disturb system that mutes the sounds of my android app if the current time is in Do not disturb range time.
It works fine if I use a range time just between a day, but I dont know how to write it with one day off, For example at 11:00 pm to 1:00 am of the next day.

This is method that I used for detecting DND time:

private boolean isInDNDTime() {
    Calendar now = Calendar.getInstance();
    Calendar startTime = Calendar.getInstance();
    Calendar endTime = Calendar.getInstance();
    MyDate myDate = new MyDate(new Date());

    if (isDNDTwoDays()) {
        startTime.setTime(myDate.getYesterday().toDate());
        startTime.set(Calendar.HOUR_OF_DAY, getDNDStartHourTime());
        startTime.set(Calendar.MINUTE, getDNDStartMinuteTime());

        endTime.setTime(myDate.getTomorrow().toDate());
        endTime.set(Calendar.HOUR_OF_DAY, getDNDEndHourTime());
        endTime.set(Calendar.MINUTE, getDNDEndMinuteTime());

    } else {
        startTime.set(Calendar.HOUR_OF_DAY, getDNDStartHourTime());
        startTime.set(Calendar.MINUTE, getDNDStartMinuteTime());

        endTime.set(Calendar.HOUR_OF_DAY, getDNDEndHourTime());
        endTime.set(Calendar.MINUTE, getDNDEndMinuteTime());
    }

    return now.after(startTime) && now.before(endTime);
}

Body:
There is a modern API for tasks like this, it is called java.time and is available from Java 8. The following example illustrates how to do that with a few lines of code:

public static void main(String[] args) {
    // create sample data
    LocalDateTime start = LocalDateTime.of(2020, 2, 19, 12, 30);
    LocalDateTime timeInDND = LocalDateTime.now();
    LocalDateTime end = LocalDateTime.of(2020, 2, 21, 12, 30);

    // just check if the time is equal to start or end or is between them
    if (timeInDND.equals(start) || timeInDND.equals(end)
            || (timeInDND.isAfter(start) && timeInDND.isBefore(end))) {
        System.out.println(timeInDND.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
                + " is in the DND period");
    } else {
        System.err.println(timeInDND.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
                + " is not in the DND period");
    }
}

Unfortunately, your support of Android API levels below 26 requires an external library, the ThreeTen Android Backport because java.time is available from API level 26. You can check another question about how to use the ThreeTenABP.


问:
How do I concatenate two lists inside nested list Python?
How do I concatenate two lists inside the nested list Python?

I have this list

```<code>lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]
</code>```

And my expected output is

```<code>lists_of_lists =[[1,2],[3,5],[6,6]]
</code>```

I tried this way

```<code>new = []
lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]
for i in range(len(lists_of_lists)):
    for list in  lists_of_lists[i]:
        for element in list:
            new.append(element)
print(new)
</code>```

But I got

```<code>[1, 2, 3, 5, 6, 6]
</code>```

Thank you for any suggestions

答:
You can use operator.concat() to group 2 separate lists into one and itertools.starmap() to iterate over main list and unpack inner lists:

```<code>from operator import concat
from itertools import starmap

result = list(starmap(concat, lists_of_lists))
</code>```

You can do it also without imports using built-in map() function and lambda expression <s>(but why?)</s>:

```<code>result = list(map(lambda x: x[0] + x[1], lists_of_lists))
</code>```

You can also use chain.from_iterable():

```<code>from itertools import chain

result = list(map(list, map(chain.from_iterable, lists_of_lists)))
</code>```

But if you want want to patch code you've written to work as you expected:

```<code>lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]
new = []
for sub_list in lists_of_lists:
    new_item = []
    for item in sub_list:
        for element in item:
           new_item.append(element)
    new.append(new_item)
</code>```

Body:
How do I concatenate two lists inside the nested list Python?

I have this list

lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]

And my expected output is

lists_of_lists =[[1,2],[3,5],[6,6]]

I tried this way

new = []
lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]
for i in range(len(lists_of_lists)):
    for list in  lists_of_lists[i]:
        for element in list:
            new.append(element)
print(new)

But I got

[1, 2, 3, 5, 6, 6]

Thank you for any suggestions

Body:
You can use operator.concat() to group 2 separate lists into one and itertools.starmap() to iterate over main list and unpack inner lists:

from operator import concat
from itertools import starmap

result = list(starmap(concat, lists_of_lists))

You can do it also without imports using built-in map() function and lambda expression <s>(but why?)</s>:

result = list(map(lambda x: x[0] + x[1], lists_of_lists))

You can also use chain.from_iterable():

from itertools import chain

result = list(map(list, map(chain.from_iterable, lists_of_lists)))

But if you want want to patch code you've written to work as you expected:

lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]
new = []
for sub_list in lists_of_lists:
    new_item = []
    for item in sub_list:
        for element in item:
           new_item.append(element)
    new.append(new_item)


问:
Emulating GCC's __builtin_unreachable?
I get a whole lot of warnings about switches that only partially covers the range of an enumeration switched over. Therefor, I would like to have a "default" for all those switches and put __builtin_unreachable (GCC builtin) in that case, so that the compiler know that case is not reachable.

However, I came to know that GCC4.3 does not support that builtin yet. Is there any good way to emulate that functionality? I thought about dereferencing a null pointer instead, but that may have other undesirable effects/warnings and such. Do you have any better idea?

答:
```<code>template<unsigned int LINE> class Unreachable_At_Line {};
#define __builtin_unreachable() throw Unreachable_At_Line<__LINE__>()
</code>```

Edit:

Since you want to have unreachable code to be omitted by compiler, below is the simplest way.

```<code>#define __builtin_unreachable() { struct X {X& operator=(const X&); } x; x=x; }
</code>```

Compiler optimizes away x = x; instruction especially when it's unreachable. Here is the usage:

```<code>int foo (int i)
{
  switch(i)
  {
  case 0:  return 0;
  case 1:  return 1;
  default: return -1;
  }
  __builtin_unreachable();  // never executed; so compiler optimizes away
}
</code>```

If you put __builtin_unreachable() in the beginning of foo() then compiler generates a linker error for unimplemented operator =. I ran these tests in gcc 3.4.6 (64-bit).

Title: Emulating GCC's __builtin_unreachable?

Body:
template<unsigned int LINE> class Unreachable_At_Line {};
#define __builtin_unreachable() throw Unreachable_At_Line<__LINE__>()

Edit:

Since you want to have unreachable code to be omitted by compiler, below is the simplest way.

#define __builtin_unreachable() { struct X {X& operator=(const X&); } x; x=x; }

Compiler optimizes away x = x; instruction especially when it's unreachable. Here is the usage:

int foo (int i)
{
  switch(i)
  {
  case 0:  return 0;
  case 1:  return 1;
  default: return -1;
  }
  __builtin_unreachable();  // never executed; so compiler optimizes away
}

If you put __builtin_unreachable() in the beginning of foo() then compiler generates a linker error for unimplemented operator =. I ran these tests in gcc 3.4.6 (64-bit).


问:
How to use command line parameters in an MSI
We have a program that has an MSI to install it. Is it possible to pass in parameters from the command line and have them populate the fields that need to be completed by the user?

Currently we have an MSI that asks for certain data and has to be filled in manually. We are now trying to automate much of this from the command line. We've found the internal field names (keys) and we can pass these from the command line, however, the log shows that the values get deleted halfway through and they end up blank. I suspect that the fields aren't being populated with the passed in data, the fields end up blank, and the data gets erased. Only the directory in which to install the program doesn't get deleted.

I've found the fields in Visual Studio (right click the Setup project > View > User Interface) but it looks like the values only take static data. Is there any way to get them to take parameters from the command line?

答:
Have a look to WiX condition properties passed from command line don't work?

The Property needs to be in UPPERCASE letters, like
<Property Id="INSTALLSTARTMENUSHORTCUT" Value="0"/>

Then use MSIEXEC, like msiexec /i MySetup.msi INSTALLSTARTUPSHORTCUT=0 to set the properties from command line


答:
```<code>[[i for inner in sub_lists for i in inner] for sub_lists in lists_of_lists]

# [[1, 2], [3, 5], [6, 6]]
</code>```

Title: How do I concatenate two lists inside nested list Python?


问:
Scala Builder a object recursively
Here is the situation

```<code>val input = "a:b:c:d:e"

def getTrait(primary: SomeTrait, secondary: SomeTrait): SomeTrait {
...
}

def convertTrait(name: String): SomeTrait {
...
}
</code>```

So what I want to do is to slide input in window of 2 and build SomeTrait based on that like this

```<code>val result = getTrait(convertTrait(a),convertTrait(b))
</code>```

and then use this result to build another result like this

```<code>val resul2 = getTrait(result, convertTrait(c))
</code>```

and so onn.......

Offcourse I wanna do it in some kind of recursion/for in scala but unable to find solution

Here is where I am

```<code>val listOfList = input.split(":").grouped(2).toList

private def builder(inputList: List[List[String]], primary: SomeTrait, secondary: SomeTrait): SomeTrait = {
    for {
      xs <- inputList
      fallback = if(xs.size == 1) providerFallBackChainBuilder(convertTrait(xs(0)), "noop") else providerFallBackChainBuilder(convertTrait(xs(1)), convertTrait(xs(0)))
    } yield fallback
    FallbackConfigProvider(primary, secondary)
  }
</code>```

I  somehow need to pass this fallback back to function .. I know this is not working and not best solution but can anyone guide me on how to dit better and correctly

答: made it to work like this  "a:b:c:d:e".split(":").iterator.map(convertTrait).reduce ( (acc, elem) => getTrait(acc, elem) )

Title: Scala Builder a object recursively

Body:
Here is the situation

val input = "a:b:c:d:e"

def getTrait(primary: SomeTrait, secondary: SomeTrait): SomeTrait {
...
}

def convertTrait(name: String): SomeTrait {
...
}

So what I want to do is to slide input in window of 2 and build SomeTrait based on that like this

val result = getTrait(convertTrait(a),convertTrait(b))

and then use this result to build another result like this

val resul2 = getTrait(result, convertTrait(c))

and so onn.......

Offcourse I wanna do it in some kind of recursion/for in scala but unable to find solution

Here is where I am

val listOfList = input.split(":").grouped(2).toList

private def builder(inputList: List[List[String]], primary: SomeTrait, secondary: SomeTrait): SomeTrait = {
    for {
      xs <- inputList
      fallback = if(xs.size == 1) providerFallBackChainBuilder(convertTrait(xs(0)), "noop") else providerFallBackChainBuilder(convertTrait(xs(1)), convertTrait(xs(0)))
    } yield fallback
    FallbackConfigProvider(primary, secondary)
  }

I  somehow need to pass this fallback back to function .. I know this is not working and not best solution but can anyone guide me on how to dit better and correctly


问:
Edge and HTML Form Validation: how to remove "red square" around the input for elements in invalid status?
On the picture (this is the Edge browser) field named BsMultiSelect have normal bootstrap invalid look (this is in css). The same I expect from "Input sample", but there Edge browser adds its own "red border" (it is not in css!) for elements in invalid state . How to disable this browser behaviour?

Chrome doesn't have such feature, doesn't add any own styles for :invalid elements.

答: did you tryed outline: 0 in css

Body: did you tryed outline: 0 in css


问:
How to split the number into given ranges accordingly (ranges are based on priority)?
Here is the scenario
Given requested amount 789
I have 4 warehouse. Warehouse 1 will be the highest priority and follow by warehouse 2 etc...
All warehouse have their own min and max stock amount to distribute.
Now I want to split the requested amount to fit the available ranges.
*Not necessary to utilize all the warehouse but the highest priority have to be utilize first.
*All warehouses only can use one time
Expecting answer as per below picture.

Is there any algorithm  to get me an answer ?> [400,189,200]
Thanks alot ]1

答:
Check if the maximum of the 1st warehouse covers the requested amount. If not, check if the max of 1 and 2 covers, if not, the max of 1,2 and 3... until it covers. Now you have x warehouses to use.

Start from the bottom now. Use the minimum possible from each warehouse until the top. Minimum of less priority warehouse, plus the minimum of 2nd less priority... The sum of all the minimums may not cover the requested amount, but let's proceed with that amount

Start adding from the more priority warehouse - add to the maximum of it. Does it cover?

If yes, remove (from that warehouse) until the requested amount is equal to the collected.

If not, Repeat steps 3 and 4 for the 2nd more priority warehouse, 3rd, 4th...


问:
Return type of constructor signature must be assignable on angular services
Hello I'm working on MEAN stack project and I want to connect My UI (angularJs 9) with my sever API (nodeJs) for that I've created a service, but when I try to get data I found an ERROR

Return type of constructor signature must be assignable to the instance type of the class.

on my method return and

Cannot find name 'get1allCollections'. Did you mean 'HTMLAllCollection'?

on the method declaration.

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})
export class TransportorService {
  uri = 'http://localhost:3000';

  constructor(private http: HttpClient) {

    get1allCollections(){
      return this.http.get(`${this.uri}/collect/get1`);
    }
    getCol(){
      const selector = {
        selector: 'all'
      }
      return this.http.post(`${this.uri}/collect/get`,selector);
    }
  }
}
</code>```

答:
Put the functions outside of the constructor:</p>

```<code>constructor(private http: HttpClient) {

}
get1allCollections(){
    return this.http.get(`${this.uri}/collect/get1`);
}
getCol(){
    const selector = {
        selector: 'all'
    }
    return this.http.post(`${this.uri}/collect/get`,selector);
}

</code>```

Body:
Hello I'm working on MEAN stack project and I want to connect My UI (angularJs 9) with my sever API (nodeJs) for that I've created a service, but when I try to get data I found an ERROR

Return type of constructor signature must be assignable to the instance type of the class.

on my method return and

Cannot find name 'get1allCollections'. Did you mean 'HTMLAllCollection'?

on the method declaration.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})
export class TransportorService {
  uri = 'http://localhost:3000';

  constructor(private http: HttpClient) {

    get1allCollections(){
      return this.http.get(`${this.uri}/collect/get1`);
    }
    getCol(){
      const selector = {
        selector: 'all'
      }
      return this.http.post(`${this.uri}/collect/get`,selector);
    }
  }
}

Body:
Put the functions outside of the constructor:

constructor(private http: HttpClient) {

}
get1allCollections(){
    return this.http.get(`${this.uri}/collect/get1`);
}
getCol(){
    const selector = {
        selector: 'all'
    }
    return this.http.post(`${this.uri}/collect/get`,selector);
}


答:
You can try this.

```<code>[sum(i,[]) for i in lists_of_lists]
</code>```

```<code>[[1, 2], [3, 5], [6, 6]]
</code>```

Some timeit analysis on the suggested solutions (python 3.7 and windows 10)

Benchmarking list =[[[1],[2]],[[3],[5]],[[6],[6]]]

```<code>In [48]: timeit [sum(i,[]) for i in lists_of_lists]
914 ns ± 103 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [49]: timeit [[i for inner in sub_lists for i in inner] for sub_lists in lists_of_lists]
1.25 µs ± 136 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [64]: timeit list(starmap(concat, lists_of_lists))
639 ns ± 30 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [70]: timeit list(map(list, map(chain.from_iterable, lists_of_lists)))
1.55 µs ± 57 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
</code>```

Benchmarking list = l=[[[1],[2]],[[3],[5]],[[6],[6]]]*1000000 (3 million).

```<code>In [60]: timeit [sum(i,[]) for i in l]
1.06 s ± 68 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [61]: timeit [[i for i in j] for j in l]
1.13 s ± 64.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [65]: timeit list(starmap(concat, l))
595 ms ± 15.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [71]: timeit list(map(list, map(chain.from_iterable, l)))
1.39 s ± 101 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code>```

Body:
You can try this.

[sum(i,[]) for i in lists_of_lists]

[[1, 2], [3, 5], [6, 6]]

Some timeit analysis on the suggested solutions (python 3.7 and windows 10)

Benchmarking list =[[[1],[2]],[[3],[5]],[[6],[6]]]

In [48]: timeit [sum(i,[]) for i in lists_of_lists]
914 ns ± 103 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [49]: timeit [[i for inner in sub_lists for i in inner] for sub_lists in lists_of_lists]
1.25 µs ± 136 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [64]: timeit list(starmap(concat, lists_of_lists))
639 ns ± 30 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [70]: timeit list(map(list, map(chain.from_iterable, lists_of_lists)))
1.55 µs ± 57 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Benchmarking list = l=[[[1],[2]],[[3],[5]],[[6],[6]]]*1000000 (3 million).

In [60]: timeit [sum(i,[]) for i in l]
1.06 s ± 68 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [61]: timeit [[i for i in j] for j in l]
1.13 s ± 64.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [65]: timeit list(starmap(concat, l))
595 ms ± 15.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [71]: timeit list(map(list, map(chain.from_iterable, l)))
1.39 s ± 101 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


问:
Is it possible to look for element by it's CSS using text contains?
Couldn't find the answer. As normal xpath has Contains(text(), 'text'), I cannot obtain the same within css selector.

```<code>By.CSS_SELECTOR, "div.class::contains('text')"
</code>```

Is there any other way to do it  ?

答:
You may want to look into sub-string matches here

So for your example, you'd be doing something like

```<code>div[class*='text']
</code>```

Body:
Couldn't find the answer. As normal xpath has Contains(text(), 'text'), I cannot obtain the same within css selector.

By.CSS_SELECTOR, "div.class::contains('text')"

Is there any other way to do it  ?

Body:
You may want to look into sub-string matches here

So for your example, you'd be doing something like

div[class*='text']


问:
how to fix the getAttribute when clicking a item for change link in angular
****list.component.html***

```<code><div *ngFor="let data of temperature">
<div (click)="navigate(data)">
                <div id="{{ 'roomChart-' + i }}" style="height: 210px;"></div>
</div>
</div>
</code>```

list.component.ts

```<code>lineChart() {
const chart = echarts.init(document.getElementById(`roomChart-${index}`) as HTMLCanvasElement);
            this.option = {
              tooltip: {
                trigger: 'axis',
                axisPointer: {
                  animation: false
                },
                backgroundColor: 'rgba(245, 245, 245, 0.8)',
                borderWidth: 1,
                borderColor: '#ccc',
                padding: 10,
                textStyle: {
                  color: '#000'
                },
                formatter: function (prm: any) {
                  let rec = prm[0].name.slice(0, 10) + '<br/>' + prm[0].name.slice(11, 19) + '<br/>';

                  for (let x = 0; x < prm.length; x++) {
                    if (prm[x].axisIndex !== 1) {
                      rec += prm[x].marker + ' ' + prm[x].seriesName + ': '
                        + prm[x].data + _this.units['Celcius'] + '<br/>';
                    } else {
                      rec += prm[x].marker + ' ' + prm[x].seriesName + ': '
                        + prm[x].data + '%' + '<br/>';
                    }
                  }
                  return rec;
                }
              },
              ...this.echart.roomChart,
              dataZoom: [{
                type: 'inside',
                show: false,
                bottom: 10,
                width: '84%',
                xAxisIndex: [0, 1],
                zoomOnMouseWheel: false
              },
              {
                type: 'slider',
                bottom: 10,
                show: false,
                width: '84%',
                xAxisIndex: [0, 1],
                zoomLock: true
              }],
              ...this.echart.roomChart.xAxis[0].data = newData[0].date.map((str: any) => {
                return format(str, 'YYYY-MM-DD hh:mm a');
              }),
              ...this.echart.roomChart.xAxis[1].data = newData[0].date.map((str: any) => {
                return format(str, 'YYY-MM-DD hh:mm a');
              }),
              ...this.echart.roomChart.xAxis[0].axisLabel.formatter = ((data: any) => {
                return format(data, 'hh:mm a');
              }),
              series: [
                {
                  name: 'Temerature',
                  data: newData[0].temperature,
                  type: 'line',
                  itemStyle: {
                    color: 'rgba(0, 101, 144, 1)'
                  },
                  areaStyle: {
                    color: 'rgba(0, 101, 144, 1)'
                  },
                  markPoint: {
                    type: 'Pin',
                    data: [
                      {
                        type: 'max',
                        itemStyle: {
                          color: 'rgba(0, 101, 144)'
                        }
                      },
                      {
                        type: 'min',
                        itemStyle: {
                          color: 'rgb(110, 151, 204)'
                        }
                      }
                    ]
                  },
                  smooth: true
                },
                {
                  name: 'Humidity',
                  data: newData[0].humidity,
                  type: 'line',
                  itemStyle: {
                    color: 'rgba(132, 219, 255, 1)'
                  },
                  areaStyle: {
                    color: 'rgba(132, 219, 255, 1)'
                  },
                  markPoint: {
                    type: 'Pin',
                    data: [
                      {
                        type: 'max',
                        itemStyle: {
                          color: 'rgba(132, 219, 255)'
                        }
                      },
                      {
                        type: 'min',
                        itemStyle: {
                          color: 'rgba(194, 237, 255)'
                        }
                      }
                    ]
                  },
                  smooth: true,
                  xAxisIndex: 1,
                  yAxisIndex: 1
                }
              ]
            };

            chart.setOption(this.option);
}

    navigate(data: any) {
    const roomName = encodeURIComponent(data.sensor);
    if (data) {
      this.router.navigate([`/dashboard/room`], {
        queryParams: { room: roomName }
      });
    }
  }
</code>```

I have an error which is the ERROR TypeError: Cannot read property 'getAttribute' of null.
when the lineChart still loading then clicking the division. I'm getting this error ERROR TypeError: Cannot read property 'getAttribute' of null

How to fix the error Cannot read property 'getAttribute' of null.

But when the chart are all loaded there's no error, but when still loading and click the division/item while loading I'm getting the error Cannot read property 'getAttribute' of null

答:
You are using getElementById. This is outside of Angular's world, that's why it can't find the element you're trying to select.

Solution 1 : ngAfterViewInit

First, you have to wait for Angular to draw the view ( = generate the HTML), then you can use getElementById on what's been generated.

```<code>ngAfterViewInit() {
 echarts.init(document.getElementById(`roomChart-${index}`) ...
}
</code>```

But that's still hacky, as everything that will happen is outside of Angular's world.

Solution 2 :

Use Echarts for Angular :)

Body:
****list.component.html***

list.component.ts

lineChart() {
const chart = echarts.init(document.getElementById(`roomChart-${index}`) as HTMLCanvasElement);
            this.option = {
              tooltip: {
                trigger: 'axis',
                axisPointer: {
                  animation: false
                },
                backgroundColor: 'rgba(245, 245, 245, 0.8)',
                borderWidth: 1,
                borderColor: '#ccc',
                padding: 10,
                textStyle: {
                  color: '#000'
                },
                formatter: function (prm: any) {
                  let rec = prm[0].name.slice(0, 10) + '
' + prm[0].name.slice(11, 19) + '
';

                  for (let x = 0; x < prm.length; x++) {
                    if (prm[x].axisIndex !== 1) {
                      rec += prm[x].marker + ' ' + prm[x].seriesName + ': '
                        + prm[x].data + _this.units['Celcius'] + '
';
                    } else {
                      rec += prm[x].marker + ' ' + prm[x].seriesName + ': '
                        + prm[x].data + '%' + '
';
                    }
                  }
                  return rec;
                }
              },
              ...this.echart.roomChart,
              dataZoom: [{
                type: 'inside',
                show: false,
                bottom: 10,
                width: '84%',
                xAxisIndex: [0, 1],
                zoomOnMouseWheel: false
              },
              {
                type: 'slider',
                bottom: 10,
                show: false,
                width: '84%',
                xAxisIndex: [0, 1],
                zoomLock: true
              }],
              ...this.echart.roomChart.xAxis[0].data = newData[0].date.map((str: any) => {
                return format(str, 'YYYY-MM-DD hh:mm a');
              }),
              ...this.echart.roomChart.xAxis[1].data = newData[0].date.map((str: any) => {
                return format(str, 'YYY-MM-DD hh:mm a');
              }),
              ...this.echart.roomChart.xAxis[0].axisLabel.formatter = ((data: any) => {
                return format(data, 'hh:mm a');
              }),
              series: [
                {
                  name: 'Temerature',
                  data: newData[0].temperature,
                  type: 'line',
                  itemStyle: {
                    color: 'rgba(0, 101, 144, 1)'
                  },
                  areaStyle: {
                    color: 'rgba(0, 101, 144, 1)'
                  },
                  markPoint: {
                    type: 'Pin',
                    data: [
                      {
                        type: 'max',
                        itemStyle: {
                          color: 'rgba(0, 101, 144)'
                        }
                      },
                      {
                        type: 'min',
                        itemStyle: {
                          color: 'rgb(110, 151, 204)'
                        }
                      }
                    ]
                  },
                  smooth: true
                },
                {
                  name: 'Humidity',
                  data: newData[0].humidity,
                  type: 'line',
                  itemStyle: {
                    color: 'rgba(132, 219, 255, 1)'
                  },
                  areaStyle: {
                    color: 'rgba(132, 219, 255, 1)'
                  },
                  markPoint: {
                    type: 'Pin',
                    data: [
                      {
                        type: 'max',
                        itemStyle: {
                          color: 'rgba(132, 219, 255)'
                        }
                      },
                      {
                        type: 'min',
                        itemStyle: {
                          color: 'rgba(194, 237, 255)'
                        }
                      }
                    ]
                  },
                  smooth: true,
                  xAxisIndex: 1,
                  yAxisIndex: 1
                }
              ]
            };

            chart.setOption(this.option);
}

    navigate(data: any) {
    const roomName = encodeURIComponent(data.sensor);
    if (data) {
      this.router.navigate([`/dashboard/room`], {
        queryParams: { room: roomName }
      });
    }
  }

I have an error which is the ERROR TypeError: Cannot read property 'getAttribute' of null.
when the lineChart still loading then clicking the division. I'm getting this error ERROR TypeError: Cannot read property 'getAttribute' of null

How to fix the error Cannot read property 'getAttribute' of null.

But when the chart are all loaded there's no error, but when still loading and click the division/item while loading I'm getting the error Cannot read property 'getAttribute' of null

Body:
You are using getElementById. This is outside of Angular's world, that's why it can't find the element you're trying to select.

Solution 1 : ngAfterViewInit

First, you have to wait for Angular to draw the view ( = generate the HTML), then you can use getElementById on what's been generated.

ngAfterViewInit() {
 echarts.init(document.getElementById(`roomChart-${index}`) ...
}

But that's still hacky, as everything that will happen is outside of Angular's world.

Solution 2 :

Use Echarts for Angular :)


问:
Is it possible to use tqdm for a process that isn't a loop?
I am writing a program in which an operation takes a few seconds (loading a large file). Luckily, it always takes the same amount of time. So, for the sake of the user, I want to make a progress bar. However, tqdm seems to be designed for loops. Let's say that sleep(10) is the process that takes time. How do I work this out?

I want to make a progress bar for a long process that is not a loop.

```<code>from time import time, sleep
from tqdm import tqdm

for i in tqdm([1]):
    sleep(10)
</code>```

The problem with this code is that the progress bar will stay at zero, then jump to 100% at the end of the process. I want a progress bar that evolves consistently over the course of 10 seconds.

答:
You can use a thread to load the file, and loop through tqdm(range(10)) until the file is loaded like this:</p>

```<code>import logging
import threading
import time
from tqdm import tqdm

def thread_function(name):
    logging.info("Thread %s: starting", name)
    logging.info("Main    : file loading...")
    time.sleep(5)
    logging.info("Thread %s: finishing", name)

if __name__ == "__main__":
    logging.basicConfig(format="%(asctime)s: %(message)s", level=logging.INFO,
                        datefmt="%H:%M:%S")

    x = threading.Thread(target=thread_function, args=(1,))
    x.start()
    for i in tqdm(range(10)):
        if not x.is_alive():
            break
        time.sleep(1)
    x.join()
    logging.info("Main    : end.")
</code>```

Body:
I am writing a program in which an operation takes a few seconds (loading a large file). Luckily, it always takes the same amount of time. So, for the sake of the user, I want to make a progress bar. However, tqdm seems to be designed for loops. Let's say that sleep(10) is the process that takes time. How do I work this out?

I want to make a progress bar for a long process that is not a loop.

from time import time, sleep
from tqdm import tqdm

for i in tqdm([1]):
    sleep(10)

The problem with this code is that the progress bar will stay at zero, then jump to 100% at the end of the process. I want a progress bar that evolves consistently over the course of 10 seconds.

Body:
You can use a thread to load the file, and loop through tqdm(range(10)) until the file is loaded like this:

import logging
import threading
import time
from tqdm import tqdm

def thread_function(name):
    logging.info("Thread %s: starting", name)
    logging.info("Main    : file loading...")
    time.sleep(5)
    logging.info("Thread %s: finishing", name)

if __name__ == "__main__":
    logging.basicConfig(format="%(asctime)s: %(message)s", level=logging.INFO,
                        datefmt="%H:%M:%S")

    x = threading.Thread(target=thread_function, args=(1,))
    x.start()
    for i in tqdm(range(10)):
        if not x.is_alive():
            break
        time.sleep(1)
    x.join()
    logging.info("Main    : end.")


问:
How to delete specific columns(not entirely) in excel vba
I am trying to delete columns when column T,U,V has 0 value at the same row. However, the code that i am using only deletes some of them and as shown below, there are still 0s at column T,U,V for some rows even though I already specify them to be deleted at specific cells that i have assigned. Which part of my code have i done wrong?

```<code>Dim j As Long

Dim lr As Long
lr = Sheets(1).Cells(Rows.Count, "U").End(xlUp).Row

For j = 1 To lr

   If Sheets(1).Cells(j, 21).Value = 0 And Sheets(1).Cells(j, 22).Value = 0 And Sheets(1).Cells(j, 23).Value = 0 Then
   Sheets(1).Range("T" & j & ":W" & j).Delete
      j = j + 1
      End If
      Next
</code>```

After applying my code, there are still left overs rows with zeros.

so eventually i want it to be

答:
Try:</p>

```<code>Sub testr()

    Dim LastRow As Long, i As Long

    With ThisWorkbook.Worksheets("Sheet1")

         LastRow = .Cells(.Rows.Count, "S").End(xlUp).Row

        For i = LastRow To 2 Step -1
            If .Range("T" & i).Value = 0 And .Range("U" & i).Value = 0 And .Range("V" & i).Value = 0 Then
                .Rows(i).EntireRow.Delete
            End If
        Next i

    End With

End Sub
</code>```

Body:
I am trying to delete columns when column T,U,V has 0 value at the same row. However, the code that i am using only deletes some of them and as shown below, there are still 0s at column T,U,V for some rows even though I already specify them to be deleted at specific cells that i have assigned. Which part of my code have i done wrong?

Dim j As Long

Dim lr As Long
lr = Sheets(1).Cells(Rows.Count, "U").End(xlUp).Row

For j = 1 To lr

   If Sheets(1).Cells(j, 21).Value = 0 And Sheets(1).Cells(j, 22).Value = 0 And Sheets(1).Cells(j, 23).Value = 0 Then
   Sheets(1).Range("T" & j & ":W" & j).Delete
      j = j + 1
      End If
      Next

After applying my code, there are still left overs rows with zeros.

so eventually i want it to be

Body:
Try:

Sub testr()

    Dim LastRow As Long, i As Long

    With ThisWorkbook.Worksheets("Sheet1")

         LastRow = .Cells(.Rows.Count, "S").End(xlUp).Row

        For i = LastRow To 2 Step -1
            If .Range("T" & i).Value = 0 And .Range("U" & i).Value = 0 And .Range("V" & i).Value = 0 Then
                .Rows(i).EntireRow.Delete
            End If
        Next i

    End With

End Sub


问:
DLL load failed error when running mitmweb.exe
I have ImportError: DLL load failed: The specified module could not be found. error when running mitmweb.exe.
My steps:

downloaded Windows installer from https://mitmproxy.org/ (v 5.0.1)

installed (with defualt settings) on Windows Server 2019 Datacenter

ran C:\Program Files (x86)\mitmproxy\bin\mitmweb.exe

Full error:

Traceback (most recent call last):
  File "mitmweb", line 2, in <module>
  File "d:\a\mitmproxy\mitmproxy\.tox\cibuild\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
  File "mitmproxy\tools\main.py", line 22, in <module>
  File "d:\a\mitmproxy\mitmproxy\.tox\cibuild\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
  File "mitmproxy\tools\_main.py", line 14, in <module>
  File "d:\a\mitmproxy\mitmproxy\.tox\cibuild\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
  File "mitmproxy\master.py", line 7, in <module>
  File "d:\a\mitmproxy\mitmproxy\.tox\cibuild\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
  File "mitmproxy\addonmanager.py", line 8, in <module>
  File "d:\a\mitmproxy\mitmproxy\.tox\cibuild\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
  File "mitmproxy\eventsequence.py", line 5, in <module>
  File "d:\a\mitmproxy\mitmproxy\.tox\cibuild\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
  File "mitmproxy\http.py", line 7, in <module>
  File "d:\a\mitmproxy\mitmproxy\.tox\cibuild\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
  File "mitmproxy\net\http\__init__.py", line 1, in <module>
  File "d:\a\mitmproxy\mitmproxy\.tox\cibuild\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
  File "mitmproxy\net\http\request.py", line 11, in <module>
  File "d:\a\mitmproxy\mitmproxy\.tox\cibuild\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
  File "mitmproxy\net\http\message.py", line 5, in <module>
  File "d:\a\mitmproxy\mitmproxy\.tox\cibuild\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
  File "mitmproxy\net\http\encoding.py", line 11, in <module>
  File "d:\a\mitmproxy\mitmproxy\.tox\cibuild\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 627, in exec_module
  File "site-packages\brotli.py", line 8, in <module>
ImportError: DLL load failed: The specified module could not be found.
[964] Failed to execute script mitmweb

So what DLLs am I missing?

答:
At the moment the only workaround I know is to use version 4.0.4.

Source(s):

https://github.com/mitmproxy/mitmproxy/issues/3804

https://github.com/mitmproxy/mitmproxy/issues/3823


Title: How to loop through dates column and assign values according to a certain condition?

Body:
I have a df as follows

       dates       winter   summer  rest  Final
2020-01-01 00:15:00 65.5    71.5    73.0   NaN
2020-01-01 00:30:00 62.6    69.0    70.1   NaN
2020-01-01 00:45:00 59.6    66.3    67.1   NaN
2020-01-01 01:00:00 57.0    63.5    64.5   NaN
2020-01-01 01:15:00 54.8    60.9    62.3   NaN
2020-01-01 01:30:00 53.1    58.6    60.6   NaN
2020-01-01 01:45:00 51.7    56.6    59.2   NaN
2020-01-01 02:00:00 50.5    55.1    57.9   NaN
2020-01-01 02:15:00 49.4    54.2    56.7   NaN
2020-01-01 02:30:00 48.5    53.7    55.6   NaN
2020-01-01 02:45:00 47.9    53.4    54.7   NaN
2020-01-01 03:00:00 47.7    53.3    54.2   NaN
2020-01-01 03:15:00 47.9    53.1    54.1   NaN
2020-01-01 03:30:00 48.7    53.2    54.6   NaN
2020-01-01 03:45:00 50.2    54.1    55.8   NaN
2020-01-01 04:00:00 52.3    56.1    57.9   NaN
2020-04-28 12:30:00 225.1   200.0   209.8  NaN
2020-04-28 12:45:00 215.7   193.8   201.9  NaN
2020-04-28 13:00:00 205.6   186.9   193.4  NaN
2020-04-28 13:15:00 195.7   179.9   185.0  NaN
2020-04-28 13:30:00 186.7   173.4   177.4  NaN
2020-04-28 13:45:00 179.2   168.1   170.9  NaN
2020-04-28 14:00:00 173.8   164.4   166.3  NaN
2020-04-28 14:15:00 171.0   163.0   163.9  NaN
2020-04-28 14:30:00 170.7   163.5   163.6  NaN
2020-12-31 21:15:00 88.5    90.2    89.2   NaN
2020-12-31 21:30:00 85.2    88.5    87.2   NaN
2020-12-31 21:45:00 82.1    86.3    85.0   NaN
2020-12-31 22:00:00 79.4    84.1    83.2   NaN
2020-12-31 22:15:00 77.6    82.4    82.1   NaN
2020-12-31 22:30:00 76.4    81.2    81.7   NaN
2020-12-31 22:45:00 75.6    80.3    81.6   NaN
2020-12-31 23:00:00 74.7    79.4    81.3   NaN
2020-12-31 23:15:00 73.7    78.4    80.6   NaN
2020-12-31 23:30:00 72.3    77.2    79.5   NaN
2020-12-31 23:45:00 70.5    75.7    77.9   NaN
2021-01-01 00:00:00 68.2    73.8    75.7   NaN

The dates column has dates starting from 2020-01-01 00:15:00 till 2021-01-01 00:00:00 split at every 15 mins.

I also have the following date range conditions:

Winter: 01.11 - 20.03

Summer: 15.05 - 14.09

Rest: 21.03 - 14.05 & 15.09 - 31.10

What I want to do is to create a new column named season that checks every date in the dates column and assigns winter if the date is in Winter range, summer if it is in Summer range and rest if it is the Rest range.

Then, based on the value in the season column, the Final column must be filled. If the value in season column is 'winter', then the values from winter column must be placed, if the value in season column is 'summer', then the values from summer column must be placed and so on.

How can this be done?

Body:
Idea is normalize datetimes for same year, then filter by Series.between and set new column by numpy.select:

d = pd.to_datetime(df['dates'].dt.strftime('%m-%d-2020'))

m1 = d.between('2020-11-01','2020-12-31') | d.between('2020-01-01','2020-03-20')
m2 = d.between('2020-05-15','2020-09-14')

df['Final'] = np.select([m1, m2], ['Winter','Summer'], default='Rest')
print (df)
                dates  winter  summer  rest   Final
0 2020-01-01 00:15:00    65.5    71.5  73.0  Winter
1 2020-06-15 00:30:00    62.6    69.0  70.1  Summer
2 2020-12-25 00:45:00    59.6    66.3  67.1  Winter
3 2020-10-10 01:00:00    57.0    63.5  64.5    Rest


问:
C# lambda expression unable to manage a certain string compare
I have a specific lambda what doesn't seem to want to work properly although the logic seems sound.

```<code>index = llCodeList.FindIndex(f => string.Compare(f.Threshold.ToString(), searchText, true ) >= 0);
</code>```

f.Threshold is an integer value, it seems that the conversion doesn't happen and it breaks my search function.  Can anyone shed some light on this?

答:
If my comment correctly got the gist of what you are trying to do then do something like this:</p>

```<code>int index = -1;
int intVal;
if (int.TryParse(seachText, intVal)){
  index = llCodeList.FindIndex(f => f.Threshold >= intVal);
}
</code>```

Body:
I have a specific lambda what doesn't seem to want to work properly although the logic seems sound.

index = llCodeList.FindIndex(f => string.Compare(f.Threshold.ToString(), searchText, true ) >= 0);

f.Threshold is an integer value, it seems that the conversion doesn't happen and it breaks my search function.  Can anyone shed some light on this?

Body:
If my comment correctly got the gist of what you are trying to do then do something like this:

int index = -1;
int intVal;
if (int.TryParse(seachText, intVal)){
  index = llCodeList.FindIndex(f => f.Threshold >= intVal);
}


问:
Hosting asp.net core + ReactJS web app with SSL containing multiple CN or domain names is causing invalid issuer error
I am facing the following problem while hosting a web app built with asp.net core 3.1 and React.

We have used default visual studio template for React. ASP.NET Identity is used for authentication and authorization.

Authentication and Authorization work as expected as long as we host the website with an SSL certificate issued for single domain or CN. (e.g. example.com)

If we host he website with an SSL with multiple CNs (e.g. example.com, sub1.example.com, sub2.example.com), it works fine for any ONE of the domains. For the remaining domains we get the following behavior:

The login works as expected. The /connect/token path issues valid token. Once logged in, when we try to invoke any api (all apis are hosted under /api route), we get 401 unauthorized error. Error description in the header:

WWW-Authenticate: Bearer error="invalid_token", error_description="The issuer 'https://sub1.example.com' is invalid".

I also tried parsing the issued token on jwt.io. The iss field (issuer) is https://sub1.example.com which exactly matches the error description. I cannot fathom why identity engine refuses to identify the issuer for which it issued token for.

Here is relevant snippet from Startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentityServer()
            .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
    services.AddAuthentication()
            .AddIdentityServerJwt();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseAuthentication();
    app.UseIdentityServer();
    app.UseAuthorization();
}
</code>```

Any ideas?

答:
Please check url http://{url}/.well-known/openid-configuration

This url is should be true

Following codes are worked different domain.
Auth Startup

```<code> services.AddIdentityServer(options =>
        {
            options.IssuerUri = Configuration["ServerSettings:Authority"].ToString();
            options.PublicOrigin = Configuration["ServerSettings:Authority"].ToString();
        })
            .AddDeveloperSigningCredential()
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryClients(Config.GetClients())
            .AddProfileService<ProfileService>();
</code>```

Api Startup

```<code>services.AddAuthentication("Bearer")
        .AddIdentityServerAuthentication(options =>
        {
            options.Authority = Configuration["ServerSettings:Authority"].ToString(); //"http://localhost:31864";
            options.RequireHttpsMetadata = false;
            options.ApiName = "api";
        });
</code>```

Works in the same domain but if different domain you should specify this

Body:
I am facing the following problem while hosting a web app built with asp.net core 3.1 and React.

We have used default visual studio template for React. ASP.NET Identity is used for authentication and authorization.

Authentication and Authorization work as expected as long as we host the website with an SSL certificate issued for single domain or CN. (e.g. example.com)

If we host he website with an SSL with multiple CNs (e.g. example.com, sub1.example.com, sub2.example.com), it works fine for any ONE of the domains. For the remaining domains we get the following behavior:

The login works as expected. The /connect/token path issues valid token. Once logged in, when we try to invoke any api (all apis are hosted under /api route), we get 401 unauthorized error. Error description in the header:

WWW-Authenticate: Bearer error="invalid_token", error_description="The issuer 'https://sub1.example.com' is invalid".

I also tried parsing the issued token on jwt.io. The iss field (issuer) is https://sub1.example.com which exactly matches the error description. I cannot fathom why identity engine refuses to identify the issuer for which it issued token for.

Here is relevant snippet from Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentityServer()
            .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
    services.AddAuthentication()
            .AddIdentityServerJwt();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseAuthentication();
    app.UseIdentityServer();
    app.UseAuthorization();
}

Any ideas?

Body:
Please check url http://{url}/.well-known/openid-configuration

This url is should be true

Following codes are worked different domain.
Auth Startup

 services.AddIdentityServer(options =>
        {
            options.IssuerUri = Configuration["ServerSettings:Authority"].ToString();
            options.PublicOrigin = Configuration["ServerSettings:Authority"].ToString();
        })
            .AddDeveloperSigningCredential()
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryClients(Config.GetClients())
            .AddProfileService<ProfileService>();

Api Startup

services.AddAuthentication("Bearer")
        .AddIdentityServerAuthentication(options =>
        {
            options.Authority = Configuration["ServerSettings:Authority"].ToString(); //"http://localhost:31864";
            options.RequireHttpsMetadata = false;
            options.ApiName = "api";
        });

Works in the same domain but if different domain you should specify this


问:
spring-data-flow problem to undeploy streams deployed on a docker platform with Kafka and Oracle
We are looking for SCDF to deploy our applications.
Actually, I use skipper-server 2.3 dataflow-server 2.4 and kafka deployed as dockers.
When I am on a local server, we don't have any problems but when we are deployed on a docker platform, the deployment and the destroy of streams are OK. But we can't un-deploy them by the GUI and the dataflow-server-shell.
In the log, we have this trace :

```<code>skipper            | 2020-02-19 14:30:58.451  INFO 1 --- [eTaskExecutor-2] o.s.c.s.s.s.DeleteDeleteAction           : About to delete testStreamSftpDataflowlaunch1
skipper            | 2020-02-19 14:30:58.471  INFO 1 --- [eTaskExecutor-2] o.s.c.d.spi.local.LocalAppDeployer       : Un-deploying app with deploymentId testStreamSftpDataflowlaunch1.sftp-dataflow-v1 instance 0.
skipper            | 2020-02-19 14:31:28.525  INFO 1 --- [eTaskExecutor-2] o.s.s.support.LifecycleObjectSupport     : stopped org.springframework.statemachine.support.DefaultStateMachineExecutor@5a876edb
skipper            | 2020-02-19 14:31:28.525  INFO 1 --- [eTaskExecutor-2] o.s.s.support.LifecycleObjectSupport     : stopped DELETE_DELETE DELETE_EXIT  /  / uuid=cfb0fc42-6277-430a-9c39-05e3f14be373 / id=testStreamSftpDataflowlaunch1
skipper            | 2020-02-19 14:31:28.525  INFO 1 --- [eTaskExecutor-2] o.s.c.s.s.s.StateMachineConfiguration    : Entering state ObjectState [getIds()=[INITIAL], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=1492058631, toString()=AbstractState [id=INITIAL, pseudoState=org.springframework.statemachine.state.DefaultPseudoState@6409e9d2, deferred=[], entryActions=[], exitActions=[org.springframework.cloud.skipper.server.statemachine.ResetVariablesAction@7139bd31], stateActions=[], regions=[], submachine=null]]
skipper            | 2020-02-19 14:31:28.525  INFO 1 --- [eTaskExecutor-2] o.s.c.s.s.s.SkipperStateMachineService   : setting future value org.springframework.cloud.skipper.domain.Release@7bab1e28

skipper |
---------

 2020-02-19 14:31:28.525  INFO 1 --- [eTaskExecutor-2] o.s.s.support.LifecycleObjectSupport     : started org.springframework.statemachine.support.DefaultStateMachineExecutor@5a876edb
skipper            | 2020-02-19 14:31:28.525  INFO 1 --- [eTaskExecutor-2] o.s.s.support.LifecycleObjectSupport     : started DELETE_DELETE DELETE_EXIT  /  / uuid=cfb0fc42-6277-430a-9c39-05e3f14be373 / id=testStreamSftpDataflowlaunch1
</code>```

However, the stream is already available.

答:
The DELETE_EXIT from Skipper state machine confirms that the deletion of the release (undeployment of the stream) exits successfully.

Looks like there are some issues when it comes to undeploying the apps that are part of the stream. Could you share more debug logs (especially the deployer side of things) to understand what went wrong when the associated apps were undeployed by Skipper server?

Body:
We are looking for SCDF to deploy our applications.
Actually, I use skipper-server 2.3 dataflow-server 2.4 and kafka deployed as dockers.
When I am on a local server, we don't have any problems but when we are deployed on a docker platform, the deployment and the destroy of streams are OK. But we can't un-deploy them by the GUI and the dataflow-server-shell.
In the log, we have this trace :

skipper            | 2020-02-19 14:30:58.451  INFO 1 --- [eTaskExecutor-2] o.s.c.s.s.s.DeleteDeleteAction           : About to delete testStreamSftpDataflowlaunch1
skipper            | 2020-02-19 14:30:58.471  INFO 1 --- [eTaskExecutor-2] o.s.c.d.spi.local.LocalAppDeployer       : Un-deploying app with deploymentId testStreamSftpDataflowlaunch1.sftp-dataflow-v1 instance 0.
skipper            | 2020-02-19 14:31:28.525  INFO 1 --- [eTaskExecutor-2] o.s.s.support.LifecycleObjectSupport     : stopped org.springframework.statemachine.support.DefaultStateMachineExecutor@5a876edb
skipper            | 2020-02-19 14:31:28.525  INFO 1 --- [eTaskExecutor-2] o.s.s.support.LifecycleObjectSupport     : stopped DELETE_DELETE DELETE_EXIT  /  / uuid=cfb0fc42-6277-430a-9c39-05e3f14be373 / id=testStreamSftpDataflowlaunch1
skipper            | 2020-02-19 14:31:28.525  INFO 1 --- [eTaskExecutor-2] o.s.c.s.s.s.StateMachineConfiguration    : Entering state ObjectState [getIds()=[INITIAL], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=1492058631, toString()=AbstractState [id=INITIAL, pseudoState=org.springframework.statemachine.state.DefaultPseudoState@6409e9d2, deferred=[], entryActions=[], exitActions=[org.springframework.cloud.skipper.server.statemachine.ResetVariablesAction@7139bd31], stateActions=[], regions=[], submachine=null]]
skipper            | 2020-02-19 14:31:28.525  INFO 1 --- [eTaskExecutor-2] o.s.c.s.s.s.SkipperStateMachineService   : setting future value org.springframework.cloud.skipper.domain.Release@7bab1e28

skipper |
---------

 2020-02-19 14:31:28.525  INFO 1 --- [eTaskExecutor-2] o.s.s.support.LifecycleObjectSupport     : started org.springframework.statemachine.support.DefaultStateMachineExecutor@5a876edb
skipper            | 2020-02-19 14:31:28.525  INFO 1 --- [eTaskExecutor-2] o.s.s.support.LifecycleObjectSupport     : started DELETE_DELETE DELETE_EXIT  /  / uuid=cfb0fc42-6277-430a-9c39-05e3f14be373 / id=testStreamSftpDataflowlaunch1

However, the stream is already available.


答:
```<code>result = []
for subList in lists_of_lists:
    newList = []
    for subSubList in subList:
        newList.extend(subSubList)
    result.append(newList)
</code>```

And result contains what is wanted.

Body:
How do I concatenate two lists inside the nested list Python?

I have this list

lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]

And my expected output is

lists_of_lists =[[1,2],[3,5],[6,6]]

I tried this way

new = []
lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]
for i in range(len(lists_of_lists)):
    for list in  lists_of_lists[i]:
        for element in list:
            new.append(element)
print(new)

But I got

[1, 2, 3, 5, 6, 6]

Thank you for any suggestions

Body:
result = []
for subList in lists_of_lists:
    newList = []
    for subSubList in subList:
        newList.extend(subSubList)
    result.append(newList)

And result contains what is wanted.


问:
Strip a comma and whitespace thats after it from a string
I'm working with a Postcode Finder and some of the address elements i.e County are returning empty at times as a ", "

I'm looking to strip them from the string to return a more readable address format

Example Data is JSON :

```<code>{
"latitude": 53.381130218505859,
"longitude": -1.4663739204406738,
"addresses": [
    "Crucible Enterprises Ltd, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "Crucible Theatre, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "Sheffield Crucible Productions Ltd, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "Sheffield Theatres Crucible Trust, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "The City Of Sheffield Theatre Trust, 55 Norfolk Street, , , , Sheffield, South Yorkshire"
]
}
</code>```

As you can see there's a lot of commas and spaces directly after with no data in.

How do I go about doing this? My current code is :

```<code>$.ajax(
            {
                type: 'POST',
                url: '/address',
                dataType: 'json',
                data: { _token: token, postcode: postcode},
                success: function( data )
                {
                    $('.addresses').html('');

                    $.each(data, function(k, v)
                    {
                        address = v.replace(/\s+/g, ' ');

                        $('.addresses').append('<option value="">'+ address +'</option>');
                    })
                }
            }
        )
</code>```

答:
You could replace the extra , by using regex.

Try this.

let str = "Crucible Enterprises Ltd, 55 Norfolk Street, , , , Sheffield, South Yorkshire";
let regex = /(,\s){2,}/g
console.log(str.replace(regex, ", "));```
</div>
</div>
</p>

<p>In your code you could use like below.</p>

```$.ajax({
  type: "POST",
  url: "/address",
  dataType: "json",
  data: { _token: token, postcode: postcode },
  success: function(data) {
    $(".addresses").html("");

    $.each(data, function(k, v) {
      address = v.replace(/\s+|(,\s){2,}/g, " ");

      $(".addresses").append('<option value="">' + address + "</option>");
    });
  }
});
```

Body:
I'm working with a Postcode Finder and some of the address elements i.e County are returning empty at times as a ", "

I'm looking to strip them from the string to return a more readable address format

Example Data is JSON :

{
"latitude": 53.381130218505859,
"longitude": -1.4663739204406738,
"addresses": [
    "Crucible Enterprises Ltd, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "Crucible Theatre, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "Sheffield Crucible Productions Ltd, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "Sheffield Theatres Crucible Trust, 55 Norfolk Street, , , , Sheffield, South Yorkshire",
    "The City Of Sheffield Theatre Trust, 55 Norfolk Street, , , , Sheffield, South Yorkshire"
]
}

As you can see there's a lot of commas and spaces directly after with no data in.

How do I go about doing this? My current code is :

$.ajax(
            {
                type: 'POST',
                url: '/address',
                dataType: 'json',
                data: { _token: token, postcode: postcode},
                success: function( data )
                {
                    $('.addresses').html('');

                    $.each(data, function(k, v)
                    {
                        address = v.replace(/\s+/g, ' ');

                        $('.addresses').append('<option value="">'+ address +'</option>');
                    })
                }
            }
        )

Body:
You could replace the extra , by using regex.

Try this.

let str = "Crucible Enterprises Ltd, 55 Norfolk Street, , , , Sheffield, South Yorkshire";
let regex = /(,\s){2,}/g
console.log(str.replace(regex, ", "));

In your code you could use like below.

$.ajax({
  type: "POST",
  url: "/address",
  dataType: "json",
  data: { _token: token, postcode: postcode },
  success: function(data) {
    $(".addresses").html("");

    $.each(data, function(k, v) {
      address = v.replace(/\s+|(,\s){2,}/g, " ");

      $(".addresses").append('<option value="">' + address + "</option>");
    });
  }
});


问:
java.sql.SQLException: ORA-22835: Buffer too small for CLOB to CHAR or BLOB to RAW conversion
I have a dynamic query build with and executed with TypedQuery<NewsContentBaseInfo> and one of the fields is CLOB object - news.stores. Here is the error I get and I can't find iformation how to solve this:

java.sql.SQLException: ORA-22835: Buffer too small for CLOB to CHAR or BLOB to RAW conversion

Here is the query:

```<code>SELECT DISTINCT new com.kaufland.newsletter.usecase.newscontent.search.dto.response.NewsContentBaseInfo(news.id, news.uuid, news.dayAndTimeOfPublish, news.title, news.subtitle, news.categoryCountry, news.newsPeriod, to_char(news.stores))
FROM com.kaufland.newsletter.domain.content.AbstractNewsContent news
LEFT OUTER JOIN news.newsLinks newsLinks
WHERE news.country = :country AND news.status = :status
AND news.dayAndTimeOfPublish >= :dayAndTimeOfPublishStart
AND news.dayAndTimeOfPublish <= :dayAndTimeOfPublishEnd
AND (news.stores LIKE '%'||:storeNumber0||'%')
AND news.categoryCountry.id in :includeCategoryIds
AND (LOWER(news.title) LIKE LOWER('%'||:searchText||'%')
    OR LOWER(news.subtitle) LIKE LOWER('%'||:searchText||'%')
    OR LOWER(news.text1) LIKE LOWER('%'||:searchTextEscaped||'%')
    OR LOWER(news.text2) LIKE LOWER('%'||:searchTextEscaped||'%')
    OR LOWER(news.text3) LIKE LOWER('%'||:searchTextEscaped||'%')
    OR LOWER(newsLinks.displayText) LIKE LOWER('%'||:searchText||'%'))
ORDER BY news.dayAndTimeOfPublish DESC
</code>```

答:
The to_char function returns a varchar that is limited to 4000 characters. If the CLOB is greater than that you can get this error (depending on the Oracle version).

If you really need an String value you can try with the dbms_lob package (https://docs.oracle.com/database/121/ARPLS/d_lob.htm#ARPLS600), that can handle more characters.

Body:
I have a dynamic query build with and executed with TypedQuery<NewsContentBaseInfo> and one of the fields is CLOB object - news.stores. Here is the error I get and I can't find iformation how to solve this:

java.sql.SQLException: ORA-22835: Buffer too small for CLOB to CHAR or BLOB to RAW conversion

Here is the query:

SELECT DISTINCT new com.kaufland.newsletter.usecase.newscontent.search.dto.response.NewsContentBaseInfo(news.id, news.uuid, news.dayAndTimeOfPublish, news.title, news.subtitle, news.categoryCountry, news.newsPeriod, to_char(news.stores))
FROM com.kaufland.newsletter.domain.content.AbstractNewsContent news
LEFT OUTER JOIN news.newsLinks newsLinks
WHERE news.country = :country AND news.status = :status
AND news.dayAndTimeOfPublish >= :dayAndTimeOfPublishStart
AND news.dayAndTimeOfPublish <= :dayAndTimeOfPublishEnd
AND (news.stores LIKE '%'||:storeNumber0||'%')
AND news.categoryCountry.id in :includeCategoryIds
AND (LOWER(news.title) LIKE LOWER('%'||:searchText||'%')
    OR LOWER(news.subtitle) LIKE LOWER('%'||:searchText||'%')
    OR LOWER(news.text1) LIKE LOWER('%'||:searchTextEscaped||'%')
    OR LOWER(news.text2) LIKE LOWER('%'||:searchTextEscaped||'%')
    OR LOWER(news.text3) LIKE LOWER('%'||:searchTextEscaped||'%')
    OR LOWER(newsLinks.displayText) LIKE LOWER('%'||:searchText||'%'))
ORDER BY news.dayAndTimeOfPublish DESC


问:
Why are Log.d() and Log.v() not printing
I have the following test code in my Activity:

```<code>@Override
public void onStart() {
    super.onStart();
    Log.e(CLASS_NAME, "ERROR onStart()");
    Log.w(CLASS_NAME, "WARN onStart()");
    Log.i(CLASS_NAME, "INFO onStart()");
    Log.d(CLASS_NAME, "DEBUG onStart()");
    Log.v(CLASS_NAME, "VERBOSE onStart()");
</code>```

On the logcat view in Android Studio, it only prints:

```<code>02-10 15:56:10.190    6194-6194/org.example.my_app E/MyActivity﹕ ERROR onStart()
02-10 15:56:10.190    6194-6194/org.example.my_app W/MyActivity﹕ WARN onStart()
02-10 15:56:10.190    6194-6194/org.example.my_app I/MyActivity﹕ INFO onStart()
</code>```

On top of the box, the menu is set to Log level: “Verbose”, and if I go into the menu next to it, choose “Edit filter configuration”, “by Log Level” is also set to “Verbose”. Why are the Log.d() and Log.v() not printing anything? What might I am missing? Any suggestions would be appreciated.

答:
I had similar problem to this one. However in my case the problem was empty first string. It worked in older version of Android Studio, but stopped working in Android Studio ver 5.6 after update.
When I used:
Log.d(string1, string2); in my logging wrapper class,
then whenever string1 was "", the logcat would ignore it. The solution was to add

```<code>if(string1 == null || string1 == "") {
    string1 = "defaultString";
}
</code>```

before

```<code>Log.d(string1, string2);
</code>```

I hope this helps anyone with this problem.

Body:
I have the following test code in my Activity:

@Override
public void onStart() {
    super.onStart();
    Log.e(CLASS_NAME, "ERROR onStart()");
    Log.w(CLASS_NAME, "WARN onStart()");
    Log.i(CLASS_NAME, "INFO onStart()");
    Log.d(CLASS_NAME, "DEBUG onStart()");
    Log.v(CLASS_NAME, "VERBOSE onStart()");

On the logcat view in Android Studio, it only prints:

02-10 15:56:10.190    6194-6194/org.example.my_app E/MyActivity﹕ ERROR onStart()
02-10 15:56:10.190    6194-6194/org.example.my_app W/MyActivity﹕ WARN onStart()
02-10 15:56:10.190    6194-6194/org.example.my_app I/MyActivity﹕ INFO onStart()

On top of the box, the menu is set to Log level: “Verbose”, and if I go into the menu next to it, choose “Edit filter configuration”, “by Log Level” is also set to “Verbose”. Why are the Log.d() and Log.v() not printing anything? What might I am missing? Any suggestions would be appreciated.

Body:
I had similar problem to this one. However in my case the problem was empty first string. It worked in older version of Android Studio, but stopped working in Android Studio ver 5.6 after update.
When I used:
Log.d(string1, string2); in my logging wrapper class,
then whenever string1 was "", the logcat would ignore it. The solution was to add

if(string1 == null || string1 == "") {
    string1 = "defaultString";
}

before

Log.d(string1, string2);

I hope this helps anyone with this problem.


问:
How to create several buffers around points of a simple feature in a loop?
I have sample data representing 2 points (sf). I want to create buffers with the width 2, 1 and 0.5. My approach is the below. Is there any way to do this in more efficient way? How can I wrap this process up in a loop?</p>

```<code>library(sf)

g = st_sfc(c(st_point(1:2),st_point(3:2)))

g.2 <- st_buffer(g,2)
g.1 <- st_buffer(g,1)
g.05 <- st_buffer(g,0.5)

plot(st_geometry(g.2))
plot(st_geometry(g.1), add=TRUE)
plot(st_geometry(g.05), add=TRUE)
plot(st_geometry(g), add=TRUE)
</code>```

答:
If you are interested in tidyverse, I made the following based mainly on purrr, relying on map*functions. In this case, the plots are made with ggplot2, and generates three plots in gg object.

library(sf)
library(tidyverse)

g <- st_sfc(c(st_point(1:2),st_point(3:2)))

buffers <- c(0.5, 1, 2)

x <- map2(buffers, g, function(buf, points){

  points %>%
    st_buffer(., buf)

}) %>%
  set_names(., nm = sprintf("g.%s", buffers))

gg <- map(names(x), function(y){
  z <- x[[y]]

  z %>%
    ggplot(.) +
    geom_sf() +
    labs(title = y)

})
```

Created on 2020-02-20 by the reprex package (v0.3.0)

Body:
I have sample data representing 2 points (sf). I want to create buffers with the width 2, 1 and 0.5. My approach is the below. Is there any way to do this in more efficient way? How can I wrap this process up in a loop?

library(sf)

g = st_sfc(c(st_point(1:2),st_point(3:2)))

g.2 <- st_buffer(g,2)
g.1 <- st_buffer(g,1)
g.05 <- st_buffer(g,0.5)

plot(st_geometry(g.2))
plot(st_geometry(g.1), add=TRUE)
plot(st_geometry(g.05), add=TRUE)
plot(st_geometry(g), add=TRUE)

Body:
If you are interested in tidyverse, I made the following based mainly on purrr, relying on map*functions. In this case, the plots are made with ggplot2, and generates three plots in gg object.

library(sf)
library(tidyverse)

g <- st_sfc(c(st_point(1:2),st_point(3:2)))

buffers <- c(0.5, 1, 2)

x <- map2(buffers, g, function(buf, points){

  points %>%
    st_buffer(., buf)

}) %>%
  set_names(., nm = sprintf("g.%s", buffers))

gg <- map(names(x), function(y){
  z <- x[[y]]

  z %>%
    ggplot(.) +
    geom_sf() +
    labs(title = y)

})

Created on 2020-02-20 by the reprex package (v0.3.0)


问:
Find URNs for Organizations that a user is associated with in v2 api?
Long story short I am trying to figure out what endpoint to call within the v2 API that will return a response in which I can extract the URN for the organizations they are admins for. I will then use that URN in a different api call to find out more information about the company itself (mainly vanityName and/or localizedName).

Our product is trying to verify that the user who logs in is associated with the company from our product.

Previously we used this: $getCompanyInfoLinkedinUrl = 'https://api.linkedin.com/v1/companies?format=json&is-company-admin=true&oauth2_access_token=' . $accessToken;

I am looking for the equivalent of that call using the new v2 organization api endpoints. So far I have had no luck. This is in PHP fyi.

I can give more code if necessary but the authorization and access token parts are working fine. It's the authentication request I can't get to work as expected.

Note: We got access to the Marketing Developer Platform but not Compliance (https://learn.microsoft.com/en-us/linkedin/compliance/) not sure if that is the endpoint I am looking for or not.

答:
You can use the Organization Access Control endpoint, as this example:

```<code>curl  -H "X-Restli-Protocol-Version: 2.0.0" "https://api.linkedin.com/v2/organizationAcls?q=roleAssignee&projection=(elements*(*,roleAssignee~(localizedFirstName,localizedLastName),organization~(id,localizedName)))&oauth2_access_token=<AUTH_TOKEN>

{
  "elements": [
    {
      "organization~": {
        "localizedName": "<name>",
        "id": 35477867
      },
      "role": "ADMINISTRATOR",
      "organization": "urn:li:organization:35477867",
      "roleAssignee": "urn:li:person:WHJGDUaMt8",
      "state": "APPROVED",
      "roleAssignee~": {
        "localizedLastName": "xxx",
        "localizedFirstName": "yyy"
      }
    },
    {
      "organization~": {
        "localizedName": "name",
        "id": 35486968
      },
      "role": "ADMINISTRATOR",
      "organization": "urn:li:organization:35486968",
      "roleAssignee": "urn:li:person:WHJGDUaMt8",
      "state": "APPROVED",
      "roleAssignee~": {
        "localizedLastName": "xxx",
        "localizedFirstName": "yyy"
      }
    },
    {
      "organization~": {
        "localizedName": "name",
        "id": 35516406
      },
      "role": "ADMINISTRATOR",
      "organization": "urn:li:organization:35516406",
      "roleAssignee": "urn:li:person:WHJGDUaMt8",
      "state": "APPROVED",
      "roleAssignee~": {
        "localizedLastName": "xxx",
        "localizedFirstName": "yyy"
      }
    },
    {
      "organization~": {
        "localizedName": "name",
        "id": 35516410
      },
      "role": "ADMINISTRATOR",
      "organization": "urn:li:organization:35516410",
      "roleAssignee": "urn:li:person:WHJGDUaMt8",
      "state": "APPROVED",
      "roleAssignee~": {
        "localizedLastName": "xxx",
        "localizedFirstName": "yyy"
      }
    },
    {
      "organization~": {
        "localizedName": "name",
        "id": 35473047
      },
      "role": "ADMINISTRATOR",
      "organization": "urn:li:organization:35473047",
      "roleAssignee": "urn:li:person:WHJGDUaMt8",
      "state": "APPROVED",
      "roleAssignee~": {
        "localizedLastName": "xxx",
        "localizedFirstName": "yyy"
      }
    },
    {
      "organization~": {
        "localizedName": "name",
        "id": 12984729
      },
      "role": "ADMINISTRATOR",
      "organization": "urn:li:organization:12984729",
      "roleAssignee": "urn:li:person:WHJGDUaMt8",
      "state": "APPROVED",
      "roleAssignee~": {
        "localizedLastName": "xxx",
        "localizedFirstName": "yyy"
      }
    }
  ]
}
</code>```

Also List companies where member has a role endpoint could be helpful

Hope this help

Body:
You can use the Organization Access Control endpoint, as this example:

curl  -H "X-Restli-Protocol-Version: 2.0.0" "https://api.linkedin.com/v2/organizationAcls?q=roleAssignee&projection=(elements*(*,roleAssignee~(localizedFirstName,localizedLastName),organization~(id,localizedName)))&oauth2_access_token=<AUTH_TOKEN>

{
  "elements": [
    {
      "organization~": {
        "localizedName": "<name>",
        "id": 35477867
      },
      "role": "ADMINISTRATOR",
      "organization": "urn:li:organization:35477867",
      "roleAssignee": "urn:li:person:WHJGDUaMt8",
      "state": "APPROVED",
      "roleAssignee~": {
        "localizedLastName": "xxx",
        "localizedFirstName": "yyy"
      }
    },
    {
      "organization~": {
        "localizedName": "name",
        "id": 35486968
      },
      "role": "ADMINISTRATOR",
      "organization": "urn:li:organization:35486968",
      "roleAssignee": "urn:li:person:WHJGDUaMt8",
      "state": "APPROVED",
      "roleAssignee~": {
        "localizedLastName": "xxx",
        "localizedFirstName": "yyy"
      }
    },
    {
      "organization~": {
        "localizedName": "name",
        "id": 35516406
      },
      "role": "ADMINISTRATOR",
      "organization": "urn:li:organization:35516406",
      "roleAssignee": "urn:li:person:WHJGDUaMt8",
      "state": "APPROVED",
      "roleAssignee~": {
        "localizedLastName": "xxx",
        "localizedFirstName": "yyy"
      }
    },
    {
      "organization~": {
        "localizedName": "name",
        "id": 35516410
      },
      "role": "ADMINISTRATOR",
      "organization": "urn:li:organization:35516410",
      "roleAssignee": "urn:li:person:WHJGDUaMt8",
      "state": "APPROVED",
      "roleAssignee~": {
        "localizedLastName": "xxx",
        "localizedFirstName": "yyy"
      }
    },
    {
      "organization~": {
        "localizedName": "name",
        "id": 35473047
      },
      "role": "ADMINISTRATOR",
      "organization": "urn:li:organization:35473047",
      "roleAssignee": "urn:li:person:WHJGDUaMt8",
      "state": "APPROVED",
      "roleAssignee~": {
        "localizedLastName": "xxx",
        "localizedFirstName": "yyy"
      }
    },
    {
      "organization~": {
        "localizedName": "name",
        "id": 12984729
      },
      "role": "ADMINISTRATOR",
      "organization": "urn:li:organization:12984729",
      "roleAssignee": "urn:li:person:WHJGDUaMt8",
      "state": "APPROVED",
      "roleAssignee~": {
        "localizedLastName": "xxx",
        "localizedFirstName": "yyy"
      }
    }
  ]
}

Also List companies where member has a role endpoint could be helpful

Hope this help


问:
R text file and text mining...how to load data
I am using the R package tm and I want to do some text mining.  This is one document and is treated as a bag of words.

I don't understand the documentation on how to load a text file and to create the necessary objects to start using features such as....

```<code>stemDocument(x, language = map_IETF(Language(x)))
</code>```

So assume that this is my doc "this is a test for R load"

How do I load the data for text processing and to create the object x?

答:
The following assumes you have a directory of text files from which you want to create a bag of words.

The only change that needs to be made is replace
path = "C:\\windows\\path\\to\\text\\files\\
with your directory path.

```<code>library(tidyverse)
library(tidytext)

# create a data frame listing all files to be analyzed
all_txts <- list.files(path = "C:\\windows\\path\\to\\text\\files\\",   # path can be relative or absolute
                       pattern = ".txt$",  # this pattern only selects files ending with .txt
                       full.names = TRUE)  # gives the file path as well as name

# create a data frame with one word per line
my_corpus <- map_dfr(all_txts, ~ tibble(txt = read_file(.x)) %>%   # read in each file in list
                      mutate(filename = basename(.x)) %>%   # add the file name as a new column
                      unnest_tokens(word, txt))   # split each word out as a separate row

# count the total # of rows/words in your corpus
my_corpus %>%
  summarize(number_rows = n())

# group and count by "filename" field and sort descending
my_corpus %>%
  group_by(filename) %>%
  summarize(number_rows = n()) %>%
  arrange(desc(number_rows))

# remove stop words
my_corpus2 <- my_corpus %>%
  anti_join(stop_words)

# repeat the count after stop words are removed
my_corpus2 %>%
  group_by(filename) %>%
  summarize(number_rows = n()) %>%
  arrange(desc(number_rows))
</code>```

Body:
I am using the R package tm and I want to do some text mining.  This is one document and is treated as a bag of words.

I don't understand the documentation on how to load a text file and to create the necessary objects to start using features such as....

stemDocument(x, language = map_IETF(Language(x)))

So assume that this is my doc "this is a test for R load"

How do I load the data for text processing and to create the object x?

Body:
The following assumes you have a directory of text files from which you want to create a bag of words.

The only change that needs to be made is replace
path = "C:\\windows\\path\\to\\text\\files\\
with your directory path.

library(tidyverse)
library(tidytext)

# create a data frame listing all files to be analyzed
all_txts <- list.files(path = "C:\\windows\\path\\to\\text\\files\\",   # path can be relative or absolute
                       pattern = ".txt$",  # this pattern only selects files ending with .txt
                       full.names = TRUE)  # gives the file path as well as name

# create a data frame with one word per line
my_corpus <- map_dfr(all_txts, ~ tibble(txt = read_file(.x)) %>%   # read in each file in list
                      mutate(filename = basename(.x)) %>%   # add the file name as a new column
                      unnest_tokens(word, txt))   # split each word out as a separate row

# count the total # of rows/words in your corpus
my_corpus %>%
  summarize(number_rows = n())

# group and count by "filename" field and sort descending
my_corpus %>%
  group_by(filename) %>%
  summarize(number_rows = n()) %>%
  arrange(desc(number_rows))

# remove stop words
my_corpus2 <- my_corpus %>%
  anti_join(stop_words)

# repeat the count after stop words are removed
my_corpus2 %>%
  group_by(filename) %>%
  summarize(number_rows = n()) %>%
  arrange(desc(number_rows))