问:
stderr out to a variable
I have a bash script that iterates through a list of file locations (filepath) and deletes them. I'd like to have any errors that the command throws (like permission issues) go to an individual log as it iterates through files. Like a confirmation that the delete actually happened.

So MASTERDELETELIST.txt has a list of DeleteMeList-Category-[A-Z].txt, each one then has lines like /foo/bar/deleteme-[01-99].txt (**brackets for illustration only)

As the script iterates, it creates a report specific to that CATEGORY list. I need to push it like so: exec 2> >> $ERRORSREPORT, which throws an error:

./script.sh: line 60: syntax error near unexpected token >>' ./script.sh: line 60:                  exec 2> >> $ERRORSREPORT'

*exact output from Terminal makes the formatting errors above)

..or exec 2> $ERRORREPORT which doesn't seem to output anything.. when a file cannot be deleted (I chown'd it to a different user and chmod'd to 600)

How do I accomplish this?

Here's the script:

```<code>#!/bin/bash

MASTERDELETELIST="/Sandbox/masterlist.txt"

file=$MASTERDELETELIST

while IFS= read list

    do   # first DeleteMeList file

        let "NUMBER+=1"
        CATEGORY="CATEGORY"
        REPORT="$CATEGORY-$NUMBER-REPORT"
        THISLOOPREPORT="/Sandbox/Dumpster/$REPORT-DELETEDFILES.txt"
        NOTFOUNDREPORT="/Sandbox/Dumpster/$REPORT-NOTFOUND.txt"
        ERRORSREPORT="/Sandbox/Dumpster/$REPORT-ERRORS.txt"

        file=$list

        while IFS= read line

            do   #run the DeleteList items

                if [ -f  "$line" ]
                    then
                    # found the file
                    echo "$line" >> $THISLOOPREPORT
                    rm "$line"
                    # exec 2> ./Sandbox/Dumpster/errors.txt this works but doesn't update with each iteration reports
                    # exec 2> $ERRORSREPORT ???

                    else
                    echo "file not found: $line" >> $NOTFOUNDREPORT
                fi

            done < $list

    done < $MASTERDELETELIST
</code>```

答:
```<code>command >> log_file 2>> err_file
</code>```

Title: stderr out to a variable

Body:
I have a bash script that iterates through a list of file locations (filepath) and deletes them. I'd like to have any errors that the command throws (like permission issues) go to an individual log as it iterates through files. Like a confirmation that the delete actually happened.

So MASTERDELETELIST.txt has a list of DeleteMeList-Category-[A-Z].txt, each one then has lines like /foo/bar/deleteme-[01-99].txt (**brackets for illustration only)

As the script iterates, it creates a report specific to that CATEGORY list. I need to push it like so: exec 2> >> $ERRORSREPORT, which throws an error:

./script.sh: line 60: syntax error near unexpected token >>' ./script.sh: line 60:                  exec 2> >> $ERRORSREPORT'

*exact output from Terminal makes the formatting errors above)

..or exec 2> $ERRORREPORT which doesn't seem to output anything.. when a file cannot be deleted (I chown'd it to a different user and chmod'd to 600)

How do I accomplish this?

Here's the script:

#!/bin/bash

MASTERDELETELIST="/Sandbox/masterlist.txt"

file=$MASTERDELETELIST

while IFS= read list

    do   # first DeleteMeList file

        let "NUMBER+=1"
        CATEGORY="CATEGORY"
        REPORT="$CATEGORY-$NUMBER-REPORT"
        THISLOOPREPORT="/Sandbox/Dumpster/$REPORT-DELETEDFILES.txt"
        NOTFOUNDREPORT="/Sandbox/Dumpster/$REPORT-NOTFOUND.txt"
        ERRORSREPORT="/Sandbox/Dumpster/$REPORT-ERRORS.txt"

        file=$list

        while IFS= read line

            do   #run the DeleteList items

                if [ -f  "$line" ]
                    then
                    # found the file
                    echo "$line" >> $THISLOOPREPORT
                    rm "$line"
                    # exec 2> ./Sandbox/Dumpster/errors.txt this works but doesn't update with each iteration reports
                    # exec 2> $ERRORSREPORT ???

                    else
                    echo "file not found: $line" >> $NOTFOUNDREPORT
                fi

            done < $list

    done < $MASTERDELETELIST

Body: command >> log_file 2>> err_file


来源: stackexchange

问:
Questions about Native applications and openId Authorization code flow
I have a few concerns with an OpenId Connect strategy that I would like to use and have been unable to find specifics on what the security concerns may be and any glaring issues with it I am overlooking.

Currently, I have an OpenId Connect implementation using Openiddict with Authorization Code flow. For the client, I have a React-Native app using react-native-app-auth.

I see from other questions on SO and from issues posted on the Openiddict repo that the recommended approach to third-party providers (e.g. Google) is: Client -> Auth server -> Google Auth -> Auth server -> Client/Auth server code and token exchange

However, it seems that a better approach from a UX standpoint (when using a SPA or native app) would be to implement something similar to GoogleSignIn on the client and either handle the identity on the server using an IdToken or authorization code from Google. This introduces an issue as the flow previously recommended could not be used as the entire initial challenge and redirect from Auth server to Google Auth has been skipped.

I have seen that this issue is mitigated by not using the authorization code grant and instead implementing a custom assertion grant. This seems to be an alright approach but would require exposing a custom grant and handling the flow differently on the client and server for local and third-party logins.

My proposed solution continues to use the authorization code flow and instead of adding a custom grant type the client could just pass a third-party identifier "Google" and the token or authorization code in the additional parameters of the OIDC authorize request. The authorize endpoint could then detect the provider and token, perform token validation, create a user or principal from it, and create an authorization code to send back to the client for the code/token exchange. This flow would look like the following:

1. Get the id token from the provider Client -> GoogleSignIn -> Client

2. Pass token to auth server and initiate code / token exchange Client -> Auth Server -> Auth server Verify Google IdToken (JWKS, issuer, audience, provider specific validation, etc...) or exchange auth code -> Auth server -> Client/Auth server code and token exchange

One downside to this approach would be the additional hops to verify the token on the server side. If the token was returned from GoogleSignIn, they themselves said that it could be trusted. https://developers.google.com/identity/protocols/oauth2/openid-connect#obtainuserinfo

I see that it is generally recommended to place the auth server between the client and the third-party but in this process the server is still between the client and auth server but only after the initial exchange from the client and third-party.

Questions,

In general am I missing something with this flow?

In this case would it be necessary to verify the token on the server side?

Is there some better way to approach this that I have completely overlooked?

Am I making this too complicated and UX should not be this much of a concern?

Instead of adding the provider and token to the additional parameters would it make more sense to pass it in the body of a post request? I don't see the issue with passing it via query string but that's also part of the reasoning for the authorization code grant from my understanding.

Apologies in advance for anything I have missed or omitted for brevity that should have been included.

Thanks.

答:
ARCHITECTURE

I'm not sure I understand the UX problem - your existing architecture feels really good. If you want to login directly to Google, just send an acr_values=google query parameter in the authorization redirect, to bypass any authentication selection screens. The exact value will depend on how Openiddict represents the Google authentication option, and some providers use a non-standard parameter such as idp. Have a closer look at the OIDC request parameters.

A key OAuth goal is that the Authorization Server (AS) -  Openiddict in your case - shields your apps from all of the provider differences and deals with their nuances and vendor specific behaviour. Your apps then also only receive one type of token, and only ever use simple code. As an example, the Curity AS supports all of these options, none of which requires any code in applications.

APPAUTH AND UX

If a user is already signed in then it can, as you say, look unnatural to spin up the system browser and them it is dismissed immediately.

A common option is to show the consent screen or an interstitial page to keep the user informed - and the user clicks one extra button. This can also be useful for getting password autofill to work. My code example and blog post shows how this might look, though of course you can improve on my basic UX.

OFFLINE ACCESS

I find this term misleading, since refresh tokens are most commonly used when the user is there. Are you just asking how to deal with tokens in a mobile client? Aim for behaviour like this:

Standard messages for API calls with access tokens in an authorization bearer header

Standard refresh token grant messages to refresh access tokens - eg as in this code

Note also that mobile apps can save tokens to encrypted secure mobile storage that is private to the app. This can improve usability, eg by avoiding logins every time the app is restarted. You should think through scenarios such as stolen devices and token lifetimes though.

ContentLicense: CC BY-SA 4.0


问:
memory loss in the following C code
I am getting memory loss of 16 byte in the following code for queuing. Could you please let me know how can get rid of this problem? The code is:

```<code>      void enqueue( enqueuenode * queueNode1 ,bplus *bplusNew){
      [98] -> enqueue *queue=NULL;
              queue = malloc(sizeof(enqueue_node));
              queue->bplus = bplusNew;
              queue->next= NULL;
                if(queueNode1->headNode == NULL){
                   queueNode1->headNode=queueNode1->tailNode = queue ;
                   }
                 else{
                 queueNode1->tailNode->next = queue;
                 queueNode1->tailNode = queue;
                 }
            }
</code>```

Following are two strucutres

```<code>         typedef struct enqueue_help{
           bplus bplusNode;
           struct enqueue_help * next;
         }*enqueue,enqueue_node;

        typedef struct enqueuenode_help{
          enqueue  headNode;
          enqueue  tailNode;
        }*enqueuenode,enqueuenode_node;
</code>```

And for the above code following is the valgrind output:

```<code>             =23800== 272 (16 direct, 256 indirect) bytes in 1 blocks are definitely lost in loss record 8 of 12
             ==23800==    at 0x4C2260E: malloc (vg_replace_malloc.c:207)
             ==23800==    by 0x4024BD:  enqueue(bplus.c:98)
             ==23800==    by 0x40260A:  PrintBplus (bplus.c:202)
             ==23800==    by 0x40286F: main (bplus.c:1251)
             ==23800==
</code>```

Here enqueuenode is the pointer for the structure which holds two enqueue as a head node and tail node. This is for traversal of queue during dequeuing. Each queue is a pointer for the structure which holds some node address which needs to be queued.

答:
Is there a reason why a pointer to enqueue is assigned a memory block that's sized for an enqueuenode?

```<code>  [98] -> enqueue *queue=NULL;
          queue = malloc(sizeof(enqueuenode));
</code>```

If, as you say, enqueuenode contains two enqueue's, the second one could be the memory you're missing.

ContentLicense: CC BY-SA 3.0

Title: memory loss in the following C code

Body:
I am getting memory loss of 16 byte in the following code for queuing. Could you please let me know how can get rid of this problem? The code is:

      void enqueue( enqueuenode * queueNode1 ,bplus *bplusNew){
      [98] -> enqueue *queue=NULL;
              queue = malloc(sizeof(enqueue_node));
              queue->bplus = bplusNew;
              queue->next= NULL;
                if(queueNode1->headNode == NULL){
                   queueNode1->headNode=queueNode1->tailNode = queue ;
                   }
                 else{
                 queueNode1->tailNode->next = queue;
                 queueNode1->tailNode = queue;
                 }
            }

