问:
FileNotFoundError:
There are lot of csv excel sheets in a folder. All excel sheet contains data only in first 3 columns. I will select corresponding csv sheet from a lot of csv sheets and then plot it.Here is the code

```<code>import os
path = "F:\\Users\\Desktop\\Data\\Summary"
files = []
folder_data = os.listdir(path)
folder_data = [i+"\\" for i in folder_data]

# r=root, d=directories, f = files
for r, d, f in os.walk(path):
    for file in f:
        if '.csv' in file:
            files.append(file)
for i, f in enumerate(files):
    print(( i,f))
    print('\n'.join(f'{i}-{v}' for i,v in enumerate(files)))
    csv_code = str(int(input("Enter corresponding code to plot: ")))
    csv_path = path + "\\" + folder_data[csv_code]

    df = pd.read_csv(csv_path, header=None)
    df1 = df.iloc[:,0:2]
    plt.plot(df1[0], df1[1])
</code>```

When i run the code i want the Output to be displayed as follows (i mean i want all csv files from the folder to be displayed so that i can select what i want):

```<code>0-Test_Summary_1.csv
1-Test_Summary_2.csv
2-Test_Summary_3.csv
3-Test_Summary_4.csv
4-Test_Summary_5.csv
5-Test_Summary_6.csv etc
</code>```

The error i a getting is

```<code>FileNotFoundError:
</code>```

In spite of csv file is there in the folder. I am getting error as File not found error

答:
If I understand your question correctly, then you could try something like this:

```<code>import os
import pandas as pd

# see this answer about absolute paths in windows
# https://stackoverflow.com/a/7767925/9225671
base_path = os.path.join('f:', os.sep, 'Users', 'Desktop', 'Data', 'Summary')

# collect all CSV files in 'base_path' and its subfolders
csv_file_list = []
for dir_path, _, file_name_list in os.walk(base_path):
    for file_name in file_name_list:
        if file_name.endswith('.csv'):
            # add full path to the list, not just 'file_name'
            csv_file_list.append(
                os.path.join(dir_path, file_name))

print('CSV files that were found:')
for i, file_path in enumerate(csv_file_list):
    print('   {:3d} {}'.format(i, file_path))

selected_i = int(input('Enter corresponding number of the file to plot: '))
selected_file_path = csv_file_list[selected_i]
print('selected_file_path:', selected_file_path)

df = pd.read_csv(selected_file_path, header=None)
...
</code>```

Does this work for you?

Title: FileNotFoundError:

Body:
There are lot of csv excel sheets in a folder. All excel sheet contains data only in first 3 columns. I will select corresponding csv sheet from a lot of csv sheets and then plot it.Here is the code

import os
path = "F:\\Users\\Desktop\\Data\\Summary"
files = []
folder_data = os.listdir(path)
folder_data = [i+"\\" for i in folder_data]

# r=root, d=directories, f = files
for r, d, f in os.walk(path):
    for file in f:
        if '.csv' in file:
            files.append(file)
for i, f in enumerate(files):
    print(( i,f))
    print('\n'.join(f'{i}-{v}' for i,v in enumerate(files)))
    csv_code = str(int(input("Enter corresponding code to plot: ")))
    csv_path = path + "\\" + folder_data[csv_code]

    df = pd.read_csv(csv_path, header=None)
    df1 = df.iloc[:,0:2]
    plt.plot(df1[0], df1[1])

When i run the code i want the Output to be displayed as follows (i mean i want all csv files from the folder to be displayed so that i can select what i want):

0-Test_Summary_1.csv
1-Test_Summary_2.csv
2-Test_Summary_3.csv
3-Test_Summary_4.csv
4-Test_Summary_5.csv
5-Test_Summary_6.csv etc

The error i a getting is

FileNotFoundError:

In spite of csv file is there in the folder. I am getting error as File not found error

Body:
If I understand your question correctly, then you could try something like this:

import os
import pandas as pd

# see this answer about absolute paths in windows
# https://stackoverflow.com/a/7767925/9225671
base_path = os.path.join('f:', os.sep, 'Users', 'Desktop', 'Data', 'Summary')

# collect all CSV files in 'base_path' and its subfolders
csv_file_list = []
for dir_path, _, file_name_list in os.walk(base_path):
    for file_name in file_name_list:
        if file_name.endswith('.csv'):
            # add full path to the list, not just 'file_name'
            csv_file_list.append(
                os.path.join(dir_path, file_name))

print('CSV files that were found:')
for i, file_path in enumerate(csv_file_list):
    print('   {:3d} {}'.format(i, file_path))

selected_i = int(input('Enter corresponding number of the file to plot: '))
selected_file_path = csv_file_list[selected_i]
print('selected_file_path:', selected_file_path)

df = pd.read_csv(selected_file_path, header=None)
...

Does this work for you?


来源: stackexchange

问:
How to import million-row Excel file to datatable?
I have an Excel file which has a million rows and 25 columns.

When I transfer the Excel data to a datatable only 8000 to 9000 rows are being transferred to the datatable. But the file has million rows.

I tried the below code:

```<code><connectionStrings>
    <!--Connect excel for bulk upload-->
    <add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>
    <add name="Excel07+ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>
  </connectionStrings>
</code>```

```<code>connString = String.Format(connString, excelPath)
        Using excel_con As New OleDbConnection(connString)
            excel_con.Open()
            Dim sheet1 As String = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing).Rows(0)("TABLE_NAME").ToString()
            Dim dtExcelData As New DataTable()
            dtExcelData.Columns.AddRange(New DataColumn(3) {New DataColumn("Document Type", GetType(String)), _
                                                            New DataColumn("Posting period", GetType(Decimal)), _
                                                            New DataColumn("Profit Center", GetType(String))                      })
            Using oda As New OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con)
                oda.Fill(dtExcelData)
            End Using
            excel_con.Close()
        End Using
</code>```

How do I solve this?

答: Don't use the Excel.Application object, read the data from the excel file directly through xml operations. I use the free and MIT licensed .NET library SpreadsheetLight (spreadsheetlight.com) for such purposes. It is incredibly fast compared to the Excel object.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have an Excel file which has a million rows and 25 columns.

When I transfer the Excel data to a datatable only 8000 to 9000 rows are being transferred to the datatable. But the file has million rows.

I tried the below code:

<connectionStrings>

    <add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>
    <add name="Excel07+ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>
  </connectionStrings>

connString = String.Format(connString, excelPath)
        Using excel_con As New OleDbConnection(connString)
            excel_con.Open()
            Dim sheet1 As String = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing).Rows(0)("TABLE_NAME").ToString()
            Dim dtExcelData As New DataTable()
            dtExcelData.Columns.AddRange(New DataColumn(3) {New DataColumn("Document Type", GetType(String)), _
                                                            New DataColumn("Posting period", GetType(Decimal)), _
                                                            New DataColumn("Profit Center", GetType(String))                      })
            Using oda As New OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con)
                oda.Fill(dtExcelData)
            End Using
            excel_con.Close()
        End Using

How do I solve this?


问:
Is there a way to make a input that needs a code to show somthing?
I am making a website in HTML and for the admin part, I want it to have an input which needs a password to show the admin page.

I tried going to w3schools and tried this code:

```<code><button onclick="1()" id="id" >ok</button>
<input id="id2">
</code>```

```<code>function 2(){
   var x = document.getElementById("thedminpage");
   if (x.innerHTML === "Hello") {
      x.innerHTML = "Swapped text!";
   } else {
      x.innerHTML = "Hello";
   }
}

function 1() {
  var x, text;

  x = document.getElementById("id2").value;

  // If x is Not a Number or less than one or greater than 10
  if (isNaN(x) || x < 1 || x > 10) {
    text = "Input not valid";
  } else {
    run function 2()
  }
  document.getElementById("demo").innerHTML = text;
}
</code>```

It didn't work. Can someone help?

答:
I see some problems here:

You can't name a function function() because it's a keyword of the language.

You can't name a function with a number, maybe you could use func2()

You are getting some DOM objects that are not in the HTML code.

Try this:

```<code><button onclick="fun2" id="id" >ok</button>
<input id="id2">
<p id='demo'></p>

function func1(){
   var x = document.getElementById("thedminpage");
   if (x.innerHTML === "Hello") {
      x.innerHTML = "Swapped text!";
   } else {
      x.innerHTML = "Hello";
   }
}

function func2() {
  var x, text;

  x = document.getElementById("id2").value;

  // If x is Not a Number or less than one or greater than 10
  if (isNaN(x) || x < 1 || x > 10) {
    text = "Input not valid";
  } else {
    func2();
  }
  document.getElementById("demo").innerHTML = text;
}
</code>```

Body:
I am making a website in HTML and for the admin part, I want it to have an input which needs a password to show the admin page.

I tried going to w3schools and tried this code:

<button onclick="1()" id="id" >ok</button>
<input id="id2">

function 2(){
   var x = document.getElementById("thedminpage");
   if (x.innerHTML === "Hello") {
      x.innerHTML = "Swapped text!";
   } else {
      x.innerHTML = "Hello";
   }
}

function 1() {
  var x, text;

  x = document.getElementById("id2").value;

  // If x is Not a Number or less than one or greater than 10
  if (isNaN(x) || x < 1 || x > 10) {
    text = "Input not valid";
  } else {
    run function 2()
  }
  document.getElementById("demo").innerHTML = text;
}

It didn't work. Can someone help?

Body:
I see some problems here:

You can't name a function function() because it's a keyword of the language.

You can't name a function with a number, maybe you could use func2()

You are getting some DOM objects that are not in the HTML code.

Try this:

<button onclick="fun2" id="id" >ok</button>
<input id="id2">
<p id='demo'></p>

function func1(){
   var x = document.getElementById("thedminpage");
   if (x.innerHTML === "Hello") {
      x.innerHTML = "Swapped text!";
   } else {
      x.innerHTML = "Hello";
   }
}

function func2() {
  var x, text;

  x = document.getElementById("id2").value;

  // If x is Not a Number or less than one or greater than 10
  if (isNaN(x) || x < 1 || x > 10) {
    text = "Input not valid";
  } else {
    func2();
  }
  document.getElementById("demo").innerHTML = text;
}


问:
How to find minimum signed value in array in assembly
i am trying to make selection sort program in assembly but i stuck how to find minimum signed number

