问:
TypeError: (‘Params must be in a list, tuple, or Row’, ‘HY000’) Error on pyodbc
I am trying to fetch all the duplicates from  tokens and load into tokn_Duplicates table. Getting Type error as below, if the sequence/format of the values passed to the insert query is causing this. Tried different options from the forum to pass the values as tuple/list, havent been successful

Code snippet below and error

```<code>
 with conn.cursor() as cur:

cur.execute("""
           select case when tokn_type_cd IS NULL Then 'Address'  else tokn_type_cd end as tokn_type_cd,case when tokn_val_tx is null then '0' else tokn_val_tx end tokn_val_tx,case when pg_duplicate_ct is null then 0 else pg_duplicate_ct end  pg_duplicate_ct  from ((SELECT 0 DUMMY ) DM LEFT OUTER JOIN (SELECT tokn_type_cd, tokn_val_tx, COUNT(*) AS pg_duplicate_ct
      FROM   devt.tokens
      GROUP BY tokn_type_cd, tokn_val_tx
      HAVING COUNT(*) > 1) on 1=1)
        """)
        rows2 = cur.fetchall()

cnxn = pyodbc.connect(server='connect to server')

crsr = cnxn.cursor()

if len(rows2):
    crsr.executemany("INSERT INTO duplicates (tokn_type_cd, tokn_val_tx, pg_duplicate_ct) VALUES (?, ?, ?)", [str(r) for r in rows2])
cnxn.commit()

print("... Successfully completed...")

</code>```

Error received below

```<code>
crsr.executemany(“INSERT INTO duplicates (tokn_type_cd, tokn_val_tx, pg_duplicate_ct) VALUES (?, ?, ?)“, [str(r) for r in rows2])
TypeError: (‘Params must be in a list, tuple, or Row’, ‘HY000’)

</code>```

Tried the below change from the forum:

```<code>crsr.executemany(“INSERT INTO duplicates (tokn_type_cd, tokn_val_tx, pg_duplicate_ct) VALUES (?, ?, ?)“, [str(tokn_type_cd), str(tokn_val_tx) ,pg_duplicate_ct])
</code>```

received the error below after the change

```<code>crsr.executemany(“INSERT INTO secret_tokn_duplicates (tokn_type_cd, tokn_val_tx, pg_duplicate_ct) VALUES (?, ?, ?)“, [str(tokn_type_cd), str(tokn_val_tx) ,pg_duplicate_ct])
NameError: name ‘tokn_type_cd’ is not defined
</code>```

Any help would be appreciated.

Thanks

答:
Try

crsr.executemany(
    "INSERT INTO secret_tokn_duplicates (tokn_type_cd, tokn_val_tx, pg_duplicate_ct) VALUES (?, ?, ?)",
    [(str(row.tokn_type_cd), str(row.tokn_val_tx), row.pg_duplicate_ct) for row in rows2])
```
<p>or if that doesn't work:</p>
```crsr.executemany(
    "INSERT INTO secret_tokn_duplicates (tokn_type_cd, tokn_val_tx, pg_duplicate_ct) VALUES (?, ?, ?)",
    [(str(row[0]), str(row[1]), row[2]) for row in rows2])
```
<p>The list <code>[(str(row.tokn_type_cd), str(row.tokn_val_tx), row.pg_duplicate_ct) for row in rows2]</code> creates a list of 3-tuples from the rows in <code>rows2</code>. I don't have access to your database, so I can't test that it works, but it's my best guess at will work given what's in your question.</p>
<p>Your first attempt</p>
<pre class="lang-py prettyprint-override"><code>crsr.executemany("INSERT INTO duplicates (tokn_type_cd, tokn_val_tx, pg_duplicate_ct) VALUES (?, ?, ?)", [str(r) for r in rows2])
</code>```

didn't work because the list you passed to crsr.executemany contained strings, which were what you got if you attempted to convert each row read from the cursor to a string. The elements in the list passed to crsr.executemany must be lists, tuples or Rows: you need to pass it a list of lists, a list of tuples or a list of Rows.

Your second attempt

crsr.executemany("INSERT INTO duplicates (tokn_type_cd, tokn_val_tx, pg_duplicate_ct) VALUES (?, ?, ?)", [str(tokn_type_cd), str(tokn_val_tx) ,pg_duplicate_ct])
```
<p>didn't work because <code>tokn_type_cd</code>, <code>tokn_val_tx</code> and <code>pg_duplicate_ct</code> aren't variables that Python knows about.  However, even if you had defined them, you would again end up passing a list of strings to <code>crsr.executemany</code> and would get the first error again.</p>
<hr>
<p>However, having said all the above, most RDBMSs support <code>INSERT INTO ... SELECT ...</code> statements, which will copy the data directly, so why not just execute the following?</p>
<pre class="lang-py prettyprint-override"><code>cur.execute("""
           INSERT INTO duplicates (tokn_type_cd, tokn_val_tx, pg_duplicate_ct)
           select case when tokn_type_cd IS NULL Then 'Address'  else tokn_type_cd end as tokn_type_cd,case when tokn_val_tx is null then '0' else tokn_val_tx end tokn_val_tx,case when pg_duplicate_ct is null then 0 else pg_duplicate_ct end  pg_duplicate_ct  from ((SELECT 0 DUMMY ) DM LEFT OUTER JOIN (SELECT tokn_type_cd, tokn_val_tx, COUNT(*) AS pg_duplicate_ct
      FROM   devt.tokens
      GROUP BY tokn_type_cd, tokn_val_tx
      HAVING COUNT(*) > 1) on 1=1)
        """)
</code>```

Body:
I am trying to fetch all the duplicates from  tokens and load into tokn_Duplicates table. Getting Type error as below, if the sequence/format of the values passed to the insert query is causing this. Tried different options from the forum to pass the values as tuple/list, havent been successful

Code snippet below and error

 with conn.cursor() as cur:

cur.execute("""
           select case when tokn_type_cd IS NULL Then 'Address'  else tokn_type_cd end as tokn_type_cd,case when tokn_val_tx is null then '0' else tokn_val_tx end tokn_val_tx,case when pg_duplicate_ct is null then 0 else pg_duplicate_ct end  pg_duplicate_ct  from ((SELECT 0 DUMMY ) DM LEFT OUTER JOIN (SELECT tokn_type_cd, tokn_val_tx, COUNT(*) AS pg_duplicate_ct
      FROM   devt.tokens
      GROUP BY tokn_type_cd, tokn_val_tx
      HAVING COUNT(*) > 1) on 1=1)
        """)
        rows2 = cur.fetchall()

cnxn = pyodbc.connect(server='connect to server')

crsr = cnxn.cursor()

if len(rows2):
    crsr.executemany("INSERT INTO duplicates (tokn_type_cd, tokn_val_tx, pg_duplicate_ct) VALUES (?, ?, ?)", [str(r) for r in rows2])
cnxn.commit()

print("... Successfully completed...")

Error received below

crsr.executemany(“INSERT INTO duplicates (tokn_type_cd, tokn_val_tx, pg_duplicate_ct) VALUES (?, ?, ?)“, [str(r) for r in rows2])
TypeError: (‘Params must be in a list, tuple, or Row’, ‘HY000’)

Tried the below change from the forum:

crsr.executemany(“INSERT INTO duplicates (tokn_type_cd, tokn_val_tx, pg_duplicate_ct) VALUES (?, ?, ?)“, [str(tokn_type_cd), str(tokn_val_tx) ,pg_duplicate_ct])

received the error below after the change

crsr.executemany(“INSERT INTO secret_tokn_duplicates (tokn_type_cd, tokn_val_tx, pg_duplicate_ct) VALUES (?, ?, ?)“, [str(tokn_type_cd), str(tokn_val_tx) ,pg_duplicate_ct])
NameError: name ‘tokn_type_cd’ is not defined

Any help would be appreciated.

Thanks

Body:
Try

crsr.executemany(
    "INSERT INTO secret_tokn_duplicates (tokn_type_cd, tokn_val_tx, pg_duplicate_ct) VALUES (?, ?, ?)",
    [(str(row.tokn_type_cd), str(row.tokn_val_tx), row.pg_duplicate_ct) for row in rows2])

or if that doesn't work:

crsr.executemany(
    "INSERT INTO secret_tokn_duplicates (tokn_type_cd, tokn_val_tx, pg_duplicate_ct) VALUES (?, ?, ?)",
    [(str(row[0]), str(row[1]), row[2]) for row in rows2])

The list [(str(row.tokn_type_cd), str(row.tokn_val_tx), row.pg_duplicate_ct) for row in rows2] creates a list of 3-tuples from the rows in rows2. I don't have access to your database, so I can't test that it works, but it's my best guess at will work given what's in your question.

Your first attempt

crsr.executemany("INSERT INTO duplicates (tokn_type_cd, tokn_val_tx, pg_duplicate_ct) VALUES (?, ?, ?)", [str(r) for r in rows2])

didn't work because the list you passed to crsr.executemany contained strings, which were what you got if you attempted to convert each row read from the cursor to a string. The elements in the list passed to crsr.executemany must be lists, tuples or Rows: you need to pass it a list of lists, a list of tuples or a list of Rows.

Your second attempt

crsr.executemany("INSERT INTO duplicates (tokn_type_cd, tokn_val_tx, pg_duplicate_ct) VALUES (?, ?, ?)", [str(tokn_type_cd), str(tokn_val_tx) ,pg_duplicate_ct])

didn't work because tokn_type_cd, tokn_val_tx and pg_duplicate_ct aren't variables that Python knows about.  However, even if you had defined them, you would again end up passing a list of strings to crsr.executemany and would get the first error again.