Following are two strucutres

         typedef struct enqueue_help{
           bplus bplusNode;
           struct enqueue_help * next;
         }*enqueue,enqueue_node;

        typedef struct enqueuenode_help{
          enqueue  headNode;
          enqueue  tailNode;
        }*enqueuenode,enqueuenode_node;

And for the above code following is the valgrind output:

             =23800== 272 (16 direct, 256 indirect) bytes in 1 blocks are definitely lost in loss record 8 of 12
             ==23800==    at 0x4C2260E: malloc (vg_replace_malloc.c:207)
             ==23800==    by 0x4024BD:  enqueue(bplus.c:98)
             ==23800==    by 0x40260A:  PrintBplus (bplus.c:202)
             ==23800==    by 0x40286F: main (bplus.c:1251)
             ==23800==

Here enqueuenode is the pointer for the structure which holds two enqueue as a head node and tail node. This is for traversal of queue during dequeuing. Each queue is a pointer for the structure which holds some node address which needs to be queued.

Body:
Is there a reason why a pointer to enqueue is assigned a memory block that's sized for an enqueuenode?

  [98] -> enqueue *queue=NULL;
          queue = malloc(sizeof(enqueuenode));

If, as you say, enqueuenode contains two enqueue's, the second one could be the memory you're missing.


问:
Why does the predict_proba function return 2 columns?
Why does the predict_proba function give 2 columns?

I looked to this website:
https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression.predict_proba

However, it just says returns: T: array-like of shape (n_samples, n_classes)

Returns the probability of the sample for each class in the model, where classes are ordered as they are in self.classes_.

I still don't understand why the output always returns 2 columns.

import numpy as np
import pandas as pd
from pylab import rcParams
import seaborn as sb
from sklearn.preprocessing import scale
from collections import Counter

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

%matplotlib inline
rcParams['figure.figsize'] = 5,4
sb.set_style('whitegrid')

from sklearn.linear_model import LogisticRegression

import os
cwd = os.getcwd()
file_path = cwd + '\\Default.xlsx'
default_data = pd.read_excel(file_path)

default_data = pd.read_excel('Default.xlsx')

default_data = default_data.drop(['Unnamed: 0'], axis=1)
default_data['default_factor'] = default_data.default.factorize()[0]
default_data['student_factor'] = default_data.student.factorize()[0]

X = default_data[['balance']]
y = default_data['default_factor']

lr = LogisticRegression()
lr.fit(X, y)

X_pred = np.linspace(start = 0, stop = 3000, num = 2).reshape(-1,1)
y_pred = lr.predict_proba(X_pred)

X_pred
X_pred.shape
y_pred.shape```

答:
Short answer

In every column it gives you information about the probability, that sample belong to this class (zero column shows the probability for belonging to class 0, first column shows the probability for belonging to class 1 and so on)

Detailed answer

Let's say that y_pred.shape gives you shape (2, 2) means, that you have 2 samples and 2 classes.

let's say that your X_pred looks like this:

```<code> In: print(X_pred)
Out: [[   0.],
      [3000.]]
</code>```

that means that you have two samples:

sample one, with only feature x = [0] and

sample two, with only feature x = [3000]

let's say that output of your prediction looks like this:

```<code>In:  print(y_pred)

Out: [[0.28, 0.72]
      [0.65, 0.35]]
</code>```

so it means, that sample one most probably belongs to class = 1 (first row tells you that it could be class 0 with probability 28% and class 1 with probability 72%)

and sample two most probably belongs to class = 0 (second row tells you that it could be class 0 with probability 65% and class 1 with probability 35%)

Body:
Short answer

In every column it gives you information about the probability, that sample belong to this class (zero column shows the probability for belonging to class 0, first column shows the probability for belonging to class 1 and so on)

Detailed answer

Let's say that y_pred.shape gives you shape (2, 2) means, that you have 2 samples and 2 classes.

let's say that your X_pred looks like this:

 In: print(X_pred)
Out: [[   0.],
      [3000.]]

that means that you have two samples:

sample one, with only feature x = [0] and

sample two, with only feature x = [3000]

let's say that output of your prediction looks like this:

In:  print(y_pred)

Out: [[0.28, 0.72]
      [0.65, 0.35]]

so it means, that sample one most probably belongs to class = 1 (first row tells you that it could be class 0 with probability 28% and class 1 with probability 72%)

and sample two most probably belongs to class = 0 (second row tells you that it could be class 0 with probability 65% and class 1 with probability 35%)


问:
Ignore URL segments in 301 Redirect rule
Struggling with a 301 redirect rule to ignore additional URL segments.  Here is the goal:

Redirect URLs in this format: example.com/product-category/category-parent/category-child/ to a new target URL.

Here is the rule in .htaccess:

```<code>Redirect 301 /product-category/category-parent/category-child/ https://newurl.com/
</code>```

The redirecting is happening fine, except that the child segment of the URL is passed thru to the new URL so I end up with newurl/category-child/ which is a 404.

EDIT:
Tried using RedirectMatch for the few specific nested category URLs with no luck:

```<code>RedirectMatch 301 /product-category/parent/child/ https://newurl.com/
</code>```

Still produces https://newurl.com/child which is a 404.

答:
Sorted out how to do what I needed.  Apache's RedirectMatch is what I needed with the proper regular expression.

```<code>RedirectMatch permanent "^/product-category/(.*)" "https://newurl.com/"
</code>```

This will match any number of any character after the /product-category/ segment and redirect to the new target URL, which is exactly what I needed.

Body:
Struggling with a 301 redirect rule to ignore additional URL segments.  Here is the goal:

Redirect URLs in this format: example.com/product-category/category-parent/category-child/ to a new target URL.

Here is the rule in .htaccess:

Redirect 301 /product-category/category-parent/category-child/ https://newurl.com/

The redirecting is happening fine, except that the child segment of the URL is passed thru to the new URL so I end up with newurl/category-child/ which is a 404.

EDIT:
Tried using RedirectMatch for the few specific nested category URLs with no luck:

RedirectMatch 301 /product-category/parent/child/ https://newurl.com/

Still produces https://newurl.com/child which is a 404.

Body:
Sorted out how to do what I needed.  Apache's RedirectMatch is what I needed with the proper regular expression.

RedirectMatch permanent "^/product-category/(.*)" "https://newurl.com/"

This will match any number of any character after the /product-category/ segment and redirect to the new target URL, which is exactly what I needed.


问:
RecyclerView items lose focus
In my fire tv app I'm using a recyclerview with horizontal layout.

Scrolling with dpad works and also items are gaining focus.

But when I hold the button it scrolls very fast because many keydown events are triggered, and items are losing their focus and it's not possible to scroll anymore because another Textview above my recyclerview is gaining the focus.

It looks like a bug. Is there any workaround for this?

答:
Updated Answer to 2023:

Recyclerview loses focus when using the DPAD and its a known bug. A little hack I use is to override onBackPressed and add the following:

```<code>@Override
public void onBackPressed() {
    Log.i("MainActivity", "getCurrentFocus(): "+getCurrentFocus());
    }