i am beginner in assembly i learned just conditional and unconditional jumps and subroutines

i have assignment of selection sort of array of signed numbers i write code it finds minimum number but after further comparison it store greater number

```<code>[org 0x0100]
          jmp  start

data:          dw   -1,-7,0,-4
temp:          dw 0

start:
    mov bx,0
    mov cx,4
    mov ax,[data+bx]
h1;
    cmp ax,[data+bx+2]
    jnle l1

    add bx,2
    cmp bx,6
    jne h1

l1:
    mov dx,[data+bx+2]
    mov [temp],dx
    add bx,2
    cmp bx,6
    jne h1

    mov  ax, 0x4c00
        int  0x21
</code>```

i expect after termination of my program array will be sorted according to following the selection sort algorithm.

答:
Your algorithm doesn't make much sense. Your current code would correspond to something like this in C:

```<code>int min = 0;
for (int i = 0; i < 3; i++) {
    if (data[i] > data[i+1]) {
        min = data[i+1];
    }
}
</code>```

Note how your comparison doesn't take the current min value into account. It only cares about the difference between adjacent elements in the array (and those elements do not move around in the loop).

What you should be doing is something like this:

```<code>int min = data[0];
for (int i = 1; i < 4; i++) {
    if (data[i] < min) {
        min = data[i];
    }
}
</code>```

It should be simple enough for you to translate that into assembly.

Body:
i am trying to make selection sort program in assembly but i stuck how to find minimum signed number

i am beginner in assembly i learned just conditional and unconditional jumps and subroutines

i have assignment of selection sort of array of signed numbers i write code it finds minimum number but after further comparison it store greater number

[org 0x0100]
          jmp  start

data:          dw   -1,-7,0,-4
temp:          dw 0

start:
    mov bx,0
    mov cx,4
    mov ax,[data+bx]
h1;
    cmp ax,[data+bx+2]
    jnle l1

    add bx,2
    cmp bx,6
    jne h1

l1:
    mov dx,[data+bx+2]
    mov [temp],dx
    add bx,2
    cmp bx,6
    jne h1

    mov  ax, 0x4c00
        int  0x21

i expect after termination of my program array will be sorted according to following the selection sort algorithm.

Body:
Your algorithm doesn't make much sense. Your current code would correspond to something like this in C:

int min = 0;
for (int i = 0; i < 3; i++) {
    if (data[i] > data[i+1]) {
        min = data[i+1];
    }
}

Note how your comparison doesn't take the current min value into account. It only cares about the difference between adjacent elements in the array (and those elements do not move around in the loop).

What you should be doing is something like this:

int min = data[0];
for (int i = 1; i < 4; i++) {
    if (data[i] < min) {
        min = data[i];
    }
}

It should be simple enough for you to translate that into assembly.


问:
Use . in JSON key and not as property
I'm trying to update data in MongoDB using NodeJs, I want to use user email as key and an object as value, like

```<code>changes : {
    user@email.com : {
        //key value pairs
    },
    user2@email.com : {
        //key value pairs
    }
}
</code>```

Problem is when I'm using this code

```<code>var query = {id:"01"},
update = { "$set": { } };
update["$set"]["changes."+ req.session.email ] = req.body; //This line is causing problem
model.findOneAndUpdate(query, update, function(err, result){
    if(err){
        throw err;
    }
    console.log('Updated');
});
</code>```

The "changes."+req.session.email is formed as changes.user@email.com and it is saved in MongoDb as

```<code>changes : {
   user@email : {
      com : {
           //data from req.body
      }
   }
}
</code>```

The . in email is interpreted as property,
So how do I tell it to use . as string in key and not as property. I tried wrapping req.session.email in [], didn't work.

Any help is appreciated, thanks.

EDIT

I know I'm not supposed to use . in key names, but it is okay to use string, and I just want to use a string that has a dot in it, but I don't know how to make Node read it as a complete string.

Here is what I want:

```<code>changes : {
    "user@email.com" : {
        //key value pairs
    },
    "user2@email.com" : {
        //key value pairs
    }
}
</code>```

What I'm getting right now is:

```<code>changes : {
   "user@email" : {
      "com" : {
           //data from req.body
      }
   }
}
</code>```

user@email and com is interpreted as string, but not the dot in between them. How do I use it as complete string?

答:
The Mongo docs suggests replacing illegal characters such as $ and . with their Unicode equivalents.

For example:

In these situations, keys will need to substitute the reserved $ and .
  characters. Any character is sufficient, but consider using the
  Unicode full-width equivalents: U+FF04 (i.e. “＄”) and U+FF0E (i.e.
  “．”).

Original answer and related discussion can be seen here

Title: Use . in JSON key and not as property

Body:
I'm trying to update data in MongoDB using NodeJs, I want to use user email as key and an object as value, like

changes : {
    user@email.com : {
        //key value pairs
    },
    user2@email.com : {
        //key value pairs
    }
}

Problem is when I'm using this code

var query = {id:"01"},
update = { "$set": { } };
update["$set"]["changes."+ req.session.email ] = req.body; //This line is causing problem
model.findOneAndUpdate(query, update, function(err, result){
    if(err){
        throw err;
    }
    console.log('Updated');
});

The "changes."+req.session.email is formed as changes.user@email.com and it is saved in MongoDb as

changes : {
   user@email : {
      com : {
           //data from req.body
      }
   }
}

The . in email is interpreted as property,
So how do I tell it to use . as string in key and not as property. I tried wrapping req.session.email in [], didn't work.

Any help is appreciated, thanks.

EDIT

I know I'm not supposed to use . in key names, but it is okay to use string, and I just want to use a string that has a dot in it, but I don't know how to make Node read it as a complete string.

Here is what I want:

changes : {
    "user@email.com" : {
        //key value pairs
    },
    "user2@email.com" : {
        //key value pairs
    }
}

What I'm getting right now is:

changes : {
   "user@email" : {
      "com" : {
           //data from req.body
      }
   }
}

user@email and com is interpreted as string, but not the dot in between them. How do I use it as complete string?


问:
Pass a directory of pdf files for performing OCR and generate .txt files for each converted file in Python
I have a directory containing pdf files. I have written the code that performs OCR when you pass a filename to an object of the wand.image class. What I want to do presently is to loop over the directory of pdf files and generate a OCR'd txt file for each pdf and save it some directory. The code that I have written till now is as follows:

```<code>import io
from PIL import Image
import pytesseract
from wand.image import Image as wi

pdf = wi(filename = r"D:\files\aba7d525-04b8-4474-a40d-e94f9656ed42.pdf", resolution = 300)

pdfImg = pdf.convert('jpeg')

imgBlobs = []

for img in pdfImg.sequence:
    page = wi(image = img)
    imgBlobs.append(page.make_blob('jpeg'))

extracted_text = []

for imgBlob in imgBlobs:
    im = Image.open(io.BytesIO(imgBlob))
    text = pytesseract.image_to_string(im, lang = 'eng')
    extracted_text.append(text)

print(extracted_text[0])
</code>```

Any suggestions on how I can generate the .txt files from the OCR'd pdf's

答:
Try this at the end of your code:</p>

```<code>with open('filename.txt', 'w') as result:
     for line in extracted_text:
          result.write(line,'\n')
</code>```

Body:
I have a directory containing pdf files. I have written the code that performs OCR when you pass a filename to an object of the wand.image class. What I want to do presently is to loop over the directory of pdf files and generate a OCR'd txt file for each pdf and save it some directory. The code that I have written till now is as follows:

import io
from PIL import Image
import pytesseract
from wand.image import Image as wi

pdf = wi(filename = r"D:\files\aba7d525-04b8-4474-a40d-e94f9656ed42.pdf", resolution = 300)

pdfImg = pdf.convert('jpeg')

imgBlobs = []

for img in pdfImg.sequence:
    page = wi(image = img)
    imgBlobs.append(page.make_blob('jpeg'))

extracted_text = []

for imgBlob in imgBlobs:
    im = Image.open(io.BytesIO(imgBlob))
    text = pytesseract.image_to_string(im, lang = 'eng')
    extracted_text.append(text)

print(extracted_text[0])

Any suggestions on how I can generate the .txt files from the OCR'd pdf's

Body:
Try this at the end of your code:

with open('filename.txt', 'w') as result:
     for line in extracted_text:
          result.write(line,'\n')


问:
genetic code and zombies!
In an alien world, the genetic codes of the creatures are in base-4 system(quartenary). The pairs "13" and "22" are considered as genetic disorders. With a genetic code of lenght n, if there are at least n/4 disorders, the creature becomes a zombie!! For example with n=5, the creature with genetic code 01321 has the disorder, but not a zombie while the creature with genetic code 22132 is a zombie( because he has two disorders which is >n/4).

Now I need to write a MATLAB program and get a value n from the user, which is easy, and display the number of creatures and how many of them are zombies

Here is what i've written so far, I can't figure out how to determine the creatures with has genetic codes of a zombie. I'd really appreciate your ideas and help.Thank you

```<code>n=input('Enter the length of the genetic sequence: ');
while (n<4) || (mod(n,1))~=0
disp('Invalid input!')
n=input('Enter the length of the genetic sequence: ');
end
nOfCreatures=4^n;
count=0;
for i=0:nOfCreatures
k=dec2base(i,4);
end
fprintf('There are %g creatures and %g of them are zombies.\n',nOfCreatures,count);
</code>```

答:
```<code>error = 0
    for i<n.len:
        if n[i] == 1:
           if n[i+1] == 3:
              error = error + 1
        if n[i] == 2:
           if n[i+1] == 2:
              error = error + 1
if error >= n/4
     zombie = true
</code>```

That is the general idea in psuedo code.

Here is a link that might help you convert this into real code: String Handling

ContentLicense: CC BY-SA 3.0

Title: genetic code and zombies!

Body:
In an alien world, the genetic codes of the creatures are in base-4 system(quartenary). The pairs "13" and "22" are considered as genetic disorders. With a genetic code of lenght n, if there are at least n/4 disorders, the creature becomes a zombie!! For example with n=5, the creature with genetic code 01321 has the disorder, but not a zombie while the creature with genetic code 22132 is a zombie( because he has two disorders which is >n/4).