However, having said all the above, most RDBMSs support INSERT INTO ... SELECT ... statements, which will copy the data directly, so why not just execute the following?

cur.execute("""
           INSERT INTO duplicates (tokn_type_cd, tokn_val_tx, pg_duplicate_ct)
           select case when tokn_type_cd IS NULL Then 'Address'  else tokn_type_cd end as tokn_type_cd,case when tokn_val_tx is null then '0' else tokn_val_tx end tokn_val_tx,case when pg_duplicate_ct is null then 0 else pg_duplicate_ct end  pg_duplicate_ct  from ((SELECT 0 DUMMY ) DM LEFT OUTER JOIN (SELECT tokn_type_cd, tokn_val_tx, COUNT(*) AS pg_duplicate_ct
      FROM   devt.tokens
      GROUP BY tokn_type_cd, tokn_val_tx
      HAVING COUNT(*) > 1) on 1=1)
        """)


来源: stackexchange

问:
printf statement including quotes and escape sequence
I'm having some trouble making a print statement that includes quotes and a new line escape sequence. I tried to use \n for a new line and backslash before open quote and before closing quotes to tell my program to include the quotations. I don't know where I went wrong and I keep getting an error in my int main(void) line (sorry if I'm not using correct terminology, I'm in an intro c MOOC).</p>
```<code>#include <stdio.h>
int main(void){
    printf("Dennis Ritchie said:\n\"The only way to learn a new programming language is by writing programs in it.\");
    return 0;
}
</code>```

答:
you forgot the closing quote</p>
```<code> printf("Dennis Ritchie said:\n\"The only way to learn a new programming language is by writing programs in it.\"");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm having some trouble making a print statement that includes quotes and a new line escape sequence. I tried to use \n for a new line and backslash before open quote and before closing quotes to tell my program to include the quotations. I don't know where I went wrong and I keep getting an error in my int main(void) line (sorry if I'm not using correct terminology, I'm in an intro c MOOC).

#include <stdio.h>
int main(void){
    printf("Dennis Ritchie said:\n\"The only way to learn a new programming language is by writing programs in it.\");
    return 0;
}

Body:
you forgot the closing quote

 printf("Dennis Ritchie said:\n\"The only way to learn a new programming language is by writing programs in it.\"");


问:
MySQL matching 2 out of 5 fields
In MySQL I'm trying to select any row that matches at least 2 fields of the provided data

Eg. I have been given firstName, lastName, dob, website, email and I want any rows that match firstName and lastName, or firstName and email, or website and email etc.

I know I could write a very long winded statement along the lines of
(this=this AND this=this) OR (this=this etc
but this query could potentially get really large, especially if we decide we want to match on more than 5 fields.

We will also need to rank the matching rows, so if some rows match 3 instead of only the minimum 2 fields then they should show up higher in the returned results.

I could process this afterwards with PHP, or do multiple SQL queries, I'm just wondering if anyone knows an easier/cleaner way to match this data?

I appreciate any help!
Jo

答:
```<code>SELECT
(CASE WHEN Field1 = Value1 THEN 1 ELSE 0 END
+CASE WHEN Field2 = Value2 THEN 1 ELSE 0 END
...
+CASE WHEN FieldN = ValueN THEN 1 ELSE 0 END
)
AS Conditions
From YourTable
WHERE Conditions >= (Min_Number_Of_Fields)
</code>```

ContentLicense: CC BY-SA 3.0

Title: MySQL matching 2 out of 5 fields


问:
error: The argument type 'void Function(bool)' can't be assigned to the parameter type 'void Function(bool?)'
the problem is the header . Im trying to build the todoye app and as you can see the call back is considered ValueChanged<bool?> not a simple function so i cant move my logic to a another statefullwidget to reduce the rebuilds in my app i tried different things but i get error evertime please help .
here is my code :

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

class TaskTile extends StatefulWidget {
  @override
  _TaskTileState createState() => _TaskTileState();
}

class _TaskTileState extends State<TaskTile> {
  bool isChecked = false;
  void checkBoxCallBack(bool checkBoxState) {
    setState(() {
      isChecked = checkBoxState;
    });
  }

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text(
        'finish up angla\'s course today',
        style: TextStyle(
          decoration: isChecked ? TextDecoration.lineThrough : null,
        ),
      ),
      trailing: TaskCheckBox(
        checkBoxState: isChecked,
        toggleCheckBoxState: checkBoxCallBack,
      ),
    );
  }
}

class TaskCheckBox extends StatelessWidget {
  final bool checkBoxState;
  final ValueChanged<bool?> toggleCheckBoxState;

  const TaskCheckBox({
    required this.checkBoxState,
    required this.toggleCheckBoxState,
  });

  @override
  Widget build(BuildContext context) {
    return Checkbox(
      activeColor: Colors.lime,
      value: checkBoxState,
      onChanged: toggleCheckBoxState,
    );
  }
}
</code>```

the error is on line 27 ...where i want to pass my custom Function to varaible of my statelessWidget.

答:
i also encounter this problem, this is how i solved it,
i updated the checkboxcallback function as shown below,

```<code>void checkboxCallBack(bool? checkboxState) {
setState(() {
  isChecked = checkboxState!;
});
</code>```

}

then on theTaskCheckbox class, i change the declaration of the togglecheckboxState function as ;

```<code>final void Function(bool?) toggleCheckboxState;
</code>```

and boom everything is working perfectly

Body:
the problem is the header . Im trying to build the todoye app and as you can see the call back is considered ValueChanged<bool?> not a simple function so i cant move my logic to a another statefullwidget to reduce the rebuilds in my app i tried different things but i get error evertime please help .
here is my code :

import 'package:flutter/material.dart';

class TaskTile extends StatefulWidget {
  @override
  _TaskTileState createState() => _TaskTileState();
}

class _TaskTileState extends State<TaskTile> {
  bool isChecked = false;
  void checkBoxCallBack(bool checkBoxState) {
    setState(() {
      isChecked = checkBoxState;
    });
  }

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text(
        'finish up angla\'s course today',
        style: TextStyle(
          decoration: isChecked ? TextDecoration.lineThrough : null,
        ),
      ),
      trailing: TaskCheckBox(
        checkBoxState: isChecked,
        toggleCheckBoxState: checkBoxCallBack,
      ),
    );
  }
}

class TaskCheckBox extends StatelessWidget {
  final bool checkBoxState;
  final ValueChanged<bool?> toggleCheckBoxState;

  const TaskCheckBox({
    required this.checkBoxState,
    required this.toggleCheckBoxState,
  });

  @override
  Widget build(BuildContext context) {
    return Checkbox(
      activeColor: Colors.lime,
      value: checkBoxState,
      onChanged: toggleCheckBoxState,
    );
  }
}

the error is on line 27 ...where i want to pass my custom Function to varaible of my statelessWidget.

Body:
i also encounter this problem, this is how i solved it,
i updated the checkboxcallback function as shown below,

void checkboxCallBack(bool? checkboxState) {
setState(() {
  isChecked = checkboxState!;
});

}

then on theTaskCheckbox class, i change the declaration of the togglecheckboxState function as ;

final void Function(bool?) toggleCheckboxState;

and boom everything is working perfectly


问:
mysql fetching data from server
When get new data from the database, does this mean a new connection? mysql database

Eg:

```<code> SELECT * FROM employees WHERE ID=1
</code>```

Does this mean a new connection on the database server?

答:
Do I need a connection to perform a query?

Yes, absolutely.

Do I need a fresh connection to get the latest data?

No, you only need to query again.

Does every query need a new connection?

No, you only need one connection, then you can make several queries. Typically, you open the connection once when starting your program, and then do whatever you need; even closing the db is optional, modern languages do that for you when you exit the script, but it's nice to take care of it when you're done.

Title: mysql fetching data from server

Body:
When get new data from the database, does this mean a new connection? mysql database

Eg:

 SELECT * FROM employees WHERE ID=1

Does this mean a new connection on the database server?


问:
Extract text data from website using Python:
I am trying to extract text data from website using regex but problem is it is not completely extracting. I am following this tutorial: https://pythonprogramming.net/parse-website-using-regular-expressions-urllib
but i dont know where i am wrong. The website i am extracting text from is http://www.sanfoundry.com/c-programming-questions-answers-variable-names-1/ and its relevant sublinks as well.

Code:

```<code>import urllib2
from urllib2 import Request
import re
#url = "http://www.tutorialspoint.com/cplusplus/cpp_basic_syntax.htm"
url = "http://www.sanfoundry.com/c-programming-questions-answers-variable-names-1/"

req = Request(url)
resp = urllib2.urlopen(req)
respData = resp.read()

regex = '<p.*?>(.*?)<\/p>'

paragraphs = re.findall(regex,str(respData))

for eachP in paragraphs:
    print(eachP)
</code>```

any idea ???

答:
I found a good one for extracting paragraphs from How to Scrape Paragraphs using Python?

With example:

```<code># import module
from bs4 import BeautifulSoup

# Html doc
html_doc = """
<html>
<head>
<title>Geeks</title>
</head>
<body>
<h2>paragraphs</h2>

<p>Welcome geeks.</p>

<p>Hello geeks.</p>

</body>
</html>
"""
soup = BeautifulSoup(html_doc, 'html.parser')

# traverse paragraphs from soup
for data in soup.find_all("p"):
    print(data.get_text())
</code>```

Output:

```<code>Welcome geeks.
Hello geeks.
</code>```

Extract Paragraphs from the given URL:

```<code># import module
import requests
import pandas as pd
from bs4 import BeautifulSoup

# link for extract html data
def getdata(url):
    r = requests.get(url)
    return r.text

htmldata = getdata("https://www.geeksforgeeks.org/")
soup = BeautifulSoup(htmldata, 'html.parser')
data = ''
for data in soup.find_all("p"):
    print(data.get_text())
</code>```

