问:
Authorization header of GET request in python/wsgi
I'm in the process of creating a POST/GET API in Python 3. I'm running Apache2 connected to a WSGI script. I've managed to retrieve very simple GET requests succesfully. My code so far:

```<code>def application(environ, start_response):
    status = '200 OK'
    output = b'Hello'

    print(environ)
    # print(environ['HTTP_AUTHORIZATION'])

    response_headers = [('Content-type', 'text/plain'),('Content-Length', str(len(output)))]
    start_response(status, response_headers)

    return [output]
</code>```

I use reqbin to test-send GET requests to my server. When you enter a token inside the Bearer token field, it is automatically added to the headers. I tested this with a server I have a bearer token for and validation completes succesfully, so I know reqbin is actually sending the token.

However, I seem to be unable to acces the authorization header on my server. Apparently, it should be inside the environ object prefixed by HTTP_. But printing environ['HTTP_AUTHORIZATION'] yields a KeyError. I then tried printing the full environ object and retrieved it from the apache log:

```<code>{
    'mod_wsgi.listener_port': '443',
    'CONTEXT_DOCUMENT_ROOT': '/var/www/gosharing',
    'SERVER_SOFTWARE': 'Apache/2.4.41 (Ubuntu)',
    'SCRIPT_NAME': '',
    'mod_wsgi.enable_sendfile': '0',
    'mod_wsgi.handler_script': '',
    'SERVER_SIGNATURE': '<address>Apache/2.4.41 (Ubuntu) Server at domain.ext Port 443</address>\\n',
    'REQUEST_METHOD': 'GET',
    'PATH_INFO': '/',
    'SERVER_PROTOCOL': 'HTTP/1.1',
    'QUERY_STRING': '',
    'wsgi.errors': <mod_wsgi.Log object at 0x7f0b517c0c10>,
    'HTTP_X_REAL_IP': '2a02:a44a:ea1e:1:9053:2c7a:daaa:16',
    'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36',
    'SERVER_NAME': 'domain.ext',
    'REMOTE_ADDR': '206.189.205.251',
    'mod_wsgi.queue_start': '1644325870796726',
    'mod_wsgi.request_handler': 'wsgi-script',
    'apache.version': (2, 4, 41),
    'mod_wsgi.version': (4, 6, 8),
    'wsgi.url_scheme': 'https',
    'PATH_TRANSLATED': '/var/www/gosharing/gosharing.wsgi/',
    'SERVER_PORT': '443',
    'mod_wsgi.total_requests': 0L,
    'wsgi.multiprocess': False,
    'SERVER_ADDR': '185.45.113.35',
    'DOCUMENT_ROOT': '/var/www/gosharing',
    'mod_wsgi.process_group': 'gosharing',
    'mod_wsgi.thread_requests': 0L,
    'mod_wsgi.daemon_connects': '1',
    'mod_wsgi.request_id': 'sn1scyGWCVM',
    'SCRIPT_FILENAME': '/var/www/gosharing/gosharing.wsgi',
    'SERVER_ADMIN': 'webmaster@localhost',
    'mod_wsgi.ignore_activity': '0',
    'wsgi.input': <mod_wsgi.Input object at 0x7f0b48f01030>,
    'HTTP_HOST': 'domain.ext',
    'CONTEXT_PREFIX': '',
    'wsgi.multithread': True,
    'mod_wsgi.callable_object': 'application',
    'mod_wsgi.daemon_restarts': '0',
    'REQUEST_URI': '/',
    'HTTP_ACCEPT': '*/*',
    'mod_wsgi.path_info': '/',
    'wsgi.file_wrapper': <type 'mod_wsgi.FileWrapper'>,
    'wsgi.version': (1, 0),
    'GATEWAY_INTERFACE': 'CGI/1.1',
    'wsgi.run_once': False,
    'mod_wsgi.script_name': '',
    'REMOTE_PORT': '39762',
    'mod_wsgi.listener_host': '',
    'REQUEST_SCHEME': 'https',
    'SSL_TLS_SNI': 'domain.ext',
    'wsgi.input_terminated': True,
    'mod_wsgi.script_start': '1644325870815229',
    'mod_wsgi.application_group': '',
    'mod_wsgi.script_reloading': '1',
    'mod_wsgi.thread_id': 1,
    'mod_wsgi.request_start': '1644325870796210',
    'HTTP_ACCEPT_ENCODING': 'deflate, gzip',
    'mod_wsgi.daemon_start': '1644325870800682'
}
</code>```

In fact, I can add any header on reqbin and be able to see it in my apache log, except for the authorization header. Maybe it is in a more protected place? Please help me out here.

答:
I figured it out. In your 000-default-le-ssl.conf or 000-default.conf file (depending on whether you use a secure connection or not) you're supposed to turn on authorization passing manually by writing WSGIPassAuthorization On inside your VirtualHost tag:

```<code><VirtualHost *:443> # or port 80 if you are using an insecure connection
    # [...]

    WSGIPassAuthorization On

    # [...]

</VirtualHost>
</code>```

Body:
I'm in the process of creating a POST/GET API in Python 3. I'm running Apache2 connected to a WSGI script. I've managed to retrieve very simple GET requests succesfully. My code so far:

def application(environ, start_response):
    status = '200 OK'
    output = b'Hello'

    print(environ)
    # print(environ['HTTP_AUTHORIZATION'])

    response_headers = [('Content-type', 'text/plain'),('Content-Length', str(len(output)))]
    start_response(status, response_headers)

    return [output]

I use reqbin to test-send GET requests to my server. When you enter a token inside the Bearer token field, it is automatically added to the headers. I tested this with a server I have a bearer token for and validation completes succesfully, so I know reqbin is actually sending the token.

However, I seem to be unable to acces the authorization header on my server. Apparently, it should be inside the environ object prefixed by HTTP_. But printing environ['HTTP_AUTHORIZATION'] yields a KeyError. I then tried printing the full environ object and retrieved it from the apache log:

{
    'mod_wsgi.listener_port': '443',
    'CONTEXT_DOCUMENT_ROOT': '/var/www/gosharing',
    'SERVER_SOFTWARE': 'Apache/2.4.41 (Ubuntu)',
    'SCRIPT_NAME': '',
    'mod_wsgi.enable_sendfile': '0',
    'mod_wsgi.handler_script': '',
    'SERVER_SIGNATURE': '<address>Apache/2.4.41 (Ubuntu) Server at domain.ext Port 443</address>\\n',
    'REQUEST_METHOD': 'GET',
    'PATH_INFO': '/',
    'SERVER_PROTOCOL': 'HTTP/1.1',
    'QUERY_STRING': '',
    'wsgi.errors': <mod_wsgi.Log object at 0x7f0b517c0c10>,
    'HTTP_X_REAL_IP': '2a02:a44a:ea1e:1:9053:2c7a:daaa:16',
    'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36',
    'SERVER_NAME': 'domain.ext',
    'REMOTE_ADDR': '206.189.205.251',
    'mod_wsgi.queue_start': '1644325870796726',
    'mod_wsgi.request_handler': 'wsgi-script',
    'apache.version': (2, 4, 41),
    'mod_wsgi.version': (4, 6, 8),
    'wsgi.url_scheme': 'https',
    'PATH_TRANSLATED': '/var/www/gosharing/gosharing.wsgi/',
    'SERVER_PORT': '443',
    'mod_wsgi.total_requests': 0L,
    'wsgi.multiprocess': False,
    'SERVER_ADDR': '185.45.113.35',
    'DOCUMENT_ROOT': '/var/www/gosharing',
    'mod_wsgi.process_group': 'gosharing',
    'mod_wsgi.thread_requests': 0L,
    'mod_wsgi.daemon_connects': '1',
    'mod_wsgi.request_id': 'sn1scyGWCVM',
    'SCRIPT_FILENAME': '/var/www/gosharing/gosharing.wsgi',
    'SERVER_ADMIN': 'webmaster@localhost',
    'mod_wsgi.ignore_activity': '0',
    'wsgi.input': <mod_wsgi.Input object at 0x7f0b48f01030>,
    'HTTP_HOST': 'domain.ext',
    'CONTEXT_PREFIX': '',
    'wsgi.multithread': True,
    'mod_wsgi.callable_object': 'application',
    'mod_wsgi.daemon_restarts': '0',
    'REQUEST_URI': '/',
    'HTTP_ACCEPT': '*/*',
    'mod_wsgi.path_info': '/',
    'wsgi.file_wrapper': <type 'mod_wsgi.FileWrapper'>,
    'wsgi.version': (1, 0),
    'GATEWAY_INTERFACE': 'CGI/1.1',
    'wsgi.run_once': False,
    'mod_wsgi.script_name': '',
    'REMOTE_PORT': '39762',
    'mod_wsgi.listener_host': '',
    'REQUEST_SCHEME': 'https',
    'SSL_TLS_SNI': 'domain.ext',
    'wsgi.input_terminated': True,
    'mod_wsgi.script_start': '1644325870815229',
    'mod_wsgi.application_group': '',
    'mod_wsgi.script_reloading': '1',
    'mod_wsgi.thread_id': 1,
    'mod_wsgi.request_start': '1644325870796210',
    'HTTP_ACCEPT_ENCODING': 'deflate, gzip',
    'mod_wsgi.daemon_start': '1644325870800682'
}

In fact, I can add any header on reqbin and be able to see it in my apache log, except for the authorization header. Maybe it is in a more protected place? Please help me out here.

Body:
I figured it out. In your 000-default-le-ssl.conf or 000-default.conf file (depending on whether you use a secure connection or not) you're supposed to turn on authorization passing manually by writing WSGIPassAuthorization On inside your VirtualHost tag:

<VirtualHost *:443> # or port 80 if you are using an insecure connection
    # [...]

    WSGIPassAuthorization On

    # [...]

</VirtualHost>


来源: stackexchange

问:
How do I create a List<Map.Entry<String, Integer>> out of a Map<String, Integer>?
So I know how to create a List of Map values
new ArrayList<String, Integer>(map.getValues());
Or from entry set map.entrySet()
However there doesn't seem to be a similar way to add a list of Map.Entry<String, Integer>
Is there a way to do this so I can write it all in just a return statement?

```<code>Map<String, Integer> map = new TreeMap<String, Integer>();

public List<Map.Entry<String, Integer>> getWordList(){
        return new ArrayList<Map.Entry<String, Integer>>(map);
}
</code>```

This doesn't work. But what does?

答:
entrySet returns a Set and not a List, which means that the map's keys may or may not be in order.

However, in the case of TreeMap the JavaDoc says the following about it:

Returns a Set view of the mappings contained in this map.

The set's iterator returns the entries in ascending key order.

Apparently, entrySet() guarantees the mappings to be in the same order as the TreeMap. In short, you could just use it anywhere where a Collection is required. Creating a List is then trivial:

new ArrayList<>(map.entrySet())
```
<p>or</p>
<pre class="lang-java prettyprint-override"><code>List.copyOf(map.entrySet())
</code>```

ContentLicense: CC BY-SA 4.0

Body:
So I know how to create a List of Map values
new ArrayList<String, Integer>(map.getValues());
Or from entry set map.entrySet()
However there doesn't seem to be a similar way to add a list of Map.Entry<String, Integer>
Is there a way to do this so I can write it all in just a return statement?

Map<String, Integer> map = new TreeMap<String, Integer>();

public List<Map.Entry<String, Integer>> getWordList(){
        return new ArrayList<Map.Entry<String, Integer>>(map);
}

This doesn't work. But what does?

Body:
entrySet returns a Set and not a List, which means that the map's keys may or may not be in order.

However, in the case of TreeMap the JavaDoc says the following about it:

Returns a Set view of the mappings contained in this map.

The set's iterator returns the entries in ascending key order.

Apparently, entrySet() guarantees the mappings to be in the same order as the TreeMap. In short, you could just use it anywhere where a Collection is required. Creating a List is then trivial:

new ArrayList<>(map.entrySet())

or

List.copyOf(map.entrySet())


问:
How to manage a button with disabled attribute using Python Selenium?
Having this button:

```<code><button id="btn-login-5" type="button" class="m-1 btn btn-warning" disabled="">Update</button>
</code>```

I want to remove the disable attribute in order to click the button.

This is the code i see everytime:

```<code>button = self.driver.find_element(
        By.XPATH, "/html/body/div/div/button")
self.driver.execute_script(
        'arguments[0].removeAttribute("disabled");', button)
</code>```

But I can't figure me out how that can work for anyone, I mean, if the element is disabled, selenium cannot run that very first line, is not able to asign the var "button" because he can't find that element.

Am I missing something? I am getting this error if a run that:

```<code>selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div/div/button"}
</code>```

Update

I just realized this is related to selenium grid, I tried to click the button in a lot of ways, and no one works, but if instead of using selenium grid I use a local webdriver all of them works! So I have no idea what to do now.

答:
If you use this relative xpath, instead of absolute one, it works:

```<code>button = driver.find_element(By.XPATH, "//button[@type='button']")
</code>```

But is this the only button in your DOM? If not, you may have to add other relative entities to it.

Refactored Code (as per your query info provided):

```<code>button = driver.find_element(By.XPATH, "//button[@type='button']")
driver.execute_script('arguments[0].removeAttribute("disabled");', button)
button.click()
</code>```

Output:

```<code>Process finished with exit code 0
</code>```

Body:
Having this button:

<button id="btn-login-5" type="button" class="m-1 btn btn-warning" disabled="">Update</button>

I want to remove the disable attribute in order to click the button.

This is the code i see everytime:

button = self.driver.find_element(
        By.XPATH, "/html/body/div/div/button")
self.driver.execute_script(
        'arguments[0].removeAttribute("disabled");', button)

But I can't figure me out how that can work for anyone, I mean, if the element is disabled, selenium cannot run that very first line, is not able to asign the var "button" because he can't find that element.

Am I missing something? I am getting this error if a run that:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div/div/button"}

Update

I just realized this is related to selenium grid, I tried to click the button in a lot of ways, and no one works, but if instead of using selenium grid I use a local webdriver all of them works! So I have no idea what to do now.

Body:
If you use this relative xpath, instead of absolute one, it works:

button = driver.find_element(By.XPATH, "//button[@type='button']")

But is this the only button in your DOM? If not, you may have to add other relative entities to it.

Refactored Code (as per your query info provided):

button = driver.find_element(By.XPATH, "//button[@type='button']")
driver.execute_script('arguments[0].removeAttribute("disabled");', button)
button.click()

Output:

Process finished with exit code 0


问:
How to extract an attachment from an email to a shared drive that is in a google sheets?
currently I have a google script that runs every x times on my Gmail which retrieves all attachments according to of the label.
I enter the email addresses and the path of the folder via a getFolderByName in a google sheets but the problem is that this does not work if the folder is on a shared drive.

I saw different topic on the forum so I know I need to use Drive API

So I would like to retrieve the id of my folder which is in my google sheet instead of my getFolderByName.

Here are the 3 functions:

getLibelleConfigs : Retrieves LibelleConfig objects from the configuration sheet

getFolderFromPath : Get or create a folder from its path

getOrCreateFolder : Recover or create a folder

function getLibelleConfigs() {
    let spreadSheet = getOrCreateSpreadSheet(config.configSheetPath, config.configSheetHeader);

    let sheet = spreadSheet.getSheets()[0];

    let values = sheet.getDataRange().getValues();

    if (values.length == 0 || values.length == 1 && values[0].length == 1 && values[0][0] == "") sheet.appendRow(config.configSheetHeader);

    return values
        .filter((row, i) => {
            return i > 0 && row.length > 0 && row[0] != "";
        })
        .map(row => {
            let libelle = row[0].trim();
            let folderPath = (row.length>1 && row[1] != "" ? row[1] : `/${row[0]}`);
            if (!folderPath.startsWith('/')) folderPath = '/' + folderPath;
            folderPath = folderPath.trim();
            return {
                libelle: libelle,
                folderPath: folderPath
            }
        });
}
```
<pre class="lang-js prettyprint-override"><code>function getFolderFromPath(path)
{
    let strings = path.split("/");

    let currentFolder = DriveApp.getRootFolder();

    strings.forEach((string, index) => {
        if (string == "") return;
        currentFolder = getOrCreateFolder(string, currentFolder);
    });

    return currentFolder;
}
</code>```

function getOrCreateFolder(folderName, parentFolder) {

    let folders = parentFolder.getFoldersByName(folderName);
    //Logger.log("folder : " + folders + ", folderName : " + folderName);
    if (folders.hasNext()) {
        return folders.next();
    }
    else {
        return parentFolder.createFolder(folderName);

  }
}
```
<p>google sheets :</p>
```+----------------+-----------+
|     LABEL      | ID FOLDER |
+----------------+-----------+
| aaaa@gmail.com | xxxxx_1   |
| aaaa@gmail.com | xxxxx_3   |
| bbbb@gmail.com | xxxxx_1   |
| bbbb@gmail.com | xxxxx_2   |
+----------------+-----------+
```
<hr />
<p>Edit</p>
<pre class="lang-js prettyprint-override"><code>function saveAttachmentsFromLibelleConfig(libelleConfig, messageIdHistory)
{
    let threads = GmailApp.search(`in:inbox has:attachment label:${libelleConfig.libelle}`);
    console.info(`${threads.length} ${threads.length > 1 ? 'threads trouvés' : 'thread trouvé'} pour le libellé '${libelleConfig.libelle}'`);

    if (threads.length == 0) return;

    let parentFolder = getFolderFromPath(libelleConfig.folderPath);

    threads.forEach(thread => {
        try
        {
            thread.getMessages().forEach(message => {
                if (messageIdHistory.includes(message.getId())) return;
                message.getAttachments().forEach(attachment => {
                    console.info(`Enregistrement de la pièces jointe '${attachment.getName()}' du mail '${message.getSubject()}' - '${message.getId()}' envoyé par '${message.getFrom()}' ayant le libellé '${libelleConfig.libelle}'`);
                    parentFolder.createFile(attachment.copyBlob());
                    appendHistory(message.getId(), libelleConfig.libelle, message.getFrom(), attachment.getName(), libelleConfig.folderPath);
                });
                message.markRead();
            });
            thread.moveToArchive();
        }
        catch (e)
        {
            console.warn(`Erreur lors du traitement du thread '${thread.getFirstMessageSubject()}' : ${e}`);
        }
    });
}
</code>```

My Solution :

```<code> function movefileToSharedDrive() {
  makeCopy("My Drive ID", "To Shared Drive ID");
  deleteFiles("My Drive ID");
}

function makeCopy(srcFolderId, dstFolderId) {
  var srcFolder = DriveApp.getFolderById(srcFolderId);
  var dstFolder = DriveApp.getFolderById(dstFolderId);
  var files = srcFolder.getFiles();
  while (files.hasNext()) {
    var file = files.next();
    var f = file.makeCopy(dstFolder);
    if (file.getMimeType() == MimeType.GOOGLE_APPS_SCRIPT) {
      Drive.Files.update({"parents": [{"id": dstFolderId}]}, f.getId());
    }
  }
}

function deleteFiles(folderId){
  var folder = DriveApp.getFolderById(folderId);
  var files = folder.getFiles()
  while(files.hasNext()){
    files.next().setTrashed(true)
  }
}
</code>```

There are three steps:

trigger that extracts attachments to my drive

then function makeCopy to drive shared

and finally one that deletes files from my drive(to avoid duplicates)

答:
You can use Drive.Files.Insert of the Advanced Drive Service to directly insert the file into the shared Drive:

function saveToSharedDrive(sharedDriveId, fileBlob) {
  const options ={
    supportsAllDrives: true
  }

  var resource = {
    title: fileBlob.getName(),
    mimeType: fileBlob.getContentType(),
    parents:[{
      "id": sharedDriveId
    }]
  }
  Drive.Files.insert(resource, fileBlob, options)
}
```
<p>Where <code>sharedDriveId</code> is the ID taken from your Sheet and <code>fileBlob</code> a <code>GmailAttachment</code> object given as an array by:</p>
<pre class="lang-js prettyprint-override"><code>GmailApp.getMessageById("message-id").getAttachments()
</code>```

Body:
currently I have a google script that runs every x times on my Gmail which retrieves all attachments according to of the label.
I enter the email addresses and the path of the folder via a getFolderByName in a google sheets but the problem is that this does not work if the folder is on a shared drive.

I saw different topic on the forum so I know I need to use Drive API

So I would like to retrieve the id of my folder which is in my google sheet instead of my getFolderByName.

Here are the 3 functions:

getLibelleConfigs : Retrieves LibelleConfig objects from the configuration sheet

getFolderFromPath : Get or create a folder from its path

getOrCreateFolder : Recover or create a folder

function getLibelleConfigs() {
    let spreadSheet = getOrCreateSpreadSheet(config.configSheetPath, config.configSheetHeader);

    let sheet = spreadSheet.getSheets()[0];

    let values = sheet.getDataRange().getValues();

    if (values.length == 0 || values.length == 1 && values[0].length == 1 && values[0][0] == "") sheet.appendRow(config.configSheetHeader);

    return values
        .filter((row, i) => {
            return i > 0 && row.length > 0 && row[0] != "";
        })
        .map(row => {
            let libelle = row[0].trim();
            let folderPath = (row.length>1 && row[1] != "" ? row[1] : `/${row[0]}`);
            if (!folderPath.startsWith('/')) folderPath = '/' + folderPath;
            folderPath = folderPath.trim();
            return {
                libelle: libelle,
                folderPath: folderPath
            }
        });
}

function getFolderFromPath(path)
{
    let strings = path.split("/");

    let currentFolder = DriveApp.getRootFolder();

    strings.forEach((string, index) => {
        if (string == "") return;
        currentFolder = getOrCreateFolder(string, currentFolder);
    });

    return currentFolder;
}

function getOrCreateFolder(folderName, parentFolder) {

    let folders = parentFolder.getFoldersByName(folderName);
    //Logger.log("folder : " + folders + ", folderName : " + folderName);
    if (folders.hasNext()) {
        return folders.next();
    }
    else {
        return parentFolder.createFolder(folderName);

  }
}

google sheets :

+----------------+-----------+
|     LABEL      | ID FOLDER |
+----------------+-----------+
| aaaa@gmail.com | xxxxx_1   |
| aaaa@gmail.com | xxxxx_3   |
| bbbb@gmail.com | xxxxx_1   |
| bbbb@gmail.com | xxxxx_2   |
+----------------+-----------+

Edit

function saveAttachmentsFromLibelleConfig(libelleConfig, messageIdHistory)
{
    let threads = GmailApp.search(`in:inbox has:attachment label:${libelleConfig.libelle}`);
    console.info(`${threads.length} ${threads.length > 1 ? 'threads trouvés' : 'thread trouvé'} pour le libellé '${libelleConfig.libelle}'`);

    if (threads.length == 0) return;

    let parentFolder = getFolderFromPath(libelleConfig.folderPath);

    threads.forEach(thread => {
        try
        {
            thread.getMessages().forEach(message => {
                if (messageIdHistory.includes(message.getId())) return;
                message.getAttachments().forEach(attachment => {
                    console.info(`Enregistrement de la pièces jointe '${attachment.getName()}' du mail '${message.getSubject()}' - '${message.getId()}' envoyé par '${message.getFrom()}' ayant le libellé '${libelleConfig.libelle}'`);
                    parentFolder.createFile(attachment.copyBlob());
                    appendHistory(message.getId(), libelleConfig.libelle, message.getFrom(), attachment.getName(), libelleConfig.folderPath);
                });
                message.markRead();
            });
            thread.moveToArchive();
        }
        catch (e)
        {
            console.warn(`Erreur lors du traitement du thread '${thread.getFirstMessageSubject()}' : ${e}`);
        }
    });
}