</code>```

This hack or line of code lets me know when I lose focus who has the current focus by pressing Back and you will get something with a hint like this:

```<code>getCurrentFocus(): androidx.recyclerview.widget.RecyclerView{12c0bcc VFED.VC.. .F...... 0,0-1843,864 #7f0a016a app:id/recycler_view}
</code>```

With this you will know who is getting focus and you can add an onFocusChange listener to that view or just disable focusability on that view all together. The important thing is you find out who is getting that focus when recyclerview loses it.

Title: RecyclerView items lose focus

Body:
Updated Answer to 2023:

Recyclerview loses focus when using the DPAD and its a known bug. A little hack I use is to override onBackPressed and add the following:

@Override
public void onBackPressed() {
    Log.i("MainActivity", "getCurrentFocus(): "+getCurrentFocus());
    }

This hack or line of code lets me know when I lose focus who has the current focus by pressing Back and you will get something with a hint like this:

getCurrentFocus(): androidx.recyclerview.widget.RecyclerView{12c0bcc VFED.VC.. .F...... 0,0-1843,864 #7f0a016a app:id/recycler_view}

With this you will know who is getting focus and you can add an onFocusChange listener to that view or just disable focusability on that view all together. The important thing is you find out who is getting that focus when recyclerview loses it.


问:
How I can clear CustomValidator ErrorMessage through JavaScript
How I can clear a CustomValidator ErrorMessage text value through a JavaScript function. Please provide me the solution.

Thanks All.

答:
The Text value of the validator is what gets displayed where the validator is rendered. The ErrorMessage value is what gets displayed in the ValidationSummary, if the page has one.

To clear the values, use the following javascript after the page has loaded.

To clear the Text value, you'll need to clear the inner contents of the validator's span that gets rendered.

```<code>document.getElementById('MyValidator').innerHTML = '';
</code>```

With javascript, .net creates a variable for each validator and sets the properties. So, just set the errormessage property after this point (usually on load of the page).

```<code>MyValidator.errormessage = '';
</code>```

Body:
The Text value of the validator is what gets displayed where the validator is rendered. The ErrorMessage value is what gets displayed in the ValidationSummary, if the page has one.

To clear the values, use the following javascript after the page has loaded.

To clear the Text value, you'll need to clear the inner contents of the validator's span that gets rendered.

document.getElementById('MyValidator').innerHTML = '';

With javascript, .net creates a variable for each validator and sets the properties. So, just set the errormessage property after this point (usually on load of the page).

MyValidator.errormessage = '';


问:
Img Src function in popup with Google Apps Script
I would to embed in my popup an image with the img src function.

How could I proceed in google apps script?

```<code>  copyDoc.saveAndClose();
  var url = "https://docs.google.com/document/d/"+ copyId +"";
  var htmlString = "<base target=\"_blank\">" +
  "<h2><a href=\"" + url + "\">Open Doc!</a></h2>";
  var html = HtmlService.createHtmlOutput(htmlString);
  SpreadsheetApp.getUi().showModalDialog(html, 'Very Good!')
</code>```

答:
Something like this?

```<code>var url = "https://docs.google.com/document/d/"+ copyId +"";
var htmlString = "<base target=\"_blank\">" +
"<h2><a href=\"" + url + "\">Open Doc!</a></h2>" +
"<p><img src='https://www.gstatic.com/script/apps_script_1x_48dp.png' /></p>";
var html = HtmlService.createHtmlOutput(htmlString);
SpreadsheetApp.getUi().showModalDialog(html, 'Very Good!')
</code>```

Body:
I would to embed in my popup an image with the img src function.

How could I proceed in google apps script?

  copyDoc.saveAndClose();
  var url = "https://docs.google.com/document/d/"+ copyId +"";
  var htmlString = "<base target=\"_blank\">" +
  "
Open Doc!
";
  var html = HtmlService.createHtmlOutput(htmlString);
  SpreadsheetApp.getUi().showModalDialog(html, 'Very Good!')

Body:
Something like this?

var url = "https://docs.google.com/document/d/"+ copyId +"";
var htmlString = "<base target=\"_blank\">" +
"<h2><a href=\"" + url + "\">Open Doc!</a></h2>" +
"<p><img src='https://www.gstatic.com/script/apps_script_1x_48dp.png' /></p>";
var html = HtmlService.createHtmlOutput(htmlString);
SpreadsheetApp.getUi().showModalDialog(html, 'Very Good!')


问:
How would I use .split() to split a string by \n instead of .split() reading \n as a new line
I'm trying to split up a string inside of a list into a list, and the string contains \n as a character.
Whenever I use .split("\n"), its of course splitting the string at a new line, but I need it to split at the character \n. Is there anyway to make .split() interpret it this way?

Example:

```<code>#original list
['\nSK Telecom Co. Ltd. ADR\nSKM\n12/31/2021\n1.49\nN/A\nN/A']
</code>```

what id like to create with .split() function:

```<code>[ [SK Telecom CO. Ltd. ADR] , [SKM] , [12/31/2021] , [1.49], [N/A], [N/A] ]
</code>```

if you have any idea on how to help i'd be very grateful, thanks!

答:
If I interpret your question literally, it looks like you want the result of split except that each string is contained in a list of length one.

Here's one approach.

```<code>orig = ['\nSK Telecom Co. Ltd. ADR\nSKM\n12/31/2021\n1.49\nN/A\nN/A']
result = [[s] for s in orig[0].split('\n')]
</code>```

Or, if each entry of the list should be a list of characters,

```<code>orig = ['\nSK Telecom Co. Ltd. ADR\nSKM\n12/31/2021\n1.49\nN/A\nN/A']
result = [list(s) for s in orig[0].split('\n')]
</code>```

Body:
I'm trying to split up a string inside of a list into a list, and the string contains \n as a character.
Whenever I use .split("\n"), its of course splitting the string at a new line, but I need it to split at the character \n. Is there anyway to make .split() interpret it this way?

Example:

#original list
['\nSK Telecom Co. Ltd. ADR\nSKM\n12/31/2021\n1.49\nN/A\nN/A']

what id like to create with .split() function:

[ [SK Telecom CO. Ltd. ADR] , [SKM] , [12/31/2021] , [1.49], [N/A], [N/A] ]

if you have any idea on how to help i'd be very grateful, thanks!

Body:
If I interpret your question literally, it looks like you want the result of split except that each string is contained in a list of length one.

Here's one approach.

orig = ['\nSK Telecom Co. Ltd. ADR\nSKM\n12/31/2021\n1.49\nN/A\nN/A']
result = [[s] for s in orig[0].split('\n')]

Or, if each entry of the list should be a list of characters,

orig = ['\nSK Telecom Co. Ltd. ADR\nSKM\n12/31/2021\n1.49\nN/A\nN/A']
result = [list(s) for s in orig[0].split('\n')]


问:
Let the user pass a user-defined type as sub-class of the parameter class to define a member
The following is some architecture I have designed.
I have a class X that has a variable member Y that is a pointer (or reference, I haven't decided yet) to class A. Class A is an abstract class. The user of X can create his own derived class from A (for example B:A) and pass it to X (probably, in the constructor) which, somehow, will store it in Y.

To make this work, the user should dynamically allocate an object of type B:A and pass it to X. However, can you think of a simpler way, for the user, of doing this without having to call new? Ideally, I would like the user to simply create an object of type B:A and pass it. Then, the constructor of X, somehow, would define Y using it (maybe creating a copy of B:A). The problem is that X doesn't know which derived type is passed and what size it is.

I want to create a single constructor to which the user could pass any type derived from A as parameter, and would be converted into a member variable. It should allow the user to create his own type for taking advantage of polymorphism.

```<code>   class A {...};   // Abstract class (has pure virtual members)

   class B : public A {...};   // Class defined by the user

   class X
   {
   public:
      X(A &param) { /* abc is defined */ }
      A* abc;
   }
</code>```

Some ideas I had:
Could it work a pure virtual copy assignment operator overloading at A? And having a member at B:A that specifies the size of B:A? However I still don't know how to make it work.

How to solve it? Is there maybe a better way? Thanks in advance.

答:
On the assumption that class X is going to own param after it is passed in, you can do this:

```<code>#include <iostream>
#include <memory>

class A { public: virtual ~A () {} };

class B : public A { public: ~B () { std::cout << "B destroyed"; } };

class X
{
public:
    X (std::unique_ptr <A> &param) : m_param (std::move (param))  { }
private:
    std::unique_ptr <A> m_param;
};

int main ()
{
    std::unique_ptr <A> b = std::make_unique <B> ();
    X x (b);
}
</code>```

When run, this code prints B destroyed.  Note that, for this to work, A must have a virtual destructor.

If ownership of param is to be shared with the caller and / or other objects, use std::shared_ptr instead (but this has more overhead).  Or, as @Remy says, if you can guarantee that the lifetime of param exceeds that of x, you can store a raw pointer (or reference).

Edit: As per the comments, a better implementation of the constructor of class X would be:

```<code>X (std::unique_ptr <A> &&param) : m_param (std::move (param))  { }
</code>```

And then you would call it like this:

```<code>X x { std::make_unique <B> (); }
</code>```

This makes it clear that x owns the object passed in.

```<code></code>```

Body:
The following is some architecture I have designed.
I have a class X that has a variable member Y that is a pointer (or reference, I haven't decided yet) to class A. Class A is an abstract class. The user of X can create his own derived class from A (for example B:A) and pass it to X (probably, in the constructor) which, somehow, will store it in Y.

To make this work, the user should dynamically allocate an object of type B:A and pass it to X. However, can you think of a simpler way, for the user, of doing this without having to call new? Ideally, I would like the user to simply create an object of type B:A and pass it. Then, the constructor of X, somehow, would define Y using it (maybe creating a copy of B:A). The problem is that X doesn't know which derived type is passed and what size it is.

I want to create a single constructor to which the user could pass any type derived from A as parameter, and would be converted into a member variable. It should allow the user to create his own type for taking advantage of polymorphism.

   class A {...};   // Abstract class (has pure virtual members)

   class B : public A {...};   // Class defined by the user

   class X
   {
   public:
      X(A &param) { /* abc is defined */ }
      A* abc;
   }

Some ideas I had:
Could it work a pure virtual copy assignment operator overloading at A? And having a member at B:A that specifies the size of B:A? However I still don't know how to make it work.

How to solve it? Is there maybe a better way? Thanks in advance.

Body:
On the assumption that class X is going to own param after it is passed in, you can do this:

#include <iostream>
#include <memory>

class A { public: virtual ~A () {} };

class B : public A { public: ~B () { std::cout << "B destroyed"; } };

class X
{
public:
    X (std::unique_ptr <A> &param) : m_param (std::move (param))  { }
private:
    std::unique_ptr <A> m_param;
};

int main ()
{
    std::unique_ptr <A> b = std::make_unique <B> ();
    X x (b);
}

When run, this code prints B destroyed.  Note that, for this to work, A must have a virtual destructor.

If ownership of param is to be shared with the caller and / or other objects, use std::shared_ptr instead (but this has more overhead).  Or, as @Remy says, if you can guarantee that the lifetime of param exceeds that of x, you can store a raw pointer (or reference).

Edit: As per the comments, a better implementation of the constructor of class X would be:

X (std::unique_ptr <A> &&param) : m_param (std::move (param))  { }

And then you would call it like this:

X x { std::make_unique <B> (); }

This makes it clear that x owns the object passed in.


问:
How to use groupby + transform instead of pipe?
Let's say I have a dataframe like this

```<code>import pandas as pd
from scipy import stats

df = pd.DataFrame(
    {
        'group': list('abaab'),
        'val1': range(5),
        'val2': range(2, 7),
        'val3': range(4, 9)
    }
)

  group  val1  val2  val3
0     a     0     2     4
1     b     1     3     5
2     a     2     4     6
3     a     3     5     7
4     b     4     6     8
</code>```

Now I want to calculate linear regressions for each group in column group using two of the vali columns (potentially all pairs, so I don't want to hardcode column names anywhere).

A potential implementation could look like this based on pipe

```<code>def do_lin_reg_pipe(df, group_col, col1, col2):
    group_names = df[group_col].unique()
    df_subsets = []
    for s in group_names:
        df_subset = df.loc[df[group_col] == s]
        x = df_subset[col1].values
        y = df_subset[col2].values
        slope, intercept, r, p, se = stats.linregress(x, y)
        df_subset = df_subset.assign(
            slope=slope,
            intercept=intercept,
            r=r,
            p=p,
            se=se
        )
        df_subsets.append(df_subset)
    return pd.concat(df_subsets)
</code>```

and then I can use

```<code>df_linreg_pipe = (
    df.pipe(do_lin_reg_pipe, group_col='group', col1='val1', col2='val3')
      .assign(p=lambda d: d['p'].round(3))
)
</code>```

which gives the desired outcome

```<code>  group  val1  val2  val3  slope  intercept    r    p   se
0     a     0     2     4    1.0        4.0  1.0  0.0  0.0
2     a     2     4     6    1.0        4.0  1.0  0.0  0.0
3     a     3     5     7    1.0        4.0  1.0  0.0  0.0
1     b     1     3     5    1.0        4.0  1.0  0.0  0.0
4     b     4     6     8    1.0        4.0  1.0  0.0  0.0
</code>```

What I don't like is that I have to loop through the groups, use and append and then also concat, so I thought I should somehow use a groupby and transform but I don't get this to work. The function call should be something like

```<code>df_linreg_transform = df.copy()
df_linreg_transform[['slope', 'intercept', 'r', 'p', 'se']] = (
    df.groupby('group').transform(do_lin_reg_transform, col1='val1', col2='val3')
)
</code>```

question is how to define do_lin_reg_transform; I would like to have something along these lines

```<code>def do_lin_reg_transform(df, col1, col2):

    x = df[col1].values
    y = df[col2].values
    slope, intercept, r, p, se = stats.linregress(x, y)

    return (slope, intercept, r, p, se)
</code>```

but that - of course - crashes with a KeyError

KeyError: 'val1'

How could one implement do_lin_reg_transform to make it work with groupby and transform?

答:
Transform is meant to aggregate results for a single column. A regression requires multiple so you should use apply.

If you wanted, you could define your aggregation to return a DataFrame as opposed to the Series (so the result doesn't reduce). For this to work, you'd want to make sure you index is unique. Then concat the result back so it aligns on the index. You won't have any issues if there's more than 1 grouping column.

```<code>def group_reg(gp, col1, col2):
    df = pd.DataFrame([stats.linregress(gp[col1], gp[col2])]*len(gp),
                      columns=['slope', 'intercept', 'r', 'p', 'se'],
                      index=gp.index)
    return df

pd.concat([df, df.groupby('group').apply(group_reg, col1='val1', col2='val3')], axis=1)
</code>```

```<code>  group  val1  val2  val3  slope  intercept    r             p   se
0     a     0     2     4    1.0        4.0  1.0  9.003163e-11  0.0
1     b     1     3     5    1.0        4.0  1.0  0.000000e+00  0.0
2     a     2     4     6    1.0        4.0  1.0  9.003163e-11  0.0
3     a     3     5     7    1.0        4.0  1.0  9.003163e-11  0.0
4     b     4     6     8    1.0        4.0  1.0  0.000000e+00  0.0
</code>```

Body:
Let's say I have a dataframe like this

import pandas as pd
from scipy import stats

df = pd.DataFrame(
    {
        'group': list('abaab'),
        'val1': range(5),
        'val2': range(2, 7),
        'val3': range(4, 9)
    }
)

  group  val1  val2  val3
0     a     0     2     4
1     b     1     3     5
2     a     2     4     6
3     a     3     5     7
4     b     4     6     8

Now I want to calculate linear regressions for each group in column group using two of the vali columns (potentially all pairs, so I don't want to hardcode column names anywhere).

A potential implementation could look like this based on pipe

def do_lin_reg_pipe(df, group_col, col1, col2):
    group_names = df[group_col].unique()
    df_subsets = []
    for s in group_names:
        df_subset = df.loc[df[group_col] == s]
        x = df_subset[col1].values
        y = df_subset[col2].values
        slope, intercept, r, p, se = stats.linregress(x, y)
        df_subset = df_subset.assign(
            slope=slope,
            intercept=intercept,
            r=r,
            p=p,
            se=se
        )
        df_subsets.append(df_subset)
    return pd.concat(df_subsets)

and then I can use

df_linreg_pipe = (
    df.pipe(do_lin_reg_pipe, group_col='group', col1='val1', col2='val3')
      .assign(p=lambda d: d['p'].round(3))
)

which gives the desired outcome

  group  val1  val2  val3  slope  intercept    r    p   se
0     a     0     2     4    1.0        4.0  1.0  0.0  0.0
2     a     2     4     6    1.0        4.0  1.0  0.0  0.0
3     a     3     5     7    1.0        4.0  1.0  0.0  0.0
1     b     1     3     5    1.0        4.0  1.0  0.0  0.0
4     b     4     6     8    1.0        4.0  1.0  0.0  0.0

What I don't like is that I have to loop through the groups, use and append and then also concat, so I thought I should somehow use a groupby and transform but I don't get this to work. The function call should be something like

df_linreg_transform = df.copy()
df_linreg_transform[['slope', 'intercept', 'r', 'p', 'se']] = (
    df.groupby('group').transform(do_lin_reg_transform, col1='val1', col2='val3')
)

question is how to define do_lin_reg_transform; I would like to have something along these lines

def do_lin_reg_transform(df, col1, col2):

    x = df[col1].values
    y = df[col2].values
    slope, intercept, r, p, se = stats.linregress(x, y)

    return (slope, intercept, r, p, se)

but that - of course - crashes with a KeyError

KeyError: 'val1'

How could one implement do_lin_reg_transform to make it work with groupby and transform?

Body:
Transform is meant to aggregate results for a single column. A regression requires multiple so you should use apply.

If you wanted, you could define your aggregation to return a DataFrame as opposed to the Series (so the result doesn't reduce). For this to work, you'd want to make sure you index is unique. Then concat the result back so it aligns on the index. You won't have any issues if there's more than 1 grouping column.

def group_reg(gp, col1, col2):
    df = pd.DataFrame([stats.linregress(gp[col1], gp[col2])]*len(gp),
                      columns=['slope', 'intercept', 'r', 'p', 'se'],
                      index=gp.index)
    return df

pd.concat([df, df.groupby('group').apply(group_reg, col1='val1', col2='val3')], axis=1)

  group  val1  val2  val3  slope  intercept    r             p   se
0     a     0     2     4    1.0        4.0  1.0  9.003163e-11  0.0
1     b     1     3     5    1.0        4.0  1.0  0.000000e+00  0.0
2     a     2     4     6    1.0        4.0  1.0  9.003163e-11  0.0
3     a     3     5     7    1.0        4.0  1.0  9.003163e-11  0.0
4     b     4     6     8    1.0        4.0  1.0  0.000000e+00  0.0


问:
Progressive download standard
Is there any document which talks about how progressive download works. I am aware it is based on HTTP but need more information as to how the data is downloaded and what kind of messages flows between the player and the HTTP server.
Is there any standard defined for the same.</p>

答:
This document is the best I could find relating to standards for HTTP progressive downloads.

Another approach to this is HTTP Live Streaming which is well documented.

Title: Progressive download standard


问:
Printing from an application in IIS to a networked printer on server
I have a line of code that I can run locally as part of a service that works perfectly fine.

```<code>sReportPath = objCrystalUtils.ExportReportToPDF("Report Name", iReportInfoID)
</code>```

This code is run as a part of a service, and when I unit test it by feeding it data, it ultimately builds the report and prints it.

When I run the exact same piece of code inside an .ashx from an ajax call. The reports are generated (I can see the pdf files being created on disk) but the printing is not happening.

```<code> oRpt.PrintToPrinter(objReport.DefaultAutoPrint, True, 0, 0)
</code>```

In both scenarios the same code is used to print the report. (objReport.DefaultAutoPrint = 0 in both cases)

My only thought is that the location of the code that is calling this method is in a different spot relative to the location of the bills themselves.

The printer that I'm trying to print to is a network printer intalled on my machine, and I'm running Windows 7 IIS 6.1

Any thoughts?

Edit:

Here is a thought... if I'm running one as a unit test locally and im running the other through a web app that is running via IIS, is there a difference in user id and user access to the default printer?

Edit:

So I added my local ASP, IUSR and SYSTEM users to the printer security and allowed them to print... no dice.  So I checked the EVERYONE user and it is set to access and NO users are denied... so I think that kinda kills that line of reasoning.

Edit:

I changed the name of this post since I no longer think that the issue is ajax related since If I try to do the same process in code bebehind from a post back instead of running it from an ajax call i still get the same problem.

答: It's not Crystal Reports or other third party app's problem. It's usually the IIS_IUSER's permission problem because it has no access to any network printers. A possible solution is in Process.Start doesn't work in IIS</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a line of code that I can run locally as part of a service that works perfectly fine.

sReportPath = objCrystalUtils.ExportReportToPDF("Report Name", iReportInfoID)

This code is run as a part of a service, and when I unit test it by feeding it data, it ultimately builds the report and prints it.

When I run the exact same piece of code inside an .ashx from an ajax call. The reports are generated (I can see the pdf files being created on disk) but the printing is not happening.

 oRpt.PrintToPrinter(objReport.DefaultAutoPrint, True, 0, 0)

In both scenarios the same code is used to print the report. (objReport.DefaultAutoPrint = 0 in both cases)

My only thought is that the location of the code that is calling this method is in a different spot relative to the location of the bills themselves.

The printer that I'm trying to print to is a network printer intalled on my machine, and I'm running Windows 7 IIS 6.1

Any thoughts?

Edit:

Here is a thought... if I'm running one as a unit test locally and im running the other through a web app that is running via IIS, is there a difference in user id and user access to the default printer?

Edit:

So I added my local ASP, IUSR and SYSTEM users to the printer security and allowed them to print... no dice.  So I checked the EVERYONE user and it is set to access and NO users are denied... so I think that kinda kills that line of reasoning.

Edit:

I changed the name of this post since I no longer think that the issue is ajax related since If I try to do the same process in code bebehind from a post back instead of running it from an ajax call i still get the same problem.


问:
Abstract out render method to add to it with custom components
I have an interesting problem. I have a component. I need to allow the user to override the existing render method with one of their own. Each custom render may act differently. Currently, I'm trying to keep the existing code in place, while abstracting out the custom code. Example:

import React from "react";
import "./styles.css";

class ShowThis extends React.Component {
  render() {
    return <> </>
  }
}

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

  render() {
    return (

Hello CodeSandbox

Start editing to see some magic happen!

        // this is the custom component
        // this is highly coupled and needs to be moved out of App
        // but I need to allow other custom components like ShowThis to handle the rendering also
        {this.state.open && <ShowThis />}

    );
  }
}

export default App;
```
<p>I've seen render props but I'm not sure how to go about it. Looking for help to solve this problem.
Looking for something like this:</p>
<pre class="lang-js prettyprint-override"><code>import React from "react";
import "./styles.css";

class ShowThis extends React.Component {
  render() {
    return (
      <TheMainCodeFromApp />
      <p>my custom code also </p>
    )
  }
}

class ShowThat extends React.Component {
  render() {
    return (
      <p>my custom code also </p>
      <TheMainCodeFromApp />
      <p>my custom code also </p>
    )
  }
}

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

  if (this.props.module) {
    module.render()
  } else {
  render() {
    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
      </div>
    );
  }
}