Output:

Multiple Urls:

```<code>from urllib.request import urlopen
from bs4 import BeautifulSoup
import re

Newlines = re.compile(r'[\r\n]\s+')

def getPageText(url):
    # given a url, get page content
    data = urlopen(url).read()
    # parse as html structured document
    soup = BeautifulSoup(data, 'html.parser')
    # kill javascript content
    for s in soup(["script", "style"]):
        s.replaceWith('')
    # find body and extract text
    for p in soup.find_all('p'):
        txt = print(p.get_text())
    # remove multiple linebreaks and whitespace
    return Newlines.sub('\n', txt)

def main():
    urls = [
        'https://www.geeksforgeeks.org/how-to-download-install-nltk-on-windows/',
        'https://www.geeksforgeeks.org/how-to-scrape-paragraphs-using-python/'
    ]
    txt = [getPageText(url) for url in urls]
    for t in txt:
        print(t)

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

Output:

```<code>NLTK is Natural Language Tool Kit. It is used to build python programming. It helps to work with human languages data. It gives a very easy user interface. It supports classification, steaming, tagging, etc.Installing NLTK on Windows using PIP:In windows, we first have to install the python current version. Then we have to install pip with it. Without pip, NLTK can not be installed.Step 1: Browse to the official site of python by clicking this link.Step 2: Move the cursor to the Download button & then click on the latest python version.Step 3: Open the downloaded file. Click on the checkbox & Click on Customize installation.Step 4: Click on Next.Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
In windows, we first have to install the python current version. Then we have to install pip with it. Without pip, NLTK can not be installed.Step 1: Browse to the official site of python by clicking this link.Step 2: Move the cursor to the Download button & then click on the latest python version.Step 3: Open the downloaded file. Click on the checkbox & Click on Customize installation.Step 4: Click on Next.Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 1: Browse to the official site of python by clicking this link.Step 2: Move the cursor to the Download button & then click on the latest python version.Step 3: Open the downloaded file. Click on the checkbox & Click on Customize installation.Step 4: Click on Next.Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 2: Move the cursor to the Download button & then click on the latest python version.Step 3: Open the downloaded file. Click on the checkbox & Click on Customize installation.Step 4: Click on Next.Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 2: Move the cursor to the Download button & then click on the latest python version.Step 3: Open the downloaded file. Click on the checkbox & Click on Customize installation.Step 4: Click on Next.Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 3: Open the downloaded file. Click on the checkbox & Click on Customize installation.Step 4: Click on Next.Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 3: Open the downloaded file. Click on the checkbox & Click on Customize installation.Step 4: Click on Next.Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 4: Click on Next.Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 4: Click on Next.Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Hence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Hence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
</code>```

Body:
I am trying to extract text data from website using regex but problem is it is not completely extracting. I am following this tutorial: https://pythonprogramming.net/parse-website-using-regular-expressions-urllib
but i dont know where i am wrong. The website i am extracting text from is http://www.sanfoundry.com/c-programming-questions-answers-variable-names-1/ and its relevant sublinks as well.

Code:

import urllib2
from urllib2 import Request
import re
#url = "http://www.tutorialspoint.com/cplusplus/cpp_basic_syntax.htm"
url = "http://www.sanfoundry.com/c-programming-questions-answers-variable-names-1/"

req = Request(url)
resp = urllib2.urlopen(req)
respData = resp.read()

regex = '
(.*?)<\/p>'

paragraphs = re.findall(regex,str(respData))

for eachP in paragraphs:
    print(eachP)

any idea ???

Body:
I found a good one for extracting paragraphs from How to Scrape Paragraphs using Python?

With example:

# import module
from bs4 import BeautifulSoup

# Html doc
html_doc = """
<html>
<head>
<title>Geeks</title>
</head>
<body>
<h2>paragraphs</h2>

<p>Welcome geeks.</p>

<p>Hello geeks.</p>

</body>
</html>
"""
soup = BeautifulSoup(html_doc, 'html.parser')

# traverse paragraphs from soup
for data in soup.find_all("p"):
    print(data.get_text())

Output:

Welcome geeks.
Hello geeks.

Extract Paragraphs from the given URL:

# import module
import requests
import pandas as pd
from bs4 import BeautifulSoup

# link for extract html data
def getdata(url):
    r = requests.get(url)
    return r.text

htmldata = getdata("https://www.geeksforgeeks.org/")
soup = BeautifulSoup(htmldata, 'html.parser')
data = ''
for data in soup.find_all("p"):
    print(data.get_text())

Output:

Multiple Urls:

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re

Newlines = re.compile(r'[\r\n]\s+')

def getPageText(url):
    # given a url, get page content
    data = urlopen(url).read()
    # parse as html structured document
    soup = BeautifulSoup(data, 'html.parser')
    # kill javascript content
    for s in soup(["script", "style"]):
        s.replaceWith('')
    # find body and extract text
    for p in soup.find_all('p'):
        txt = print(p.get_text())
    # remove multiple linebreaks and whitespace
    return Newlines.sub('\n', txt)

def main():
    urls = [
        'https://www.geeksforgeeks.org/how-to-download-install-nltk-on-windows/',
        'https://www.geeksforgeeks.org/how-to-scrape-paragraphs-using-python/'
    ]
    txt = [getPageText(url) for url in urls]
    for t in txt:
        print(t)

if __name__=="__main__":
    main()

Output:

NLTK is Natural Language Tool Kit. It is used to build python programming. It helps to work with human languages data. It gives a very easy user interface. It supports classification, steaming, tagging, etc.Installing NLTK on Windows using PIP:In windows, we first have to install the python current version. Then we have to install pip with it. Without pip, NLTK can not be installed.Step 1: Browse to the official site of python by clicking this link.Step 2: Move the cursor to the Download button & then click on the latest python version.Step 3: Open the downloaded file. Click on the checkbox & Click on Customize installation.Step 4: Click on Next.Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
In windows, we first have to install the python current version. Then we have to install pip with it. Without pip, NLTK can not be installed.Step 1: Browse to the official site of python by clicking this link.Step 2: Move the cursor to the Download button & then click on the latest python version.Step 3: Open the downloaded file. Click on the checkbox & Click on Customize installation.Step 4: Click on Next.Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 1: Browse to the official site of python by clicking this link.Step 2: Move the cursor to the Download button & then click on the latest python version.Step 3: Open the downloaded file. Click on the checkbox & Click on Customize installation.Step 4: Click on Next.Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 2: Move the cursor to the Download button & then click on the latest python version.Step 3: Open the downloaded file. Click on the checkbox & Click on Customize installation.Step 4: Click on Next.Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 2: Move the cursor to the Download button & then click on the latest python version.Step 3: Open the downloaded file. Click on the checkbox & Click on Customize installation.Step 4: Click on Next.Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 3: Open the downloaded file. Click on the checkbox & Click on Customize installation.Step 4: Click on Next.Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 3: Open the downloaded file. Click on the checkbox & Click on Customize installation.Step 4: Click on Next.Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 4: Click on Next.Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 4: Click on Next.Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 5: Click on Install.Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 6: Wait till installation finish.Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 7: Click on Close.Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 8: Open Command Prompt & execute the following commands:python --version
pip --version
pip install nltkHence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Hence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Hence, NLTK installation will start.Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Step 9: Then you can see the successfully installed message.Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Hence NLTK installation is successfulMy Personal Notes
arrow_drop_upSave
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.


答:
You're only missing closing " and \n for readability:

```<code>printf("Dennis Ritchie said:\n\"The only way to learn a new programming language is by writing programs in it.\"\n");
</code>```

Title: printf statement including quotes and escape sequence

Body:
You're only missing closing " and \n for readability:

printf("Dennis Ritchie said:\n\"The only way to learn a new programming language is by writing programs in it.\"\n");


问:
SQL to return all the rows of a table as a single string
I'm using MySQL, and I have a table with 3 records:

```<code>id, name
1, bill
2, joe
3, sam
</code>```

I'm looking for a single SQL statement that will return all the ids as a CSV string:

```<code>'1,2,3'
</code>```

This gives me multiple records:

```<code>select id from tablename
</code>```

I'm thinking that I need to use version of the concat function in MySQL, but it's not clear what.

```<code>select concat(id) from tablename
</code>```

But this returns the same as the original (multiple records). Is there an easy way to "collapse" the records to a single row?

Please note that I just need a single string of the "id" column values, not any other columns.

答:
You need GROUP_CONCAT():

```<code>SELECT GROUP_CONCAT(id)
FROM tablename;
</code>```

or:

```<code>SELECT GROUP_CONCAT(id ORDER BY id)
FROM tablename;
</code>```

Body:
I'm using MySQL, and I have a table with 3 records:

id, name
1, bill
2, joe
3, sam

I'm looking for a single SQL statement that will return all the ids as a CSV string:

'1,2,3'

This gives me multiple records:

select id from tablename

I'm thinking that I need to use version of the concat function in MySQL, but it's not clear what.

select concat(id) from tablename

But this returns the same as the original (multiple records). Is there an easy way to "collapse" the records to a single row?

Please note that I just need a single string of the "id" column values, not any other columns.

Body:
You need GROUP_CONCAT():

SELECT GROUP_CONCAT(id)
FROM tablename;

or:

SELECT GROUP_CONCAT(id ORDER BY id)
FROM tablename;


答:
rows2 is the result of a .fetchall() which means that it is a list of pyodbc.Row objects. Such a list is suitable without modification for use as parameters for a subsequent .executemany() operation. In other words, don't mess with rows2; just pass it to the .executemany() for your INSERT:

if len(rows2):
    crsr.executemany(
        "INSERT INTO duplicates (tokn_type_cd, tokn_val_tx, pg_duplicate_ct) VALUES (?, ?, ?)",
        rows2
    )
cnxn.commit()
```