My Solution :

 function movefileToSharedDrive() {
  makeCopy("My Drive ID", "To Shared Drive ID");
  deleteFiles("My Drive ID");
}

function makeCopy(srcFolderId, dstFolderId) {
  var srcFolder = DriveApp.getFolderById(srcFolderId);
  var dstFolder = DriveApp.getFolderById(dstFolderId);
  var files = srcFolder.getFiles();
  while (files.hasNext()) {
    var file = files.next();
    var f = file.makeCopy(dstFolder);
    if (file.getMimeType() == MimeType.GOOGLE_APPS_SCRIPT) {
      Drive.Files.update({"parents": [{"id": dstFolderId}]}, f.getId());
    }
  }
}

function deleteFiles(folderId){
  var folder = DriveApp.getFolderById(folderId);
  var files = folder.getFiles()
  while(files.hasNext()){
    files.next().setTrashed(true)
  }
}

There are three steps:

trigger that extracts attachments to my drive

then function makeCopy to drive shared

and finally one that deletes files from my drive(to avoid duplicates)

Body:
You can use Drive.Files.Insert of the Advanced Drive Service to directly insert the file into the shared Drive:

function saveToSharedDrive(sharedDriveId, fileBlob) {
  const options ={
    supportsAllDrives: true
  }

  var resource = {
    title: fileBlob.getName(),
    mimeType: fileBlob.getContentType(),
    parents:[{
      "id": sharedDriveId
    }]
  }
  Drive.Files.insert(resource, fileBlob, options)
}

Where sharedDriveId is the ID taken from your Sheet and fileBlob a GmailAttachment object given as an array by:

GmailApp.getMessageById("message-id").getAttachments()


问:
Calculating the mean by name of a named numeric returing another named numeric as a result
I am working on a code which has a for loop. At the end of each iteration, a named numeric vector is concatenated to the one of the previous loop.

```<code>all_obj <- c()
for (i in 1:3){
  obj <- 1:3*i
  names(obj) <- c('foo', 'baz', 'bar')
  all_obj <- c(all_obj, obj)
}
</code>```

At the end, all_obj looks like this:

```<code>foo baz bar foo baz bar foo baz bar
  1   2   3   2   4   6   3   6   9
</code>```

What I would need now is to have a result which is the mean by name of this vector, and it is a named numeric itself.

Expected result

```<code>foo baz bar
  2   4   6
</code>```

I know I can get the values with name foo (for example) with all_obj[names(all_obj) == "foo"]. But I am bit stuck as to how would I reach my desired result from here without having to convert the data too much (e.g. avoiding doing as.data.frame for instance). Not that there is anything wrong with this, it's just a matter of preference and curiosity.

This was my best attempt so far.

```<code>lapply(unique(names(all_obj)), function(x) mean(all_obj[names(all_obj) == x]))
#[[1]]
#[1] 2
#
#[[2]]
#[1] 4
#
#[[3]]
#[1] 6
</code>```

答:
tapply is well suited for that task:

tapply(all_obj, names(all_obj), mean)

# bar baz foo
#   6   4   2
```

Body:
I am working on a code which has a for loop. At the end of each iteration, a named numeric vector is concatenated to the one of the previous loop.

all_obj <- c()
for (i in 1:3){
  obj <- 1:3*i
  names(obj) <- c('foo', 'baz', 'bar')
  all_obj <- c(all_obj, obj)
}

At the end, all_obj looks like this:

foo baz bar foo baz bar foo baz bar
  1   2   3   2   4   6   3   6   9

What I would need now is to have a result which is the mean by name of this vector, and it is a named numeric itself.

Expected result

foo baz bar
  2   4   6

I know I can get the values with name foo (for example) with all_obj[names(all_obj) == "foo"]. But I am bit stuck as to how would I reach my desired result from here without having to convert the data too much (e.g. avoiding doing as.data.frame for instance). Not that there is anything wrong with this, it's just a matter of preference and curiosity.

This was my best attempt so far.

lapply(unique(names(all_obj)), function(x) mean(all_obj[names(all_obj) == x]))
#[[1]]
#[1] 2
#
#[[2]]
#[1] 4
#
#[[3]]
#[1] 6


问:
How to add [ExcludeFromCodeCoverage] attribute at an assembly-level in a .Net Standard 2.1 project
I have a .Net Core application which has got one .Net Standard 2.1 project in it. I am using Coverlet to get the code coverage in Cobertura format.

I am using "coverlet.msbuild" nuget package in all my Test projects.

I want to add [ExcludeFromCodeCoverage] attribute at a assembly-level so that coverlet ignores this project while performing the analysis.

I cannot find AssemblyInfo.cs file in .Net Core / .Net Standard projects.

I tried adding below tag in the proejct's .csproj file

```<code>  <ItemGroup>
     <AssemblyAttribute Include="System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute" />
  </ItemGroup>
</code>```

but still no luck.

The only workaround for me is to add [ExcludeFromCodeCoverage] attribute manually in all the class files which is not a best way.

答:
This worked for .NET 6. I suspect it will work for .NET Core 3.1+

Add the following to the csproj file

```<code>    <ItemGroup>
        <AssemblyAttribute Include="System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage" />
    </ItemGroup>
</code>```

Or this in any file in the project for the assembly

using System.Diagnostics.CodeAnalysis;

[assembly: ExcludeFromCodeCoverage]
```

Body:
I have a .Net Core application which has got one .Net Standard 2.1 project in it. I am using Coverlet to get the code coverage in Cobertura format.

I am using "coverlet.msbuild" nuget package in all my Test projects.

I want to add [ExcludeFromCodeCoverage] attribute at a assembly-level so that coverlet ignores this project while performing the analysis.

I cannot find AssemblyInfo.cs file in .Net Core / .Net Standard projects.

I tried adding below tag in the proejct's .csproj file

  <ItemGroup>
     <AssemblyAttribute Include="System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute" />
  </ItemGroup>

but still no luck.

The only workaround for me is to add [ExcludeFromCodeCoverage] attribute manually in all the class files which is not a best way.

Body:
This worked for .NET 6. I suspect it will work for .NET Core 3.1+

Add the following to the csproj file

    <ItemGroup>
        <AssemblyAttribute Include="System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage" />
    </ItemGroup>

Or this in any file in the project for the assembly

using System.Diagnostics.CodeAnalysis;

[assembly: ExcludeFromCodeCoverage]


问:
Linked List insertion isn't working in for/while loop
I am learning DSA, and was trying to implement linked list but the insertion function that i wrote is not
working in a for or while loop, its not the same when i call that function outside the loop, it works that way. I am not able to figure it out, please someone help me.

```<code>#include <iostream>

class Node {

public:
  int data;
  Node *next;

  Node(int &num) {
    this->data = num;
    next = NULL;
  }
};

class LinkedList {

  Node *head = NULL;

public:
  void insert(int num) {
    Node *tmp;
    if (head == NULL) {
      head = new Node(num);
      tmp = head;
    } else {
      tmp->next = new Node(num);
      tmp = tmp->next;
    }
  }

  void printList() {
    Node *tmp = head;
    while (tmp) {
      std::cout << tmp->data << "  ";
      tmp = tmp->next;
    }
    std::cout << std::endl;
  }

  void reverseList() {
    Node *curr = head, *prev = NULL, *nextNode;
    while (curr) {
      nextNode = curr->next;
      curr->next = prev;
      prev = curr;
      curr = nextNode;
    }
    head = prev;
  }
};

int main() {
  LinkedList list1;
  // This is not working
  int num;
  while (num != -1) {
    std::cin >> num;
    list1.insert(num);
  }

  // This is working
  // list1.insert(1);
  // list1.insert(2);
  // list1.insert(3);
  // list1.insert(4);
  // list1.insert(5);

  list1.printList();
  list1.reverseList();
  list1.printList();

  return 0;
}
</code>```

I expect this after insertion

Edit:
although @Roberto Montalti solved this for me, but before that I tried passing incrementing value using a for loop which worked but as soon as I pull that cin out it crashes. can someone tell me what's happening under the hood?

```<code>for (int i = 1; i <= 10; i++)
{
    list1.insert(i);
}
</code>```

答:
You need to loop until you reach the end of the list and then add the new node after that. Like this.</p>
```<code>void insert(int num) {
    Node *tmp = head;
    if (head == NULL) {
        head = new Node(num);
    }
    else {
        while (tmp->next != NULL) {
            tmp = tmp->next;
        }
        tmp->next = new Node(num);
    }
  }
</code>```

Body:
I am learning DSA, and was trying to implement linked list but the insertion function that i wrote is not
working in a for or while loop, its not the same when i call that function outside the loop, it works that way. I am not able to figure it out, please someone help me.

#include <iostream>

class Node {

public:
  int data;
  Node *next;

  Node(int &num) {
    this->data = num;
    next = NULL;
  }
};

class LinkedList {

  Node *head = NULL;

public:
  void insert(int num) {
    Node *tmp;
    if (head == NULL) {
      head = new Node(num);
      tmp = head;
    } else {
      tmp->next = new Node(num);
      tmp = tmp->next;
    }
  }

  void printList() {
    Node *tmp = head;
    while (tmp) {
      std::cout << tmp->data << "  ";
      tmp = tmp->next;
    }
    std::cout << std::endl;
  }

  void reverseList() {
    Node *curr = head, *prev = NULL, *nextNode;
    while (curr) {
      nextNode = curr->next;
      curr->next = prev;
      prev = curr;
      curr = nextNode;
    }
    head = prev;
  }
};

int main() {
  LinkedList list1;
  // This is not working
  int num;
  while (num != -1) {
    std::cin >> num;
    list1.insert(num);
  }

  // This is working
  // list1.insert(1);
  // list1.insert(2);
  // list1.insert(3);
  // list1.insert(4);
  // list1.insert(5);

  list1.printList();
  list1.reverseList();
  list1.printList();

  return 0;
}

I expect this after insertion

Edit:
although @Roberto Montalti solved this for me, but before that I tried passing incrementing value using a for loop which worked but as soon as I pull that cin out it crashes. can someone tell me what's happening under the hood?

for (int i = 1; i <= 10; i++)
{
    list1.insert(i);
}

Body:
You need to loop until you reach the end of the list and then add the new node after that. Like this.

void insert(int num) {
    Node *tmp = head;
    if (head == NULL) {
        head = new Node(num);
    }
    else {
        while (tmp->next != NULL) {
            tmp = tmp->next;
        }
        tmp->next = new Node(num);
    }
  }


问:
Changing background color on any number input higher than 0 in JavaScript
My question is simple so I hope it shouldn't be so hard to solve. Not as hard as it is for me at least :).

```<code><div id="block">
    <input type="number" min="0" value="0">
</div>
</code>```

https://jsfiddle.net/wbrnmldr/9n60r82y/2/

[EDIT ]Ok since I'm clearly too dumb to explain it properly I will do it again. The grey  around the input field is supposed to go yellow, not the input field itself.

So I have this simple div as seen above. What is supposed to happen is that the background color of this div changes from #F1F1F1 to #FFD200 anytime the input value doesn't equal 0 anymore. And to make it more complicated, if the value is zero again it should return to #F1F1F1. I already got it to work when submitting the value but my goal is to see it happen in real-time.

Can anybody help me tackle this problem?
Thanks in advance!

Following are some of the things I tried but I didn't get to work:

```<code>$('.input').each(function() {
    var inputValue = $(this);

    inputValue.data('oldValue', inputValue.val());

    inputValue.bind("propertychange change click keyup input paste",   function(event){
        if (inputValue.data('oldValue') != inputValue.val()) {
        inputValue.data('oldValue', inputValue.val());

        document.getElementsByClassName('block').style.backgroundColor = "#FFD200";
    }

    });
});
</code>```
```<code>function changeColor() {
    document.getElementById("tracker-option-block").style.backgroundColor = "FFD200";
    return false;
}
</code>```