Now I need to write a MATLAB program and get a value n from the user, which is easy, and display the number of creatures and how many of them are zombies

Here is what i've written so far, I can't figure out how to determine the creatures with has genetic codes of a zombie. I'd really appreciate your ideas and help.Thank you

n=input('Enter the length of the genetic sequence: ');
while (n<4) || (mod(n,1))~=0
disp('Invalid input!')
n=input('Enter the length of the genetic sequence: ');
end
nOfCreatures=4^n;
count=0;
for i=0:nOfCreatures
k=dec2base(i,4);
end
fprintf('There are %g creatures and %g of them are zombies.\n',nOfCreatures,count);

Body:
error = 0
    for i<n.len:
        if n[i] == 1:
           if n[i+1] == 3:
              error = error + 1
        if n[i] == 2:
           if n[i+1] == 2:
              error = error + 1
if error >= n/4
     zombie = true

That is the general idea in psuedo code.

Here is a link that might help you convert this into real code: String Handling


问:
How to put text inside triangle button?
I create triangle button at header of my page, and i would like to put text in button.

Now text is outside button.

My code:

.collapsible {
    position: absolute;
    left: 40%;
}

.triangle {
    font-size: 22px;
    color: #000;
    width: 190px;
    height: 140px;
    border-top: solid 140px #2b2b2b;
    border-left: solid 140px transparent;
    border-right: solid 140px transparent;
    border-bottom: transparent;
    background-color: transparent;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="collapsible triangle" id="collapse">Some content</button></code>```

So as u can see text is outside of buuton, how it's possible to set inside button?

答:
.collapsible {
    position: absolute;
    left: 40%;
}

.triangle {
    font-size: 22px;
    color: #000;
    width: 190px;
    height: 140px;
    border-top: solid 140px #2b2b2b;
    border-left: solid 140px transparent;
    border-right: solid 140px transparent;
    border-bottom: transparent;
    background-color: transparent;
}
.collapsible span{
    position: absolute;
    color:red;
    top:-120px;
    left: -30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="collapsible triangle" id="collapse">
<span>Some content</span></button></code>```

Title: How to put text inside triangle button?

Body:
I create triangle button at header of my page, and i would like to put text in button.

Now text is outside button.

My code:

.collapsible {
    position: absolute;
    left: 40%;
}

.triangle {
    font-size: 22px;
    color: #000;
    width: 190px;
    height: 140px;
    border-top: solid 140px #2b2b2b;
    border-left: solid 140px transparent;
    border-right: solid 140px transparent;
    border-bottom: transparent;
    background-color: transparent;
}

<button class="collapsible triangle" id="collapse">Some content</button>

So as u can see text is outside of buuton, how it's possible to set inside button?

Body:
.collapsible {
    position: absolute;
    left: 40%;
}

.triangle {
    font-size: 22px;
    color: #000;
    width: 190px;
    height: 140px;
    border-top: solid 140px #2b2b2b;
    border-left: solid 140px transparent;
    border-right: solid 140px transparent;
    border-bottom: transparent;
    background-color: transparent;
}
.collapsible span{
    position: absolute;
    color:red;
    top:-120px;
    left: -30px;
}

<button class="collapsible triangle" id="collapse">
<span>Some content</span></button>


问:
How do you calculate the average of an array of arrays in Python?
Say we have the following:

a = [(R1, G1, B1),
     (R2, G2, B2),
     (R3, G3, B3)]
```

<p>How can I calculate the averages of the arrays and put it in a new array? Like the following:</p>

<pre class="lang-py prettyprint-override"><code>a = [(R, B, G)]
</code>```

Where R, G, B are the averages of R1, R2 and R3 etc.

答:
I'd use numpy:

```<code>import numpy as np
a = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
arr = np.array(a)
means = means = np.mean(arr, axis=0)
print(means)

# prints array([4., 5., 6.])
</code>```

If you want to obtain the result in your format, i.e. list with just one tuple, you could do

```<code>result = [tuple(means)]
</code>```

Body:
Say we have the following:

a = [(R1, G1, B1),
     (R2, G2, B2),
     (R3, G3, B3)]

How can I calculate the averages of the arrays and put it in a new array? Like the following:

a = [(R, B, G)]

Where R, G, B are the averages of R1, R2 and R3 etc.

Body:
I'd use numpy:

import numpy as np
a = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
arr = np.array(a)
means = means = np.mean(arr, axis=0)
print(means)

# prints array([4., 5., 6.])

If you want to obtain the result in your format, i.e. list with just one tuple, you could do

result = [tuple(means)]


问:
Trying to Adding Select Dropdown in ANT D table
I am a beginner in react and trying to implement dropdown inside table cell using Ant link UI framework.

I have tried to render Dropdown component inside renderCell function but I am stuck.

My implementation: codesandbox

Could anyone help me with this?

答:
As per your question, I think you want to have dropdown when you click on a table cell to do editing, correct me if I am wrong?

In your code, I have seen that instead of select or Dropdown component you have used input.

I have forked your sandbox which you have provided and updated the code.
https://codesandbox.io/s/pensive-shamir-lxvk3

This is what I have done and it's working.

```<code>renderCell = form => {
    this.form = form;
    const { children, dataIndex, record, title } = this.props;
    const { editing } = this.state;
    const menu = (
      <Menu>
        <Menu.Item key="1">1st menu item</Menu.Item>
        <Menu.Item key="2">2nd menu item</Menu.Item>
        <Menu.Item key="3">3rd menu item</Menu.Item>
      </Menu>
    );
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: true,
              message: `${title} is required.`
            }
          ],
          initialValue: record[dataIndex]
        })(
          <Dropdown overlay={menu}>
            <span style={{ userSelect: "none" }}>hover on Me</span>
          </Dropdown>
        )}
      </Form.Item>
    ) : (
      <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={this.toggleEdit}>
        {children}
      </div>
    );
  };
</code>```

If you want Droupdown to be rendered as default then add Dropdown component in else condition

Note: Please hover on the text.

https://codesandbox.io/s/peaceful-haze-k387u

```<code>renderCell = form => {
    this.form = form;
    const { children, dataIndex, record, title } = this.props;
    const { editing } = this.state;
    const menu = (
      <Menu>
        <Menu.Item key="1">1st menu item</Menu.Item>
        <Menu.Item key="2">2nd menu item</Menu.Item>
        <Menu.Item key="3">3rd menu item</Menu.Item>
      </Menu>
    );
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: true,
              message: `${title} is required.`
            }
          ],
          initialValue: record[dataIndex]
        })(<Input ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save} />)}
      </Form.Item>
    ) : (
      <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={this.toggleEdit}>
        <Dropdown overlay={menu}>
          <span style={{ userSelect: "none" }}>{children}</span>
        </Dropdown>
      </div>
    );
  };
</code>```

Body:
As per your question, I think you want to have dropdown when you click on a table cell to do editing, correct me if I am wrong?

In your code, I have seen that instead of select or Dropdown component you have used input.

I have forked your sandbox which you have provided and updated the code.
https://codesandbox.io/s/pensive-shamir-lxvk3

This is what I have done and it's working.

renderCell = form => {
    this.form = form;
    const { children, dataIndex, record, title } = this.props;
    const { editing } = this.state;
    const menu = (
      <Menu>
        <Menu.Item key="1">1st menu item</Menu.Item>
        <Menu.Item key="2">2nd menu item</Menu.Item>
        <Menu.Item key="3">3rd menu item</Menu.Item>
      </Menu>
    );
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: true,
              message: `${title} is required.`
            }
          ],
          initialValue: record[dataIndex]
        })(
          <Dropdown overlay={menu}>
            <span style={{ userSelect: "none" }}>hover on Me</span>
          </Dropdown>
        )}
      </Form.Item>
    ) : (
      <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={this.toggleEdit}>
        {children}
      </div>
    );
  };

If you want Droupdown to be rendered as default then add Dropdown component in else condition

Note: Please hover on the text.

https://codesandbox.io/s/peaceful-haze-k387u

renderCell = form => {
    this.form = form;
    const { children, dataIndex, record, title } = this.props;
    const { editing } = this.state;
    const menu = (
      <Menu>
        <Menu.Item key="1">1st menu item</Menu.Item>
        <Menu.Item key="2">2nd menu item</Menu.Item>
        <Menu.Item key="3">3rd menu item</Menu.Item>
      </Menu>
    );
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: true,
              message: `${title} is required.`
            }
          ],
          initialValue: record[dataIndex]
        })(<Input ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save} />)}
      </Form.Item>
    ) : (
      <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={this.toggleEdit}>
        <Dropdown overlay={menu}>
          <span style={{ userSelect: "none" }}>{children}</span>
        </Dropdown>
      </div>
    );
  };


问:
Files.createTempDirectory("") throws NullPointerException
When I call Files.createTempDirectory("") I get the below exception:

```<code>java.lang.NullPointerException
at sun.nio.fs.WindowsSecurityDescriptor.fromAttribute(WindowsSecurityDescriptor.java:353)
at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:220)
at java.nio.file.Files.newByteChannel(Files.java:315)
at java.nio.file.Files.createFile(Files.java:586)
at java.nio.file.TempFileHelper.create(TempFileHelper.java:138)
at java.nio.file.TempFileHelper.createTempFile(TempFileHelper.java:161)
at java.nio.file.Files.createTempFile(Files.java:803)
</code>```

None of the examples of the usage of Files.createTempDirectory("") I have found passed in any FileAttributes.
I have tried with Files.createTempDirectory("", new FileAttribute<?>[] { }); but it did not help either.

I am using 32 bit JDK 7 on Windows 7 system.
I am not local admin on the machine.

Has anybody come accross this?

UPDATE 1:

Files.createTempFile(this.tempDir.toPath(), "tmpFile", ""); seems to have the same problem.

As a workaround I have moved to com.google.common.io.Files.createTempDir().

答:
Have you tried with Files.createTempDirectory(null) instead of Files.createTempDirectory(""). In the documentation, you can read that it's possible pass the prefix as null object.

https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#createTempDirectory-java.lang.String-java.nio.file.attribute.FileAttribute...-

Body:
When I call Files.createTempDirectory("") I get the below exception:

java.lang.NullPointerException
at sun.nio.fs.WindowsSecurityDescriptor.fromAttribute(WindowsSecurityDescriptor.java:353)
at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:220)
at java.nio.file.Files.newByteChannel(Files.java:315)
at java.nio.file.Files.createFile(Files.java:586)
at java.nio.file.TempFileHelper.create(TempFileHelper.java:138)
at java.nio.file.TempFileHelper.createTempFile(TempFileHelper.java:161)
at java.nio.file.Files.createTempFile(Files.java:803)

None of the examples of the usage of Files.createTempDirectory("") I have found passed in any FileAttributes.
I have tried with Files.createTempDirectory("", new FileAttribute<?>[] { }); but it did not help either.

I am using 32 bit JDK 7 on Windows 7 system.
I am not local admin on the machine.

Has anybody come accross this?

UPDATE 1:

Files.createTempFile(this.tempDir.toPath(), "tmpFile", ""); seems to have the same problem.

As a workaround I have moved to com.google.common.io.Files.createTempDir().


问:
Form an array of Integers from integer value
Not sure how tag a question. I want to create an array of Int values from Int value. For example, if i have 1234 i want to output [1,2,3,4], for 8765 [8,7,6,5] etc. Function should look like:</p>

```<code>private static func formAnArray(_ value: Int) -> [Int] {
// code
}
</code>```

答:
You can convert number to String and map it to array:

```<code>private static func formAnArray(_ value: Int) -> [Int] {
    return String(value).compactMap { Int(String($0)) }
}
</code>```

Another way (preferred for big numbers) is by using combination of % and /:

```<code>private static func formAnArray(_ value: Int) -> [Int] {
    var value = value
    var result: [Int] = []
    while value > 0 {
        result.insert(value % 10, at: 0)
        value /= 10
    }
    return result
}
</code>```

Body:
Not sure how tag a question. I want to create an array of Int values from Int value. For example, if i have 1234 i want to output [1,2,3,4], for 8765 [8,7,6,5] etc. Function should look like:

private static func formAnArray(_ value: Int) -> [Int] {
// code
}

Body:
You can convert number to String and map it to array:

private static func formAnArray(_ value: Int) -> [Int] {
    return String(value).compactMap { Int(String($0)) }
}

Another way (preferred for big numbers) is by using combination of % and /:

private static func formAnArray(_ value: Int) -> [Int] {
    var value = value
    var result: [Int] = []
    while value > 0 {
        result.insert(value % 10, at: 0)
        value /= 10
    }
    return result
}


答:
```<code>import numpy as np

x = np.random.rand(3,3)
y = x.mean(axis=0)
print(y)

</code>```

Title: How do you calculate the average of an array of arrays in Python?


问:
Python Using Selenium to Locate 404 Error for If Else Condition
Condition Statement - Try, Except, Else -

I am using Selenium/Python to automate some tasks for downloading and uploading files.

Is there a way to have Selenium/Python recognize if a page is loaded as a 404? ie my "Try" attempt below.

My goal is to have the script close out the tab if it loads as a 404 error and loop until a downloadable file is found. The file is a PDF.

I've attempted using XPath to search for specific text such as:

'Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.' - but am not certain as to the proper coding needed. I'm new to this so thanks for bearing with me.

Below is the bottom portion of the script and it is in a loop as well - (the 'icon' is the download button which shows on the downloadable page, but not on the 404 page)

```<code>    try:
       Download = driver.find_element_by_id('icon')
       if Download == driver.find_element_by_id('icon'):
           raise Exception

    except Exception:
        pyautogui.time.sleep(2)
        pyautogui.hotkey('ctrl','s')
        pyautogui.time.sleep(2)
        pyautogui.hotkey('enter')
        pyautogui.time.sleep(2)
        pyautogui.hotkey('ctrl','w')
        pyautogui.click(771, 374, duration=0.55)
        pyautogui.click(867, 276, duration=0.55)

    else:
        pyautogui.time.sleep(2)
        pyautogui.hotkey('ctrl','w')
        pyautogui.time.sleep(2)
        pyautogui.doubleClick(79, 136, duration=0.55)
        pyautogui.time.sleep(15)
        pyautogui.click(642, 442, duration=0.55)
        pyautogui.time.sleep(2)
        pyautogui.hotkey('ctrl','s')
        pyautogui.time.sleep(2)
        pyautogui.hotkey('enter')
        pyautogui.time.sleep(2)
        pyautogui.hotkey('ctrl','w')
        pyautogui.click(771, 374, duration=0.55)
        pyautogui.click(867, 276, duration=0.55)
</code>```

The code above doesn't close out the 404 webpage if it loads. Rather the script saves the webpage 404 instead of attempting the "Else" portion of the script.

Thanks for the help! (If I can give an upvote I will.)

答: Webdriver wont catch the http404, this is not implemented in the API and it wont be, check their issue tracker. You could use just python for that, maybe this will help. </p>

Body:
Condition Statement - Try, Except, Else -

I am using Selenium/Python to automate some tasks for downloading and uploading files.

Is there a way to have Selenium/Python recognize if a page is loaded as a 404? ie my "Try" attempt below.

My goal is to have the script close out the tab if it loads as a 404 error and loop until a downloadable file is found. The file is a PDF.

I've attempted using XPath to search for specific text such as:

'Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.' - but am not certain as to the proper coding needed. I'm new to this so thanks for bearing with me.

Below is the bottom portion of the script and it is in a loop as well - (the 'icon' is the download button which shows on the downloadable page, but not on the 404 page)

    try:
       Download = driver.find_element_by_id('icon')
       if Download == driver.find_element_by_id('icon'):
           raise Exception

    except Exception:
        pyautogui.time.sleep(2)
        pyautogui.hotkey('ctrl','s')
        pyautogui.time.sleep(2)
        pyautogui.hotkey('enter')
        pyautogui.time.sleep(2)
        pyautogui.hotkey('ctrl','w')
        pyautogui.click(771, 374, duration=0.55)
        pyautogui.click(867, 276, duration=0.55)

    else:
        pyautogui.time.sleep(2)
        pyautogui.hotkey('ctrl','w')
        pyautogui.time.sleep(2)
        pyautogui.doubleClick(79, 136, duration=0.55)
        pyautogui.time.sleep(15)
        pyautogui.click(642, 442, duration=0.55)
        pyautogui.time.sleep(2)
        pyautogui.hotkey('ctrl','s')
        pyautogui.time.sleep(2)
        pyautogui.hotkey('enter')
        pyautogui.time.sleep(2)
        pyautogui.hotkey('ctrl','w')
        pyautogui.click(771, 374, duration=0.55)
        pyautogui.click(867, 276, duration=0.55)

The code above doesn't close out the 404 webpage if it loads. Rather the script saves the webpage 404 instead of attempting the "Else" portion of the script.

Thanks for the help! (If I can give an upvote I will.)


答:
You can use compactMap to get and convert digits to an array of int</p>

```<code>print(formAnArray(value: 1234))
func formAnArray(value: Int) -> [Int] {
    let string = String(value)
    return string.compactMap{Int(String($0))}
}
</code>```

Title: Form an array of Integers from integer value

Body:
You can use compactMap to get and convert digits to an array of int

print(formAnArray(value: 1234))
func formAnArray(value: Int) -> [Int] {
    let string = String(value)
    return string.compactMap{Int(String($0))}
}


问:
Relay local state management. How to add and use flag on client side?

The problem:

I want to have simple boolean flag that will be true when modal is opened and false when it is closed. And I want to update other components reactively depends on that flag

I hope there is a way to do it with relay only (Apollo has a solution for that). I don't want to connect redux of mobx or something like that (It is just simple boolean flag!).

What I already have:

It is possible to use commitLocalUpdate in order to modify your state.
Indeed I was able to create and modify my new flag like that:

class ModalComponent extends PureComponent {
    componentDidMount() {
        // Here I either create or update value if it exists
        commitLocalUpdate(environment, (store) => {
            if (!store.get('isModalOpened')) {
                store.create('isModalOpened', 'Boolean').setValue(true);
            } else {
                store.get('isModalOpened').setValue(true);
            }
        });
    }

    componentWillUnmount() {
        // Here I mark flag as false
        commitLocalUpdate(environment, (store) => {
            store.get('isModalOpened').setValue(false);
        });
    }

    render() {
        // This is just react component so you have full picture
        return ReactDOM.createPortal(

                dummy modal

,
            document.getElementById('modal'),
        );
    }
}
```
<h3>The challenge:</h3>
<p><strong>How to update other components reactively depends on that flag?</strong>
I can't fetch my flag like this:</p>
<pre class="lang-js prettyprint-override"><code>
const MyComponent = (props) => {
    return (
    <QueryRenderer
        environment={ environment }
        query={ graphql`
            query MyComponentQuery {
                isModalOpened
            }`
        } //PROBLEM IS HERE GraphQLParser: Unknown field `isModalOpened` on type `Query`
        render={ ({ error, props: data, retry }) => {

            return (
                <div>
                    {data.isModalOpened}
                <div/>
            );
        } }
    />);
};
</code>```

Because Relay compiler throws me an error: GraphQLParser: Unknown field 'isModalOpened' on type 'Query'.

And the last problem:
How to avoid server request?
That information is stored on client side so there is no need for request.

I know there a few maybe similar questions like that and that. But they doesn't ask most difficult part of reactive update and answers are outdated.

答:
If you need to store just one flag as you said, I recommend you to use React Context instead of Relay. You could do next:

Add Context to App component:

```<code>const ModalContext = React.createContext('modal');

export class App extends React.Component {
    constructor() {
        super();
        this.state = {
            isModalOpened: false
        }
    }

    toggleModal = (value) => {
        this.setState({
            isModalOpened: value
        })
    };

    getModalContextValue() {
        return {
            isModalOpened: this.state.isModalOpened,
            toggleModal: this.toggleModal
        }
    }

    render() {
        return (
            <ModalContext.Provider value={this.getModalContextValue()}>
                //your child components
            </ModalContext.Provider>
        )
    }

}

</code>```

Get value from context everywhere you want:

```<code>const MyComponent = (props) => {
    const { isModalOpened } = useContext(ModalContext);

    return (
        <div>
            {isModalOpened}
        </div>
    );
};
</code>```

If you will use this solution you will get rid of using additional libraries such as Relay and server requests.

Body:
The problem:

I want to have simple boolean flag that will be true when modal is opened and false when it is closed. And I want to update other components reactively depends on that flag