Your initial attempt failed because [str(r) for r in rows2] returns a list of string objects (scalars) instead of a list of Row objects.

Title: TypeError: (‘Params must be in a list, tuple, or Row’, ‘HY000’) Error on pyodbc

Body:
rows2 is the result of a .fetchall() which means that it is a list of pyodbc.Row objects. Such a list is suitable without modification for use as parameters for a subsequent .executemany() operation. In other words, don't mess with rows2; just pass it to the .executemany() for your INSERT:

if len(rows2):
    crsr.executemany(
        "INSERT INTO duplicates (tokn_type_cd, tokn_val_tx, pg_duplicate_ct) VALUES (?, ?, ?)",
        rows2
    )
cnxn.commit()

Your initial attempt failed because [str(r) for r in rows2] returns a list of string objects (scalars) instead of a list of Row objects.


问:
How to eval string/convert string to Expr
Is there a method to convert a string to Expr? I tried the following but it doesn't work:</p>

```<code>julia> convert(Expr, "a=2")
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Expr
This may have arisen from a call to the constructor Expr(...),
since type constructors fall back to convert methods.

julia> Expr("a=2")
ERROR: TypeError: Expr: expected Symbol, got String
 in Expr(::Any) at ./boot.jl:279
</code>```

答:
parse doesn't work here anymore. Now you need Meta.parse:

```<code>eval(Meta.parse("a = 2"))
</code>```

(As pointed out by Markus Hauschel in a comment.)

Body:
Is there a method to convert a string to Expr? I tried the following but it doesn't work:

julia> convert(Expr, "a=2")
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Expr
This may have arisen from a call to the constructor Expr(...),
since type constructors fall back to convert methods.

julia> Expr("a=2")
ERROR: TypeError: Expr: expected Symbol, got String
 in Expr(::Any) at ./boot.jl:279

Body:
parse doesn't work here anymore. Now you need Meta.parse:

eval(Meta.parse("a = 2"))

(As pointed out by Markus Hauschel in a comment.)


问:
How to format array of date
I am getting an array of dates in this format

```<code>Sat Feb 12 2022 01:00:00 GMT+0100 (West Africa Standard Time),Sun Feb 13 2022 01:00:00 GMT+0100 (West Africa Standard Time),Mon Feb 14 2022 01:00:00 GMT+0100 (West Africa Standard Time)
</code>```

But i want it in a format like this

```<code>Sat, Feb 12, 2022,
Sun, Feb 13, 2022,
Mon, Feb 14, 2022
</code>```

This is the code that output my date

```<code>function dateRange(startDate, endDate, steps = 1) {
  const dateArray = [];
  let currentDate = new Date(startDate);

  while (currentDate <= new Date(endDate)) {
    dateArray.push(new Date(currentDate));
    currentDate.setUTCDate(currentDate.getUTCDate() + steps);
  }

  return dateArray;
}
var currD = new Date().toISOString().slice(0,10);

function addDays(date, days) {
  var result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}
 const futureDate = addDays(currD, 3);

const dates = dateRange(currD, futureDate);
console.log(dates);
alert(dates)
</code>```

答:
Try this

const dates = [
    'Sat Feb 12 2022 01:00:00 GMT+0100 (West Africa Standard Time)',
    'Sun Feb 13 2022 01:00:00 GMT+0100 (West Africa Standard Time)',
    'Mon Feb 14 2022 01:00:00 GMT+0100 (West Africa Standard Time)',
];

const formatted = dates.map((date) => new Date(date).toDateString());

console.log(formatted);```

Title: How to format array of date

Body:
I am getting an array of dates in this format

Sat Feb 12 2022 01:00:00 GMT+0100 (West Africa Standard Time),Sun Feb 13 2022 01:00:00 GMT+0100 (West Africa Standard Time),Mon Feb 14 2022 01:00:00 GMT+0100 (West Africa Standard Time)

But i want it in a format like this

Sat, Feb 12, 2022,
Sun, Feb 13, 2022,
Mon, Feb 14, 2022

This is the code that output my date

function dateRange(startDate, endDate, steps = 1) {
  const dateArray = [];
  let currentDate = new Date(startDate);

  while (currentDate <= new Date(endDate)) {
    dateArray.push(new Date(currentDate));
    currentDate.setUTCDate(currentDate.getUTCDate() + steps);
  }

  return dateArray;
}
var currD = new Date().toISOString().slice(0,10);

function addDays(date, days) {
  var result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}
 const futureDate = addDays(currD, 3);

const dates = dateRange(currD, futureDate);
console.log(dates);
alert(dates)


问:
Why doesn't GridSearchCV have best_estimator_ even after fitting?
I am learning about multiclass classification using scikit learn.
My goal is to develop a code which tries to include all the possible metrics needed to evaluate the classification.
This is my code:

```<code>from sklearn.model_selection import GridSearchCV
from sklearn.metrics import make_scorer, precision_score, recall_score, f1_score

param_grid = [
    {'estimator__randomforestclassifier__n_estimators': [3, 10], 'estimator__randomforestclassifier__max_features': [2]},
#    {'estimator__randomforestclassifier__bootstrap': [False], 'estimator__randomforestclassifier__n_estimators': [3, 10], 'estimator__randomforestclassifier__max_features': [2, 3, 4]}
]

rf_classifier = OneVsRestClassifier(
    make_pipeline(RandomForestClassifier(random_state=42))
)

scoring = {'accuracy': make_scorer(accuracy_score),
           'precision_macro': make_scorer(precision_score, average = 'macro'),
           'recall_macro': make_scorer(recall_score, average = 'macro'),
           'f1_macro': make_scorer(f1_score, average = 'macro'),
           'precision_micro': make_scorer(precision_score, average = 'micro'),
           'recall_micro': make_scorer(recall_score, average = 'micro'),
           'f1_micro': make_scorer(f1_score, average = 'micro'),
           'f1_weighted': make_scorer(f1_score, average = 'weighted')}

grid_search = GridSearchCV(rf_classifier, param_grid=param_grid, cv=2,
scoring=scoring, refit=False)
grid_search.fit(X_train_prepared, y_train)
</code>```

However when I try to find out the best estimator, I get the following error message:

```<code>print(grid_search.best_params_)
print(grid_search.best_estimator_)

AttributeError: 'GridSearchCV' object has no attribute 'best_params_'
</code>```

Question: How is it possible that even after fitting the model I do not get the best estimator?
I noticed that if I set refit="some_of_the_metrics", I get an estimator but I do not understand why I should use it since it would fit the method to optimize a metric instead of all of them.
Therefore, how can I get the best estimator for all the scores? And what is the the point of refit?

Note: I tried to read the documentation but it still does not make sense to me.

答:
The point of refit is that the model will be refitted using the best parameter set found before and the entire dataset. To find the best parameters, cross-validation is used which means that the dataset is always split into a training and a validation set, i.e. not the entire dataset is used for training here.

When you define multiple metrics, you have to tell scikit-learn how it should determine what best means for you. For convenience, you can just specify any of your scorers to be used as the decider so to say. In that case, the parameter set that maximizes this metric will be used for refitting.

If you want something more sophisticated, like taking the parameter set that returned the highest mean of all scorers, you have to pass a function to refit that given all the created metrics returns the index of the corresponding best parameter set. This parameter set will then be used to refit the model.

Those metrics will be passed as a dictionary of strings as keys and NumPy arrays as values. Those NumPy arrays have as many entries as parameter sets that have been evaluated. You find a lot of things in there. What is probably the most relevant is mean_test_*scorer-name*. Those arrays contain for each tested parameter set the mean scorer-name-scorer computed across the cv splits.

In code, to get the index of the parameter set, that returns the highest mean across all scorers, you can do the following

def find_best_index(eval_results: dict[str, np.array]) -> int:
    # returns a n-scorers x n-parameter-set dimensional array
    means_of_splits = np.array(
        [values for name, values in eval_results.items() if name.startswith('mean_test')]
    )
    # this is a n-parameter-set dimensional vector
    mean_of_all_scores = np.mean(means_of_splits, axis=0)
    # get index of maximum value which corresponds to the best parameter set
    return np.argmax(mean_of_all_scores)

grid_search = GridSearchCV(
    rf_classifier, param_grid=param_grid, cv=2, scoring=scoring, refit=find_best_index
)
grid_search.fit(X_train_prepared, y_train)

```

Body:
I am learning about multiclass classification using scikit learn.
My goal is to develop a code which tries to include all the possible metrics needed to evaluate the classification.
This is my code:

from sklearn.model_selection import GridSearchCV
from sklearn.metrics import make_scorer, precision_score, recall_score, f1_score

param_grid = [
    {'estimator__randomforestclassifier__n_estimators': [3, 10], 'estimator__randomforestclassifier__max_features': [2]},
#    {'estimator__randomforestclassifier__bootstrap': [False], 'estimator__randomforestclassifier__n_estimators': [3, 10], 'estimator__randomforestclassifier__max_features': [2, 3, 4]}
]

rf_classifier = OneVsRestClassifier(
    make_pipeline(RandomForestClassifier(random_state=42))
)

scoring = {'accuracy': make_scorer(accuracy_score),
           'precision_macro': make_scorer(precision_score, average = 'macro'),
           'recall_macro': make_scorer(recall_score, average = 'macro'),
           'f1_macro': make_scorer(f1_score, average = 'macro'),
           'precision_micro': make_scorer(precision_score, average = 'micro'),
           'recall_micro': make_scorer(recall_score, average = 'micro'),
           'f1_micro': make_scorer(f1_score, average = 'micro'),
           'f1_weighted': make_scorer(f1_score, average = 'weighted')}