答:
You need to listen any input value changes using 'input' event like this:

document
.querySelector('#block input')
.addEventListener('input', event => {
  document.querySelector('#block').style.backgroundColor =
    event.target.value === '0' ? '#F1F1F1' : '#FFD200';
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#block {
    margin: 10px;
    padding:30px;
    background-color: #F1F1F1;
    /* target color: #FFD200;*/
}</code>```

    <input type="number" min="0" value="0">

```

Refs: .querySelector()

Body:
My question is simple so I hope it shouldn't be so hard to solve. Not as hard as it is for me at least :).

    <input type="number" min="0" value="0">

https://jsfiddle.net/wbrnmldr/9n60r82y/2/

[EDIT ]Ok since I'm clearly too dumb to explain it properly I will do it again. The grey  around the input field is supposed to go yellow, not the input field itself.

So I have this simple div as seen above. What is supposed to happen is that the background color of this div changes from #F1F1F1 to #FFD200 anytime the input value doesn't equal 0 anymore. And to make it more complicated, if the value is zero again it should return to #F1F1F1. I already got it to work when submitting the value but my goal is to see it happen in real-time.

Can anybody help me tackle this problem?
Thanks in advance!

Following are some of the things I tried but I didn't get to work:

$('.input').each(function() {
    var inputValue = $(this);

    inputValue.data('oldValue', inputValue.val());

    inputValue.bind("propertychange change click keyup input paste",   function(event){
        if (inputValue.data('oldValue') != inputValue.val()) {
        inputValue.data('oldValue', inputValue.val());

        document.getElementsByClassName('block').style.backgroundColor = "#FFD200";
    }

    });
});

function changeColor() {
    document.getElementById("tracker-option-block").style.backgroundColor = "FFD200";
    return false;
}

Body:
You need to listen any input value changes using 'input' event like this:

document
.querySelector('#block input')
.addEventListener('input', event => {
  document.querySelector('#block').style.backgroundColor =
    event.target.value === '0' ? '#F1F1F1' : '#FFD200';
})

#block {
    margin: 10px;
    padding:30px;
    background-color: #F1F1F1;
    /* target color: #FFD200;*/
}

<div id="block">
    <input type="number" min="0" value="0">
</div>

Refs: .querySelector()


问:
"Does not provide an export named 'Tooltip'," even though I can output Tooltip
When this code runs:

```<code>// index.svelte
import Chart, { Tooltip } from 'chart.js/auto.esm';
console.log({ Tooltip });
</code>```

Tooltip is successfully output to the console, but I also get an error (in the browser):

The requested module '/node_modules/.vite/chart_js_auto.js?v=9674d8be' does not provide an export named 'Tooltip'

So SvelteKit is obviously running this code multiple times. Why does it work once, then fail later? How do I get it to work all the time?

I imported 'chart.js/auto.esm' instead of just 'chart.js' because SvelteKit needs ESM modules. I can import { Tooltip } from 'chart.js' and this works locally, but a there's a different build error on Vercel:

SyntaxError: Named export 'Tooltip' not found. The requested module
'chart.js' is a CommonJS module, which may not support all
module.exports as named exports.

答:
Tooltip needs to be imported like this (with SvelteKit):

```<code>import { Tooltip } from 'chart.js/dist/chart.esm;
</code>```

Full import code:

```<code>import { Chart, registerables } from 'chart.js/dist/chart.esm';
Chart.register(...registerables);

import { Tooltip } from 'chart.js/dist/chart.esm';
</code>```

Besides importing from chart.js/dist/chart.esm, I had to manually register the modules because /auto was not used.

Body:
When this code runs:

// index.svelte
import Chart, { Tooltip } from 'chart.js/auto.esm';
console.log({ Tooltip });

Tooltip is successfully output to the console, but I also get an error (in the browser):

The requested module '/node_modules/.vite/chart_js_auto.js?v=9674d8be' does not provide an export named 'Tooltip'

So SvelteKit is obviously running this code multiple times. Why does it work once, then fail later? How do I get it to work all the time?

I imported 'chart.js/auto.esm' instead of just 'chart.js' because SvelteKit needs ESM modules. I can import { Tooltip } from 'chart.js' and this works locally, but a there's a different build error on Vercel:

SyntaxError: Named export 'Tooltip' not found. The requested module
'chart.js' is a CommonJS module, which may not support all
module.exports as named exports.

Body:
Tooltip needs to be imported like this (with SvelteKit):

import { Tooltip } from 'chart.js/dist/chart.esm;

Full import code:

import { Chart, registerables } from 'chart.js/dist/chart.esm';
Chart.register(...registerables);

import { Tooltip } from 'chart.js/dist/chart.esm';

Besides importing from chart.js/dist/chart.esm, I had to manually register the modules because /auto was not used.


问:
Finding GCD and LCM giving correct output for some test cases but my submission shows wrong answer
My c++ code of finding gcd and lcm is giving correct output for some test cases but my submission shows wrong answer.

```<code>int T;
cin>>T;
int x,y,a,b;

while(T--)
{
    cin>>x>>y;
    a=(x>y)?x:y;  // a will be the greater number
    b=(y>x)?x:y;  // b will be the smaller number
    int product=a*b;

    ///we will find gcd, and lcm will be a*b/gcd

    if(a%b==0)
        cout<<b<<" "<<a<<endl;   // the smaller one will be gcd and the greater one, lcm
    else
    {
        int rem=a%b;

        while(rem!=0)
        {
            a=b;
            b=rem;
            rem=a%b;
        }
        cout<<b<<" "<<product/b<<endl;
    }
}
</code>```

Are there certain test cases I am missing? Or maybe my code is wrong.

答:
The correct code is as follows:

`

```<code>int T;
cin>>T;
long int x,y,a,b;

while(T--)
{

    cin>>x>>y;
    a=(x>y)?x:y;  // a will be the greater number
    b=(y>x)?x:y;  // b will be the smaller number
    long int product=a*b;

    ///we will find gcd, and lcm will be a*b/gcd

    if(a==0 && b==0)
    {
        cout<<"0 0"<<endl;
    }

     else if(b==0)
    {
        cout<<a<<" 0"<<endl;
    }

    else
    {

    if(a%b==0)
    cout<<b<<" "<<a<<endl;   // the smaller one will be gcd and the greater one, lcm

    else
    {
        int rem=b;

        while(a%b!=0)
        {
            rem=a%b;
            a=b;
            b=rem;

        }
        cout<<rem<<" "<<product/b<<endl;

    }

    }

}
</code>```

`

Body:
My c++ code of finding gcd and lcm is giving correct output for some test cases but my submission shows wrong answer.

int T;
cin>>T;
int x,y,a,b;

while(T--)
{
    cin>>x>>y;
    a=(x>y)?x:y;  // a will be the greater number
    b=(y>x)?x:y;  // b will be the smaller number
    int product=a*b;

    ///we will find gcd, and lcm will be a*b/gcd

    if(a%b==0)
        cout<<b<<" "<<a<<endl;   // the smaller one will be gcd and the greater one, lcm
    else
    {
        int rem=a%b;

        while(rem!=0)
        {
            a=b;
            b=rem;
            rem=a%b;
        }
        cout<<b<<" "<<product/b<<endl;
    }
}

Are there certain test cases I am missing? Or maybe my code is wrong.

Body:
The correct code is as follows:

`

int T;
cin>>T;
long int x,y,a,b;

while(T--)
{

    cin>>x>>y;
    a=(x>y)?x:y;  // a will be the greater number
    b=(y>x)?x:y;  // b will be the smaller number
    long int product=a*b;

    ///we will find gcd, and lcm will be a*b/gcd

    if(a==0 && b==0)
    {
        cout<<"0 0"<<endl;
    }

     else if(b==0)
    {
        cout<<a<<" 0"<<endl;
    }

    else
    {

    if(a%b==0)
    cout<<b<<" "<<a<<endl;   // the smaller one will be gcd and the greater one, lcm

    else
    {
        int rem=b;

        while(a%b!=0)
        {
            rem=a%b;
            a=b;
            b=rem;

        }
        cout<<rem<<" "<<product/b<<endl;

    }

    }

}

`


问:
PHP SESSIONS: how do I store the quantities alongside the products which the user has added to their cart?
I have been trying to find this out for weeks and I'm not seeing it. how do I store the quantities alongside the products which the user has added to their cart? I need to have this because I need the users to be able to update the quantity from the items.

already tried a few things such as creating an array and trying to store quantity in a array but it only remembers the last number that the user put in. This is because its a post request. and to fix that I need to store quantities alongs side the products in cart. and thats where I'm stuck.

I tried:

```<code>if(isset($_POST['quantity'])){
    $quantity = $_POST['quantity'];
    $_SESSION['basket'][] = $quantity;
}
</code>```

but this put the last item a lot in the shopping cart
like this:

then I tried:

```<code>if (isset($_POST['quantity']) && !empty($_POST['quantity'])){
    $_SESSION['quantity'] = $_POST['quantity'];
//           //$qty = $_SESSION["qty"] + 1;
     if (isset($_POST['broodnaam']) && !empty($_POST['broodnaam'])){
           if ($_POST['broodnaam'] == $row['broodnaam']){
                $quantity = $_POST['quantity'];
//                    //array_push($_SESSION['qty'], $quantity);
//                 //    var_dump($_SESSION['qty']);
           }
     }
}
</code>```

but this only updates the last updated item from the cart.
I really don't know how to fix this can someone help me