export default App;
</code>```

答:
Looks like you're pretty much there. Here's an example of a very basic render prop pattern.</p>
```<code>const RenderContainer = ({render}) => {
  const [open, setOpen] = useState(false);

  return <div onClick={() => setOpen(true)}>
    {open && render()}
  </div>;
};

// Used like
const Comp1 = () => {
  return <RenderContainer render={() => <ShowThis />} />;
};
</code>```

Body:
I have an interesting problem. I have a component. I need to allow the user to override the existing render method with one of their own. Each custom render may act differently. Currently, I'm trying to keep the existing code in place, while abstracting out the custom code. Example:

import React from "react";
import "./styles.css";

class ShowThis extends React.Component {
  render() {
    return <> </>
  }
}

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

  render() {
    return (

Hello CodeSandbox

Start editing to see some magic happen!

        // this is the custom component
        // this is highly coupled and needs to be moved out of App
        // but I need to allow other custom components like ShowThis to handle the rendering also
        {this.state.open && <ShowThis />}

    );
  }
}

export default App;

I've seen render props but I'm not sure how to go about it. Looking for help to solve this problem.
Looking for something like this:

import React from "react";
import "./styles.css";

class ShowThis extends React.Component {
  render() {
    return (
      <TheMainCodeFromApp />

my custom code also

    )
  }
}

class ShowThat extends React.Component {
  render() {
    return (

my custom code also

      <TheMainCodeFromApp />

my custom code also

    )
  }
}

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

  if (this.props.module) {
    module.render()
  } else {
  render() {
    return (

Hello CodeSandbox

Start editing to see some magic happen!

    );
  }
}

export default App;

Body:
Looks like you're pretty much there. Here's an example of a very basic render prop pattern.

const RenderContainer = ({render}) => {
  const [open, setOpen] = useState(false);

  return <div onClick={() => setOpen(true)}>
    {open && render()}
  </div>;
};

// Used like
const Comp1 = () => {
  return <RenderContainer render={() => <ShowThis />} />;
};


问:
Using the cosmosdb SQLAPI, I'm able to create the partitionKey and ID I'm specifying, but no other content
I'm using the CosmosDB SQLAPI to create temporary storage of debug data during email processing.  I only have less than a dozen known senders, and only a couple of hundred known recipients of that email.  So, here's my code for Upserting into Cosmos.

```<code>messageEntity.PartitionKey = $"{messageEntity.SenderAddress}.to.{messageEntity.RecipientAddress}";
messageEntity.Id = $"{messageEntity.PartitionKey}.at.{messageEntity.Timestamp}";