grid_search = GridSearchCV(rf_classifier, param_grid=param_grid, cv=2,
scoring=scoring, refit=False)
grid_search.fit(X_train_prepared, y_train)

However when I try to find out the best estimator, I get the following error message:

print(grid_search.best_params_)
print(grid_search.best_estimator_)

AttributeError: 'GridSearchCV' object has no attribute 'best_params_'

Question: How is it possible that even after fitting the model I do not get the best estimator?
I noticed that if I set refit="some_of_the_metrics", I get an estimator but I do not understand why I should use it since it would fit the method to optimize a metric instead of all of them.
Therefore, how can I get the best estimator for all the scores? And what is the the point of refit?

Note: I tried to read the documentation but it still does not make sense to me.


问:
Date '2017/02/23' not recognized in SnowFlake
I have a csv with example data as:

61| MXN| Mexican Peso| 2017/02/23

I'm trying to insert this into snowflake using the following commands:

```<code>create or replace stage table_stage file_format = (TYPE=CSV,ENCODING = 'WINDOWS1252');

copy into table from @table_stage/table.csv.gz file_format = (TYPE=CSV FIELD_DELIMITER='|' error_on_column_count_mismatch=false, ENCODING = 'WINDOWS1252');

put file://table.csv @table_stage auto_compress=true
</code>```

But I get the error as

Date '2017/02/23' not recognized

Using alter session set date_input_format = 'YYYY-DD-MM' to change the date format fixes it.

But what can I add in the create stage or the copy command itself to change the date format?

答:
Snowflake has session parameter DATE_INPUT_FORMAT that control over the input format for DATE data type.

The default value is AUTO specifies that Snowflake attempts to automatically detect the format of dates stored in the system during the session meaning the COPY INTO
 command attempts to match all date strings in the staged data files with one of the formats listed in Supported Formats for AUTO Detection.

To guarantee correct loading of data, Snowflake strongly recommends explicitly setting the file format options for data loading (as explain in documentation)

To solve your issue you need to set the DATE_INPUT_FORMAT parameter with the expected format of dates in your staged files.

Body:
I have a csv with example data as:

61| MXN| Mexican Peso| 2017/02/23

I'm trying to insert this into snowflake using the following commands:

create or replace stage table_stage file_format = (TYPE=CSV,ENCODING = 'WINDOWS1252');

copy into table from @table_stage/table.csv.gz file_format = (TYPE=CSV FIELD_DELIMITER='|' error_on_column_count_mismatch=false, ENCODING = 'WINDOWS1252');

put file://table.csv @table_stage auto_compress=true

But I get the error as

Date '2017/02/23' not recognized

Using alter session set date_input_format = 'YYYY-DD-MM' to change the date format fixes it.

But what can I add in the create stage or the copy command itself to change the date format?

Body:
Snowflake has session parameter DATE_INPUT_FORMAT that control over the input format for DATE data type.

The default value is AUTO specifies that Snowflake attempts to automatically detect the format of dates stored in the system during the session meaning the COPY INTO <table> command attempts to match all date strings in the staged data files with one of the formats listed in Supported Formats for AUTO Detection.

To guarantee correct loading of data, Snowflake strongly recommends explicitly setting the file format options for data loading (as explain in documentation)

To solve your issue you need to set the DATE_INPUT_FORMAT parameter with the expected format of dates in your staged files.


问:
'ts-node' is not recognized as an internal or external command, operable program or batch file
I'm getting error in my Vs Code terminal and command prompt that 'ts-node' is not recognized as an internal or external command, operable program or batch file. while i'm trying the start command in the terminal npm run dev and i have added my package.json file also.

```<code>{
"name": "tsnode",
"version": "1.0.0",
"description": "ts-node experiment.",
"scripts": {
    "dev": "nodemon --exec 'ts-node --cache-directory .tscache' ./server.ts",
    "start": "ts-node --fast ./server.ts"
},
"author": "Mugesh",
"license": "ISC",
"dependencies": {
    "@types/body-parser": "^1.16.3",
    "@types/chalk": "^0.4.31",
    "@types/express": "^4.0.35",
    "@types/node": "^7.0.18",
    "body-parser": "^1.17.1",
    "chalk": "^1.1.3",
    "express": "^4.15.2",
    "nodemon": "^1.11.0",
    "ts-node": "^3.0.4",
    "typescript": "^2.3.4"
}
</code>```

}

答:
yarn add -D ts-node

"scripts": {
    "start": "ts-node src/index.ts"
}```

'yarn start' now works

Body:
I'm getting error in my Vs Code terminal and command prompt that 'ts-node' is not recognized as an internal or external command, operable program or batch file. while i'm trying the start command in the terminal npm run dev and i have added my package.json file also.

{
"name": "tsnode",
"version": "1.0.0",
"description": "ts-node experiment.",
"scripts": {
    "dev": "nodemon --exec 'ts-node --cache-directory .tscache' ./server.ts",
    "start": "ts-node --fast ./server.ts"
},
"author": "Mugesh",
"license": "ISC",
"dependencies": {
    "@types/body-parser": "^1.16.3",
    "@types/chalk": "^0.4.31",
    "@types/express": "^4.0.35",
    "@types/node": "^7.0.18",
    "body-parser": "^1.17.1",
    "chalk": "^1.1.3",
    "express": "^4.15.2",
    "nodemon": "^1.11.0",
    "ts-node": "^3.0.4",
    "typescript": "^2.3.4"
}

}

Body:
yarn add -D ts-node

"scripts": {
    "start": "ts-node src/index.ts"
}

'yarn start' now works


问:
AJAX - Update div content - Going backwards?
A current web based tool is template driven, rendering HTML and serving it a page at a time. I've been experimenting with using more modern tools such as ajax to load page contents, purely what changes between pages.

One problem I've discovered in testing is that if I a 'back' link (which calls JavaScript:history.go(-1); ) as with out current tool it doesn't work. In our previous system such links take you to the previous page (where one existed).

In the test system I'm updating div content using jQuerys ajax.

Does anyone have a strategy for working around this with dynamic content, providing a link which takes you back one step in a hierarchy?

答:
The back link won't work because you are not loading the entire page (the URL does not change), but this is obvious.

Try out saving the user's history in a javascript-cookie and then just loading the page listed one unit above. That way, clicking on "back" wouldn't also allow to get back to an extern page they browsed before, what javascript:history.back() does.


问:
Random access for HashMap keys
I need to randomly access keys in a HashMap. Right now, I am using Set's toArray() method on the Set that HashMap's keySet() returns, and casting it as a String[] (my keys are Strings). Then I use Random to pick a random element of the String array.

```<code>public String randomKey() {
    String[] keys = (String[]) myHashMap.keySet().toArray();
    Random rand = new Random();
    return keyring[rand.nextInt(keyring.length)];
}
</code>```

It seems like there ought to be a more elegant way of doing this!
I've read the following post, but it seems even more convoluted than the way I'm doing it. If the following solution is the better, why is that so?Selecting random key and value sets from a Map in Java

答:
If you really just want any element of a set, this will work fine.

```<code>String s = set.iterator().next();
</code>```

If you are unsure whether there is an element in the set, use:

```<code>String s;
Iterator<String> it = set.iterator();
if (it.hasNext()) {
    s = it.next();
}
else {
    // set was empty
}
</code>```

Title: Random access for HashMap keys

Body:
I need to randomly access keys in a HashMap. Right now, I am using Set's toArray() method on the Set that HashMap's keySet() returns, and casting it as a String[] (my keys are Strings). Then I use Random to pick a random element of the String array.

public String randomKey() {
    String[] keys = (String[]) myHashMap.keySet().toArray();
    Random rand = new Random();
    return keyring[rand.nextInt(keyring.length)];
}

It seems like there ought to be a more elegant way of doing this!
I've read the following post, but it seems even more convoluted than the way I'm doing it. If the following solution is the better, why is that so?Selecting random key and value sets from a Map in Java

Body:
If you really just want any element of a set, this will work fine.

String s = set.iterator().next();

If you are unsure whether there is an element in the set, use:

String s;
Iterator<String> it = set.iterator();
if (it.hasNext()) {
    s = it.next();
}
else {
    // set was empty
}


问:
How to access WEB API on .NET Core from the outside network?
I want to access my API from the outside ?

On the local machine I access my API like this:

```<code>https://localhost:44377/api/stations
</code>```

So my IP address for example is: 186.143.119.43

What do I need to change to see it through external networks?

This is my launchSettings.json file:

```<code>    {
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:51429",
      "sslPort": 44377
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "WebAPI": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
</code>```

How to access this API from outside network ?

答:
The default binding of the Kestral web server only binds to the localhost, and it is not be allowed for the public access. However, you can override this setting by sending a custom URL value from the command line:

dotnet run --urls http://0.0.0.0:8080

You can also configure the custom URL value directly in the Program.cs file:

```<code>public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder
                .UseUrls("http://0.0.0.0:8080")
                .UseStartup<Startup>();
            });
 }