code: ( part of the code as I don't feel like I need to share the styling and sessions_start() part

```<code><?php
$broodjes = $_GET['broodjes_ID'];
if (isset($_SESSION['basket'])){
  if( in_array( $broodjes ,$_SESSION['basket']) )
  {
  }else{
     $_SESSION['basket'][] = $broodjes;
  }
}else{
  $_SESSION['basket'][]= $broodjes;
}
$sumtotal = 0;
foreach($_SESSION['basket'] as $key => $value){
    //echo "Key = $key; value = $value; <br>";
    $sql = "SELECT broodjes_ID, broodnaam, prijs, voorraad FROM broodjes WHERE broodjes_ID=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $value);
    $stmt->execute();
    $result = $stmt->get_result();
    if($row = $result->fetch_assoc()){
        //session for quantity
        $_SESSION["qty"] = array();
        echo '<div class="cart-items">';
        echo '<div class="cart-row">';
        echo '<div class="cart-item cart-column">';
        echo $row['broodnaam'];
        echo '</div>';
        echo '<div class="cart-item cart-column">';
        echo '€ ' . $row['prijs'];
        echo '</div>';
        //quantity
        echo '<div class="cart-item cart-column">';
        echo '<form method="POST" action="">';
        echo '<div class="col-xs-4">';
        echo '<input type="hidden" name="broodnaam" id="broodnaam" value="' . $row['broodnaam'] . '">';
        echo '<input type="number" name="quantity" id="quantity" class="form-control input-sm" value="1" min="1" max="'.$row['voorraad'].'">';
        echo '</div>';
        echo '</form>';
        echo '</div>';
        //ik moet de quantity ergens in opslaan , denk in db, om zo nog de voorraad te verminderen
        if (isset($_POST['quantity']) && !empty($_POST['quantity'])){
            $_SESSION['quantity'] = $_POST['quantity'];
            //           //$qty = $_SESSION["qty"] + 1;
            if (isset($_POST['broodnaam']) && !empty($_POST['broodnaam'])){
                if ($_POST['broodnaam'] == $row['broodnaam']){
                    $quantity = $_POST['quantity'];
                    ////array_push($_SESSION['qty'], $quantity);
                    ////    var_dump($_SESSION['qty']);
                }
            }
        }
        echo '<div class="cart-item cart-column">';
        $rowtotaal = $row['prijs'] * $quantity;
        $sumtotal += $rowtotaal;
        echo $rowtotaal;
        echo '</div>';
        echo '</div>';
        echo '</div>';
    }
}
?> <br />
<div class="cart-total">
    <strong class="cart-total-title">Total</strong>
    <span class="cart-total-price"> € <?php   echo $sumtotal;?></span>
</div>
<br/>
</code>```

答:
Update the new quantity ($_POST['quantity']) by adding the old one ($_SESSION['qty']).like this -</p>
```<code>   if (isset($_POST['quantity'])){
        if (isset($_POST['broodnaam'])){
            if ($_POST['broodnaam'] == $row['broodnaam']){
                $_SESSION['qty'] = $_POST['quantity'] + $_SESSION['qty'];
            }
        }
   }
</code>```

Body:
I have been trying to find this out for weeks and I'm not seeing it. how do I store the quantities alongside the products which the user has added to their cart? I need to have this because I need the users to be able to update the quantity from the items.

already tried a few things such as creating an array and trying to store quantity in a array but it only remembers the last number that the user put in. This is because its a post request. and to fix that I need to store quantities alongs side the products in cart. and thats where I'm stuck.

I tried:

if(isset($_POST['quantity'])){
    $quantity = $_POST['quantity'];
    $_SESSION['basket'][] = $quantity;
}

but this put the last item a lot in the shopping cart
like this:

then I tried:

if (isset($_POST['quantity']) && !empty($_POST['quantity'])){
    $_SESSION['quantity'] = $_POST['quantity'];
//           //$qty = $_SESSION["qty"] + 1;
     if (isset($_POST['broodnaam']) && !empty($_POST['broodnaam'])){
           if ($_POST['broodnaam'] == $row['broodnaam']){
                $quantity = $_POST['quantity'];
//                    //array_push($_SESSION['qty'], $quantity);
//                 //    var_dump($_SESSION['qty']);
           }
     }
}

but this only updates the last updated item from the cart.
I really don't know how to fix this can someone help me

code: ( part of the code as I don't feel like I need to share the styling and sessions_start() part

<?php
$broodjes = $_GET['broodjes_ID'];
if (isset($_SESSION['basket'])){
  if( in_array( $broodjes ,$_SESSION['basket']) )
  {
  }else{
     $_SESSION['basket'][] = $broodjes;
  }
}else{
  $_SESSION['basket'][]= $broodjes;
}
$sumtotal = 0;
foreach($_SESSION['basket'] as $key => $value){
    //echo "Key = $key; value = $value;
";
    $sql = "SELECT broodjes_ID, broodnaam, prijs, voorraad FROM broodjes WHERE broodjes_ID=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $value);
    $stmt->execute();
    $result = $stmt->get_result();
    if($row = $result->fetch_assoc()){
        //session for quantity
        $_SESSION["qty"] = array();
        echo '
';
        echo '
';
        echo '
';
        echo $row['broodnaam'];
        echo '
';
        echo '
';
        echo '€ ' . $row['prijs'];
        echo '
';
        //quantity
        echo '
';
        echo '<form method="POST" action="">';
        echo '
';
        echo '<input type="hidden" name="broodnaam" id="broodnaam" value="' . $row['broodnaam'] . '">';
        echo '<input type="number" name="quantity" id="quantity" class="form-control input-sm" value="1" min="1" max="'.$row['voorraad'].'">';
        echo '
';
        echo '</form>';
        echo '
';
        //ik moet de quantity ergens in opslaan , denk in db, om zo nog de voorraad te verminderen
        if (isset($_POST['quantity']) && !empty($_POST['quantity'])){
            $_SESSION['quantity'] = $_POST['quantity'];
            //           //$qty = $_SESSION["qty"] + 1;
            if (isset($_POST['broodnaam']) && !empty($_POST['broodnaam'])){
                if ($_POST['broodnaam'] == $row['broodnaam']){
                    $quantity = $_POST['quantity'];
                    ////array_push($_SESSION['qty'], $quantity);
                    ////    var_dump($_SESSION['qty']);
                }
            }
        }
        echo '
';
        $rowtotaal = $row['prijs'] * $quantity;
        $sumtotal += $rowtotaal;
        echo $rowtotaal;
        echo '
';
        echo '
';
        echo '
';
    }
}
?>

    Total
     € <?php   echo $sumtotal;?>

Body:
Update the new quantity ($_POST['quantity']) by adding the old one ($_SESSION['qty']).like this -

   if (isset($_POST['quantity'])){
        if (isset($_POST['broodnaam'])){
            if ($_POST['broodnaam'] == $row['broodnaam']){
                $_SESSION['qty'] = $_POST['quantity'] + $_SESSION['qty'];
            }
        }
   }


问:
Can't install heroku-cli. Path is missing
I've been trying to install heroku. When I run curl https://cli-assets.heroku.com/install.sh | sh on terminal I get this message : 'Your path is missing /usr/local/bin, you need to add this to use this installer.'.

I've already tried to add this to $PATH, but I'm not sure if I did it correctly. When I run echo $PATH this is what I get : '/home/rasklow/usr/local/bin:/home/rasklow/.rbenv/shims:/home/rasklow/.rbenv/bin:/home/rasklow/.rbenv/shims:/home/rasklow/.rbenv/bin:/sbin:/bin:/usr/sbin:/usr/bin:**/usr/local/bin**:/snap/bin.

Now /usr/local/bin appears to be in there, so I don't how else to install heroku. I've tried to download directly the tar.gz file but I'm fairly new to linux and I don't know how to install the package correctly.

答:
Another hack which worked for me (On Amazon Linux 2) was to download the install script and after verifying that /user/local/bin was added to the path, I commented out the check in the script (lines 20-23 in the version as of 2/8/22) and then ran the script:

Step 1: download script: curl https://cli-assets.heroku.com/install.sh > ./install_heroku.sh

Step 2: add /usr/bin/local to path: export PATH=$PATH:/usr/bin/local

Step 3: Comment out the if statement on lines 20-23 of the install script (just add # to the beginning of each line)

Step 4: Run cat ./install_heroku.sh | sudo sh


问:
What is the Alternative for Form Tag in React Fluent-UI?
I am currently developing Microsoft Addin with react. I have added TextField to the AddIn.
But I couldn't get the value from inputs because there is no Form tag in fluent-ui.

What can I do to resolve this?

This is the component.

```<code><Stack>
  <TextField placeholder="User Name" />
  <TextField placeholder="Password" type="password" />
  <PrimaryButton className="ms-welcome__action" iconProps={{ iconName: "ChevronRight" }}>
    Sign In
  </PrimaryButton>
</Stack>
</code>```

答:
I don't know if it is the best way to solve you're problem, but you can add a value to each TextField that is linked to a prop in your component, like that :

```<code><Stack>
  <TextField placeholder="User Name" value={userName} onChange={(e) => setUserName(e.target.value)} />
  <TextField placeholder="Password" type="password" value={passWord} onChange={(e) => setPassWord(e.target.value)} />
  <PrimaryButton className="ms-welcome__action" iconProps={{ iconName: "ChevronRight" }}>
    Sign In
  </PrimaryButton>
</Stack>
</code>```

The onChange handler reset the prop the user is modifying.
Don't forget to declare userName and passWord via the useState hook :

```<code>const [userName, setUserName] = useState("");
const [passWord, setPassWord] = useState("");
</code>```

Body:
I am currently developing Microsoft Addin with react. I have added TextField to the AddIn.
But I couldn't get the value from inputs because there is no Form tag in fluent-ui.

What can I do to resolve this?

This is the component.

<Stack>
  <TextField placeholder="User Name" />
  <TextField placeholder="Password" type="password" />
  <PrimaryButton className="ms-welcome__action" iconProps={{ iconName: "ChevronRight" }}>
    Sign In
  </PrimaryButton>
</Stack>

Body:
I don't know if it is the best way to solve you're problem, but you can add a value to each TextField that is linked to a prop in your component, like that :

<Stack>
  <TextField placeholder="User Name" value={userName} onChange={(e) => setUserName(e.target.value)} />
  <TextField placeholder="Password" type="password" value={passWord} onChange={(e) => setPassWord(e.target.value)} />
  <PrimaryButton className="ms-welcome__action" iconProps={{ iconName: "ChevronRight" }}>
    Sign In
  </PrimaryButton>
</Stack>

The onChange handler reset the prop the user is modifying.
Don't forget to declare userName and passWord via the useState hook :

const [userName, setUserName] = useState("");
const [passWord, setPassWord] = useState("");


问:
how to sorting date in array C++
I have a date in the form of ddmmyyyy in array

```<code>    int checkIn[n], checkOut[n];
    int a = sizeof(checkIn) / sizeof(checkIn[0]);
    int a2 = sizeof(checkOut) / sizeof(checkOut[0]);

    sort(checkIn, checkIn + a);
    sort(checkOut, checkOut + a2);

</code>```

Input:

```<code>3
08022022 15022022
10022025 14022025
15032022 20032022
</code>```

Output:

```<code>8022022 10022025 15032022
</code>```

How to fix. Thank you

答:
I think the best idea to solve this date sort in C++ is to use this struct:

```<code>struct tm {
   int tm_sec;   // seconds of minutes from 0 to 61
   int tm_min;   // minutes of hour from 0 to 59
   int tm_hour;  // hours of day from 0 to 24
   int tm_mday;  // day of month from 1 to 31
   int tm_mon;   // month of year from 0 to 11
   int tm_year;  // year since 1900
   int tm_wday;  // days since sunday
   int tm_yday;  // days since January 1st
   int tm_isdst; // hours of daylight savings time
}
</code>```

You should load the dates you want to sort in this struct and then you can use mktime() to get the time_t for using the following function:

```<code>double difftime (time_t end, time_t beginning);
</code>```

(https://www.cplusplus.com/reference/ctime/difftime/)

This function will calculate the difference between the time_t's. Then you can sort the list or the array. For example for the list you can do: https://www.cplusplus.com/reference/list/list/sort/

Title: how to sorting date in array C++

Body:
I have a date in the form of ddmmyyyy in array

    int checkIn[n], checkOut[n];
    int a = sizeof(checkIn) / sizeof(checkIn[0]);
    int a2 = sizeof(checkOut) / sizeof(checkOut[0]);

    sort(checkIn, checkIn + a);
    sort(checkOut, checkOut + a2);

Input:

3
08022022 15022022
10022025 14022025
15032022 20032022

Output:

8022022 10022025 15032022

How to fix. Thank you

Body:
I think the best idea to solve this date sort in C++ is to use this struct:

struct tm {
   int tm_sec;   // seconds of minutes from 0 to 61
   int tm_min;   // minutes of hour from 0 to 59
   int tm_hour;  // hours of day from 0 to 24
   int tm_mday;  // day of month from 1 to 31
   int tm_mon;   // month of year from 0 to 11
   int tm_year;  // year since 1900
   int tm_wday;  // days since sunday
   int tm_yday;  // days since January 1st
   int tm_isdst; // hours of daylight savings time
}

You should load the dates you want to sort in this struct and then you can use mktime() to get the time_t for using the following function:

double difftime (time_t end, time_t beginning);

(https://www.cplusplus.com/reference/ctime/difftime/)

This function will calculate the difference between the time_t's. Then you can sort the list or the array. For example for the list you can do: https://www.cplusplus.com/reference/list/list/sort/


问:
Running a cron in Yii2
I'm using the advanced template application of yii2 and i want to create a cron.
I could find only little information while googling the subject and so far found that cron jobs should go in the console folder.

my structure:

```<code>backend/
.
.
.
console/
    models/
        Subscriptions.php   // my custom table model
    .
    .
    .
    controllers/
        TimelineController.php
    .
    .
    .
</code>```

I don't know where to go from now or how to proceed? How can I run the cron?

LAMP environment.

答:
In yii2, command which worked for me is:

path/to/php path/to/project/yii command-name

ContentLicense: CC BY-SA 3.0

Title: Running a cron in Yii2

Body:
I'm using the advanced template application of yii2 and i want to create a cron.
I could find only little information while googling the subject and so far found that cron jobs should go in the console folder.

my structure:

backend/
.
.
.
console/
    models/
        Subscriptions.php   // my custom table model
    .
    .
    .
    controllers/
        TimelineController.php
    .
    .
    .

I don't know where to go from now or how to proceed? How can I run the cron?

LAMP environment.


问:
Is there a way to use version of dependency declared in Spring Boot BOM
I have a Gradle-based project with root build.gradle declaring dependency on Spring Boot BOM:

```<code>ext {
  springBootVersion = '2.6.3'
}

subprojects {
  dependencies {
    implementation platform("org.springframework.boot:spring-boot-dependencies:$springBootVersion")
  }
}
</code>```

then in a subproject I have dependencies on liquibase-core and liquibase-cdi:

```<code>ext {
  liquiBaseVersion = '4.4.3'
}

dependencies {
  runtimeOnly "org.liquibase:liquibase-cdi:$liquiBaseVersion"
  runtimeOnly "org.liquibase:liquibase-core"
}
</code>```

the problem is that the version of liquibase-core is automatically picked up from Spring Boot BOM declared in root build.gradle, but liquibase-cdi is not specified in that BOM, so I have to declare its version explicitly (otherwise gradle build fails).

I'd like to use somehow the version of liquibase-core specified in Spring Boot BOM for liquibase-cdi like this can be done with Maven placeholder ${liquibase.version} referencing the property specified in <properties/> of parent pom.

Is there a way to do the same with Gradle?

答:
You can use

```<code>dependencyManagement.importedProperties['spring.version']
</code>```

to get for example the spring.version property which is managed via the Dependency Management Plugin.

See https://docs.spring.io/dependency-management-plugin/docs/current/reference/html/#accessing-properties for details.

You can also use the programmatic access to the dependency management to find the managed version of Liquibase:

```<code>def liquibaseVersion = managedVersions['org.liquibase:liquibase-core']
</code>```

See https://docs.spring.io/dependency-management-plugin/docs/current/reference/html/#working-with-managed-versions-programmatic-access

Body:
I have a Gradle-based project with root build.gradle declaring dependency on Spring Boot BOM:

ext {
  springBootVersion = '2.6.3'
}

subprojects {
  dependencies {
    implementation platform("org.springframework.boot:spring-boot-dependencies:$springBootVersion")
  }
}

then in a subproject I have dependencies on liquibase-core and liquibase-cdi:

ext {
  liquiBaseVersion = '4.4.3'
}

dependencies {
  runtimeOnly "org.liquibase:liquibase-cdi:$liquiBaseVersion"
  runtimeOnly "org.liquibase:liquibase-core"
}

the problem is that the version of liquibase-core is automatically picked up from Spring Boot BOM declared in root build.gradle, but liquibase-cdi is not specified in that BOM, so I have to declare its version explicitly (otherwise gradle build fails).

I'd like to use somehow the version of liquibase-core specified in Spring Boot BOM for liquibase-cdi like this can be done with Maven placeholder ${liquibase.version} referencing the property specified in <properties/> of parent pom.

Is there a way to do the same with Gradle?

Body:
You can use

dependencyManagement.importedProperties['spring.version']

to get for example the spring.version property which is managed via the Dependency Management Plugin.

See https://docs.spring.io/dependency-management-plugin/docs/current/reference/html/#accessing-properties for details.

You can also use the programmatic access to the dependency management to find the managed version of Liquibase:

def liquibaseVersion = managedVersions['org.liquibase:liquibase-core']

See https://docs.spring.io/dependency-management-plugin/docs/current/reference/html/#working-with-managed-versions-programmatic-access


问:
How should I document my C# code?
I am building the documentation for our C# API containing:

A general overview and description of the current state as a doc/pdf file.

A class library API in a .chm file using Sandcastle.

Questions:

Should I merge these two into the same .chm file? What is a good way to merge them?

I need to exclude certain classes/packages. How can I specify that in SandCastle?

It generates documentation for the VB code and the Visual C++ code. How can I change this? Or should I leave it, knowing that I am only using safe code?

Where can I find HTML Help 2.x Viewer Path on my system?

Edit:

The comments I make above methods, fields and classes are not generated in the documentation.

What should I do?

答:
Sandcastle Help File  Builder (SHFB) itself has a .chm file where you can find the answers to questions like "how can I exclude certain namespaces or classes from the generated doc?"

You may think I know the answer and I am being snarky by not telling you. Not true.  But I was skimming the doc last night and saw an entry on this very topic.

I don't know why you wouldn't just leave in the VB and C++ stuff; there may in the future be someone who uses a language that is (shockingly) not C# with your library.  The language is normally settable by the help viewer, so C# devs can ignore the VB syntax.

As for merging, SHFB has a mechanism to add in arbitrary HTML in an arbitrary hierarchy.  In the GUI it is here:

http://www.freeimagehosting.net/uploads/7de19ea568.jpg

Using this, you could convert the PDF/DOC to HTML and then just embed it in the .chm.

OwnerDisplayName: Sasha

LastEditorDisplayName: Rich B

ContentLicense: CC BY-SA 2.5

Title: How should I document my C# code?

OwnerDisplayName: Cheeso

LastEditorDisplayName: Cheeso


问:
Basics of I18n For Yii Framework
Yii's I18n topic isn't enough for me.

My source lang is Turkish , target lang is English (for example)

My test controller's index action :

```<code>public function actionIndex()
    {
        Yii::app()->language='en';
        $this->render("index");
    }
</code>```

This is my view file's content :

```<code>echo Yii::t('test', 'Deneme');
</code>```

And lastly, this is my protected/messages/en/test.php file's content:

```<code>return array(
    'Deneme' => 'Example',
);
</code>```

Everything OK, it's returning Example . But as you can see, i'm setting language manually on my index action. How can i do it automatically ? Must i add Yii::app()->language='en'; to all actions? How you are using l18n on your projects ?

Note : I'm Yii and l18n noob, so please describe step by step .

Thank you.

答: it's fairly simple. You do all language translations as you said. Then, in the parent controller, in the init method, yo can check the desired language and set the current language. That way, you don't have to do that in every action, just once.</p>

Title: Basics of I18n For Yii Framework

Body:
Yii's I18n topic isn't enough for me.

My source lang is Turkish , target lang is English (for example)

My test controller's index action :

public function actionIndex()
    {
        Yii::app()->language='en';
        $this->render("index");
    }

This is my view file's content :

echo Yii::t('test', 'Deneme');

And lastly, this is my protected/messages/en/test.php file's content:

return array(
    'Deneme' => 'Example',
);

Everything OK, it's returning Example . But as you can see, i'm setting language manually on my index action. How can i do it automatically ? Must i add Yii::app()->language='en'; to all actions? How you are using l18n on your projects ?

Note : I'm Yii and l18n noob, so please describe step by step .

Thank you.


问:
how to convert this C# using RingCentral API to VB Net
I have an existing VB. Net application I am trying to add functionality to.  The example code is in C# and I am not sure how to convert this section.  I have converted the rest of it but stuck on this....</p>
```<code>        var parameters = new CreateSMSMessage();
        parameters.from = new MessageStoreCallerInfoRequest { phoneNumber = "19998887777"};
        parameters.to = new MessageStoreCallerInfoRequest[]
            {
            new MessageStoreCallerInfoRequest
                {
                phoneNumber = "12223334444"
            } };
        parameters.text = "Hello World from C#";

        var resp = await restClient.Restapi().Account().Extension().Sms().Post(parameters);
</code>```

答:
I assume the part you're having trouble with is this:

parameters.from = new MessageStoreCallerInfoRequest { phoneNumber = "19998887777"};
parameters.to = new MessageStoreCallerInfoRequest[]
    {
        new MessageStoreCallerInfoRequest
        {
            phoneNumber = "12223334444"
        }
    };
```
<p>VB has virtually identical array initializer syntax and slightly different member initializer syntax requiring the <code>With</code> keyword and prepending <code>.</code> on the member access.</p>
<p>The equivalent in VB is:</p>
<pre class="lang-vb prettyprint-override"><code>parameters.from = New MessageStoreCallerInfoRequest With {.phoneNumber = "19998887777"}
parameters.to = New MessageStoreCallerInfoRequest()
    {
        New MessageStoreCallerInfoRequest With {.phoneNumber = "12223334444"}
    }
</code>```

Body:
I have an existing VB. Net application I am trying to add functionality to.  The example code is in C# and I am not sure how to convert this section.  I have converted the rest of it but stuck on this....

        var parameters = new CreateSMSMessage();
        parameters.from = new MessageStoreCallerInfoRequest { phoneNumber = "19998887777"};
        parameters.to = new MessageStoreCallerInfoRequest[]
            {
            new MessageStoreCallerInfoRequest
                {
                phoneNumber = "12223334444"
            } };
        parameters.text = "Hello World from C#";

        var resp = await restClient.Restapi().Account().Extension().Sms().Post(parameters);

Body:
I assume the part you're having trouble with is this:

parameters.from = new MessageStoreCallerInfoRequest { phoneNumber = "19998887777"};
parameters.to = new MessageStoreCallerInfoRequest[]
    {
        new MessageStoreCallerInfoRequest
        {
            phoneNumber = "12223334444"
        }
    };

VB has virtually identical array initializer syntax and slightly different member initializer syntax requiring the With keyword and prepending . on the member access.

The equivalent in VB is:

parameters.from = New MessageStoreCallerInfoRequest With {.phoneNumber = "19998887777"}
parameters.to = New MessageStoreCallerInfoRequest()
    {
        New MessageStoreCallerInfoRequest With {.phoneNumber = "12223334444"}
    }


问:
Why do the col divs stack instead of aligning aside?
I'm new to Vue.JS and new to front-end programming more in general.
I was trying to set a page with a fixed sidebar and a content page, which is  to rendered below a navbar.
I tried using this configuration:

```<code><template>
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-6">.col-md-6</div>
      <div class="col-md-12">.col-md-12</div>
    </div>
  </div>
</template>
</code>```

To place my sidebar content in the .col-md-6 div, but they're being rendered stacked instead of being aside.

Screenshot of app

答:
I don't think you can use col-md-6 and col-md-12 together
You should try and understand the bootstrap grid system.

For a sidebar, you can try using col-md-3 and col-md-9.

Body:
I'm new to Vue.JS and new to front-end programming more in general.
I was trying to set a page with a fixed sidebar and a content page, which is  to rendered below a navbar.
I tried using this configuration:

<template>

.col-md-6

.col-md-12

</template>

To place my sidebar content in the .col-md-6 div, but they're being rendered stacked instead of being aside.

Screenshot of app


问:
How to read content of a file from a folder in S3 bucket using python?
I was trying to read a file from a folder structure in S3 bucket using python with boto3.

I want to return boolean value wether the report is present in S3 bucket or not.

Code

```<code>import boto3
import json

S3_BUCKET_NAME = ''
KEY = '@@@/%%%.json'

def notification():
    report = get_report()
    print(report)

def get_report():
    s3_client = boto3.client('s3')
    response = s3_client.get_object(Bucket=S3_BUCKET_NAME, Prefix=PREFIX, Key=KEY)
    data = response['Body'].read()
    report = json.loads(data)
    return report

</code>```

How to check if the report is present and return a boolean value ?

答:
2 answers to your questions:

How to read content of a file from a folder in S3 bucket using python?

How to check if the report is present and return a boolean value ?

Get S3-object

S3-object as bytes

```<code>    s3_client = boto3.client('s3')
    response = s3_client.get_object(Bucket=S3_BUCKET_NAME, Prefix=PREFIX, Key=KEY)
    bytes = response['Body'].read()  # returns bytes since Python 3.6+
</code>```

NOTE: For Python 3.6+ read() returns bytes. So if you want to get a string out of it, you must use .decode(charset) on it:

```<code>pythonObject = json.loads(obj['Body'].read().decode('utf-8'))
</code>```

S3-object as string

See Open S3 object as a string with Boto3.

Check if S3-object is present

For example to check the availability of the report as S3.Object just retrieve it and test on the key attribute:

import boto3
import json

S3_BUCKET_NAME = ''
KEY = 'fee_summary/fee_summary_report.json'

def send_fee_summary_notification():
    fee_summary_report = get_fee_summary_report()
    print(fee_summary_report)

def get_fee_summary_report():
    s3_client = boto3.client('s3')
    response = s3_client.get_object(Bucket=S3_BUCKET_NAME, Prefix=PREFIX, Key=KEY)
    data = response['Body'].read()
    fee_summary_report = json.loads(data)
    return fee_summary_report

def has_fee_summary_report():
    s3 = boto3.client('s3')
    obj = s3.Object(S3_BUCKET_NAME, KEY).get()  # define object with KEY (report) and get
    return obj.key != None # returns False if not found
```
<h3>Use paging to literally scan (for debugging)</h3>
<p>You can also iterate over all objects in you bucket via paging and test, if the desired report (with specified KEY) exists:</p>
<pre class="lang-py prettyprint-override"><code>for page in s3.Bucket('boto3').objects.pages():
    for obj in page:
        print(obj.key)  # debug print
        if obj.key == KEY:
            return True
    return False
</code>```

Body:
I was trying to read a file from a folder structure in S3 bucket using python with boto3.

I want to return boolean value wether the report is present in S3 bucket or not.

Code

import boto3
import json

S3_BUCKET_NAME = ''
KEY = '@@@/%%%.json'

def notification():
    report = get_report()
    print(report)

def get_report():
    s3_client = boto3.client('s3')
    response = s3_client.get_object(Bucket=S3_BUCKET_NAME, Prefix=PREFIX, Key=KEY)
    data = response['Body'].read()
    report = json.loads(data)
    return report

How to check if the report is present and return a boolean value ?

Body:
2 answers to your questions:

How to read content of a file from a folder in S3 bucket using python?

How to check if the report is present and return a boolean value ?

Get S3-object

S3-object as bytes

    s3_client = boto3.client('s3')
    response = s3_client.get_object(Bucket=S3_BUCKET_NAME, Prefix=PREFIX, Key=KEY)
    bytes = response['Body'].read()  # returns bytes since Python 3.6+

NOTE: For Python 3.6+ read() returns bytes. So if you want to get a string out of it, you must use .decode(charset) on it:

pythonObject = json.loads(obj['Body'].read().decode('utf-8'))

S3-object as string

See Open S3 object as a string with Boto3.

Check if S3-object is present

For example to check the availability of the report as S3.Object just retrieve it and test on the key attribute:

import boto3
import json

S3_BUCKET_NAME = ''
KEY = 'fee_summary/fee_summary_report.json'

def send_fee_summary_notification():
    fee_summary_report = get_fee_summary_report()
    print(fee_summary_report)

def get_fee_summary_report():
    s3_client = boto3.client('s3')
    response = s3_client.get_object(Bucket=S3_BUCKET_NAME, Prefix=PREFIX, Key=KEY)
    data = response['Body'].read()
    fee_summary_report = json.loads(data)
    return fee_summary_report

def has_fee_summary_report():
    s3 = boto3.client('s3')
    obj = s3.Object(S3_BUCKET_NAME, KEY).get()  # define object with KEY (report) and get
    return obj.key != None # returns False if not found

Use paging to literally scan (for debugging)

You can also iterate over all objects in you bucket via paging and test, if the desired report (with specified KEY) exists:

for page in s3.Bucket('boto3').objects.pages():
    for obj in page:
        print(obj.key)  # debug print
        if obj.key == KEY:
            return True
    return False


问:
Type narrowing: checking variable object key existence when noUncheckedIndexedAccess is true
I have "noUncheckedIndexedAccess": true in my tsconfig.json. The whole point of the switch is to force the check of existence of the item at an index before accessing it.

 I struggle to do the check for object with a variable key:

Say I have the following structure:

const items: Record<string, {name: string}> = {
  '123': {
    name: 'asdf'
  }
}
```
<p>when I try to check the existence using a literal key, the type narrowing works ok:</p>
<pre class="lang-js prettyprint-override"><code>if (items['123']) {
  // OK: Compiles no problem
  console.log(items['123'].name)
}
</code>```

If I try to check the existence using a variable key, the compiler starts to complain.

const id = '123';
if (items[id]) {
  // ERROR: items[id] - Object possibly undefined
  console.log(items[id].name)
}
```
<p> <em>Why is it not possible to check the existence that way?</em></p>
<p>I tried even different checks:</p>
<pre class="lang-js prettyprint-override"><code>if (id in items) {}
if (items.hasOwnProperty(id)) {}
if (typeof items[id] !== 'undefined') {}
</code>```

no luck there.

The only thing that worked was

const id = '123';
const item = items[id];
if (item) {
  // OK
  console.log(item.name)
}
```

I find it a bit too chatty, though.

▶ Examples above in TypeScript Playground

Environment: TypeScript v4.5.4

答:
There's an issue on GitHub that's essentially describing this exact situation:

Can't narrow T | undefined into T with a falsy check when using --noUncheckedIndexedAccess

That issue is closed as a duplicate of this issue, which is still open as of February 2022:

Discriminant property type guard not applied with bracket notation

Based on the discussion on that second issue and other linked issues, it sounds like this is a known limitation due to the performance overhead that would be required to implement this in the type checker, e.g. here:

Declined due to performance reasons. Since it should almost always be possible to write const j = list[i] instead, this shouldn't be too burdensome.

Given that the issue is still open, it seems possible that this may be re-addressed at some point to support the behavior that you expect.

Body:
I have "noUncheckedIndexedAccess": true in my tsconfig.json. The whole point of the switch is to force the check of existence of the item at an index before accessing it.

 I struggle to do the check for object with a variable key:

Say I have the following structure:

const items: Record<string, {name: string}> = {
  '123': {
    name: 'asdf'
  }
}

when I try to check the existence using a literal key, the type narrowing works ok:

if (items['123']) {
  // OK: Compiles no problem
  console.log(items['123'].name)
}

If I try to check the existence using a variable key, the compiler starts to complain.

const id = '123';
if (items[id]) {
  // ERROR: items[id] - Object possibly undefined
  console.log(items[id].name)
}

 Why is it not possible to check the existence that way?

I tried even different checks:

if (id in items) {}
if (items.hasOwnProperty(id)) {}
if (typeof items[id] !== 'undefined') {}

no luck there.

The only thing that worked was

const id = '123';
const item = items[id];
if (item) {
  // OK
  console.log(item.name)
}

I find it a bit too chatty, though.

▶ Examples above in TypeScript Playground

Environment: TypeScript v4.5.4


问:
Querying a Stored Procedure from a stored procedure
Ok, this might be my another bad question, but still I am hopeful. If you look at my recent question, It was an desperate attempt to simplify the need of nesting a stored procedure inside another.

Basically, I needed to select few rows satisfying a particular condition from a view (view_game), and generate other views(view_pupil_game, view_pupil_doubles, view_game_winner) and combine the outputs to create a another view.

But, looking ahead for alternatives I would like to create a stored procedure, which takes a parameters and gives it to others procedure, and take the output as result set and use it to finalize the main procedure.

Please, help me, give a simple example of treating a stored procedure as a table( or record set) and query it inside a store procedure

Update

To give an idea of what i want, here is a dummy query

```<code>begin
Create procedure someProcedure
    @param1 int(3),
    @param2 int(3)
as
begin
    SELECT * FROM <anotherStoreProcedure @param1, @param2> as set1
    inner join <anotherStoreProcedure2 @param1, @param2> as set2 on set2.id=set1.id
end
go
</code>```

答:
Probably you need something like:</p>

```<code>-- tables to save result of calling stored procs below
DECLARE @set1 AS TABLE(id INT, value1 varchar(10))
DECLARE @set2 AS TABLE(id INT, value2 varchar(10))

-- save result of dbo.anotherStoreProcedure call into table variable @set1
INSERT INTO @set1 (id, value1)
EXEC dbo.anotherStoreProcedure @param1, @param2

-- save result of dbo.anotherStoreProcedure2 call into table variable @set2
INSERT INTO @set2 (id, value12)
EXEC dbo.anotherStoreProcedure2 @param1, @param2

SELECT
  *
FROM
  set1
INNER JOIN
  set2
ON
  set2.id = set1.id
</code>```

Body:
Ok, this might be my another bad question, but still I am hopeful. If you look at my recent question, It was an desperate attempt to simplify the need of nesting a stored procedure inside another.

Basically, I needed to select few rows satisfying a particular condition from a view (view_game), and generate other views(view_pupil_game, view_pupil_doubles, view_game_winner) and combine the outputs to create a another view.

But, looking ahead for alternatives I would like to create a stored procedure, which takes a parameters and gives it to others procedure, and take the output as result set and use it to finalize the main procedure.

Please, help me, give a simple example of treating a stored procedure as a table( or record set) and query it inside a store procedure

Update

To give an idea of what i want, here is a dummy query

begin
Create procedure someProcedure
    @param1 int(3),
    @param2 int(3)
as
begin
    SELECT * FROM <anotherStoreProcedure @param1, @param2> as set1
    inner join <anotherStoreProcedure2 @param1, @param2> as set2 on set2.id=set1.id
end
go

Body:
Probably you need something like:

-- tables to save result of calling stored procs below
DECLARE @set1 AS TABLE(id INT, value1 varchar(10))
DECLARE @set2 AS TABLE(id INT, value2 varchar(10))

-- save result of dbo.anotherStoreProcedure call into table variable @set1
INSERT INTO @set1 (id, value1)
EXEC dbo.anotherStoreProcedure @param1, @param2

-- save result of dbo.anotherStoreProcedure2 call into table variable @set2
INSERT INTO @set2 (id, value12)
EXEC dbo.anotherStoreProcedure2 @param1, @param2

SELECT
  *
FROM
  set1
INNER JOIN
  set2
ON
  set2.id = set1.id


问:
How to save a list locally to a database with shared preferences in flutter?
How can I  save a list locally to a database with shared preferences in flutter .
for example :- I have list List notification = []; How can I save this list locally with shared preferences?</p>

答:
The plugin itself already has a method for storing List<String>, it's called setStringList.

If you have some other type of data to store, you simply have to convert them in String and have a function to convert them back in your data type.

The other question linked in the comments is just a collection of convenience methods to store different data types, but it's nothing you can't write on your own.


问:
Window that was opened by window.open won't close
I'm having problems with a piece of code that has worked before for years, but seems to have stopped working now.

I'm opening a window with a login form and I'm listening via a WebSocket for events regarding that login. After the login was successful, I want to close the window (that my script has opened and kept the reference to) after a short moment. I'm using the following code:

const windowManager = {
  window: null,
  eventType: null,
}
function openWindow({ url, eventType }) {
  windowManager.window = window.open(url)
  windowManager.eventType = eventType
}
function closeWindow({ eventType }) {
  if (windowManager.window && windowManager.eventType == eventType) {
    setTimeout(() => {
      windowManager.window && windowManager.window.close()
      windowManager.window = null
    }, 100)
  }
}
```

I have confirmed that windowManager.window.close() is called and does not thrown an error. I have also extracted the code from the application and tested it separately and it still won't close the window. As I said, this piece of code has worked before and was not changed in the past two years or so.

I'm using the following browsers:

Safari 15.3

Firefox 97.0b9 (Developer Edition)

Chromium 94.0.4606.61

I'm grateful for any pointers which could help resolve this issue. Thanks a lot!

答:
After figuring out that the above code worked totally fine with other sites like Google or GitHub, I found that the Cross-Origin-Opener-Policy header in our auth backend (which was the site that was opened with the code) is the culprit. We had just updated Helmet to version 5 which added the header by default.

Our solution was to set Cross-Origin-Opener-Policy to same-origin-allow-popups on both source and target window (which are hosted on the same origin, but served by different servers). It also worked when setting it to unsafe-none for the target window without setting it at all on the source window.

Body:
I'm having problems with a piece of code that has worked before for years, but seems to have stopped working now.

I'm opening a window with a login form and I'm listening via a WebSocket for events regarding that login. After the login was successful, I want to close the window (that my script has opened and kept the reference to) after a short moment. I'm using the following code:

const windowManager = {
  window: null,
  eventType: null,
}
function openWindow({ url, eventType }) {
  windowManager.window = window.open(url)
  windowManager.eventType = eventType
}
function closeWindow({ eventType }) {
  if (windowManager.window && windowManager.eventType == eventType) {
    setTimeout(() => {
      windowManager.window && windowManager.window.close()
      windowManager.window = null
    }, 100)
  }
}

I have confirmed that windowManager.window.close() is called and does not thrown an error. I have also extracted the code from the application and tested it separately and it still won't close the window. As I said, this piece of code has worked before and was not changed in the past two years or so.

I'm using the following browsers:

Safari 15.3

Firefox 97.0b9 (Developer Edition)

Chromium 94.0.4606.61

I'm grateful for any pointers which could help resolve this issue. Thanks a lot!


问:
how to write laravel code in css to change value of property
```<code>background-color: #55ce63;
color: #fff;
content:<? {{__('trans.On')}} ?>;
padding-right: 14px
</code>```

this code css in header of blade how to write laravel code in css  to change

答:
You can't use php or blade in your css file, but you can set a css variable in your .blade.php file as a style attribute:

```<code>style="--content-on: '{{ __('trans.On') }}';"
</code>```

And use that variable in your css file:

```<code>content: var(--content-on);
</code>```

Body:
background-color: #55ce63;
color: #fff;
content:<? {{__('trans.On')}} ?>;
padding-right: 14px

this code css in header of blade how to write laravel code in css  to change

Body:
You can't use php or blade in your css file, but you can set a css variable in your .blade.php file as a style attribute:

style="--content-on: '{{ __('trans.On') }}';"

And use that variable in your css file:

content: var(--content-on);


问:
How to remove one value from a key in localstorage that has many values?
I've seen this question asked before but the solutions didn't help me hence why i've asked it again.

Currently, I am storing values into an array and that array is getting stored into localstorage.

This is the object

```<code>data.items -

0: {id: 190217270, node_id: 'MDEwOlJlcG9zaXRvcnkxOTAyMTcyNzA=', name: '3-Bit-CNC-Starter-Pack'}
1: {id: 187179414, node_id: 'MDEwOlJlcG9zaXRvcnkxODcxNzk0MTQ=', name: 'inb-go}
</code>```

I have mapped through this and used 'name' as the value. I am calling this value through a button using this function

```<code>const favs = [];

  function checkId(e) {
    if (e.target.value !== ""){
      if (!favs.includes(e.target.value)){
      favs.push(e.target.value);
      localStorage.setItem("name", JSON.stringify(favs));
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
      }
    }

    }
</code>```

and to remove the value from localstorage I am using this function.

```<code>function removeId(e, value) {
    if (e.target.value !== "") {

      favs.pop(e.target.value);
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
      const stored = JSON.parse(localStorage.getItem("name"));
      delete stored[value, e.target.value];
      localStorage.setItem("name", JSON.stringify(stored));
      console.log(stored);

    }
  }
</code>```

Although the value is being removed from the array, it is not being removed from localstorage.

side note - I am calling this function with a separate button.

console log

```<code>array (item is gone)
[]

localstorage (the value is still there)
[
    "Spiral-Up-Cut-Router-Bit"
]
</code>```

But if I select another item to be added to localstorage, then the previous item gets removed.

```<code>UNFAVORITE - FUNCTION REMOVEid
[
        "Spiral-Up-Cut-Router-Bit"
    ]

 NEW FAVORITE - FUNCTION NEWId

[
    "graphqless"
]
</code>```

I hope this makes sense, I tried to add detail to it as best as possible.

答:
I am not sure whether this will help you but anyway I am sharing.

I don't understand this part of the abovementioned code:

```<code>delete stored[value, e.target.value];
</code>```

What are you passing in the value and e.target.value? If it is the name ("Spiral-Up-Cut-Router-Bit") itself then the delete won't remove the value from the array. Usually, when you use the delete operator on the JS array you need to pass the index of the value, not the value itself.

Also, When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array.

When the delete operator removes an array element, that element is no longer in the array.

You can refer to the above output image, when I deleted the array values using the value even though its output is true it does not delete the value from the array. But when I used the index value for the delete, it deleted the value from the array.

Note: The array just removed the value but did not clear the index.

Maybe, you should use splice to remove specific values from the array and store the new array into the storage.

Also, the delete operator works well with JS objects. If you want to read more about this you can go to this link.✌

Delete using splice:

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; trees.splice(3,1); console.log(trees);

Body:
I've seen this question asked before but the solutions didn't help me hence why i've asked it again.

Currently, I am storing values into an array and that array is getting stored into localstorage.

This is the object

data.items -

0: {id: 190217270, node_id: 'MDEwOlJlcG9zaXRvcnkxOTAyMTcyNzA=', name: '3-Bit-CNC-Starter-Pack'}
1: {id: 187179414, node_id: 'MDEwOlJlcG9zaXRvcnkxODcxNzk0MTQ=', name: 'inb-go}

I have mapped through this and used 'name' as the value. I am calling this value through a button using this function

const favs = [];

  function checkId(e) {
    if (e.target.value !== ""){
      if (!favs.includes(e.target.value)){
      favs.push(e.target.value);
      localStorage.setItem("name", JSON.stringify(favs));
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
      }
    }

    }

and to remove the value from localstorage I am using this function.

function removeId(e, value) {
    if (e.target.value !== "") {

      favs.pop(e.target.value);
      console.log(favs);
      document.getElementById("favsarray").innerHTML = favs;
      const stored = JSON.parse(localStorage.getItem("name"));
      delete stored[value, e.target.value];
      localStorage.setItem("name", JSON.stringify(stored));
      console.log(stored);

    }
  }

Although the value is being removed from the array, it is not being removed from localstorage.

side note - I am calling this function with a separate button.

console log

array (item is gone)
[]

localstorage (the value is still there)
[
    "Spiral-Up-Cut-Router-Bit"
]

But if I select another item to be added to localstorage, then the previous item gets removed.

UNFAVORITE - FUNCTION REMOVEid
[
        "Spiral-Up-Cut-Router-Bit"
    ]

 NEW FAVORITE - FUNCTION NEWId

[
    "graphqless"
]

I hope this makes sense, I tried to add detail to it as best as possible.

Body:
I am not sure whether this will help you but anyway I am sharing.

I don't understand this part of the abovementioned code:

delete stored[value, e.target.value];

What are you passing in the value and e.target.value? If it is the name ("Spiral-Up-Cut-Router-Bit") itself then the delete won't remove the value from the array. Usually, when you use the delete operator on the JS array you need to pass the index of the value, not the value itself.

Also, When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array.

When the delete operator removes an array element, that element is no longer in the array.

You can refer to the above output image, when I deleted the array values using the value even though its output is true it does not delete the value from the array. But when I used the index value for the delete, it deleted the value from the array.

Note: The array just removed the value but did not clear the index.

Maybe, you should use splice to remove specific values from the array and store the new array into the storage.

Also, the delete operator works well with JS objects. If you want to read more about this you can go to this link.✌

Delete using splice:

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; trees.splice(3,1); console.log(trees);


答:
Bootstrap operates on a row having 12 columns that you can divide among the child elements, so in your case where you have one div with a col-md-6 and a col-md-12 you will not have enough room for both on one row, but if you divide those 12 columns equally you will have both on the same row

```<code><template>
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-6">.col-md-6</div>
      <div class="col-md-6">.col-md-6</div>
    </div>
  </div>
</template>
</code>```

Another thing, the proportion that each child element has of the columns will be equal to the amount of the row that they take up so in the case of above they will share the same amount but you may want one to be larger than the other so you could allocate 1/3 of the columns to one container and 2/3 of the columns to the other. As in the example below

```<code><template>
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-4">.col-md-4</div>
      <div class="col-md-8">.col-md-8</div>
    </div>
  </div>
</template>
</code>```

Title: Why do the col divs stack instead of aligning aside?

Body:
Bootstrap operates on a row having 12 columns that you can divide among the child elements, so in your case where you have one div with a col-md-6 and a col-md-12 you will not have enough room for both on one row, but if you divide those 12 columns equally you will have both on the same row

<template>
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-6">.col-md-6</div>
      <div class="col-md-6">.col-md-6</div>
    </div>
  </div>
</template>

Another thing, the proportion that each child element has of the columns will be equal to the amount of the row that they take up so in the case of above they will share the same amount but you may want one to be larger than the other so you could allocate 1/3 of the columns to one container and 2/3 of the columns to the other. As in the example below

<template>
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-4">.col-md-4</div>
      <div class="col-md-8">.col-md-8</div>
    </div>
  </div>
</template>


问:
Why avro, or Parquet format is faster than csv?
I can read articles where I can read that csv is slower and bad for large dataset.

but I cant understand what is it with avro/parquet internally which makes it faster for larger dataset than csv.

答: Binary data is always faster than the same textual representation. Avro sends data over the wire in binary format and the keys are also omitted making the packet size smaller. Hence, avro is good for bigger data formats.</p>


问:
Pandas: Creating DataFrame from Series
My current code is shown below - I'm importing a MAT file and trying to create a DataFrame from variables within it:

```<code>mat = loadmat(file_path)  # load mat-file
Variables = mat.keys()    # identify variable names

df = pd.DataFrame         # Initialise DataFrame

for name in Variables:

    B = mat[name]
    s = pd.Series (B[:,1])
</code>```

So within the loop, I can create a series of each variable (they're arrays with two columns - so the values I need are in column 2)

My question is how do I append the series to the dataframe? I've looked through the documentation and none of the examples seem to fit what I'm trying to do.

答:
Nowadays there is a pandas.Series.to_frame method:

Series.to_frame(name=NoDefault.no_default)

Convert Series to DataFrame.

Parameters

nameobject, optional: The passed name should substitute for the series name (if it has one).

Returns

DataFrame: DataFrame representation of Series.

Examples

```<code>s = pd.Series(["a", "b", "c"], name="vals")
s.to_frame()
</code>```

Title: Pandas: Creating DataFrame from Series

Body:
My current code is shown below - I'm importing a MAT file and trying to create a DataFrame from variables within it:

mat = loadmat(file_path)  # load mat-file
Variables = mat.keys()    # identify variable names

df = pd.DataFrame         # Initialise DataFrame

for name in Variables:

    B = mat[name]
    s = pd.Series (B[:,1])

So within the loop, I can create a series of each variable (they're arrays with two columns - so the values I need are in column 2)

My question is how do I append the series to the dataframe? I've looked through the documentation and none of the examples seem to fit what I'm trying to do.

Body:
Nowadays there is a pandas.Series.to_frame method:

Series.to_frame(name=NoDefault.no_default)

Convert Series to DataFrame.

Parameters

nameobject, optional: The passed name should substitute for the series name (if it has one).

Returns

DataFrame: DataFrame representation of Series.

Examples

s = pd.Series(["a", "b", "c"], name="vals")
s.to_frame()