var result = await container.UpsertItemAsync<MessageEntity>(messageEntity);
</code>```

The result comes back Created, and I can see the key and id using the Cosmos Data Explorer.  But I do not see the rest of the messageEntity properties.

I've tried both with annotation...

```<code>[JsonObject(MemberSerialization.OptIn)]
public class MessageEntity
{
    ...
    [JsonProperty(PropertyName = "status")]
    public MessageStatus Status { get; set; }
    ...
}
</code>```

and without - it doesn't make a difference.

I'm not seing any exceptions or errors.  Any thoughts?

答:
The easiest way to do this is to change the type on your Upsert call to dynamic instead of your POCO. Something like this.</p>
```<code>var result = await container.UpsertItemAsync<dynamic>(messageEntity);
</code>```

Body:
I'm using the CosmosDB SQLAPI to create temporary storage of debug data during email processing.  I only have less than a dozen known senders, and only a couple of hundred known recipients of that email.  So, here's my code for Upserting into Cosmos.

messageEntity.PartitionKey = $"{messageEntity.SenderAddress}.to.{messageEntity.RecipientAddress}";
messageEntity.Id = $"{messageEntity.PartitionKey}.at.{messageEntity.Timestamp}";

var result = await container.UpsertItemAsync<MessageEntity>(messageEntity);

The result comes back Created, and I can see the key and id using the Cosmos Data Explorer.  But I do not see the rest of the messageEntity properties.

I've tried both with annotation...

[JsonObject(MemberSerialization.OptIn)]
public class MessageEntity
{
    ...
    [JsonProperty(PropertyName = "status")]
    public MessageStatus Status { get; set; }
    ...
}

and without - it doesn't make a difference.

I'm not seing any exceptions or errors.  Any thoughts?

Body:
The easiest way to do this is to change the type on your Upsert call to dynamic instead of your POCO. Something like this.

var result = await container.UpsertItemAsync<dynamic>(messageEntity);


问:
regex replace last occurance of number in between 2 chars javascript
I am trying to replace the last number of each match in between parenthesis.

so if I had cos(3 * 3)

before this regex

result = result.replace(/\d+(?:\.\d+)?/g, x => `${x}deg`)
```

would turn cos(3 * 3) into cos(3deg * 3deg)

I need only the last number to be changed to deg

So if  I had cos(3 * 3) + cos(3 * 2) it would be cos(3 * 3deg) + cos(3 * 2deg)

What regular expression magic could I use to do this.

答:
You can simply use the closing braces to replace like this:

var result = "cos(3 * 3) + cos(3 * 245)"

result = result.replace(/(\d+)(\))/g,'$1deg)')

console.log(result)```
</div>
</div>
</p>
<blockquote>
<p>Or just replace the last bracket.</p>
</blockquote>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var result = "cos(3 * 90) + sin(3 * 2)"

result = result.replace(/\)/g,'deg)')

console.log(result)</code>```

With Decimal add a character class using [] for . and digits

var result = "cos(3 * 3.4) + cos(3 * 245.5)"

result = result.replace(/([\d\.]+)(\))/g,'$1deg)')

console.log(result)```
</div>
</div>
</p>
<blockquote>
<p>Any equation at the last number</p>
</blockquote>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var result = "3*(1571-sin(12))"

result = result.replace(/(\d\s{0,}\*+\d{0,})(.*\))/g,'$1$2deg')

console.log(result)</code>```

Body:
I am trying to replace the last number of each match in between parenthesis.

so if I had cos(3 * 3)

before this regex

result = result.replace(/\d+(?:\.\d+)?/g, x => `${x}deg`)

would turn cos(3 * 3) into cos(3deg * 3deg)

I need only the last number to be changed to deg

So if  I had cos(3 * 3) + cos(3 * 2) it would be cos(3 * 3deg) + cos(3 * 2deg)

What regular expression magic could I use to do this.

Body:
You can simply use the closing braces to replace like this:

var result = "cos(3 * 3) + cos(3 * 245)"

result = result.replace(/(\d+)(\))/g,'$1deg)')

console.log(result)

Or just replace the last bracket.

var result = "cos(3 * 90) + sin(3 * 2)"

result = result.replace(/\)/g,'deg)')

console.log(result)

With Decimal add a character class using [] for . and digits

var result = "cos(3 * 3.4) + cos(3 * 245.5)"

result = result.replace(/([\d\.]+)(\))/g,'$1deg)')

console.log(result)

Any equation at the last number

var result = "3*(1571-sin(12))"

result = result.replace(/(\d\s{0,}\*+\d{0,})(.*\))/g,'$1$2deg')

console.log(result)


问:
(SwiftUI) can anyone tell me why my NavigationView is creating extra NavigationBars and blank space in the footer? (video included)
I have an app with 3 views. they are connected by a NavigationView and have NavigationLinks that link to the next view. however, all views are created with an extra NavigationBar and with lots of blank white space on the bottom that travels up the screen every time you click through the views and go back to the home page. I remember a few days ago having this issue when I went from the HomeView() to the TimerView() but I'm not sure how I got rid of it. and also I definitely did not get rid of it because I'm still having the same problem. and also I don't remember how I worked around this the first time. I have seen other posts which say I should set the navigationBar color to clear but that does nothing. not sure what is going on. most other posts on this topic are about removing the space up top and very few talk about the blank space on the bottom so I'm not really sure what to do.

I go into the capture view hierarchy and I see that white footer bar is created when the view is created but then just seems to stack on top of every other view until the application is unusable. using Xcode 13.1 and running in simulator on iPhone 12 with iOS 15.0.

here's the video as well as pictures from the capture view hierarchy thing https://imgur.com/a/jBprYbN

and here's the code

```<code>struct ContentView: View {

    @State private var selectedTab = 0
    let numTabs = 2
    let minDragTranslationForSwipe: CGFloat = 50
    @State var secondScreenShown = true

    @State private var tabSelection = 0
    @State private var tappedTwice:Bool = false
    @State private var homeID = UUID()
    var handler: Binding<Int> { Binding (
        get: {self.tabSelection},
        set: {
            if $0 == self.tabSelection {
                tappedTwice = true
                print("tappedTwice = true")
            }
            self.tabSelection = $0
        }

    )}

    init() {
        UITabBar.appearance().isTranslucent = false
    }

    var body: some View {
        TabView(selection:handler) {
            NavigationView {
            HomeView()
                .id(homeID)
                .tabItem {
                  Label("Home", systemImage: "house.fill")
                }.tag(0)
                .onChange(of: tappedTwice, perform: { tappedTwice in
                    guard tappedTwice else { return }
                    homeID = UUID()
                    self.tappedTwice = false
                })
            }

        }
        .edgesIgnoringSafeArea(.all)
        .frame(
            minWidth: UIScreen.main.bounds.width,
            maxWidth: .infinity,
            minHeight: UIScreen.main.bounds.height,
            maxHeight: .infinity,
            alignment: .center
        )
    }
}
</code>```

here's the HomeView()

```<code>    struct HomeView: View {

    @State var secondScreenShown = false
    @State var timerVal = 1
    @State private var chosenSound = "None"
    var times = [1, 2, 3, 4, 5, 10, 15, 20, 30, 45, 60]
    var sounds = ["None", "Creepy Kids", "Conjuring The Dark Ones", "The Forbidden Forest" ]

    init() {
        UITableView.appearance().tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: Double.leastNonzeroMagnitude))
        UITableView.appearance().tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: Double.leastNonzeroMagnitude))
    }

    var body: some View {
 //       NavigationView {
            VStack {
                VStack {
                            VStack {
                                Group {
                                    VStack {

                                                NavigationLink(
                                                    destination: TimerView(timerScreenShown: $secondScreenShown, timerVal: timerVal, chosenSound: chosenSound, initialTime: timerVal),
                                                    isActive: $secondScreenShown,
                                                    label: {Text("Go")

                                                        .font(.title2)
                                                        .padding()
                                                        .frame(minWidth: 250)
                                                        .overlay(
                                                            Capsule(style: .continuous)
                                                                .stroke(Color.black, lineWidth: 3)
                                                        )
                                                    })
                                                    .frame(minWidth: /*@START_MENU_TOKEN@*/0/*@END_MENU_TOKEN@*/, maxWidth: 100, alignment: .bottom)
                                                    .padding(.top, 10)

                                } // third group
                            }

                } // VStack just outside rectangle
                .frame(
                    maxWidth: .infinity,
                    minHeight: UIScreen.main.bounds.height,
                    maxHeight: .infinity,
                    alignment: .center
                )
                .padding()
 //               ) // rectangle.overlay()

            } // VStack
            .edgesIgnoringSafeArea([.top, .bottom])
            .background(Color.pink)
            .frame(
                minWidth: UIScreen.main.bounds.width,
                maxWidth: .infinity,
                minHeight: UIScreen.main.bounds.height,
                maxHeight: .infinity,
                alignment: .center
            )

     //   } // NavigationView
        .navigationViewStyle(StackNavigationViewStyle())
        .navigationBarTitle("main level")
    }
}
}
</code>```

And here's the TimerView()

```<code>    struct TimerView: View {

    @Binding var timerScreenShown:Bool
    @State var timerVal:Int
    @State var chosenSound:String

    @State private var showNextView = false
    @State private var paused = false

    var initialTime:Int

    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {

        VStack {
            VStack {
                        VStack {
                                NavigationLink(
                                    destination: HomeView(),
                                    label: {Text("Home Page")})
                                        .font(.title2)
                                        .frame(minWidth: 0,maxWidth: 200, alignment: .center)
                                        .overlay(
                                            Capsule(style: .continuous)
                                                .stroke(Color.black, lineWidth: 3)
                                        )
                                        .padding(.top, 35)

                            //    } // else
                        } // innermost VStack

                        .frame(
                            alignment: .center
                        )
                        .padding()
  //              )

            } // VStack 2
            .frame(
                minWidth: UIScreen.main.bounds.width,
                maxWidth: .infinity,
                minHeight: UIScreen.main.bounds.height,
                maxHeight: .infinity,
                alignment: .center
            )

        } // VStack
        .edgesIgnoringSafeArea([.top, .bottom])
        .background(Color.purple
//            Image("HomePageBackground")
//                .resizable()
//                .ignoresSafeArea()
        )
        .frame(
            minWidth: UIScreen.main.bounds.width,
            maxWidth: .infinity,
            minHeight: UIScreen.main.bounds.height,
            maxHeight: .infinity,
            alignment: .center
        )

        .onAppear(){
            UITableView.appearance().tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: Double.leastNonzeroMagnitude))
            UITableView.appearance().tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: Double.leastNonzeroMagnitude))
        }

        .navigationBarTitle("timer view")
    } // View

}
</code>```