</code>```

p.s. The above approaches work only when your firewall allows access to the configured TCP port(8080).

Body:
I want to access my API from the outside ?

On the local machine I access my API like this:

https://localhost:44377/api/stations

So my IP address for example is: 186.143.119.43

What do I need to change to see it through external networks?

This is my launchSettings.json file:

    {
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:51429",
      "sslPort": 44377
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "WebAPI": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

How to access this API from outside network ?

Body:
The default binding of the Kestral web server only binds to the localhost, and it is not be allowed for the public access. However, you can override this setting by sending a custom URL value from the command line:

dotnet run --urls http://0.0.0.0:8080

You can also configure the custom URL value directly in the Program.cs file:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder
                .UseUrls("http://0.0.0.0:8080")
                .UseStartup<Startup>();
            });
 }

p.s. The above approaches work only when your firewall allows access to the configured TCP port(8080).


问:
Can C++ return different memory address for same variable with & operator?
If two or more processor cores copy a variable into their local cache, how C++ handles that? Does &var return a different memory address depending on which core executed that instruction?</p>

答: The address you get is the logical address in RAM not the address in cache. Its the cache controllers job to 'know' what RAM address are in what parts of its caches</p>


问:
Azure DevOps - Automatic merge after deployment
We have a development branch that is fed from feature branches through pull requests. After merge a build occurs and the artifact created triggers the release pipeline with some deployments happening automatically and others happening after manual approval.

After the approval happens for production, and after successful deployment, we would like to merge the PR that was was merge to develop to our main branch. I was wondering if this could be achieved automatically from the pipeline.

Note that not all the PR are going to make its way to production and the latest may not be the one being deployed in production.

答:
Assuming that you must complete the PR to trigger the CI build and release pipelines, you won't be able to re-use the existing PR to merge into another branch because PRs are specific to branches and once completed they can't be re-opened.

In theory, you could add logic to your release pipeline to create a new PR after successfully deploying into production but this is dangerous because PRs are based on branches and not individual commits. So if the develop branch changes while you're deploying into production the new PR would contain changes that haven't been deployed. If you have a small team and the number of PullRequests are low, this might not be a problem for you.

However, if you have a large team and dozens of pull-requests a day, you might benefit by adjusting your a gitflow branching strategy. In that model you would create a release branch and deploy that into other environments. Creating the pull request at the end of that pipeline flow makes total sense because you're deploying and merging a static branch.

For example, you could add a step in your release pipeline to create the PR using the Azure CLI:

```<code>$pr = az repos pr create `
         --source-branch develop `
         --target-branch main `
         --title 'merge $(Build.BuildId) into main' |
      ConvertFrom-Json
Write-Host 'Created PR $($pr.pullRequestId)'
</code>```

There's another question where they're doing something similar.

Alternatively, look at the "Github flow" model. They use a trunk-based branching strategy where the PR is king and changes in the PR ultimately go to production or they don't get merged. The GitHub team had a model where they concentrated on a single PR at a time with a flow that looked like:

Designate a PR as a candidate for production

Automation would lock the target branch and create a temporary merge of the PR and the target branch

Automation would build this branch and deploy it to various environments.

Upon successful build into the environment, the automation would unlock the target branch and complete the PR.

It's worth pointing out that Azure DevOps does support triggering Releases from Pull Requests, and each PR-triggered build is a temporary merge of the target branch, so you could create a release and deploy it into your environments with your approval gates. You could add automation to your release to approve the PR:

```<code>az repos pr set-vote --id $pr.pullRequestId --vote approve
</code>```

Body:
Assuming that you must complete the PR to trigger the CI build and release pipelines, you won't be able to re-use the existing PR to merge into another branch because PRs are specific to branches and once completed they can't be re-opened.

In theory, you could add logic to your release pipeline to create a new PR after successfully deploying into production but this is dangerous because PRs are based on branches and not individual commits. So if the develop branch changes while you're deploying into production the new PR would contain changes that haven't been deployed. If you have a small team and the number of PullRequests are low, this might not be a problem for you.

However, if you have a large team and dozens of pull-requests a day, you might benefit by adjusting your a gitflow branching strategy. In that model you would create a release branch and deploy that into other environments. Creating the pull request at the end of that pipeline flow makes total sense because you're deploying and merging a static branch.

For example, you could add a step in your release pipeline to create the PR using the Azure CLI:

$pr = az repos pr create `
         --source-branch develop `
         --target-branch main `
         --title 'merge $(Build.BuildId) into main' |
      ConvertFrom-Json
Write-Host 'Created PR $($pr.pullRequestId)'

There's another question where they're doing something similar.

Alternatively, look at the "Github flow" model. They use a trunk-based branching strategy where the PR is king and changes in the PR ultimately go to production or they don't get merged. The GitHub team had a model where they concentrated on a single PR at a time with a flow that looked like:

Designate a PR as a candidate for production

Automation would lock the target branch and create a temporary merge of the PR and the target branch

Automation would build this branch and deploy it to various environments.

Upon successful build into the environment, the automation would unlock the target branch and complete the PR.

It's worth pointing out that Azure DevOps does support triggering Releases from Pull Requests, and each PR-triggered build is a temporary merge of the target branch, so you could create a release and deploy it into your environments with your approval gates. You could add automation to your release to approve the PR:

az repos pr set-vote --id $pr.pullRequestId --vote approve


问:
User specific global variable in Node.js
my program looks as follows:

```<code>var globVar=[];

function1(usr){
   //calculations with globVar
}

function2(usr){
   //calculations with globVar
}

app.post('/', function(req, res) {
    var formString = req.body.filter1;
    globVar.push(formString);
    usr= req.connection.user;
    function1(usr);
    function2(usr);
    res.redirect('/');
});
</code>```

req.connection.user comes from  nodeSSPI module. I need to make this globVar user specific so it doesn't mixed up when users runs this app concurrently. Now it works well but only for single user :)

Thank you for your consideration on this matter.

答:
I've been looking at what seems like the same problem and my solution was to simply use cookies, and set a variable within the cookies client-side.

In my case the problem was setting language choice permanently for each user and that was simplest.

This guide helps:
https://www.tutorialspoint.com/expressjs/expressjs_cookies.htm

Body:
my program looks as follows:

var globVar=[];

function1(usr){
   //calculations with globVar
}

function2(usr){
   //calculations with globVar
}

app.post('/', function(req, res) {
    var formString = req.body.filter1;
    globVar.push(formString);
    usr= req.connection.user;
    function1(usr);
    function2(usr);
    res.redirect('/');
});

req.connection.user comes from  nodeSSPI module. I need to make this globVar user specific so it doesn't mixed up when users runs this app concurrently. Now it works well but only for single user :)

Thank you for your consideration on this matter.


答: Just set the date format in the file format: https://docs.snowflake.com/en/sql-reference/sql/create-file-format.html</p>

Title: Date '2017/02/23' not recognized in SnowFlake


问:
FindFirst with Date value
I'm using a splitform to navigate information and I have a command button that selects a record based on today's date.

Private Sub FindDate_Click()
  TodayDate = DateTime.Date
     Me![Start Date].SetFocus
     DoCmd.FindRecord TodayDate
End Sub
```
<p>I discovered that wouldn't work if the date didn't exist in my recordset.</p>
<p>I modified the code but I get</p>
<blockquote>
<p>"Run-time error '3251': Operation is not supported for this type of
object."</p>
</blockquote>
<p>The new line of code is</p>
<pre class="lang-vb prettyprint-override"><code>Dim CurrDB As DAO.Database
Dim CurrRec As DAO.Recordset

Set CurrDB = CurrentDb
Set CurrRec = CurrDB.OpenRecordset("AIM")

TodayDate = DateTime.Date

StrSQl = "[Start Date] = #" & TodayDate & "#"

CurrRec.FindFirst (StrSQl)
</code>```

I'm trying to use that FindFirst function to tell me if there is a record that matches my criteria and if not I was going to -1 to TodayDate and check again until I get a record to lock onto.

答:
Assuming you have your records sorted by date, use the RecordsetClone:

Private Sub FindDate_Click()

    Dim Records As DAO.Recordset

    Set Records = Me.RecordsetClone

    If Records.RecordCount > 0 Then
        Records.FindFirst "[Start Date] <= Date()"
        If Not Records.NoMatch Then
            Me.Bookmark = Records.Bookmark
            Me![Start Date].SetFocus
        End If
    End If
    Records.Close

End Sub
```

Title: FindFirst with Date value

Body:
I'm using a splitform to navigate information and I have a command button that selects a record based on today's date.

Private Sub FindDate_Click()
  TodayDate = DateTime.Date
     Me![Start Date].SetFocus
     DoCmd.FindRecord TodayDate
End Sub

I discovered that wouldn't work if the date didn't exist in my recordset.

I modified the code but I get

"Run-time error '3251': Operation is not supported for this type of
object."

The new line of code is

Dim CurrDB As DAO.Database
Dim CurrRec As DAO.Recordset

Set CurrDB = CurrentDb
Set CurrRec = CurrDB.OpenRecordset("AIM")

TodayDate = DateTime.Date

StrSQl = "[Start Date] = #" & TodayDate & "#"

CurrRec.FindFirst (StrSQl)

I'm trying to use that FindFirst function to tell me if there is a record that matches my criteria and if not I was going to -1 to TodayDate and check again until I get a record to lock onto.


问:
syntax explanation for copying object array and add new property
Can someone explain to me why this is the only version I've tried that works for copying state with es6 and adding another field, out of the other ways tried that are listed below? :

```<code>const values = [{key: "1", val: "one"}, {key: "2", val: "two"}];

var works = values.map(v => {
    return {
       ...v,
       extra: "stuff"
   }
})
</code>```

And all of these produce these errors:

```<code>//Unexpected token '...'
var notWorks1 = values.map(v => ...v, extra: "stuff");

// Rest parameter must be last formal parameter
var notWorks2 = values.map(v => {...v, extra: "stuff"})

// Rest parameter must be last formal parameter
var notWorks3 = values.map(v => {
  {
   ...v,
   extra: "stuff"
  }
})

// unexpected token 'return'
var notWorks4 = values.map(v =>
   return {
    ...v,
    extra: "stuff"
   }
)
// unexpected 'return'
var notWorks5 = values.map(v => return ...v, extra: "stuff");
</code>```

I thought the arrow was implicit return (see first 3 attempts).