I hope there is a way to do it with relay only (Apollo has a solution for that). I don't want to connect redux of mobx or something like that (It is just simple boolean flag!).

What I already have:

It is possible to use commitLocalUpdate in order to modify your state.
Indeed I was able to create and modify my new flag like that:

class ModalComponent extends PureComponent {
    componentDidMount() {
        // Here I either create or update value if it exists
        commitLocalUpdate(environment, (store) => {
            if (!store.get('isModalOpened')) {
                store.create('isModalOpened', 'Boolean').setValue(true);
            } else {
                store.get('isModalOpened').setValue(true);
            }
        });
    }

    componentWillUnmount() {
        // Here I mark flag as false
        commitLocalUpdate(environment, (store) => {
            store.get('isModalOpened').setValue(false);
        });
    }

    render() {
        // This is just react component so you have full picture
        return ReactDOM.createPortal(

                dummy modal

,
            document.getElementById('modal'),
        );
    }
}

The challenge:

How to update other components reactively depends on that flag?
I can't fetch my flag like this:

const MyComponent = (props) => {
    return (
    <QueryRenderer
        environment={ environment }
        query={ graphql`
            query MyComponentQuery {
                isModalOpened
            }`
        } //PROBLEM IS HERE GraphQLParser: Unknown field `isModalOpened` on type `Query`
        render={ ({ error, props: data, retry }) => {

            return (

                    {data.isModalOpened}

            );
        } }
    />);
};

Because Relay compiler throws me an error: GraphQLParser: Unknown field 'isModalOpened' on type 'Query'.

And the last problem:
How to avoid server request?
That information is stored on client side so there is no need for request.

I know there a few maybe similar questions like that and that. But they doesn't ask most difficult part of reactive update and answers are outdated.

Body:
If you need to store just one flag as you said, I recommend you to use React Context instead of Relay. You could do next:

Add Context to App component:

const ModalContext = React.createContext('modal');

export class App extends React.Component {
    constructor() {
        super();
        this.state = {
            isModalOpened: false
        }
    }

    toggleModal = (value) => {
        this.setState({
            isModalOpened: value
        })
    };

    getModalContextValue() {
        return {
            isModalOpened: this.state.isModalOpened,
            toggleModal: this.toggleModal
        }
    }

    render() {
        return (
            <ModalContext.Provider value={this.getModalContextValue()}>
                //your child components
            </ModalContext.Provider>
        )
    }

}

Get value from context everywhere you want:

const MyComponent = (props) => {
    const { isModalOpened } = useContext(ModalContext);

    return (
        <div>
            {isModalOpened}
        </div>
    );
};

If you will use this solution you will get rid of using additional libraries such as Relay and server requests.


问:
React: ReferenceError: regeneratorRuntime is not defined
I am trying to use async and await in my react application.

```<code>   onSubmit = async (model) => {
        await this.setState({ data: model });
    }
</code>```

After adding the above code i get an error in my browser console.

ReferenceError: regeneratorRuntime is not defined

.babelrc

```<code>{
    "presets": ["@babel/preset-env", "@babel/preset-react"],
    "plugins": [
        "@babel/plugin-proposal-class-properties"
    ],
    "sourceMaps": "inline"

}
</code>```

webpack.config.js

```<code>const path = require("path");
const WebpackShellPlugin = require("webpack-shell-plugin");
const nodeExternals = require("webpack-node-externals");
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = [
    {
    Server config removed

 },

    {
        entry: {
            app1: './src/public/app1/index.js',
            app2: './src/public/app2/index.js',
            app3: './src/public/app3/index.js',
        },
        devtool: "source-map",
        output: {
            path: __dirname + '/dist/public/',
            publicPath: '/',
            filename: '[name]/bundle.js',
            devtoolLineToLine: true,
            sourceMapFilename: "[name]/bundle.js.map",

        },
        module: {
            rules: [
                {
                    test: /(\.css|.scss)$/,
                    use: [{
                        loader: "style-loader" // creates style nodes from JS strings
                    }, {
                        loader: "css-loader" // translates CSS into CommonJS
                    }, {
                        loader: "sass-loader" // compiles Sass to CSS
                    }]
                },
                {
                    test: /\.(jsx|js)?$/,
                    use: [{
                        loader: "babel-loader",
                        // options: {
                        //     cacheDirectory: true,
                        //     presets: ['react', 'es2015'] // Transpiles JSX and ES6
                        // }
                    }]
                }
            ],

        },
        "plugins": [
            new CopyWebpackPlugin([
                {
                    from: 'src/public/app1/index.html',
                    to: 'app1'
                },
                {
                    from: 'src/public/app2/index.html',
                    to: 'app2'
                },
                {
                    from: 'src/public/app3/index.html',
                    to: 'app3'
                },
            ]),

        ]

    }
];
</code>```

I have added my babelrc and webpack config. Please let me know if i am missing something that would cause this error to appear in my browser console.

答:
Adding polyfills from create-react-app worked for me.

```<code>yarn add --dev react-app-polyfill
</code>```

Then add the following lines to webpack.config.js

```<code>entry: {
  app: [
    'react-app-polyfill/ie9', // Only if you want to support IE 9
    'react-app-polyfill/stable',
    './src/index.jsx',
  ],
},
</code>```

See more examples on the react-app-polyfill GitHub page.

Body:
I am trying to use async and await in my react application.

   onSubmit = async (model) => {
        await this.setState({ data: model });
    }

After adding the above code i get an error in my browser console.

ReferenceError: regeneratorRuntime is not defined

.babelrc

{
    "presets": ["@babel/preset-env", "@babel/preset-react"],
    "plugins": [
        "@babel/plugin-proposal-class-properties"
    ],
    "sourceMaps": "inline"

}

webpack.config.js

const path = require("path");
const WebpackShellPlugin = require("webpack-shell-plugin");
const nodeExternals = require("webpack-node-externals");
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = [
    {
    Server config removed

 },

    {
        entry: {
            app1: './src/public/app1/index.js',
            app2: './src/public/app2/index.js',
            app3: './src/public/app3/index.js',
        },
        devtool: "source-map",
        output: {
            path: __dirname + '/dist/public/',
            publicPath: '/',
            filename: '[name]/bundle.js',
            devtoolLineToLine: true,
            sourceMapFilename: "[name]/bundle.js.map",

        },
        module: {
            rules: [
                {
                    test: /(\.css|.scss)$/,
                    use: [{
                        loader: "style-loader" // creates style nodes from JS strings
                    }, {
                        loader: "css-loader" // translates CSS into CommonJS
                    }, {
                        loader: "sass-loader" // compiles Sass to CSS
                    }]
                },
                {
                    test: /\.(jsx|js)?$/,
                    use: [{
                        loader: "babel-loader",
                        // options: {
                        //     cacheDirectory: true,
                        //     presets: ['react', 'es2015'] // Transpiles JSX and ES6
                        // }
                    }]
                }
            ],

        },
        "plugins": [
            new CopyWebpackPlugin([
                {
                    from: 'src/public/app1/index.html',
                    to: 'app1'
                },
                {
                    from: 'src/public/app2/index.html',
                    to: 'app2'
                },
                {
                    from: 'src/public/app3/index.html',
                    to: 'app3'
                },
            ]),

        ]

    }
];

I have added my babelrc and webpack config. Please let me know if i am missing something that would cause this error to appear in my browser console.

Body:
Adding polyfills from create-react-app worked for me.

yarn add --dev react-app-polyfill

Then add the following lines to webpack.config.js

entry: {
  app: [
    'react-app-polyfill/ie9', // Only if you want to support IE 9
    'react-app-polyfill/stable',
    './src/index.jsx',
  ],
},

See more examples on the react-app-polyfill GitHub page.


问:
setSmallIcon() and setLargeIcon() not working in Android Notification
I am pushing the notification from the Firebase Console. I am able to easily receive the notification data and notification also appears but what i am trying to do is change the small icon and the large icon of the notification.

I am using both the methods but none of them seem to work. I have also tried making the small icon using the Vector option via res>New>Vector>Clip Art.
Neither small icon appears nor does the large icon and the notification is also not expandable.

MessagingService.kt

class MessagingService(): FirebaseMessagingService() {

  override fun onMessageReceived(p0: RemoteMessage ? ) {
    super.onMessageReceived(p0)
    showNotification(p0!!.notification!!.title!!, p0!!.notification!!.body!!)
  }

  fun showNotification(title: String, body: String) {
    val icon = BitmapFactory.decodeResource(resources,
      R.drawable.iphn)
    NotificationCompat.Builder(this, "MyNotifications")
      .setLargeIcon(icon)
      .setSmallIcon(R.drawable.ic_notif)
      .setContentTitle(title)
      .setContentText(body)
      .setStyle(NotificationCompat.BigPictureStyle()
        .bigPicture(icon)
        .bigLargeIcon(null))
      .build()

  }
}
```

ic_notif is the drawable i created using Vector

答:
Here is working example :

call sendNotification(yourResponse) inside onMessageReceived(remoteMessage: RemoteMessage?) this way you can set large icon statically or dynamically.

```<code>private fun sendNotification(response: NotifyResponse) {
        var bmp: Bitmap? = null
        try {
//loading the image from server

//            if (!TextUtils.isEmpty(response.image)) {
//                val futureTarget = GlideApp.with(this).asBitmap().load(response.image).submit()
//                try {
//                    bmp = futureTarget.get()
//                    GlideApp.with(this).clear(futureTarget)
//
//                } catch (e: ExecutionException) {
//                    e.printStackTrace()
//                } catch (e: InterruptedException) {
//                    e.printStackTrace()
//                }
//
//            }

            val uniqueInt = (System.currentTimeMillis() and 0xfffffff).toInt()
            val pendingIntent = PendingIntent.getActivity(this, uniqueInt, getIntent(response.type), PendingIntent.FLAG_ONE_SHOT)

            val channelId = BuildConfig.FLAVOR
            val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
            val notificationBuilder = NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(notificationIcon)
                    .setContentTitle(response.title)
                    .setContentText(response.message)
                    .setAutoCancel(true)
                    .setSound(soundUri)
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
            if (bmp != null) {
                notificationBuilder.setLargeIcon(bmp)
                notificationBuilder.setStyle(NotificationCompat.BigPictureStyle().bigPicture(bmp).bigLargeIcon(null))
            }
            notificationBuilder.setContentIntent(pendingIntent)

            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val channel = NotificationChannel(BuildConfig.FLAVOR,
                        "Channel human readable title",
                        NotificationManager.IMPORTANCE_DEFAULT)
                notificationManager.createNotificationChannel(channel)
            }

            notificationManager.notify(0, notificationBuilder.build())
        } catch (o: Exception) {
            o.printStackTrace()
        }

    }