so yeah it's obvious there's extra navigation views being created somewhere but I'm not sure where. it's also obvious that blank space in the footer is created when the view is loaded but I don't know where. so yeah any help would be appreciated.

if there are any brackets/parenthesis missing it's because I accidentally deleted it while removing commented out extraneous code.

答:
The issue is caused by the UITabBar.appearance().isTranslucent = false line -- without that, as you confirmed in the comments, it behaves as expected.

Here's a working version with a note about that line:

```<code>import SwiftUI

struct ContentView: View {

    init() {
        UITabBar.appearance().isTranslucent = false //REMOVE THIS and functionality will be as-expected
    }

    var body: some View {
        TabView {
            NavigationView {
                HomeView()
            }.tabItem {
                Label("Home", systemImage: "house.fill")
            }
            .navigationViewStyle(StackNavigationViewStyle())
            .tag(0)
        }
    }
}

struct TimerView: View {
    var body: some View {
        VStack {
            NavigationLink(
                destination: HomeView(),
                label: {Text("Home Page")})
        }
        .padding()
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
        .background(Color.purple)
        .edgesIgnoringSafeArea([.top, .bottom])

        .navigationBarTitle("timer view")
    }

}

struct HomeView: View {
    var body: some View {
        VStack {
            NavigationLink(
                destination: TimerView(),
                label: {
                    Text("Go")
                })
                .frame(minWidth: 0, maxWidth: 100, alignment: .bottom)
                .padding(.top, 10)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.pink)
        .edgesIgnoringSafeArea([.top, .bottom])
        .navigationBarTitle("main level")
    }
}
</code>```

Body:
I have an app with 3 views. they are connected by a NavigationView and have NavigationLinks that link to the next view. however, all views are created with an extra NavigationBar and with lots of blank white space on the bottom that travels up the screen every time you click through the views and go back to the home page. I remember a few days ago having this issue when I went from the HomeView() to the TimerView() but I'm not sure how I got rid of it. and also I definitely did not get rid of it because I'm still having the same problem. and also I don't remember how I worked around this the first time. I have seen other posts which say I should set the navigationBar color to clear but that does nothing. not sure what is going on. most other posts on this topic are about removing the space up top and very few talk about the blank space on the bottom so I'm not really sure what to do.

I go into the capture view hierarchy and I see that white footer bar is created when the view is created but then just seems to stack on top of every other view until the application is unusable. using Xcode 13.1 and running in simulator on iPhone 12 with iOS 15.0.

here's the video as well as pictures from the capture view hierarchy thing https://imgur.com/a/jBprYbN

and here's the code

struct ContentView: View {

    @State private var selectedTab = 0
    let numTabs = 2
    let minDragTranslationForSwipe: CGFloat = 50
    @State var secondScreenShown = true

    @State private var tabSelection = 0
    @State private var tappedTwice:Bool = false
    @State private var homeID = UUID()
    var handler: Binding<Int> { Binding (
        get: {self.tabSelection},
        set: {
            if $0 == self.tabSelection {
                tappedTwice = true
                print("tappedTwice = true")
            }
            self.tabSelection = $0
        }

    )}

    init() {
        UITabBar.appearance().isTranslucent = false
    }

    var body: some View {
        TabView(selection:handler) {
            NavigationView {
            HomeView()
                .id(homeID)
                .tabItem {
                  Label("Home", systemImage: "house.fill")
                }.tag(0)
                .onChange(of: tappedTwice, perform: { tappedTwice in
                    guard tappedTwice else { return }
                    homeID = UUID()
                    self.tappedTwice = false
                })
            }

        }
        .edgesIgnoringSafeArea(.all)
        .frame(
            minWidth: UIScreen.main.bounds.width,
            maxWidth: .infinity,
            minHeight: UIScreen.main.bounds.height,
            maxHeight: .infinity,
            alignment: .center
        )
    }
}

here's the HomeView()

    struct HomeView: View {

    @State var secondScreenShown = false
    @State var timerVal = 1
    @State private var chosenSound = "None"
    var times = [1, 2, 3, 4, 5, 10, 15, 20, 30, 45, 60]
    var sounds = ["None", "Creepy Kids", "Conjuring The Dark Ones", "The Forbidden Forest" ]

    init() {
        UITableView.appearance().tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: Double.leastNonzeroMagnitude))
        UITableView.appearance().tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: Double.leastNonzeroMagnitude))
    }

    var body: some View {
 //       NavigationView {
            VStack {
                VStack {
                            VStack {
                                Group {
                                    VStack {

                                                NavigationLink(
                                                    destination: TimerView(timerScreenShown: $secondScreenShown, timerVal: timerVal, chosenSound: chosenSound, initialTime: timerVal),
                                                    isActive: $secondScreenShown,
                                                    label: {Text("Go")

                                                        .font(.title2)
                                                        .padding()
                                                        .frame(minWidth: 250)
                                                        .overlay(
                                                            Capsule(style: .continuous)
                                                                .stroke(Color.black, lineWidth: 3)
                                                        )
                                                    })
                                                    .frame(minWidth: /*@START_MENU_TOKEN@*/0/*@END_MENU_TOKEN@*/, maxWidth: 100, alignment: .bottom)
                                                    .padding(.top, 10)

                                } // third group
                            }

                } // VStack just outside rectangle
                .frame(
                    maxWidth: .infinity,
                    minHeight: UIScreen.main.bounds.height,
                    maxHeight: .infinity,
                    alignment: .center
                )
                .padding()
 //               ) // rectangle.overlay()

            } // VStack
            .edgesIgnoringSafeArea([.top, .bottom])
            .background(Color.pink)
            .frame(
                minWidth: UIScreen.main.bounds.width,
                maxWidth: .infinity,
                minHeight: UIScreen.main.bounds.height,
                maxHeight: .infinity,
                alignment: .center
            )

     //   } // NavigationView
        .navigationViewStyle(StackNavigationViewStyle())
        .navigationBarTitle("main level")
    }
}
}

And here's the TimerView()

    struct TimerView: View {

    @Binding var timerScreenShown:Bool
    @State var timerVal:Int
    @State var chosenSound:String

    @State private var showNextView = false
    @State private var paused = false

    var initialTime:Int

    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {

        VStack {
            VStack {
                        VStack {
                                NavigationLink(
                                    destination: HomeView(),
                                    label: {Text("Home Page")})
                                        .font(.title2)
                                        .frame(minWidth: 0,maxWidth: 200, alignment: .center)
                                        .overlay(
                                            Capsule(style: .continuous)
                                                .stroke(Color.black, lineWidth: 3)
                                        )
                                        .padding(.top, 35)

                            //    } // else
                        } // innermost VStack

                        .frame(
                            alignment: .center
                        )
                        .padding()
  //              )

            } // VStack 2
            .frame(
                minWidth: UIScreen.main.bounds.width,
                maxWidth: .infinity,
                minHeight: UIScreen.main.bounds.height,
                maxHeight: .infinity,
                alignment: .center
            )

        } // VStack
        .edgesIgnoringSafeArea([.top, .bottom])
        .background(Color.purple
//            Image("HomePageBackground")
//                .resizable()
//                .ignoresSafeArea()
        )
        .frame(
            minWidth: UIScreen.main.bounds.width,
            maxWidth: .infinity,
            minHeight: UIScreen.main.bounds.height,
            maxHeight: .infinity,
            alignment: .center
        )

        .onAppear(){
            UITableView.appearance().tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: Double.leastNonzeroMagnitude))
            UITableView.appearance().tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: Double.leastNonzeroMagnitude))
        }

        .navigationBarTitle("timer view")
    } // View

}

so yeah it's obvious there's extra navigation views being created somewhere but I'm not sure where. it's also obvious that blank space in the footer is created when the view is loaded but I don't know where. so yeah any help would be appreciated.

if there are any brackets/parenthesis missing it's because I accidentally deleted it while removing commented out extraneous code.

Body:
The issue is caused by the UITabBar.appearance().isTranslucent = false line -- without that, as you confirmed in the comments, it behaves as expected.

Here's a working version with a note about that line:

import SwiftUI

struct ContentView: View {

    init() {
        UITabBar.appearance().isTranslucent = false //REMOVE THIS and functionality will be as-expected
    }

    var body: some View {
        TabView {
            NavigationView {
                HomeView()
            }.tabItem {
                Label("Home", systemImage: "house.fill")
            }
            .navigationViewStyle(StackNavigationViewStyle())
            .tag(0)
        }
    }
}

struct TimerView: View {
    var body: some View {
        VStack {
            NavigationLink(
                destination: HomeView(),
                label: {Text("Home Page")})
        }
        .padding()
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
        .background(Color.purple)
        .edgesIgnoringSafeArea([.top, .bottom])

        .navigationBarTitle("timer view")
    }

}