Is that first way the only syntax that can be used? If there are any others, I'd like to know as I'm trying to practice and learn multiple options.. and I want the most terse, smallest option (one line).

答:
The answer of @Bulent is correct, but I'd like to add some more information:

```<code>//Unexpected token '...'
var notWorks1 = values.map(v => ...v, extra: "stuff");
</code>```

This syntax doesn't make sense. As @Bulent says, the spread syntax (...) can only be used inside object literals ({ ...v }), array literals ([ ...v ], only if v is an array) or function calls (f( ...v ), again only if v is an array).

```<code>// Rest parameter must be last formal parameter
var notWorks2 = values.map(v => {...v, extra: "stuff"})
</code>```

The problem here is that in JavaScript braces ({, }) have two functions: either for object literals, as you are trying to use here, but also for code blocks, for example around the body of a function. In this case JavaScript is expecting the braces to be the body of the arrow function. What needs to be done is change the context so that an expression (which an object literal is) is expected. This can for example be done by putting the object literal in round brackets:

```<code>var notWorks2 = values.map(v => ({...v, extra: "stuff"}))
</code>```

```<code>// Rest parameter must be last formal parameter
var notWorks3 = values.map(v => {
  {
   ...v,
   extra: "stuff"
  }
})
</code>```

Again the first pair of braces is consider a (function body) block, and inside a block braces are again expected to be another block. This time wrapping the object literal in round brackets wouldn't do anything, because an expression alone does nothing inside a function body. Instead you have to use return.

```<code>// unexpected token 'return'
var notWorks4 = values.map(v =>
   return {
    ...v,
    extra: "stuff"
   }
)
</code>```

Arrow functions can consist of either an expression (no braces) or a function body block (with braces). A return statement isn't an expression, so this doesn't work. return statements can only be used inside a function body block.

One final point: Avoid using var. It is outdated. Use const or let instead.

Body:
Can someone explain to me why this is the only version I've tried that works for copying state with es6 and adding another field, out of the other ways tried that are listed below? :

const values = [{key: "1", val: "one"}, {key: "2", val: "two"}];

var works = values.map(v => {
    return {
       ...v,
       extra: "stuff"
   }
})

And all of these produce these errors:

//Unexpected token '...'
var notWorks1 = values.map(v => ...v, extra: "stuff");

// Rest parameter must be last formal parameter
var notWorks2 = values.map(v => {...v, extra: "stuff"})

// Rest parameter must be last formal parameter
var notWorks3 = values.map(v => {
  {
   ...v,
   extra: "stuff"
  }
})

// unexpected token 'return'
var notWorks4 = values.map(v =>
   return {
    ...v,
    extra: "stuff"
   }
)
// unexpected 'return'
var notWorks5 = values.map(v => return ...v, extra: "stuff");

I thought the arrow was implicit return (see first 3 attempts).

Is that first way the only syntax that can be used? If there are any others, I'd like to know as I'm trying to practice and learn multiple options.. and I want the most terse, smallest option (one line).

Body:
The answer of @Bulent is correct, but I'd like to add some more information:

//Unexpected token '...'
var notWorks1 = values.map(v => ...v, extra: "stuff");

This syntax doesn't make sense. As @Bulent says, the spread syntax (...) can only be used inside object literals ({ ...v }), array literals ([ ...v ], only if v is an array) or function calls (f( ...v ), again only if v is an array).

// Rest parameter must be last formal parameter
var notWorks2 = values.map(v => {...v, extra: "stuff"})

The problem here is that in JavaScript braces ({, }) have two functions: either for object literals, as you are trying to use here, but also for code blocks, for example around the body of a function. In this case JavaScript is expecting the braces to be the body of the arrow function. What needs to be done is change the context so that an expression (which an object literal is) is expected. This can for example be done by putting the object literal in round brackets:

var notWorks2 = values.map(v => ({...v, extra: "stuff"}))

// Rest parameter must be last formal parameter
var notWorks3 = values.map(v => {
  {
   ...v,
   extra: "stuff"
  }
})

Again the first pair of braces is consider a (function body) block, and inside a block braces are again expected to be another block. This time wrapping the object literal in round brackets wouldn't do anything, because an expression alone does nothing inside a function body. Instead you have to use return.

// unexpected token 'return'
var notWorks4 = values.map(v =>
   return {
    ...v,
    extra: "stuff"
   }
)

Arrow functions can consist of either an expression (no braces) or a function body block (with braces). A return statement isn't an expression, so this doesn't work. return statements can only be used inside a function body block.

One final point: Avoid using var. It is outdated. Use const or let instead.


答:
Use the DATE_FORMAT parameter in file_format condition.
More you can read here: COPY INTO

copy into table
from @table_stage/table.csv.gz
file_format = (TYPE=CSV
               FIELD_DELIMITER='|'
               ERROR_ON_COLUMN_COUNT_MISMATCH = FALSE
               ENCODING = 'WINDOWS1252'
               DATE_FORMAT = 'YYYY/MM/DD');
```


问:
Where do I add repositories in my root-level build.gradle file?
Recently, I updated my Android Studio to Bumblebee(stable version) that was released around 2 weeks back. The structure of the build.gradle(root-level) file seems to have changed a lot since the last version.

I am facing issue in adding dependencies in the root-level build.gradle file.

Here is what I want to add.

in the build.gradle file

答:
I think you should use buildscript instead of allprojects. Found question in stackoverflow which explain difference between buildscript and allprojects What's the difference between buildscript and allprojects in build.gradle?
So I would suggest to try:

```<code>buildscript {
    repositories {
        ...
    }
}

</code>```

Hopefully this will help :)

Body:
I think you should use buildscript instead of allprojects. Found question in stackoverflow which explain difference between buildscript and allprojects What's the difference between buildscript and allprojects in build.gradle?
So I would suggest to try:

buildscript {
    repositories {
        ...
    }
}

Hopefully this will help :)


问:
How do I get the name of the current executable in C#? (.NET 5 edition)
How do I get the name the executable was invoked as (equivalent to C's argv[0])? I actually need to handle somebody renaming the executable and stuff like that.

There's a famous question with lots of answers that don't work. Answers tried:

```<code>System.AppDomain.CurrentDomain.FriendlyName
</code>```

returns the name it was compiled as

```<code>System.Diagnostics.Process.GetCurrentProcess().ProcessName
</code>```

strips extension (ever rename a .exe to a .com?), also sees through symbolic links

```<code>Environment.GetCommandLineArgs()[0]
</code>```

It returns a name ending in .dll, clearly an error.

```<code>Assembly.GetEntryAssembly().Location
</code>```

Returns null

```<code>System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName
</code>```

Returns a .dll name again.

The documentation for .net 5.0 says Environment.GetCommandLineArguments()[0] works; however it doesn't actually work. It somehow sees through symbolic links and returns the real executable name.

What I'm trying to do is link all of our stuff into a single multi-call binary so I can use the .net 5 framework reducer on the resulting binary so I don't have to ship about 30MB of .net 5 framework we're not using. I really don't want to do a platform ladder and P/Invoke a bunch of stuff unless I have to.

I'm after argv[0] directly, not the running process executable name. In the case of symbolic links, these differ.

答:
After watching everything fail, it became necessary to P/Invoke stuff to make this work. While Process.GetCurrentProcess().MainModule?.FileName reliably returns the executable binary (at least when not running under the debugger), this does not provide the command invocation the binary was launched with.

On Windows, GetCommandLine() is P/Invokable and needs only some parsing to get the information. On *n?x, reading /proc/self/cmdline does the same job.

I built a library encapsulating this. https://github.com/joshudson/Emet/tree/master/MultiCall You can find binaries on nuget.org ready to go.

I should have self-answered a long time ago. Better late than never. Nobody seemed to care until now.

Body:
How do I get the name the executable was invoked as (equivalent to C's argv[0])? I actually need to handle somebody renaming the executable and stuff like that.

There's a famous question with lots of answers that don't work. Answers tried:

System.AppDomain.CurrentDomain.FriendlyName

returns the name it was compiled as

System.Diagnostics.Process.GetCurrentProcess().ProcessName

strips extension (ever rename a .exe to a .com?), also sees through symbolic links

Environment.GetCommandLineArgs()[0]

It returns a name ending in .dll, clearly an error.

Assembly.GetEntryAssembly().Location

Returns null

System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName

Returns a .dll name again.

The documentation for .net 5.0 says Environment.GetCommandLineArguments()[0] works; however it doesn't actually work. It somehow sees through symbolic links and returns the real executable name.

What I'm trying to do is link all of our stuff into a single multi-call binary so I can use the .net 5 framework reducer on the resulting binary so I don't have to ship about 30MB of .net 5 framework we're not using. I really don't want to do a platform ladder and P/Invoke a bunch of stuff unless I have to.

I'm after argv[0] directly, not the running process executable name. In the case of symbolic links, these differ.


问:
MongoDB lookup and unwind
I'm trying to perform a look up which works fine and in the correct document as 'metrics'. The lookup document has an array inside of its object called 'history'. I'm trying to unwind that history and perform a facet on it, an aggregation query that I have directly on the lookup collection that works fine.

However when using it here it's not returning anything. Am I unwinding this incorrectly? should it be $metrics.history ?

```<code>{
  from: 'historicprices',
  localField: 'collectibleId',
  foreignField: 'collectibleId',
  pipeline: [
    {$set: {"target-date": "$$NOW"}},
    {$unwind: {path: "$history"}},
    {$facet: {
        "one_day": [
            { $match: { $expr: { $lte: [{$subtract: ["$target-date", "$history.date" ]}, {$multiply: [24,60,60,1000] }] } } },
            { $group: { _id: null, "first": { $first: "$history.value" }, "last": { $last: "$history.value" }, "min-price": {"$min": "$history.value"}, "max-price": {"$max": "$history.value"} } },
            { $unset: ["_id"]}
        ]
        "one_week": [
             { $match: { $expr: { $lte: [{$subtract: ["$target-date", "$history.date" ]}, {$multiply: [7, 24, 60, 60, 1000] }] } } },
             { $group: { _id: null, "min-price": {"$min": "$history.value"}, "first": { $first: "$history.value" }, "last": { $last: "$history.value" }, "max-price": {"$max": "$history.value"} } },
             { $unset: ["_id"]}
        ]
    }}
  ],
  as: 'metrics',
}
</code>```

Thanks

答: Maybe you need to add preserveNullAndEmptyArrays: true to your unwind stage. Otherwise no data will be received if one of the docs doesn't return this field.

Title: MongoDB lookup and unwind

Body:
I'm trying to perform a look up which works fine and in the correct document as 'metrics'. The lookup document has an array inside of its object called 'history'. I'm trying to unwind that history and perform a facet on it, an aggregation query that I have directly on the lookup collection that works fine.

However when using it here it's not returning anything. Am I unwinding this incorrectly? should it be $metrics.history ?

{
  from: 'historicprices',
  localField: 'collectibleId',
  foreignField: 'collectibleId',
  pipeline: [
    {$set: {"target-date": "$$NOW"}},
    {$unwind: {path: "$history"}},
    {$facet: {
        "one_day": [
            { $match: { $expr: { $lte: [{$subtract: ["$target-date", "$history.date" ]}, {$multiply: [24,60,60,1000] }] } } },
            { $group: { _id: null, "first": { $first: "$history.value" }, "last": { $last: "$history.value" }, "min-price": {"$min": "$history.value"}, "max-price": {"$max": "$history.value"} } },
            { $unset: ["_id"]}
        ]
        "one_week": [
             { $match: { $expr: { $lte: [{$subtract: ["$target-date", "$history.date" ]}, {$multiply: [7, 24, 60, 60, 1000] }] } } },
             { $group: { _id: null, "min-price": {"$min": "$history.value"}, "first": { $first: "$history.value" }, "last": { $last: "$history.value" }, "max-price": {"$max": "$history.value"} } },
             { $unset: ["_id"]}
        ]
    }}
  ],
  as: 'metrics',
}

Thanks


问:
quarkus: blocked by CORS policy
although I configured the property file I still get the error:

```<code>blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