</code>```

Body:
I am pushing the notification from the Firebase Console. I am able to easily receive the notification data and notification also appears but what i am trying to do is change the small icon and the large icon of the notification.

I am using both the methods but none of them seem to work. I have also tried making the small icon using the Vector option via res>New>Vector>Clip Art.
Neither small icon appears nor does the large icon and the notification is also not expandable.

MessagingService.kt

class MessagingService(): FirebaseMessagingService() {

  override fun onMessageReceived(p0: RemoteMessage ? ) {
    super.onMessageReceived(p0)
    showNotification(p0!!.notification!!.title!!, p0!!.notification!!.body!!)
  }

  fun showNotification(title: String, body: String) {
    val icon = BitmapFactory.decodeResource(resources,
      R.drawable.iphn)
    NotificationCompat.Builder(this, "MyNotifications")
      .setLargeIcon(icon)
      .setSmallIcon(R.drawable.ic_notif)
      .setContentTitle(title)
      .setContentText(body)
      .setStyle(NotificationCompat.BigPictureStyle()
        .bigPicture(icon)
        .bigLargeIcon(null))
      .build()

  }
}

ic_notif is the drawable i created using Vector

Body:
Here is working example :

call sendNotification(yourResponse) inside onMessageReceived(remoteMessage: RemoteMessage?) this way you can set large icon statically or dynamically.

private fun sendNotification(response: NotifyResponse) {
        var bmp: Bitmap? = null
        try {
//loading the image from server

//            if (!TextUtils.isEmpty(response.image)) {
//                val futureTarget = GlideApp.with(this).asBitmap().load(response.image).submit()
//                try {
//                    bmp = futureTarget.get()
//                    GlideApp.with(this).clear(futureTarget)
//
//                } catch (e: ExecutionException) {
//                    e.printStackTrace()
//                } catch (e: InterruptedException) {
//                    e.printStackTrace()
//                }
//
//            }

            val uniqueInt = (System.currentTimeMillis() and 0xfffffff).toInt()
            val pendingIntent = PendingIntent.getActivity(this, uniqueInt, getIntent(response.type), PendingIntent.FLAG_ONE_SHOT)

            val channelId = BuildConfig.FLAVOR
            val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
            val notificationBuilder = NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(notificationIcon)
                    .setContentTitle(response.title)
                    .setContentText(response.message)
                    .setAutoCancel(true)
                    .setSound(soundUri)
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
            if (bmp != null) {
                notificationBuilder.setLargeIcon(bmp)
                notificationBuilder.setStyle(NotificationCompat.BigPictureStyle().bigPicture(bmp).bigLargeIcon(null))
            }
            notificationBuilder.setContentIntent(pendingIntent)

            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val channel = NotificationChannel(BuildConfig.FLAVOR,
                        "Channel human readable title",
                        NotificationManager.IMPORTANCE_DEFAULT)
                notificationManager.createNotificationChannel(channel)
            }

            notificationManager.notify(0, notificationBuilder.build())
        } catch (o: Exception) {
            o.printStackTrace()
        }

    }


问:
Regular expression for an alphanumeric word
I have a requirement to find and return the first occurrence of a pattern from a string.

Example: hello my SNO is 05FK3NEK900058V please add it

expected output: 05FK3NEK900058V

Condition for the pattern to match

Combination of digits and alphabets

Character length between 12 to 16

Can I do it using regular expression or do I need to loop thought the words?

What I tried but it didn't work

```<code>const regex = /\b^(?!\d*$|[a-zA-Z]*$)[a-zA-Z\d]{12,16}$\b/gm;
const str = `hello my SNO is 05FK3NEK900058V please add it `;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}
</code>```

答:
let str = "hello (plus SomeLongWord) my SNO is 05FK3NEK900058V please add it ";
const reg = /\b[\w\d]{12,16}\b/g;

let m = str.match(reg);
if (typeof m === "object" && m.length) {
  for (var indexM = 0; indexM < m.length; indexM++) {
    // You can add more checks to filter long words
    console.log(m[indexM]);
  }
} else {
  console.log("Not found any SNO here");
}

// results:
// SomeLongWord
// 05FK3NEK900058V```

That will help you to handle long words but probably more check will be needed.

Body:
I have a requirement to find and return the first occurrence of a pattern from a string.

Example: hello my SNO is 05FK3NEK900058V please add it

expected output: 05FK3NEK900058V

Condition for the pattern to match

Combination of digits and alphabets

Character length between 12 to 16

Can I do it using regular expression or do I need to loop thought the words?

What I tried but it didn't work

const regex = /\b^(?!\d*$|[a-zA-Z]*$)[a-zA-Z\d]{12,16}$\b/gm;
const str = `hello my SNO is 05FK3NEK900058V please add it `;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

Body:
let str = "hello (plus SomeLongWord) my SNO is 05FK3NEK900058V please add it ";
const reg = /\b[\w\d]{12,16}\b/g;

let m = str.match(reg);
if (typeof m === "object" && m.length) {
  for (var indexM = 0; indexM < m.length; indexM++) {
    // You can add more checks to filter long words
    console.log(m[indexM]);
  }
} else {
  console.log("Not found any SNO here");
}

// results:
// SomeLongWord
// 05FK3NEK900058V

That will help you to handle long words but probably more check will be needed.


问:
How to unmarshal a field that can be an array or a string in Go?
I'm trying to unmarshal this file:

```<code>{
  "@babel/code-frame@7.0.0": {
    "licenses": "MIT",
    "repository": "https://github.com/babel/babel/tree/master/packages/babel-code-frame",
    "publisher": "Sebastian McKenzie",
    "email": "sebmck@gmail.com",
    "path": "/Users/lislab/workspace/falcon-enrolment/frontend-customer/node_modules/@babel/code-frame",
    "licenseFile": "/Users/lislab/workspace/falcon-enrolment/frontend-customer/node_modules/@babel/code-frame/LICENSE"
  },
  "json-schema@0.2.3": {
    "licenses": [
      "AFLv2.1",
      "BSD"
    ],
    "repository": "https://github.com/kriszyp/json-schema",
    "publisher": "Kris Zyp",
    "path": "/Users/lislab/workspace/falcon-enrolment/frontend-customer/node_modules/json-schema",
    "licenseFile": "/Users/lislab/workspace/falcon-enrolment/frontend-customer/node_modules/json-schema/README.md"
  }
}
</code>```

into this struct:

```<code>type Dependency struct {
    Name    string
    URL     string
    Version string
    License string
}
</code>```

using these instructions:

```<code>dependencies := map[string]*json.RawMessage{}
err = json.Unmarshal(file, &dependencies)
// boilerplate

for key, value := range dependencies {
    depVal := map[string]string{}
    err = json.Unmarshal(*value, &depVal)
    // boilerplate
    result = append(result, depVal)
}
</code>```

The problem with this is that in "json-schema@0.2.3" we have an array of licenses instead of a string, and due to that I obviously get

```<code>json: cannot unmarshal array into Go value of type string
</code>```

Is there a way to automatically deal with the field license which can be an array or a string?

Thanks

答:
Unfortunately, there is no real automatic solution for this provided by the json package.

But you can unmarshal the dependencies to a map[string]*json.RawMessage instead of map[string]string. json.RawMessage is just a []byte, so you can decide on the type of the message based on the first byte.

Example:

for _, value := range dependencies {
    depVal := map[string]*json.RawMessage{}

    _ = json.Unmarshal(*value, &depVal)

    // check if the first character of the RawMessage is a bracket
    if rune([]byte(*depVal["licenses"])[0]) == '[' {
        var licenses []string
        json.Unmarshal(*depVal["licenses"], &licenses)
        fmt.Println(licenses)
        // do something with the array
    }

    result = append(result, Dependency{
        URL:     string(*depVal["repository"]),
        License: string(*depVal["licenses"]),
    })
}
```

<p>Another solution would be to use 2 structs. One contains the dependencies as string, the other as array. You can then try to call <code>json.Unmarshal</code> on both of them.
Example: </p>

<pre class="lang-golang prettyprint-override"><code>
type Dependency struct {
    Licenses string
    // other fields
}

type DependencyWithArr struct {
    Licenses []string
    // other fields
}

// in your function
for _, value := range dependencies {
    type1 := Dependency{}
    type2 := DependencyWithArr{}

    err = json.Unmarshal(*value, &type1)
    if err != nil {
        err = json.Unmarshal(*value, &type2)
        // use the array type
    } else {
        // use the single string type
    }
}
</code>```

Body:
I'm trying to unmarshal this file:

{
  "@babel/code-frame@7.0.0": {
    "licenses": "MIT",
    "repository": "https://github.com/babel/babel/tree/master/packages/babel-code-frame",
    "publisher": "Sebastian McKenzie",
    "email": "sebmck@gmail.com",
    "path": "/Users/lislab/workspace/falcon-enrolment/frontend-customer/node_modules/@babel/code-frame",
    "licenseFile": "/Users/lislab/workspace/falcon-enrolment/frontend-customer/node_modules/@babel/code-frame/LICENSE"
  },
  "json-schema@0.2.3": {
    "licenses": [
      "AFLv2.1",
      "BSD"
    ],
    "repository": "https://github.com/kriszyp/json-schema",
    "publisher": "Kris Zyp",
    "path": "/Users/lislab/workspace/falcon-enrolment/frontend-customer/node_modules/json-schema",
    "licenseFile": "/Users/lislab/workspace/falcon-enrolment/frontend-customer/node_modules/json-schema/README.md"
  }
}

into this struct:

type Dependency struct {
    Name    string
    URL     string
    Version string
    License string
}

using these instructions:

dependencies := map[string]*json.RawMessage{}
err = json.Unmarshal(file, &dependencies)
// boilerplate