struct HomeView: View {
    var body: some View {
        VStack {
            NavigationLink(
                destination: TimerView(),
                label: {
                    Text("Go")
                })
                .frame(minWidth: 0, maxWidth: 100, alignment: .bottom)
                .padding(.top, 10)
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(Color.pink)
        .edgesIgnoringSafeArea([.top, .bottom])
        .navigationBarTitle("main level")
    }
}


问:
How to make HTML email appear pretty on a BlackBerry?
I have written a system that sends HTML marketing emails to a list of opted-in subscribers.

A significant number of those subscribers are BlackBerry users - and my emails look horrible on them... aside from the layout problems with the smaller screen, the message gets truncated at a certain length, and some images don't get displayed at all.

I am unfamiliar with the eccentricities of BB email - so could you please fill me in on what restrictions BB email has that I need to take into consideration when designing a template for the BB users?

答:
There is a new Sitepoint book Create Stunning HTML Mail -

maybe it could help you?

(I'm not affiliated in any way with them)


问:
Add unknown number of email to database with with email-validation using only html and PHP
Making a school assignment where I have to make a CRUD app containing members. Part of the assignment is as follows:

each member can has many (unknown) number of email adresses

I have to use HTML to validate if each of those is an email adres

I CAN'T use JS or any other language beside PHP and HTML (and SQL)

The things I tried (and the teacher said they are not correct):

Use the 'multiple' attribute on a input field (he doesn't want me to use 'multiple')

Use a textarea and seperate each email on a new line (can't use regex)

I am really stuck here.. anyone has any idea on how I can approach this in a way that I can upload an unknown number of email adresses (upon creating a member) and still have each be validated?

答:
Solution 1

Well, you can indeed use a textarea, split the posted value into an array, trim the lines, validate that each line contains a valid E-Mail address and do whatever you would like with the mails:

<form method="POST">

            One E-Mail per line:

        <textarea name="emails" id="emails" cols="80" rows="10">jdsjdhs@sdhjsdhj.de
jsddhs@ssdddhjsdhj.email
jsddhs@sdsddhj.tk
jdsjdsdhs@sdhjsdhj.org
jdsjdsdhs@sdhjsdhj.jetzt</textarea>

        <input type="submit" value="Validate">

</form>

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $emails = explode("\n", $_POST['emails']);

    $emails = array_map('trim', $emails);

    $emails = array_filter($emails, function ($email) {
        return filter_var($email, FILTER_VALIDATE_EMAIL);
    });

    $validEmailCount = count($emails);

    echo <<<HTML

        $validEmailCount valid E-Mails found.

    HTML;

    // Your database logic here
}
```
<hr />
<h1>Solution 2</h1>
<p>Based on the below comment thread, the OP is looking for an HTML only email "validation".</p>
<p>For that purpose, the <code>input[type=email]</code> is probably the best choice.</p>
<p>To allow as many emails as wanted, I have written the below PHP, which adds a blank email field every time the form is submitted with the checkbox asking for another field is marked as <em>on</em>.</p>
<pre class="lang-php prettyprint-override"><code><?php

$emails = [''];

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['emails']) &&
    is_array($_POST['emails'])
) {
    $emails = $_POST['emails'];

    if (
        isset($_POST['add_mail']) &&
        $_POST['add_mail'] === 'on'
    ) {
        $emails[] = '';
    } else {
        print_r($emails);
        die;
    }
}

?>

<form method="POST">
    <?php foreach ($emails as $email) : ?>
        <p>
            <input type="email" name="emails[]" value="<?= $email ?>">
        </p>
    <?php endforeach; ?>

    <p>
        <label for="add_mail">
            Would like to enter one more E-Mail?
        </label>
        <input type="checkbox" name="add_mail" id="add_mail">
    </p>

    <p>
        <input type="submit" value="Send">
    </p>
</form>
</code>```

Solution 3

Another solution would be to use a single input[type=text] in combination with the [pattern] attribute, and write a regular expression for it, that allows multiple email addresses.

<input type="text" pattern="…" required>
```

The emails could be separated by space, commas or semicolons, for example.

You would then do something like ,? to allow a delimiter or not.

To write and test your regex: https://regex101.com

E-Mail regex examples: How can I validate an email address using a regular expression?

Body:
Solution 1

Well, you can indeed use a textarea, split the posted value into an array, trim the lines, validate that each line contains a valid E-Mail address and do whatever you would like with the mails:

<form method="POST">
    <p>
        <label for="emails">
            One E-Mail per line:
        </label>
        <textarea name="emails" id="emails" cols="80" rows="10">jdsjdhs@sdhjsdhj.de
jsddhs@ssdddhjsdhj.email
jsddhs@sdsddhj.tk
jdsjdsdhs@sdhjsdhj.org
jdsjdsdhs@sdhjsdhj.jetzt</textarea>
    </p>
    <p>
        <input type="submit" value="Validate">
    </p>
</form>

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $emails = explode("\n", $_POST['emails']);

    $emails = array_map('trim', $emails);

    $emails = array_filter($emails, function ($email) {
        return filter_var($email, FILTER_VALIDATE_EMAIL);
    });

    $validEmailCount = count($emails);

    echo <<<HTML
    <p>
        $validEmailCount valid E-Mails found.
    </p>
    HTML;

    // Your database logic here
}

Solution 2

Based on the below comment thread, the OP is looking for an HTML only email "validation".

For that purpose, the input[type=email] is probably the best choice.

To allow as many emails as wanted, I have written the below PHP, which adds a blank email field every time the form is submitted with the checkbox asking for another field is marked as on.

<?php

$emails = [''];

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['emails']) &&
    is_array($_POST['emails'])
) {
    $emails = $_POST['emails'];

    if (
        isset($_POST['add_mail']) &&
        $_POST['add_mail'] === 'on'
    ) {
        $emails[] = '';
    } else {
        print_r($emails);
        die;
    }
}

?>

<form method="POST">
    <?php foreach ($emails as $email) : ?>
        <p>
            <input type="email" name="emails[]" value="<?= $email ?>">
        </p>
    <?php endforeach; ?>

    <p>
        <label for="add_mail">
            Would like to enter one more E-Mail?
        </label>
        <input type="checkbox" name="add_mail" id="add_mail">
    </p>

    <p>
        <input type="submit" value="Send">
    </p>
</form>

Solution 3

Another solution would be to use a single input[type=text] in combination with the [pattern] attribute, and write a regular expression for it, that allows multiple email addresses.

<input type="text" pattern="…" required>

The emails could be separated by space, commas or semicolons, for example.

You would then do something like ,? to allow a delimiter or not.

To write and test your regex: https://regex101.com

E-Mail regex examples: How can I validate an email address using a regular expression?


问:
How to solve "Property muws_disruptive_ads_minor.POLICY_NAME not found"
App Status: Rejected
Your app has been rejected and wasn't published due to the policy issue(s) listed below. If you submitted an update, the previous version of your app is still available on Google Play.
Issue found: Property muws_disruptive_ads_minor.TITLE not found
Property muws_disruptive_ads_minor.SHORT_DESCRIPTION not found
Issue details
We found an issue in the following area(s):
•   SPLIT_BUNDLE 1:
About the Property muws_disruptive_ads_minor.POLICY_NAME is not found Policy
Property muws_disruptive_ads_minor.POLICY_DESCRIPTION not found
About the Property muws_disruptive_ads_minor.POLICY_NAME2 not found Policy
Property muws_disruptive_ads_minor.POLICY_DESCRIPTION2 not found
Action required: Submit an updated app for review
Here's what to do to help get your app on Google Play:
1.  Make sure to read the applicable policies or requirements:
o   Property muws_disruptive_ads_minor.POLICY_NAME not found
o   Property muws_disruptive_ads_minor.POLICY_NAME2 not found
2.  Visit Google Play’s Academy for App Success to get contextual learning on this Google Play policy.
3.  Make appropriate changes to your app (if possible), and be sure to address the issue described above. You may also want to check your app's store listing for compliance, if applicable.
4.  Additionally, follow these steps to bring your app into compliance
Property muws_disruptive_ads_minor.NEXT_STEPS not found
5.  Double check that your app is compliant with all other Developer Program Policies.
6.  If you made changes to your app bundle, store listing, or APK, please sign in to your Play Console and submit the update(s).

What can I do?

答: Same here, I think this an error from Google Play that don't fill the message vars but the remanent error is disruptive ads. Check if you are sending clear traffic (no https) to all hosts.</p>


问:
How to adjust size of the displayed image in rhandsontable?
I am trying to display images in a rhandsontable. The images are of various sizes. I would like to normalize the display size of the images to a single size. In this regard, I need help with how to adjust the display size of the image in a rhandsontable.</p>
```<code>library(rhandsontable)

DF = data.frame(
  comments = c(
    "I would rate it ★★★★☆",
    "This is the book about JavaScript"
  ),
  cover = c(
    "http://ecx.images-amazon.com/images/I/51bRhyVTVGL._SL50_.jpg",
    "http://ecx.images-amazon.com/images/I/51gdVAEfPUL._SL50_.jpg",
 ),
 stringsAsFactors = FALSE
)

rhandsontable(DF, allowedTags = "<em><b><strong><a><big>",
              width = 800, height = 450, rowHeaders = FALSE) %>%
  hot_cols(colWidths = c(200, 80)) %>%
  hot_col(1, renderer = htmlwidgets::JS("safeHtmlRenderer")) %>%
  hot_col(2, renderer = "
    function(instance, td, row, col, prop, value, cellProperties) {
      var escaped = Handsontable.helper.stringify(value),
        img;

      if (escaped.indexOf('http') === 0) {
        img = document.createElement('IMG');
        img.src = value;

        Handsontable.dom.addEvent(img, 'mousedown', function (e){
          e.preventDefault(); // prevent selection quirk
        });

        Handsontable.dom.empty(td);
        td.appendChild(img);
      }
      else {
        // render as text
        Handsontable.renderers.TextRenderer.apply(this, arguments);
      }

      return td;
    }")
</code>```

答:
Adding the width and height (img.style.width = '80px'; img.style.height = '80px';) to the image property solved the issue.

```<code>library(rhandsontable)

DF = data.frame(
  comments = c(
    "I would rate it ★★★★☆",
    "This is the book about JavaScript"
  ),
  cover = c(
    "http://ecx.images-amazon.com/images/I/51bRhyVTVGL._SL50_.jpg",
    "http://ecx.images-amazon.com/images/I/51gdVAEfPUL._SL50_.jpg",
 ),
 stringsAsFactors = FALSE
)

rhandsontable(DF, allowedTags = "<em><b><strong><a><big>",
              width = 800, height = 450, rowHeaders = FALSE) %>%
  hot_cols(colWidths = c(200, 80)) %>%
  hot_col(1, renderer = htmlwidgets::JS("safeHtmlRenderer")) %>%
  hot_col(2, renderer = "
    function(instance, td, row, col, prop, value, cellProperties) {
      var escaped = Handsontable.helper.stringify(value),
        img;

      if (escaped.indexOf('http') === 0) {
        img = document.createElement('IMG');
        img.src = value; img.style.width = '80px'; img.style.height = '80px';

        Handsontable.dom.addEvent(img, 'mousedown', function (e){
          e.preventDefault(); // prevent selection quirk
        });

        Handsontable.dom.empty(td);
        td.appendChild(img);
      }
      else {
        // render as text
        Handsontable.renderers.TextRenderer.apply(this, arguments);
      }

      return td;
    }")
</code>```

Body:
I am trying to display images in a rhandsontable. The images are of various sizes. I would like to normalize the display size of the images to a single size. In this regard, I need help with how to adjust the display size of the image in a rhandsontable.

library(rhandsontable)

DF = data.frame(
  comments = c(
    "I would rate it ★★★★☆",
    "This is the book about JavaScript"
  ),
  cover = c(
    "http://ecx.images-amazon.com/images/I/51bRhyVTVGL._SL50_.jpg",
    "http://ecx.images-amazon.com/images/I/51gdVAEfPUL._SL50_.jpg",
 ),
 stringsAsFactors = FALSE
)

rhandsontable(DF, allowedTags = "<big>",
              width = 800, height = 450, rowHeaders = FALSE) %>%
  hot_cols(colWidths = c(200, 80)) %>%
  hot_col(1, renderer = htmlwidgets::JS("safeHtmlRenderer")) %>%
  hot_col(2, renderer = "
    function(instance, td, row, col, prop, value, cellProperties) {
      var escaped = Handsontable.helper.stringify(value),
        img;

      if (escaped.indexOf('http') === 0) {
        img = document.createElement('IMG');
        img.src = value;

        Handsontable.dom.addEvent(img, 'mousedown', function (e){
          e.preventDefault(); // prevent selection quirk
        });

        Handsontable.dom.empty(td);
        td.appendChild(img);
      }
      else {
        // render as text
        Handsontable.renderers.TextRenderer.apply(this, arguments);
      }

      return td;
    }")

Body:
Adding the width and height (img.style.width = '80px'; img.style.height = '80px';) to the image property solved the issue.

library(rhandsontable)

DF = data.frame(
  comments = c(
    "I would rate it &#x2605;&#x2605;&#x2605;&#x2605;&#x2606;",
    "This is the book about JavaScript"
  ),
  cover = c(
    "http://ecx.images-amazon.com/images/I/51bRhyVTVGL._SL50_.jpg",
    "http://ecx.images-amazon.com/images/I/51gdVAEfPUL._SL50_.jpg",
 ),
 stringsAsFactors = FALSE
)

rhandsontable(DF, allowedTags = "<em><b><strong><a><big>",
              width = 800, height = 450, rowHeaders = FALSE) %>%
  hot_cols(colWidths = c(200, 80)) %>%
  hot_col(1, renderer = htmlwidgets::JS("safeHtmlRenderer")) %>%
  hot_col(2, renderer = "
    function(instance, td, row, col, prop, value, cellProperties) {
      var escaped = Handsontable.helper.stringify(value),
        img;

      if (escaped.indexOf('http') === 0) {
        img = document.createElement('IMG');
        img.src = value; img.style.width = '80px'; img.style.height = '80px';

        Handsontable.dom.addEvent(img, 'mousedown', function (e){
          e.preventDefault(); // prevent selection quirk
        });

        Handsontable.dom.empty(td);
        td.appendChild(img);
      }
      else {
        // render as text
        Handsontable.renderers.TextRenderer.apply(this, arguments);
      }

      return td;
    }")


问:
Creating Oracle Procedure To Update Table
I'm trying to create a procedure in an Oracle database that will update the PMBPCSB with an 'X' if any of the other columns have a value present. If all of the columns are NULL then I don't want it to do anything. I'm not exactly sure how to format the procedure to accomplish what I'm wanting. Any help is appreciated.

COLUMN_NAME
DATA

PMBPCSB

PMBPCFBB

PMBPCHUB

PMBCITNC

PMBCITNSB

PMBCSDB

PMBCSDVOS

PMBCVOSB

PMBCWOB

答:
That's just an ordinary UPDATE, is it not?

```<code>SQL> create table pm
  2    (pmbpcsb  varchar2(1),
  3     pmbpcfbb varchar2(10),
  4     pmbpchub varchar2(10),
  5     pmbcitnc varchar2(10)
  6    );

Table created.

SQL> insert into pm values (null, '100', '200', '300');

1 row created.

SQL> insert into pm values (null, '300', null , '500');

1 row created.

SQL> insert into pm values (null, null , null , null );

1 row created.
</code>```

Update:

```<code>SQL> update pm set
  2    pmbpcsb = 'X'
  3  where coalesce(pmbpcfbb, pmbpchub, pmbcitnc) is not null;

2 rows updated.
</code>```

Result:

```<code>SQL> select * from pm;

PMBPCSB    PMBPCFBB   PMBPCHUB   PMBCITNC
---------- ---------- ---------- ----------
X          100        200        300
X          300                   500
                                            --> this is a row whose columns are NULL (all of them)

SQL>
</code>```

How to convert it to a procedure? Simply:

```<code>SQL> create or replace procedure p_pm as
  2  begin
  3    update pm set
  4      pmbpcsb = 'X'
  5    where coalesce(pmbpcfbb, pmbpchub, pmbcitnc) is not null;
  6  end;
  7  /

Procedure created.

SQL>
</code>```

However, perhaps you'd rather use CASE and affect all rows because - what if table contents changes?

```<code>SQL> update pm set
  2    pmbpcsb = case when coalesce(pmbpcfbb, pmbpchub, pmbcitnc) is not null then 'X'
  3                   else null
  4              end;

3 rows updated.

SQL>
</code>```

Or, as people commented, create a view (using the same principle):

```<code>SQL> create or replace view v_pm as
  2  select case when coalesce(pmbpcfbb, pmbpchub, pmbcitnc) is not null then 'X'
  3              else null
  4         end pmbpcsb,
  5     pmbpcfbb,
  6     pmbpchub,
  7     pmbcitnc
  8  from pm;

View created.

SQL> select * From v_pm;

PMBPCSB    PMBPCFBB   PMBPCHUB   PMBCITNC
---------- ---------- ---------- ----------
X          100        200        300
X          300                   500

SQL>
</code>```

Body:
That's just an ordinary UPDATE, is it not?

SQL> create table pm
  2    (pmbpcsb  varchar2(1),
  3     pmbpcfbb varchar2(10),
  4     pmbpchub varchar2(10),
  5     pmbcitnc varchar2(10)
  6    );

Table created.

SQL> insert into pm values (null, '100', '200', '300');

1 row created.

SQL> insert into pm values (null, '300', null , '500');

1 row created.

SQL> insert into pm values (null, null , null , null );

1 row created.

Update:

SQL> update pm set
  2    pmbpcsb = 'X'
  3  where coalesce(pmbpcfbb, pmbpchub, pmbcitnc) is not null;

2 rows updated.

Result:

SQL> select * from pm;

PMBPCSB    PMBPCFBB   PMBPCHUB   PMBCITNC
---------- ---------- ---------- ----------
X          100        200        300
X          300                   500
                                            --> this is a row whose columns are NULL (all of them)

SQL>

How to convert it to a procedure? Simply:

SQL> create or replace procedure p_pm as
  2  begin
  3    update pm set
  4      pmbpcsb = 'X'
  5    where coalesce(pmbpcfbb, pmbpchub, pmbcitnc) is not null;
  6  end;
  7  /

Procedure created.

SQL>

However, perhaps you'd rather use CASE and affect all rows because - what if table contents changes?

SQL> update pm set
  2    pmbpcsb = case when coalesce(pmbpcfbb, pmbpchub, pmbcitnc) is not null then 'X'
  3                   else null
  4              end;

3 rows updated.

SQL>

Or, as people commented, create a view (using the same principle):

SQL> create or replace view v_pm as
  2  select case when coalesce(pmbpcfbb, pmbpchub, pmbcitnc) is not null then 'X'
  3              else null
  4         end pmbpcsb,
  5     pmbpcfbb,
  6     pmbpchub,
  7     pmbcitnc
  8  from pm;

View created.

SQL> select * From v_pm;

PMBPCSB    PMBPCFBB   PMBPCHUB   PMBCITNC
---------- ---------- ---------- ----------
X          100        200        300
X          300                   500

SQL>


问:
What is the reason for difference between integer division and float to int conversion in python?
I have recently noticed that int() rounds a float towards 0, while integer division rounds a float towards its floor.

for instance:

```<code>-7 // 2 == -4
int(-7/2) == -3
</code>```

I have read the documentation which specifies:

class int(x, base=10)

Return an integer object constructed from a number or string x, or return 0 if no arguments are >given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

and:

floor division

Mathematical division that rounds down to nearest integer. The floor division operator is //. For example, the expression 11 // 4 evaluates to 2 in contrast to the 2.75 returned by float true division. Note that (-11) // 4 is -3 because that is -2.75 rounded downward. See PEP 238.

But it seems illogical for me that 2 similar operations (float division to integer) should return different results.

Is there any motivation for the differences between the functions?

答:
Based on the answer by @thomas-weller I also found myself a maybe novice explanation for the floor division result from his example of division with a remainder:

7 / 4 =  1 R 3 = 1 + 0,75 = 1.75

-> R3 = 3/4 = 0.75

-1 /4 = -1 R 3 = -1 + 0,75 (R3) = -0.25

Body:
I have recently noticed that int() rounds a float towards 0, while integer division rounds a float towards its floor.

for instance:

-7 // 2 == -4
int(-7/2) == -3

I have read the documentation which specifies:

class int(x, base=10)

Return an integer object constructed from a number or string x, or return 0 if no arguments are >given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

and:

floor division

Mathematical division that rounds down to nearest integer. The floor division operator is //. For example, the expression 11 // 4 evaluates to 2 in contrast to the 2.75 returned by float true division. Note that (-11) // 4 is -3 because that is -2.75 rounded downward. See PEP 238.

But it seems illogical for me that 2 similar operations (float division to integer) should return different results.

Is there any motivation for the differences between the functions?


问:
simple Tkinter program - window vanishes after clicking button - maintop problem?
Coders,
I guess I have a newbie question: my windows disappears when I click on a button. If I put in root.mainloop() as last line in the buttonClicked-function, then the program is fine - but it looks not right...what is wrong here?</p>
```<code>import tkinter as tk

def buttonClicked(event):
    print(tf1.get())
    tf1Content.set("button clicked")
    # root.mainloop() ... would work

root = tk.Tk()

frame = tk.Frame(root, relief="ridge", borderwidth=2)
frame.pack(fill="both",expand=1)
label = tk.Label(frame, text="Input:")
label.pack(expand=1)
tf1Content = tk.StringVar()
tf1 = tk.Entry(frame, text="input here", textvariable=tf1Content)
tf1.pack(expand=1)
bOk = tk.Button(frame,text="OK",command=root.destroy)
bOk.bind("<Button-1>", buttonClicked)
bOk.widget = "bOK"
bOk.pack(side="bottom")

tf1.focus()

root.mainloop()
</code>```

答:
It turns out that you just copied this line:

bOk = tk.Button(frame,text="OK",command=root.destroy)
```
<p>which binds a call to <code>root.destroy()</code> to the button press.</p>
<p>The fix is to just remove the <code>command</code> parameter:</p>
<pre class="lang-py prettyprint-override"><code>bOk = tk.Button(frame,text="OK")
</code>```

Body:
Coders,
I guess I have a newbie question: my windows disappears when I click on a button. If I put in root.mainloop() as last line in the buttonClicked-function, then the program is fine - but it looks not right...what is wrong here?

import tkinter as tk

def buttonClicked(event):
    print(tf1.get())
    tf1Content.set("button clicked")
    # root.mainloop() ... would work

root = tk.Tk()

frame = tk.Frame(root, relief="ridge", borderwidth=2)
frame.pack(fill="both",expand=1)
label = tk.Label(frame, text="Input:")
label.pack(expand=1)
tf1Content = tk.StringVar()
tf1 = tk.Entry(frame, text="input here", textvariable=tf1Content)
tf1.pack(expand=1)
bOk = tk.Button(frame,text="OK",command=root.destroy)
bOk.bind("<Button-1>", buttonClicked)
bOk.widget = "bOK"
bOk.pack(side="bottom")

tf1.focus()

root.mainloop()

Body:
It turns out that you just copied this line:

bOk = tk.Button(frame,text="OK",command=root.destroy)

which binds a call to root.destroy() to the button press.

The fix is to just remove the command parameter:

bOk = tk.Button(frame,text="OK")