I also created a @Provider extending ContainerRequestFilter, but it
  never reaches there

application.properties

```<code># Configuration file
quarkus.http.port=9090
quarkus.http.cors=true
quarkus.http.origins=http://localhost:4200, localhost:9090
quarkus.http.headers=accept, authorization, content-type, x-requested-with
quarkus.http.methods=GET, OPTIONS
</code>```

edited

```<code>17:11:09 WARN  [io.qu.config]] (build-3) Unrecognized configuration key "quarkus.http.methods" provided
17:11:09 WARN  [io.qu.config]] (build-3) Unrecognized configuration key "quarkus.http.headers" provided
17:11:09 WARN  [io.qu.config]] (build-3) Unrecognized configuration key "quarkus.http.origins" provided
</code>```

答:
Try the following code, this worked for me.</p>
```<code><code>
@Provider
public class CorsFilter implements ContainerResponseFilter {
  @Override
  public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
    responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
    responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
    responseContext.getHeade`enter code here`rs().add("Access-Control-Allow-Headers", "*");
    responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    responseContext.getHeaders().add("Access-Control-Max-Age", "100000");
  }
}
</code>
</code>```

Title: quarkus: blocked by CORS policy

Body:
although I configured the property file I still get the error:

blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I also created a @Provider extending ContainerRequestFilter, but it
  never reaches there

application.properties

# Configuration file
quarkus.http.port=9090
quarkus.http.cors=true
quarkus.http.origins=http://localhost:4200, localhost:9090
quarkus.http.headers=accept, authorization, content-type, x-requested-with
quarkus.http.methods=GET, OPTIONS

edited

17:11:09 WARN  [io.qu.config]] (build-3) Unrecognized configuration key "quarkus.http.methods" provided
17:11:09 WARN  [io.qu.config]] (build-3) Unrecognized configuration key "quarkus.http.headers" provided
17:11:09 WARN  [io.qu.config]] (build-3) Unrecognized configuration key "quarkus.http.origins" provided

Body:
Try the following code, this worked for me.

<code>
@Provider
public class CorsFilter implements ContainerResponseFilter {
  @Override
  public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
    responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
    responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
    responseContext.getHeade`enter code here`rs().add("Access-Control-Allow-Headers", "*");
    responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    responseContext.getHeaders().add("Access-Control-Max-Age", "100000");
  }
}
</code>


问:
What does those D3DCOMPILE constants mean?
In the D3DCompiler library there's these flags called "D3DCompile Constants", but the description that Microsoft give us about them is very brief and difficult to have proper understanding of what they do. I wish someone could be able to explain at least what those three mean:</p>
```<code>D3DCOMPILE_PARTIAL_PRECISION, D3DCOMPILE_NO_PRESHADER, D3DCOMPILE_ALL_RESOURCES_BOUND
</code>```

答:
That doc page is pretty poor. It's just the content of D3DCompiler.h comments put into a Markdown page. I'll see about submitting some edits to help it at least a little. Most of these flags are aliases for older D3DX constants as listed on Microsoft Docs where they are better documented at the moment.

UPDATE: The Microsoft Docs page has been updated.

The D3DCOMPILE_PARTIAL_PRECISION flag is equivalent to FXC's /Gpp switch and is an alias for D3DXSHADER_PARTIALPRECISION. It basically treats float32 values as float16 in some cases and enable use of some approximation functions.

The D3DCOMPILE_NO_PRESHADER flag is equivalent to FXC's /Op switch and is an alias for D3DXSHADER_PARTIALPRECISION. This feature is deprecated and only applies to legacy Direct3D 9 era "Effects" (FX). See this Microsoft Docs page for what this was about.

D3DCOMPILE_RESOURCES_MAY_ALIAS, D3DCOMPILE_ENABLE_UNBOUNDED_DESCRIPTOR_TABLES, and D3DCOMPILE_ALL_RESOURCES_BOUND flags are HLSL options for informing the HLSL compiler some assumptions when performing optimizations for DirectX 12 Shader Model 5.1.

Note for DirectX 12, D3DCompile and FXC.EXE are legacy and only support Shader Model 5.1. For DirectX12, you should use Shader Model 6 via the DXIL compiler and DXC.EXE command-line tool. See GitHub.

Body:
In the D3DCompiler library there's these flags called "D3DCompile Constants", but the description that Microsoft give us about them is very brief and difficult to have proper understanding of what they do. I wish someone could be able to explain at least what those three mean:

D3DCOMPILE_PARTIAL_PRECISION, D3DCOMPILE_NO_PRESHADER, D3DCOMPILE_ALL_RESOURCES_BOUND


问:
Can i use ejs for render values from server and use it as an attribute value inside html TAG?
Anyone help me with this? How to do this ?this is my app.js fileThis is my index.ejs file

```<code><h1 style="color:'<%= color %>'">
</code>```

I also tried like this,but did not get result as expected.

答:
i changed color value to "color:red"
and used inside H1 Like this

Now its working.

Body:
Anyone help me with this? How to do this ?this is my app.js fileThis is my index.ejs file

<h1 style="color:'<%= color %>'">

I also tried like this,but did not get result as expected.


问:
Combine similar columns with different character names data?
```<code>ID <- c("IDa", "IDb","IDc","IDe","IDd","IDe")
names1 <- c("robin", "bob", "eric", "charlie", "robin", "gabby")
matrix1 <- matrix(names1, 1, 6)
colnames(matrix1) <- c("IDa", "IDb", "IDc","IDe", "IDd", "IDe")

</code>```

This is the output:

IDa
IDb
IDc
IDe
IDd
IDe

robin
bob
eric
charlie
robin
gabby

But I want it to look like this:

IDa
IDb
IDc
IDe
IDd

robin
bob
eric
charlie
robin

gabby

答:
Another option:</p>
```<code>library(reshape2)
library(tidyverse)

melt(matrix1) %>%
  select(-Var1) %>%
  group_by(Var2) %>%
  mutate(id = row_number()) %>%
  pivot_wider(
    names_from = Var2,
    values_from = value
  ) %>%
  select(-id)
</code>```
```<code>  IDa   IDb   IDc   IDe     IDd
  <chr> <chr> <chr> <chr>   <chr>
1 robin bob   eric  charlie robin
2 NA    NA    NA    gabby   NA
</code>```

Body:
ID <- c("IDa", "IDb","IDc","IDe","IDd","IDe")
names1 <- c("robin", "bob", "eric", "charlie", "robin", "gabby")
matrix1 <- matrix(names1, 1, 6)
colnames(matrix1) <- c("IDa", "IDb", "IDc","IDe", "IDd", "IDe")

This is the output:

IDa
IDb
IDc
IDe
IDd
IDe

robin
bob
eric
charlie
robin
gabby

But I want it to look like this:

IDa
IDb
IDc
IDe
IDd

robin
bob
eric
charlie
robin

gabby

Body:
Another option:

library(reshape2)
library(tidyverse)

melt(matrix1) %>%
  select(-Var1) %>%
  group_by(Var2) %>%
  mutate(id = row_number()) %>%
  pivot_wider(
    names_from = Var2,
    values_from = value
  ) %>%
  select(-id)

  IDa   IDb   IDc   IDe     IDd
  <chr> <chr> <chr> <chr>   <chr>
1 robin bob   eric  charlie robin
2 NA    NA    NA    gabby   NA