for key, value := range dependencies {
    depVal := map[string]string{}
    err = json.Unmarshal(*value, &depVal)
    // boilerplate
    result = append(result, depVal)
}

The problem with this is that in "json-schema@0.2.3" we have an array of licenses instead of a string, and due to that I obviously get

json: cannot unmarshal array into Go value of type string

Is there a way to automatically deal with the field license which can be an array or a string?

Thanks

Body:
Unfortunately, there is no real automatic solution for this provided by the json package.

But you can unmarshal the dependencies to a map[string]*json.RawMessage instead of map[string]string. json.RawMessage is just a []byte, so you can decide on the type of the message based on the first byte.

Example:

for _, value := range dependencies {
    depVal := map[string]*json.RawMessage{}

    _ = json.Unmarshal(*value, &depVal)

    // check if the first character of the RawMessage is a bracket
    if rune([]byte(*depVal["licenses"])[0]) == '[' {
        var licenses []string
        json.Unmarshal(*depVal["licenses"], &licenses)
        fmt.Println(licenses)
        // do something with the array
    }

    result = append(result, Dependency{
        URL:     string(*depVal["repository"]),
        License: string(*depVal["licenses"]),
    })
}

Another solution would be to use 2 structs. One contains the dependencies as string, the other as array. You can then try to call json.Unmarshal on both of them.
Example:

type Dependency struct {
    Licenses string
    // other fields
}

type DependencyWithArr struct {
    Licenses []string
    // other fields
}

// in your function
for _, value := range dependencies {
    type1 := Dependency{}
    type2 := DependencyWithArr{}

    err = json.Unmarshal(*value, &type1)
    if err != nil {
        err = json.Unmarshal(*value, &type2)
        // use the array type
    } else {
        // use the single string type
    }
}


问:
Capturing OpenMP exceptions with SetUnhandledExceptionFilter
I have an exception handler set up using SetUnhandledExceptionFilter, which works fine. However, if I throw an exception from within OpenMP code, I get the standard "the application crashed" window and the handler is not called -- however, I can attach a debugger just fine and see that the call stack is ending with _CxxThrowException and continues into KernelBase.dll!RaiseException. I know that an OpenMP program which throws exceptions inside the parallel regions is wrong, but I'd still like to get a crash dump. How can I get my exception handler get called in this case?

Should be possible, especially as the debugger manges to get an "Unhandled exception" window, when attached to the application after the crash (i.e. I can get a nice stack trace and stuff.) This is on Windows 7 with VC++ 2010.

(Eventually, each thread actually calls my exception handler. If it crashes, and I select 'Debug', and then continue on each unhandled exception, the handler eventually gets called and it also manages to write out a meaningful minidump. Wtf?)

答:
Interesting.  Going out on a limb, I'll wager that the OpenMP concurrency runtime doesn't honor the SetUnhandledExceptionFilter (which will work for "standard" threads), and isn't integrated into this feature of Structured Exception Handling.

Note this warning from the MSDN page on Exception Handling in the Concurrency Runtime

To prevent abnormal termination of your application, make sure that your code handles exceptions when it calls into the runtime. Also handle exceptions when you call into external code that uses the Concurrency Runtime, for example, a third-party library.

Perhaps you can try wrapping your OpenMP stuff in the style of exception handling outlined above, and then see if you can re-package and throw it (outside of OpenMP context) to get caught by the filter?


问:
Is PHP gmp_random_range function from GMP extension cryptographically secure?
I use PHP to write a software that generates random combinations of characters. For this I need arbitrary length integers random generation. So I use GMP extension and especially gmp_random_range(). But I need to prove with a link for example that it is cryptographically secure. Or at least it is enough random.

GMP random functions use seed (gmp_random_seed ), and if I don't set a seed everything looks random enough. So, I suppose when I don't set the seed explicitly it takes it from some reliable random source. I could not find something clearly stating such thing.

答:
As shown in "Random State Initialization", in the GMP documentation, the only random generator algorithms included in GMP are—

A Mersenne Twister algorithm,

linear congruential generators of various sizes, and

a "default algorithm" for "applications with no special requirements", including security requirements.

Curiously, the GMP documentation says in "Random State Seeding" that the "method for choosing a seed is critical if the generated numbers are to be used for important applications, such as generating cryptographic keys", even though none of the algorithms included in GMP are appropriate for cryptographic use.

As it appears, you can use random_bytes or random_int in PHP to generate cryptographic random numbers. The only thing left is to transform the numbers they deliver into arbitrary-precision numbers.* In that sense, GMP appears not to allow custom RNGs (besides the ones it provides) for the gmp_random_range and similar functions. Thus, you will have to transform those random numbers "manually", with the help of GMP's arithmetic functions. I have an article that discusses how to transform random numbers into a variety of distributions. To generate uniform random integers in a given range, the algorithm you need is called RNDINT or RNDINTEXC in that article.

* Where information security is involved, using random numbers as the seed for a noncryptographic RNG is not appropriate since an attacker, given enough random numbers, can then work backwards to derive the seed, even if the seed was generated in a cryptographically secure way.

If your goal is merely to generate a cryptographically random string of characters, you don't even need to go the GMP route. Just build the string one character at a time by calling random_int for each character you want to generate:

Build a list of characters allowed to appear in the random string.

For each character in the string, call random_int with a max of the list's size (a size which will almost certainly be within the range of integers PHP can handle), then append the character found at the given random index in the list (starting at 0).


问:
Solr 8.1 startup error - maxBooleanClauses
We've upgraded our Solr version from 7.6.0 to 8.1 and started seeing the following on the server startup:

```<code>2019-05-29 16:18:28.475 ERROR (main) [   ] o.a.s.c.SolrCore null:org.apache.solr.common.SolrException: Unknown configuration value in solr.xml: maxBooleanClauses
at org.apache.solr.core.SolrXmlConfig.fillSolrSection(SolrXmlConfig.java:279)
at org.apache.solr.core.SolrXmlConfig.fromConfig(SolrXmlConfig.java:109)
at org.apache.solr.core.SolrXmlConfig.fromInputStream(SolrXmlConfig.java:140)
at org.apache.solr.core.SolrXmlConfig.fromFile(SolrXmlConfig.java:122)
at org.apache.solr.core.SolrXmlConfig.fromSolrHome(SolrXmlConfig.java:150)
at org.apache.solr.servlet.SolrDispatchFilter.loadNodeConfig(SolrDispatchFilter.java:284)
at org.apache.solr.servlet.SolrDispatchFilter.createCoreContainer(SolrDispatchFilter.java:250)
at org.apache.solr.servlet.SolrDispatchFilter.init(SolrDispatchFilter.java:172)
at org.eclipse.jetty.servlet.FilterHolder.initialize(FilterHolder.java:136)
at org.eclipse.jetty.servlet.ServletHandler.lambda$initialize$0(ServletHandler.java:750)
at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:734)
at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:734)
at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:744)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:368)
at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1497)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1459)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:852)
at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:278)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:545)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:46)
at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:192)
at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:505)
at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:151)
at org.eclipse.jetty.deploy.providers.ScanningAppProvider.fileAdded(ScanningAppProvider.java:180)
at org.eclipse.jetty.deploy.providers.WebAppProvider.fileAdded(WebAppProvider.java:453)
at org.eclipse.jetty.deploy.providers.ScanningAppProvider$1.fileAdded(ScanningAppProvider.java:64)
at org.eclipse.jetty.util.Scanner.reportAddition(Scanner.java:610)
at org.eclipse.jetty.util.Scanner.reportDifferences(Scanner.java:529)
at org.eclipse.jetty.util.Scanner.scan(Scanner.java:392)
at org.eclipse.jetty.util.Scanner.doStart(Scanner.java:313)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.deploy.providers.ScanningAppProvider.doStart(ScanningAppProvider.java:150)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.deploy.DeploymentManager.startAppProvider(DeploymentManager.java:579)
at org.eclipse.jetty.deploy.DeploymentManager.doStart(DeploymentManager.java:240)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:138)
at org.eclipse.jetty.server.Server.start(Server.java:415)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:117)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:113)
at org.eclipse.jetty.server.Server.doStart(Server.java:382)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.xml.XmlConfiguration$1.run(XmlConfiguration.java:1572)
at org.eclipse.jetty.xml.XmlConfiguration$1.run(XmlConfiguration.java:1512)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at org.eclipse.jetty.xml.XmlConfiguration.main(XmlConfiguration.java:1511)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.eclipse.jetty.start.Main.invokeMain(Main.java:220)
at org.eclipse.jetty.start.Main.start(Main.java:490)
at org.eclipse.jetty.start.Main.main(Main.java:77)
</code>```

What can be causing this and how can we fix it?  Any pointers are much appreciated.

答: Turns out the old Solr jars were put by the build script into the solr web-app lib folder thus forcing Solr server to start the 7.6.0 version.  Kudos go to a coworker noticing the discrepancy by closely examining Solr log file.</p>

Body:
We've upgraded our Solr version from 7.6.0 to 8.1 and started seeing the following on the server startup:

2019-05-29 16:18:28.475 ERROR (main) [   ] o.a.s.c.SolrCore null:org.apache.solr.common.SolrException: Unknown configuration value in solr.xml: maxBooleanClauses
at org.apache.solr.core.SolrXmlConfig.fillSolrSection(SolrXmlConfig.java:279)
at org.apache.solr.core.SolrXmlConfig.fromConfig(SolrXmlConfig.java:109)
at org.apache.solr.core.SolrXmlConfig.fromInputStream(SolrXmlConfig.java:140)
at org.apache.solr.core.SolrXmlConfig.fromFile(SolrXmlConfig.java:122)
at org.apache.solr.core.SolrXmlConfig.fromSolrHome(SolrXmlConfig.java:150)
at org.apache.solr.servlet.SolrDispatchFilter.loadNodeConfig(SolrDispatchFilter.java:284)
at org.apache.solr.servlet.SolrDispatchFilter.createCoreContainer(SolrDispatchFilter.java:250)
at org.apache.solr.servlet.SolrDispatchFilter.init(SolrDispatchFilter.java:172)
at org.eclipse.jetty.servlet.FilterHolder.initialize(FilterHolder.java:136)
at org.eclipse.jetty.servlet.ServletHandler.lambda$initialize$0(ServletHandler.java:750)
at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:734)
at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:734)
at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:744)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:368)
at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1497)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1459)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:852)
at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:278)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:545)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:46)
at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:192)
at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:505)
at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:151)
at org.eclipse.jetty.deploy.providers.ScanningAppProvider.fileAdded(ScanningAppProvider.java:180)
at org.eclipse.jetty.deploy.providers.WebAppProvider.fileAdded(WebAppProvider.java:453)
at org.eclipse.jetty.deploy.providers.ScanningAppProvider$1.fileAdded(ScanningAppProvider.java:64)
at org.eclipse.jetty.util.Scanner.reportAddition(Scanner.java:610)
at org.eclipse.jetty.util.Scanner.reportDifferences(Scanner.java:529)
at org.eclipse.jetty.util.Scanner.scan(Scanner.java:392)
at org.eclipse.jetty.util.Scanner.doStart(Scanner.java:313)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.deploy.providers.ScanningAppProvider.doStart(ScanningAppProvider.java:150)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.deploy.DeploymentManager.startAppProvider(DeploymentManager.java:579)
at org.eclipse.jetty.deploy.DeploymentManager.doStart(DeploymentManager.java:240)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:138)
at org.eclipse.jetty.server.Server.start(Server.java:415)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:117)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:113)
at org.eclipse.jetty.server.Server.doStart(Server.java:382)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.xml.XmlConfiguration$1.run(XmlConfiguration.java:1572)
at org.eclipse.jetty.xml.XmlConfiguration$1.run(XmlConfiguration.java:1512)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at org.eclipse.jetty.xml.XmlConfiguration.main(XmlConfiguration.java:1511)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.eclipse.jetty.start.Main.invokeMain(Main.java:220)
at org.eclipse.jetty.start.Main.start(Main.java:490)
at org.eclipse.jetty.start.Main.main(Main.java:77)

What can be causing this and how can we fix it?  Any pointers are much appreciated.


问:
Angular material expansion panel in virtual scroll
I have a Virtual scroll feature on my website. Every item in virtual scroll is expansion panel with different count of lines within. When I implement  <cdk-virtual-scroll-viewport> expansion panels are rendered fine, but when I click on current panel it not expand and only increase his height with maybe 5 px. I don't know how to do it, that expansion panel will expand properly.

I've tried to move expansion panel to <ng-container> but id didn't help.

```<code><div class="container">
  <mat-card>
        <mat-card-title>
          <span class="panelItem">Id</span>
          <span class="secondPanelItem">Name</span>
          <span class="lastPanelItem">Version</span>
        </mat-card-title>
  </mat-card>
  <cdk-virtual-scroll-viewport itemSize="50" class="viewport">
    <mat-accordion>
      <ng-container *cdkVirtualFor="let description of allDescriptions">
        <mat-expansion-panel>
          <mat-expansion-panel-header>
            <mat-panel-title>
              <span class="panelItem">{{description.id}}</span>
              <span class="secondPanelItem">{{description.name}}</span>
              <span class="lastPanelItem">{{description.version}}</span>
            </mat-panel-title>
          </mat-expansion-panel-header>
        </mat-expansion-panel>
      </ng-container>
    </mat-accordion>
  </cdk-virtual-scroll-viewport>
</div>
</code>```

答: I finally found where was problem. I was setted in scss file height of expansion panel to 50 px so It can't expand more. When I removed this everything is OK.</p>

Body:
I have a Virtual scroll feature on my website. Every item in virtual scroll is expansion panel with different count of lines within. When I implement  <cdk-virtual-scroll-viewport> expansion panels are rendered fine, but when I click on current panel it not expand and only increase his height with maybe 5 px. I don't know how to do it, that expansion panel will expand properly.

I've tried to move expansion panel to <ng-container> but id didn't help.

  <mat-card>
        <mat-card-title>
          Id
          Name
          Version
        </mat-card-title>
  </mat-card>
  <cdk-virtual-scroll-viewport itemSize="50" class="viewport">
    <mat-accordion>
      <ng-container *cdkVirtualFor="let description of allDescriptions">
        <mat-expansion-panel>
          <mat-expansion-panel-header>
            <mat-panel-title>
              {{description.id}}
              {{description.name}}
              {{description.version}}
            </mat-panel-title>
          </mat-expansion-panel-header>
        </mat-expansion-panel>
      </ng-container>
    </mat-accordion>
  </cdk-virtual-scroll-viewport>


问:
When controller call method from another class produce produce invalid operation
Calling a method from controller produce the error InvalidOperationException: Unable to resolve service for type 'AwardManagement.Class.Season' while attempting to activate 'AwardManagement.Controllers.TabsController'.

This is the code call from Controller

```<code>
   public TabsController(AwardContext context,Season seasons)
   {
       _context = context;
       _seasons = seasons;
   }
   public ActionResult GetTabs(int id)
   {
       var tabs =  _context.Tabs.Find(id);
       if (tabs == null)
       {
          return NotFound();
       }
       var season = _seasons.GetSingle(tabs.SeasonId);
       var result = new { tab = tabs, season = season };
       return  Ok(result);
   }
</code>```

GetSingle() Definition in Season Class

```<code>public class Season
{
     private readonly AwardContext _context;
     public Season(AwardContext context)
     {
        _context = context;
     }
     public  Seasons GetSingle(int? id)
     {
        return _context.Seasons.FirstOrDefault(x => x.Id == id);
     }
 }
</code>```

答:
The problem is that you didn't registered your Season class in the DI container so when a request is received in that controller no one knows how to instantiate TabsController because it doesn't know from where to get the Season parameter.

You can read more here: https://aspnetcore.readthedocs.io/en/stable/mvc/controllers/dependency-injection.html

Apart from this there are two ways to resolve this one:

Change the GetTabs to directly use _context.Seasons

```<code>   public TabsController(AwardContext context)
   {
       _context = context;
   }
   public ActionResult GetTabs(int id)
   {
       var tabs =  _context.Tabs.Find(id);
       if (tabs == null)
       {
          return NotFound();
       }
       var season = _context.Seasons.FirstOrDefault(tabs.SeasonId);
       var result = new { tab = tabs, season = season };
       return  Ok(result);
   }
</code>```

Or you move the logic into a separate class (like a service): SeasonService, then you register that in the DI container, then you re-use it in both TabsController and SeasonController.

The SeasonService will look something like this:

```<code>public class SeasonService
{
     private readonly AwardContext _context;
     public SeasonService(AwardContext context)
     {
        _context = context;
     }
     public  Seasons GetSingle(int? id)
     {
        return _context.Seasons.FirstOrDefault(x => x.Id == id);
     }
 }
</code>```

And you need to register it in DI container: https://medium.com/volosoft/asp-net-core-dependency-injection-best-practices-tips-tricks-c6e9c67f9d96

And then you'll be able to use it inside your controllers:

```<code>   public TabsController(TabsService tabsService, SeasonService seasonService)
   {
       _tabsService = tabsService;
       _seasonService = seasonService;
   }
   public ActionResult GetTabs(int id)
   {
       var tabs =  _tabsService.FindById(id);
       if (tabs == null)
       {
          return NotFound();
       }
       var season = _seasonService.GetSingleById(tabs.SeasonId);
       var result = new { tab = tabs, season = season };
       return  Ok(result);
   }
</code>```

As you can see, you'll need to also create TabsService and register it too in DI Container.

You can read more about this design pattern/architectural approach here: MVCS - Model View Controller Service

Body:
Calling a method from controller produce the error InvalidOperationException: Unable to resolve service for type 'AwardManagement.Class.Season' while attempting to activate 'AwardManagement.Controllers.TabsController'.

This is the code call from Controller

   public TabsController(AwardContext context,Season seasons)
   {
       _context = context;
       _seasons = seasons;
   }
   public ActionResult GetTabs(int id)
   {
       var tabs =  _context.Tabs.Find(id);
       if (tabs == null)
       {
          return NotFound();
       }
       var season = _seasons.GetSingle(tabs.SeasonId);
       var result = new { tab = tabs, season = season };
       return  Ok(result);
   }

GetSingle() Definition in Season Class

public class Season
{
     private readonly AwardContext _context;
     public Season(AwardContext context)
     {
        _context = context;
     }
     public  Seasons GetSingle(int? id)
     {
        return _context.Seasons.FirstOrDefault(x => x.Id == id);
     }
 }

Body:
The problem is that you didn't registered your Season class in the DI container so when a request is received in that controller no one knows how to instantiate TabsController because it doesn't know from where to get the Season parameter.

You can read more here: https://aspnetcore.readthedocs.io/en/stable/mvc/controllers/dependency-injection.html

Apart from this there are two ways to resolve this one:

Change the GetTabs to directly use _context.Seasons

   public TabsController(AwardContext context)
   {
       _context = context;
   }
   public ActionResult GetTabs(int id)
   {
       var tabs =  _context.Tabs.Find(id);
       if (tabs == null)
       {
          return NotFound();
       }
       var season = _context.Seasons.FirstOrDefault(tabs.SeasonId);
       var result = new { tab = tabs, season = season };
       return  Ok(result);
   }

Or you move the logic into a separate class (like a service): SeasonService, then you register that in the DI container, then you re-use it in both TabsController and SeasonController.

The SeasonService will look something like this:

public class SeasonService
{
     private readonly AwardContext _context;
     public SeasonService(AwardContext context)
     {
        _context = context;
     }
     public  Seasons GetSingle(int? id)
     {
        return _context.Seasons.FirstOrDefault(x => x.Id == id);
     }
 }

And you need to register it in DI container: https://medium.com/volosoft/asp-net-core-dependency-injection-best-practices-tips-tricks-c6e9c67f9d96

And then you'll be able to use it inside your controllers:

   public TabsController(TabsService tabsService, SeasonService seasonService)
   {
       _tabsService = tabsService;
       _seasonService = seasonService;
   }
   public ActionResult GetTabs(int id)
   {
       var tabs =  _tabsService.FindById(id);
       if (tabs == null)
       {
          return NotFound();
       }
       var season = _seasonService.GetSingleById(tabs.SeasonId);
       var result = new { tab = tabs, season = season };
       return  Ok(result);
   }

As you can see, you'll need to also create TabsService and register it too in DI Container.

You can read more about this design pattern/architectural approach here: MVCS - Model View Controller Service