问:
I'm unable to upload a file whose name has a space in it to Google Cloud Storage using Python. What am I doing wrong?
I'm new to Python and Google Cloud. Using Flask I have created a web page where a user can choose a file from their computer and upload it to a GCS bucket that I have already created. I'm following Google's documentation example which uses the Google Python API library. I'm able to upload files whose names are just a single word, like 'image' but if my file is named 'image one' then I get the following error-
 FileNotFoundError: [Errno 2] No such file or directory: 'image one.jpg'

Here's my code:

```<code>@app.route('/upload', methods = ['GET'  , 'POST'])
def upload():
    if request.method == "POST":
        f = request.files['file']
        f.save(secure_filename(f.filename))
        gcs_upload(f.filename)

def gcs_upload(filename):
    storage_client = storage.Client()   # instantiate a client
    bucket = storage_client.bucket('bucket_name')
    blob=bucket.blob(filename)      # file name at the destination should be the same
    blob.upload_from_filename(filename)     # file to be uploaded

if __name__ == '__main__':
    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
    app.run(port=8080, debug=True)
</code>```

If I'm writing a production level application then I would want a user to upload a file even if it has spaces in its name.

答:
Try to quote  filename (by using urllib) before. This is an example by using python3:

```<code>import urllib.parse
filename = "files name.jpg"
new_file = str(urllib.parse.quote(filename))
</code>```

Body:
I'm new to Python and Google Cloud. Using Flask I have created a web page where a user can choose a file from their computer and upload it to a GCS bucket that I have already created. I'm following Google's documentation example which uses the Google Python API library. I'm able to upload files whose names are just a single word, like 'image' but if my file is named 'image one' then I get the following error-
 FileNotFoundError: [Errno 2] No such file or directory: 'image one.jpg'

Here's my code:

@app.route('/upload', methods = ['GET'  , 'POST'])
def upload():
    if request.method == "POST":
        f = request.files['file']
        f.save(secure_filename(f.filename))
        gcs_upload(f.filename)

def gcs_upload(filename):
    storage_client = storage.Client()   # instantiate a client
    bucket = storage_client.bucket('bucket_name')
    blob=bucket.blob(filename)      # file name at the destination should be the same
    blob.upload_from_filename(filename)     # file to be uploaded

if __name__ == '__main__':
    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
    app.run(port=8080, debug=True)

If I'm writing a production level application then I would want a user to upload a file even if it has spaces in its name.

Body:
Try to quote  filename (by using urllib) before. This is an example by using python3:

import urllib.parse
filename = "files name.jpg"
new_file = str(urllib.parse.quote(filename))


来源: stackexchange

问:
Connect MongoDB compass client to the mongodb database inside kubernetes cluster
I am running a mongo docker container service inside a kubernetes cluster.
Incoming traffic from outside is routed via ingress-nginx (https://kubernetes.github.io/ingress-nginx/) load balancer to the mongo docker container service.

Application is working as expected and I need to know whether there is a way I can connect the MongoDB compass client (which i installed in my local machine) to the running mongodb container to visualize the data easily.

I am having issues since the container is inside kubernetes and there is a load balancer in between.

Would be of great help if someone could assist. Thanks

答:
You can use port-forward</p>

```<code>$ kubectl port-forward -h
Forward one or more local ports to a pod. This command requires the node to have 'socat' installed.

 Use resource type/name such as deployment/mydeployment to select a pod. Resource type defaults to 'pod' if omitted.

 If there are multiple pods matching the criteria, a pod will be selected automatically. The forwarding session ends
when the selected pod terminates, and rerun of the command is needed to resume forwarding.

Examples:
  # Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in the pod
  kubectl port-forward pod/mypod 5000 6000

  # Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in a pod selected by the
deployment
  kubectl port-forward deployment/mydeployment 5000 6000

  # Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in a pod selected by the service
  kubectl port-forward service/myservice 5000 6000

  # Listen on port 8888 locally, forwarding to 5000 in the pod
  kubectl port-forward pod/mypod 8888:5000

  # Listen on port 8888 on all addresses, forwarding to 5000 in the pod
  kubectl port-forward --address 0.0.0.0 pod/mypod 8888:5000

  # Listen on port 8888 on localhost and selected IP, forwarding to 5000 in the pod
  kubectl port-forward --address localhost,10.19.21.23 pod/mypod 8888:5000

  # Listen on a random port locally, forwarding to 5000 in the pod
  kubectl port-forward pod/mypod :5000

Options:
      --address=[localhost]: Addresses to listen on (comma separated). Only accepts IP addresses or localhost as a
value. When localhost is supplied, kubectl will try to bind on both 127.0.0.1 and ::1 and will fail if neither of these
addresses are available to bind.
      --pod-running-timeout=1m0s: The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one
pod is running

Usage:
  kubectl port-forward TYPE/NAME [options] [LOCAL_PORT:]REMOTE_PORT [...[LOCAL_PORT_N:]REMOTE_PORT_N]

Use "kubectl options" for a list of global command-line options (applies to all commands).

</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can use port-forward

$ kubectl port-forward -h
Forward one or more local ports to a pod. This command requires the node to have 'socat' installed.

 Use resource type/name such as deployment/mydeployment to select a pod. Resource type defaults to 'pod' if omitted.

 If there are multiple pods matching the criteria, a pod will be selected automatically. The forwarding session ends
when the selected pod terminates, and rerun of the command is needed to resume forwarding.

Examples:
  # Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in the pod
  kubectl port-forward pod/mypod 5000 6000

  # Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in a pod selected by the
deployment
  kubectl port-forward deployment/mydeployment 5000 6000

  # Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in a pod selected by the service
  kubectl port-forward service/myservice 5000 6000

  # Listen on port 8888 locally, forwarding to 5000 in the pod
  kubectl port-forward pod/mypod 8888:5000

  # Listen on port 8888 on all addresses, forwarding to 5000 in the pod
  kubectl port-forward --address 0.0.0.0 pod/mypod 8888:5000

  # Listen on port 8888 on localhost and selected IP, forwarding to 5000 in the pod
  kubectl port-forward --address localhost,10.19.21.23 pod/mypod 8888:5000

  # Listen on a random port locally, forwarding to 5000 in the pod
  kubectl port-forward pod/mypod :5000

Options:
      --address=[localhost]: Addresses to listen on (comma separated). Only accepts IP addresses or localhost as a
value. When localhost is supplied, kubectl will try to bind on both 127.0.0.1 and ::1 and will fail if neither of these
addresses are available to bind.
      --pod-running-timeout=1m0s: The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one
pod is running

Usage:
  kubectl port-forward TYPE/NAME [options] [LOCAL_PORT:]REMOTE_PORT [...[LOCAL_PORT_N:]REMOTE_PORT_N]

Use "kubectl options" for a list of global command-line options (applies to all commands).


问:
How can I extend the div content of my page to fit the screen?
take a look at it
-> the page (simulated).

```<code><!doctype html>
<html>
<head>
<style type=text/css media=all>
*{  margin:0; padding:0; }
#header
{
    background-color:orange;
    position:relative;
    top:0;
}
#header #image
{
    width:120px;
    height:120px;
    background-color:#000;
}
#content
{
    background-color:red;
}

#footer
{
    background-color:green;
}
</style>
</head>
<body>
    <div id=header>
        <div id=image></div><!-- emulating an image -->
    </div>
    <div id=content>
        <p> BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA</p>
    </div>
    <div id=footer>
        <p><center>Copyright</center></p>
    </div>
</body>
</html>
</code>```

I'd like to extend the div content that it can fit the whole page whatever if the content of the div is too short or too long I just want it to fit the height between the header and the footer (the footer is always laying on the bottom) and if the content is too long for the page's height in that case then add a scrollbar, and if the window is resized then the content has to get the new height, I've intermingled my brushes

答:
```<code>#content {
    min-height: 100%
}
</code>```

(short and simple)

Edit + explanation: The above code works when you want to make sure the length of content div is always longer than the page. Yes, that always pushes the footer to the next visible page, but there is nothing wrong with it as long as you accept that.

For me the better solution out there is to do a div scroll:

```<code>html, body {
    height: 100%; margin: 0; padding: 0; overflow: hidden;
}

#header {
    position: absolute;
    top: 0; height: 100px;
}

#footer {
    position: absolute;
    bottom: 0; height: 100px;
}

#content {
    position: absolute;
    top: 100px; bottom: 100px;
    overflow: auto;
}
</code>```

In this way, the header and the footer is always visible, and the size of content is fixed (with scroll bar if the content overflows). Not sure this is the solution you wanted but this is an option.

ContentLicense: CC BY-SA 3.0

Body:
take a look at it
-> the page (simulated).

<!doctype html>

 BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA

Copyright

I'd like to extend the div content that it can fit the whole page whatever if the content of the div is too short or too long I just want it to fit the height between the header and the footer (the footer is always laying on the bottom) and if the content is too long for the page's height in that case then add a scrollbar, and if the window is resized then the content has to get the new height, I've intermingled my brushes

Body:
#content {
    min-height: 100%
}

(short and simple)

Edit + explanation: The above code works when you want to make sure the length of content div is always longer than the page. Yes, that always pushes the footer to the next visible page, but there is nothing wrong with it as long as you accept that.

For me the better solution out there is to do a div scroll:

html, body {
    height: 100%; margin: 0; padding: 0; overflow: hidden;
}

#header {
    position: absolute;
    top: 0; height: 100px;
}

#footer {
    position: absolute;
    bottom: 0; height: 100px;
}

#content {
    position: absolute;
    top: 100px; bottom: 100px;
    overflow: auto;
}

In this way, the header and the footer is always visible, and the size of content is fixed (with scroll bar if the content overflows). Not sure this is the solution you wanted but this is an option.


问:
Django model relationship with circular relationship
I am new to Django and trying to understand the model relationships, here is my use case:

I have a Creator object which can create multiple Listing under a Category. Category can have multiple Listings from multiple Creators.

Creator -- Creates a Listing about a service -- under a Category or multiple Category

I am trying to find the thought process behind picking the correct relationship while defining this kind circular  relationship.  Which one of the model should go first? Is it Category which is first and Creator second and Listing at the end, is Creator, Category and Listing all belong to a Many to Many relationship, if then how are they linked?

答:
You don't have a circular relationship, this should cover your use case:

```<code>class Creator:
    ...

class Category:
    ...

class Listing:
    creator = models.ForeignKey(Creator, on_delete=models.PROTECT)
    category = models.ManyToMany(Category)
</code>```

I am assuming that a Listing can be under multiple Categorys. If each listing can only have one Category, the second (category) relation must be a ForeignKey too.

Body:
You don't have a circular relationship, this should cover your use case:

class Creator:
    ...

class Category:
    ...

class Listing:
    creator = models.ForeignKey(Creator, on_delete=models.PROTECT)
    category = models.ManyToMany(Category)

I am assuming that a Listing can be under multiple Categorys. If each listing can only have one Category, the second (category) relation must be a ForeignKey too.


问:
How to stop password field from showing 'null' as a placeholder?
I have a password field which is interactive and has some js going on behind the scenes. However I have this issue of when I click on the field, it shows 'null' as a value, as per the image.

This only shows when I click on the field, and I have no placeholder given to the input either. How do I prevent this from showing?

The code

//floating input controller

const FloatLabel = (() => {

  // add active class
  const handleFocus = (e) => {
    const target = e.target;
    target.parentNode.classList.add('active');
    target.setAttribute('placeholder', target.getAttribute('data-placeholder'));
  };

  // remove active class
  const handleBlur = (e) => {
    const target = e.target;
    if (!target.value) {
      target.parentNode.classList.remove('active');
    }
    target.removeAttribute('placeholder');
  };

  // register events
  const bindEvents = (element) => {
    const floatField = element.querySelector('input');
    floatField.addEventListener('focus', handleFocus);
    floatField.addEventListener('blur', handleBlur);
  };

  // get DOM elements
  const init = () => {
    const floatContainers = document.querySelectorAll('.float-container');

    floatContainers.forEach((element) => {

      if (element.querySelector('input').value) {
        element.classList.add('active');
      }

      bindEvents(element);
    });
  };

  return {
    init: init
  };
})();

FloatLabel.init();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.float-container {
  position: relative;
  background-color: #dfecff;
  width: 100%;
  border-radius: 5px;
  transition: 150ms;
  padding-top: .6em;
  padding-bottom: .6em;
  border: 2px solid #b9d6ff;
}

.float-container:hover {
  background-color: #1a73e8;
  cursor: text;
}

.password-toggle-button {
  position: absolute;
  font-size: 1em;
  padding-top: 8px;
  color: #333333;
  margin-left: 93%;
}

.password-toggle-button:hover {
  cursor: pointer;
  color: #eeeeee;
}

label {
  font-size: 1em;
  font-family: Arial, Helvetica, sans-serif;
  color: #5e5e5e;
  position: absolute;
  margin-left: 3%;
  z-index: 140;
  transform: translate(0, 0) scale(1);
  pointer-events: none;
  user-select: none;
  transform-origin: top left;
  transition: all .1s ease-in-out;
}

.float-container input {
  color: #eeeeee;
}

.float-container.active label {
  transform: translate(-0.5em, -1.5em) scale(.95);
  font-style: italic;
  font-weight: 200;
  border-radius: 10px;
  background-color: #1a73e8;
  padding-left: .5em;
  padding-right: .5em;
  color: #eeeeee;
}

.float-container.active input {
  color: #eeeeee;
}

.float-container.active {
  background-color: #1a73e8;
  border: 2px solid #eeeeee;
}

.form-center {
  display: relative;
  margin-top: 3em;
  margin-left: 5vw;
  margin-bottom: 5em;
  word-break: break-all;
  padding-top: 3%;
  padding-left: 5vw;
  padding-right: 3vw;
  padding-bottom: 5%;
  width: 60vw;
  line-height: 2em;
  background-color: #1a73e8;
  border-radius: 20px;
  border-width: 3px;
  border-style: solid;
  border-color: #333333;
}

input{
  border: none;
  background-color: transparent;
  color: #333333;
  outline: 0;
  margin-top: auto;
  margin-left: 3%;
  margin-right: 20%;
  width: 90%;
  z-index: 150;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/css/all.min.css" rel="stylesheet" />

  Password

  <input type="password" class="floatField id="pw" placeholder="">

```

答:
You have to verify if the value is null before setting it as the input placeholder:</p>

```<code>const handleFocus = (e) => {
    const target = e.target;
    target.parentNode.classList.add('active');
    const placeholder = target.getAttribute('data-placeholder');

    if (!!placeholder && placeholder !== 'null') {
        target.setAttribute('placeholder', placeholder);
    } else {
        // Do something else
    }
};
</code>```

Body:
I have a password field which is interactive and has some js going on behind the scenes. However I have this issue of when I click on the field, it shows 'null' as a value, as per the image.

This only shows when I click on the field, and I have no placeholder given to the input either. How do I prevent this from showing?

The code

//floating input controller

const FloatLabel = (() => {

  // add active class
  const handleFocus = (e) => {
    const target = e.target;
    target.parentNode.classList.add('active');
    target.setAttribute('placeholder', target.getAttribute('data-placeholder'));
  };

  // remove active class
  const handleBlur = (e) => {
    const target = e.target;
    if (!target.value) {
      target.parentNode.classList.remove('active');
    }
    target.removeAttribute('placeholder');
  };

  // register events
  const bindEvents = (element) => {
    const floatField = element.querySelector('input');
    floatField.addEventListener('focus', handleFocus);
    floatField.addEventListener('blur', handleBlur);
  };

  // get DOM elements
  const init = () => {
    const floatContainers = document.querySelectorAll('.float-container');

    floatContainers.forEach((element) => {

      if (element.querySelector('input').value) {
        element.classList.add('active');
      }

      bindEvents(element);
    });
  };

  return {
    init: init
  };
})();

FloatLabel.init();

.float-container {
  position: relative;
  background-color: #dfecff;
  width: 100%;
  border-radius: 5px;
  transition: 150ms;
  padding-top: .6em;
  padding-bottom: .6em;
  border: 2px solid #b9d6ff;
}

.float-container:hover {
  background-color: #1a73e8;
  cursor: text;
}

.password-toggle-button {
  position: absolute;
  font-size: 1em;
  padding-top: 8px;
  color: #333333;
  margin-left: 93%;
}

.password-toggle-button:hover {
  cursor: pointer;
  color: #eeeeee;
}

label {
  font-size: 1em;
  font-family: Arial, Helvetica, sans-serif;
  color: #5e5e5e;
  position: absolute;
  margin-left: 3%;
  z-index: 140;
  transform: translate(0, 0) scale(1);
  pointer-events: none;
  user-select: none;
  transform-origin: top left;
  transition: all .1s ease-in-out;
}

.float-container input {
  color: #eeeeee;
}

.float-container.active label {
  transform: translate(-0.5em, -1.5em) scale(.95);
  font-style: italic;
  font-weight: 200;
  border-radius: 10px;
  background-color: #1a73e8;
  padding-left: .5em;
  padding-right: .5em;
  color: #eeeeee;
}

.float-container.active input {
  color: #eeeeee;
}

.float-container.active {
  background-color: #1a73e8;
  border: 2px solid #eeeeee;
}

.form-center {
  display: relative;
  margin-top: 3em;
  margin-left: 5vw;
  margin-bottom: 5em;
  word-break: break-all;
  padding-top: 3%;
  padding-left: 5vw;
  padding-right: 3vw;
  padding-bottom: 5%;
  width: 60vw;
  line-height: 2em;
  background-color: #1a73e8;
  border-radius: 20px;
  border-width: 3px;
  border-style: solid;
  border-color: #333333;
}

input{
  border: none;
  background-color: transparent;
  color: #333333;
  outline: 0;
  margin-top: auto;
  margin-left: 3%;
  margin-right: 20%;
  width: 90%;
  z-index: 150;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/css/all.min.css" rel="stylesheet" />

  Password

  <input type="password" class="floatField id="pw" placeholder="">

Body:
You have to verify if the value is null before setting it as the input placeholder:

const handleFocus = (e) => {
    const target = e.target;
    target.parentNode.classList.add('active');
    const placeholder = target.getAttribute('data-placeholder');

    if (!!placeholder && placeholder !== 'null') {
        target.setAttribute('placeholder', placeholder);
    } else {
        // Do something else
    }
};


问:
How can I get OnNewIntent to fire
I can't get OnNewIntent to fire. I've read dozens of articles on the issue and tried all combinations of code.

Regardless of whether I use LaunchMode.SingleTask or SingleTop it won't fire and always passes through the OnCreate method.

What am I doing wrong here? Am I missing something? What do I need to add to get it to work?

```<code>using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using System;
using System.Threading.Tasks;
using Xamarin.Forms;
using static MyApp.ClipboardMgr;

namespace MyApp.Droid
{
    //[Activity(Label = "SplashActivity")]
    [Activity(LaunchMode = LaunchMode.SingleTask, Theme = "@style/Theme.Splash",
                MainLauncher = true, NoHistory = true)]

    //Can't get this to work with LaunchMode.SingleTop or SingleTask. Always creates a new instance.
    [IntentFilter(new[] { Intent.ActionProcessText },
                Categories = new[] { Intent.CategoryDefault },
                DataMimeType = @"text/plain", Icon = "@drawable/icon", Label = "MyApp")]

    public class SplashActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            try
            {
                //taking these out for readability
                //AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                //TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
                //AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironment_UnhandledExceptionRaiser;

                base.OnCreate(savedInstanceState);

                // Create your application
                StartActivity(typeof(MainActivity));

                //don't want to do this here, better to do it in event
                if (Intent.Action == Intent.ActionProcessText)
                {
                    //always comes here
                    HandleProcessTextIntent();

                }
            }
            catch(Exception e)
            {
                App.LogException(e);
                throw;
            }
        }

        /// <summary>
        /// this is not firing!
        /// </summary>
        /// <param name="intent"></param>
        protected override void OnNewIntent(Intent intent)
        {
            base.OnNewIntent(intent);

            HandleProcessTextIntent();

        }

        void HandleProcessTextIntent()
        {
            string input = Intent.GetStringExtra(Intent.ExtraProcessText).Trim();

            if (input == string.Empty)
                return;

            ClipMgr.SetText(input);
        }

    }
}
</code>```

答:
You didn't miss anything since when I test with my own intent to start your activity, it works well and the OnNewIntent() is called when SingleTask or SingleTop used, here's how I call the activity from another project(I did this in native Android):

```<code>ComponentName component = new ComponentName("com.example.textHandlerDemo", "com.example.textHandlerDemo.TextHandlerActivity");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PROCESS_TEXT);
intent.setComponent(component);
startActivity(intent);
</code>```

I did some research and find something that may explain why the OnNewIntent() never gets fired:

According to the guidance of ACTION_PROCESS_TEXT, it mentioned:

You can use this as a hint to offer the ability to return altered text to the sending app, replacing the selected text. This works as your Activity was actually started with startActivityForResult()

So, when you click your app's label in the floating text selection toolbar, Android will start your activity registered with ActionProcessText with startActivityForResult(), and by using startActivityForResult(), your activity will be started as a sub-activity of current activity(implied from Android doc of startActivityForResult), that is to say, rather than redirecting to your app which is already running, Android will put your activity into current app's stack.

This way, your target activity will still be called from OnCreate() since it's isolated from your running app.

Moreover, the floating text selection toolbar is used to provide a quick in-app experience for text operations like translation as mentioned in this blog, I didn't find any swich to enable/disable redirect to app, you may need to handle the intent in both OnCreate() and OnNewIntent() if you're using LaunchMode.SingleTask or SingleTop.

Title: How can I get OnNewIntent to fire

Body:
I can't get OnNewIntent to fire. I've read dozens of articles on the issue and tried all combinations of code.

Regardless of whether I use LaunchMode.SingleTask or SingleTop it won't fire and always passes through the OnCreate method.

What am I doing wrong here? Am I missing something? What do I need to add to get it to work?

using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using System;
using System.Threading.Tasks;
using Xamarin.Forms;
using static MyApp.ClipboardMgr;

namespace MyApp.Droid
{
    //[Activity(Label = "SplashActivity")]
    [Activity(LaunchMode = LaunchMode.SingleTask, Theme = "@style/Theme.Splash",
                MainLauncher = true, NoHistory = true)]

    //Can't get this to work with LaunchMode.SingleTop or SingleTask. Always creates a new instance.
    [IntentFilter(new[] { Intent.ActionProcessText },
                Categories = new[] { Intent.CategoryDefault },
                DataMimeType = @"text/plain", Icon = "@drawable/icon", Label = "MyApp")]

    public class SplashActivity : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            try
            {
                //taking these out for readability
                //AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                //TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
                //AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironment_UnhandledExceptionRaiser;

                base.OnCreate(savedInstanceState);

                // Create your application
                StartActivity(typeof(MainActivity));

                //don't want to do this here, better to do it in event
                if (Intent.Action == Intent.ActionProcessText)
                {
                    //always comes here
                    HandleProcessTextIntent();

                }
            }
            catch(Exception e)
            {
                App.LogException(e);
                throw;
            }
        }

        ///
        /// this is not firing!
        ///
        /// <param name="intent"></param>
        protected override void OnNewIntent(Intent intent)
        {
            base.OnNewIntent(intent);

            HandleProcessTextIntent();

        }

        void HandleProcessTextIntent()
        {
            string input = Intent.GetStringExtra(Intent.ExtraProcessText).Trim();

            if (input == string.Empty)
                return;

            ClipMgr.SetText(input);
        }

    }
}

Body:
You didn't miss anything since when I test with my own intent to start your activity, it works well and the OnNewIntent() is called when SingleTask or SingleTop used, here's how I call the activity from another project(I did this in native Android):

ComponentName component = new ComponentName("com.example.textHandlerDemo", "com.example.textHandlerDemo.TextHandlerActivity");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PROCESS_TEXT);
intent.setComponent(component);
startActivity(intent);

I did some research and find something that may explain why the OnNewIntent() never gets fired:

According to the guidance of ACTION_PROCESS_TEXT, it mentioned:

You can use this as a hint to offer the ability to return altered text to the sending app, replacing the selected text. This works as your Activity was actually started with startActivityForResult()

So, when you click your app's label in the floating text selection toolbar, Android will start your activity registered with ActionProcessText with startActivityForResult(), and by using startActivityForResult(), your activity will be started as a sub-activity of current activity(implied from Android doc of startActivityForResult), that is to say, rather than redirecting to your app which is already running, Android will put your activity into current app's stack.

This way, your target activity will still be called from OnCreate() since it's isolated from your running app.

Moreover, the floating text selection toolbar is used to provide a quick in-app experience for text operations like translation as mentioned in this blog, I didn't find any swich to enable/disable redirect to app, you may need to handle the intent in both OnCreate() and OnNewIntent() if you're using LaunchMode.SingleTask or SingleTop.


问:
Is JavaScript single threaded?
As it is obvious that nodeJs is single-threaded. But JavaScript as a language is also single-threaded?

答:
Javascript isn't inherently single-threaded or multi-threaded as a language.  There are Javsacript environments that don't offer Javascript threads and environments that do offer Javascript threads. The language itself doesn't specify single-threadedness or multi-threadedness.  Instead, it's up to the environment whether it wants to make threads of Javascript available.

So, to your specific question:

Is JavaScript single threaded?

No.  It's not specifically single threaded or multiple threaded.  The language specification doesn't require either.  The threading of Javascript is up to the run-time environment to implement.  It so happens that both the browser and node.js started out without Javascript threads and an event-driven architecture which led to this notion that there are no threads in a Javascript environment, but there ARE.  They now both offer Javascript threads (WebWorkers in the browser and WorkerThreads in node.js).

The Javascript specification offers some features that are useful in multi-threaded environments such as SharedArrayBuffer objects and Atomics and environments that offer threading provide additional libraries.  So, the current language specification recognizes some of the needs of multi-threading and provides some tools for it, though there is no specific requirement that a Javascript runtime has or doesn't have threads.  It's up to the run-time whether they want to offer that capability to run multiple Javascript threads of execution in parallel or not.

Title: Is JavaScript single threaded?


问:
Getting current day number with awk and date
The output of date command has two spaces when the day number is less than 10. For example

```<code>Mon May 31 10:24:01 +0430 2020
Mon Jun  1 10:24:01 +0430 2020
</code>```

For the first one, date | cut -d " " -f 3 returns 31. But, for the second one, it returns SPACE. Any way to fix that?

答:
You could simple try awk to get the 3rd field, which will be definitely better than cut command.

```<code>date | awk '{print $3}'
</code>```

Now why cut command is not working IMHO because space between May and 31 is equal but space between Jun and 1 is not equal so you need to use f4 in your cut command(for single digit date numbers with your current approach). Its better to use awk in this case.

Or In ideal scenario if you want to get only date then use date '+%d' to get date always in 2 digit as per @anubhava sir's comments.

Body:
The output of date command has two spaces when the day number is less than 10. For example

Mon May 31 10:24:01 +0430 2020
Mon Jun  1 10:24:01 +0430 2020

For the first one, date | cut -d " " -f 3 returns 31. But, for the second one, it returns SPACE. Any way to fix that?

Body:
You could simple try awk to get the 3rd field, which will be definitely better than cut command.

date | awk '{print $3}'

Now why cut command is not working IMHO because space between May and 31 is equal but space between Jun and 1 is not equal so you need to use f4 in your cut command(for single digit date numbers with your current approach). Its better to use awk in this case.

Or In ideal scenario if you want to get only date then use date '+%d' to get date always in 2 digit as per @anubhava sir's comments.


问:
Unable to register child component in vue.js
Getting following error.

Unknown custom element:  - did you register the component correctly? For recursive components, make sure to provide the "name" option.

I am not sure what is wrong with the code. I have followed this link https://michaelnthiessen.com/solve-unknown-custom-element-vue/
I have used Local registration for child component. ( RobotBuilder.vue)

```<code><template>
  <div class="content">
    <button class="add-to-cart" @click="addToCart()">Add to Cart</button>
    <div class="top-row">
      <PartSelector />
    </div>
    <div class="middle-row">
      <PartSelector />
      <PartSelector />
      <PartSelector />
    </div>
    <div class="bottom-row">
      <PartSelector />
    </div>
    <div>
      <table>
        <thead>
          <tr>
            <th>Robot</th>
            <th class="cost">Cost</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(robot,index) in cart" :key="index">
            <td>{{robot.head.title}}</td>
            <td>{{robot.cost}}</td>
            <td>
              <button @click="removeItem([index])">X</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import availableParts from '../data/parts';
import { PartSelector } from './PartSelector.vue';

export default {
  name: 'RobotBuilder',
  components: { PartSelector },
  data() {
    return {
      availableParts,
      cart: [],
      selectedRobot: {
        head: {},
        leftArm: {},
        rightArm: {},
        torso: {},
        base: {},
      },
    };
  },
  computed: {},
  methods: {
    addToCart() {
      const robot = this.selectedRobot;
      const cost = robot.head.cost
        + robot.leftArm.cost
        + robot.torso.cost
        + robot.rightArm.cost
        + robot.base.cost;
      this.cart.push({ ...robot, cost });
    },
    removeItem(index) {
      this.cart.splice(index, 1);
    },
  },
};
</script>

<style scoped>

</style>
</code>```

PartSelector.vue

```<code> <template>
  <div class="part">
    <img :src="selectedPart.src" title="arm"/>
    <button @click="selectPreviousPart()" class="prev-selector"></button>
    <button @click="selectNextPart()" class="next-selector"></button>
    <span class="sale" v-show="selectedPart.onSale">Sale!</span>
  </div>
</template>

<script>
import availableParts from '../data/parts';

const parts = availableParts.heads;

function getPreviousValidIndex(index, length) {
  const deprecatedIndex = index - 1;
  return deprecatedIndex < 0 ? length - 1 : deprecatedIndex;
}

function getNextValidIndex(index, length) {
  const incrementedIndex = index + 1;
  return incrementedIndex > length - 1 ? 0 : incrementedIndex;
}

export default {
  name: 'PartSelector',
  data() {
    return { selectedPartIndex: 0 };
  },
  computed: {
    selectedPart() {
      return parts[this.selectedPartIndex];
    },
  },
  methods: {
    selectNextPart() {
      this.selectedPartIndex = getNextValidIndex(
        this.selectedPartIndex,
        parts.length,
      );
    },
    selectPreviousPart() {
      this.selectedPartIndex = getPreviousValidIndex(
        this.selectedPartIndex,
        parts.length,
      );
    },

  },
};

</script>
</code>```

答:
You are exporting as default but importing as named import.

In Robot builder, import like this :

```<code>import PartSelector from './PartSelector.vue';
</code>```

Body:
Getting following error.

Unknown custom element:  - did you register the component correctly? For recursive components, make sure to provide the "name" option.

I am not sure what is wrong with the code. I have followed this link https://michaelnthiessen.com/solve-unknown-custom-element-vue/
I have used Local registration for child component. ( RobotBuilder.vue)

<template>

    <button class="add-to-cart" @click="addToCart()">Add to Cart</button>

      <PartSelector />

      <PartSelector />
      <PartSelector />
      <PartSelector />

      <PartSelector />

            Robot
            Cost

            {{robot.head.title}}
            {{robot.cost}}

              <button @click="removeItem([index])">X</button>

</template>

PartSelector.vue

 <template>

    <button @click="selectPreviousPart()" class="prev-selector"></button>
    <button @click="selectNextPart()" class="next-selector"></button>
    Sale!

</template>

Body:
You are exporting as default but importing as named import.

In Robot builder, import like this :

import PartSelector from './PartSelector.vue';


问:
question about shift operation and bracket operation
```<code>for(i=0; i<8 ;i++)
{
    SRCLK = 0;
    SER = (sendData>>7);
    sendData <<= 1;
    SRCLK = 1;
}
</code>```

and

```<code>for(i=0; i<8 ;i++)
{
    SRCLK = 0;
    SER = (sendData>>(7-i));
    SRCLK = 1;
}
</code>```

i think there is no difference bettween them. i builded the code and download to my 51MCU. i use SER to send serial data to 74HC595, these codes displayed different phenomenon. thank for your explanation of this question.

答:
Assuming sendData is an 8-bit unsigned char the first version of the code will send the binary bits one by one, starting with the most significant one. It does this by clearing the bits from the highest down at each step before shifting the next one to the lowest position.

```<code>    unsigned char sendData = 0xB0; // 0b11000000

                            // i = 0
    SER = (sendData >> 7);  // SER      = 0x01
    sendData <<= 1;         // sendData = 0x80

                            // i = 1
    SER = (sendData >> 7);  // SER      = 0x01
    sendData <<= 1;         // sendData = 0x00

                            // i = 2...7
    SER = (sendData >> 7);  // SER      = 0x00
    sendData <<= 1;         // sendData = 0x00
</code>```

The second version does no such clearing and just shifts the same bits each time.

```<code>                            // i = 0
    SER = (sendData >> 7);  // SER      = 0x01

                            // i = 1
    SER = (sendData >> 6);  // SER      = 0x03

                            // i = 2
    SER = (sendData >> 5);  // SER      = 0x06
</code>```

[ EDIT ] To address the points made in comments, the first version of the code always has the leftmost 7 bits set to 0 in SER. It's only the rightmost (least significant) bit which can be 0 or 1.

This is because at the i'th step the leftmost i bits of sendData are 0 after i repeats of the left << shift. Then right >> shifting sendData by i-1 discards the rightmost i-1 bits. So in the end the 8-i'th  bit of sendData gets placed into the least significant bit of SER, and all other SER bits are set to 0.

As noted by @ChrisDodd, the second version of the code could be corrected to achieve the same result by replacing SER = (sendData>>(7-i)) with SER = (sendData>>(7-i)) & 1.

Body:
for(i=0; i<8 ;i++)
{
    SRCLK = 0;
    SER = (sendData>>7);
    sendData <<= 1;
    SRCLK = 1;
}

and

for(i=0; i<8 ;i++)
{
    SRCLK = 0;
    SER = (sendData>>(7-i));
    SRCLK = 1;
}

i think there is no difference bettween them. i builded the code and download to my 51MCU. i use SER to send serial data to 74HC595, these codes displayed different phenomenon. thank for your explanation of this question.

Body:
Assuming sendData is an 8-bit unsigned char the first version of the code will send the binary bits one by one, starting with the most significant one. It does this by clearing the bits from the highest down at each step before shifting the next one to the lowest position.

    unsigned char sendData = 0xB0; // 0b11000000

                            // i = 0
    SER = (sendData >> 7);  // SER      = 0x01
    sendData <<= 1;         // sendData = 0x80

                            // i = 1
    SER = (sendData >> 7);  // SER      = 0x01
    sendData <<= 1;         // sendData = 0x00

                            // i = 2...7
    SER = (sendData >> 7);  // SER      = 0x00
    sendData <<= 1;         // sendData = 0x00

The second version does no such clearing and just shifts the same bits each time.

                            // i = 0
    SER = (sendData >> 7);  // SER      = 0x01

                            // i = 1
    SER = (sendData >> 6);  // SER      = 0x03

                            // i = 2
    SER = (sendData >> 5);  // SER      = 0x06

[ EDIT ] To address the points made in comments, the first version of the code always has the leftmost 7 bits set to 0 in SER. It's only the rightmost (least significant) bit which can be 0 or 1.

This is because at the i'th step the leftmost i bits of sendData are 0 after i repeats of the left << shift. Then right >> shifting sendData by i-1 discards the rightmost i-1 bits. So in the end the 8-i'th  bit of sendData gets placed into the least significant bit of SER, and all other SER bits are set to 0.

As noted by @ChrisDodd, the second version of the code could be corrected to achieve the same result by replacing SER = (sendData>>(7-i)) with SER = (sendData>>(7-i)) & 1.


问:
how to matches double quotes in java?
See the code below. My question is why the assertion failed? Thanks!

```<code>@Test
public void test_name() {
    String s = "\"name\":\"alice\"";
    Assertions.assertTrue(s.matches("\"name\":"));
}
</code>```

EDIT AND THE ANSWER

Thanks, @James McLeod. The regex in s.match(regex) is used to match the whole s, but not substring of s.

Title: how to matches double quotes in java?

Body:
See the code below. My question is why the assertion failed? Thanks!

@Test
public void test_name() {
    String s = "\"name\":\"alice\"";
    Assertions.assertTrue(s.matches("\"name\":"));
}

EDIT AND THE ANSWER

Thanks, @James McLeod. The regex in s.match(regex) is used to match the whole s, but not substring of s.

Body: "\"name\":.+" OR "\"name\":.*" would do


问:
Generate an enum class from a list in python
Supppose I have the following enum class:

```<code>from enum import Enum, unique

@unique
class Indication(Enum):
    Fruit1 = 'apple'
    Fruit2 = 'orange'
    Fruit3 = 'banana'
</code>```

Is want to generate this enum class from a python list, i.e.

```<code>Listoffruits = [('Fruit1', 'apple'),  ('Fruit2', 'orange'), ('Fruit3',  'banana')]
</code>```

How can this be done effectively?

答:
Use the Functional API if you want to dynamically define an Enum:

import enum

Listoffruits = [('Fruit1', 'apple'),  ('Fruit2', 'orange'), ('Fruit3',  'banana')]

Indication = enum.Enum('Indication', dict(Listoffruits))
```

<p>You can use string formatting to "generate" the Python code:</p>

<pre class="lang-py prettyprint-override"><code>def generate_enum(enumClass, enumDict):
    """
    Generates python code for an Enum
    """

    enum_template = """
@unique
class {enumClass}(Enum)
{enumBody}
"""

    enumBody = '\n'.join([f"    {name} = '{value}'" for (name,value) in enumDict.items()])

    return enum_template.format(enumClass=enumClass,enumBody=enumBody)

print(generate_enum('Indication',dict(Listoffruits)))

</code>```

The generated code will be:

@unique
class Indication(Enum)
    Fruit1 = 'apple'
    Fruit2 = 'orange'
    Fruit3 = 'banana'
```

Body:
Supppose I have the following enum class:

from enum import Enum, unique

@unique
class Indication(Enum):
    Fruit1 = 'apple'
    Fruit2 = 'orange'
    Fruit3 = 'banana'

Is want to generate this enum class from a python list, i.e.

Listoffruits = [('Fruit1', 'apple'),  ('Fruit2', 'orange'), ('Fruit3',  'banana')]

How can this be done effectively?

Body:
Use the Functional API if you want to dynamically define an Enum:

import enum

Listoffruits = [('Fruit1', 'apple'),  ('Fruit2', 'orange'), ('Fruit3',  'banana')]

Indication = enum.Enum('Indication', dict(Listoffruits))

You can use string formatting to "generate" the Python code:

def generate_enum(enumClass, enumDict):
    """
    Generates python code for an Enum
    """

    enum_template = """
@unique
class {enumClass}(Enum)
{enumBody}
"""

    enumBody = '\n'.join([f"    {name} = '{value}'" for (name,value) in enumDict.items()])

    return enum_template.format(enumClass=enumClass,enumBody=enumBody)

print(generate_enum('Indication',dict(Listoffruits)))

The generated code will be:

@unique
class Indication(Enum)
    Fruit1 = 'apple'
    Fruit2 = 'orange'
    Fruit3 = 'banana'


问:
How to determine how many times '0' to '9' have been used in a specific range instantly
I want to count how many times '0' to '9' have been used in a specific range

e.g. 112 has two '1' and one '2'

Thanks for your advices, I changed my code now.

But it is not efficient as I want.

```<code>num = int(input('n : '))
start_time = time.time()
num_arr = [0] * 10
progress_arr = ['%d' % (num * (i / 100)) for i in range(1, 101)]

for i in range(1, num + 1):
    if str(i) in progress_arr:
        print(str(progress_arr.index(str(i)) + 1) + '%')
    for digit in str(i):
        num_arr[int(digit)] += 1

print('Time : %.2f' % (time.time() - start_time))
print(num_arr)
</code>```

When I input 1000 as n, my program will print this arr instantly

[192, 301, 300, 300, 300, 300, 300, 300, 300, 300]

It means for 1 to 1000,
'0' has been used 192 times and '1' has been used 301 times and ···

But when I input 2,000,000,000 as n, my program will print the result after
11 minutes(Using pypy3, Ryzen 2600).

So I want to change my code as efficient to get the result of a very large number instantly.

And in my previous question, I mentioned the time complexity of O(N), which confused you because of my poor understanding of algorithm and time complexity. So I deleted it.

What I want to know is just the efficient algorithm.

I'm trying to find a specific rule by analyzing the difference in the results of increment, but it's not easy.

答:
Ok, I gave it a go at being even s-m-r-t'er. I took a look at the counts at a bunch of powers of 10:

```<code>At 10 totaldigits=11, counts are: [1, 2, 1, 1, 1, 1, 1, 1, 1, 1]
At 100 totaldigits=192, counts are: [11, 21, 20, 20, 20, 20, 20, 20, 20, 20]
At 1000 totaldigits=2893, counts are: [192, 301, 300, 300, 300, 300, 300, 300, 300, 300]
At 10000 totaldigits=38894, counts are: [2893, 4001, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000]
At 100000 totaldigits=488895, counts are: [38894, 50001, 50000, 50000, 50000, 50000, 50000, 50000, 50000, 50000]
At 1000000 totaldigits=5888896, counts are: [488895, 600001, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000]
At 10000000 totaldigits=68888897, counts are: [5888896, 7000001, 7000000, 7000000, 7000000, 7000000, 7000000, 7000000, 7000000, 7000000]
</code>```

A pattern has started to emerge! After 10^n numbers, the counts for 2,3,...,9 are equal to n * 10^(n-1), and the counts for 1 are 1 more than that, n * 10^(n-1) + 1. The counts for 0 are less than the others, and appear to be equal to the total digits at the previous power of ten! So, we can count the digits in the numbers through 10, and then for every power after that, the counts for 1 thru 9 can be computed directly, and the counts for 0 can be obtained from the previous total counts. i.e.:

```<code>total_digits_in = {}
total_digits_in[10] = 11
highest_power = 9
for cur_power in range(2, highest_power+1):
    counts = [
        total_digits_in[10**(cur_power-1)],     # zero = total counts at previous power of 10
        cur_power * (10**(cur_power - 1)) + 1,  # one = n * 10^(n-1) + 1
        cur_power * (10 ** (cur_power - 1)) ,   # 2 thru 9 = n * 10^(n-1)
        cur_power * (10 ** (cur_power - 1)),
        cur_power * (10 ** (cur_power - 1)),
        cur_power * (10 ** (cur_power - 1)),
        cur_power * (10 ** (cur_power - 1)),
        cur_power * (10 ** (cur_power - 1)),
        cur_power * (10 ** (cur_power - 1)),
        cur_power * (10 ** (cur_power - 1)),
    ]
    total_digits_in[10**cur_power] = sum(counts)
    print(f'Counts for 10^{cur_power}: {counts}')

Counts for 10^2: [11, 21, 20, 20, 20, 20, 20, 20, 20, 20]
Counts for 10^3: [192, 301, 300, 300, 300, 300, 300, 300, 300, 300]
Counts for 10^4: [2893, 4001, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000]
Counts for 10^5: [38894, 50001, 50000, 50000, 50000, 50000, 50000, 50000, 50000, 50000]
Counts for 10^6: [488895, 600001, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000]
Counts for 10^7: [5888896, 7000001, 7000000, 7000000, 7000000, 7000000, 7000000, 7000000, 7000000, 7000000]
Counts for 10^8: [68888897, 80000001, 80000000, 80000000, 80000000, 80000000, 80000000, 80000000, 80000000, 80000000]
Counts for 10^9: [788888898, 900000001, 900000000, 900000000, 900000000, 900000000, 900000000, 900000000, 900000000, 900000000]
</code>```

This gets you the exact counts of each digit if going through the integers from 1 through a power of 10, essentially instantly. I think it will be significantly harder to get the counts for an arbitrary number between powers of 10. I don't think it's impossible, just ... difficult. Anyhow, hope you like this new solution!

Body:
I want to count how many times '0' to '9' have been used in a specific range

e.g. 112 has two '1' and one '2'

Thanks for your advices, I changed my code now.

But it is not efficient as I want.

num = int(input('n : '))
start_time = time.time()
num_arr = [0] * 10
progress_arr = ['%d' % (num * (i / 100)) for i in range(1, 101)]

for i in range(1, num + 1):
    if str(i) in progress_arr:
        print(str(progress_arr.index(str(i)) + 1) + '%')
    for digit in str(i):
        num_arr[int(digit)] += 1

print('Time : %.2f' % (time.time() - start_time))
print(num_arr)

When I input 1000 as n, my program will print this arr instantly

[192, 301, 300, 300, 300, 300, 300, 300, 300, 300]

It means for 1 to 1000,
'0' has been used 192 times and '1' has been used 301 times and ···

But when I input 2,000,000,000 as n, my program will print the result after
11 minutes(Using pypy3, Ryzen 2600).

So I want to change my code as efficient to get the result of a very large number instantly.

And in my previous question, I mentioned the time complexity of O(N), which confused you because of my poor understanding of algorithm and time complexity. So I deleted it.

What I want to know is just the efficient algorithm.

I'm trying to find a specific rule by analyzing the difference in the results of increment, but it's not easy.

Body:
Ok, I gave it a go at being even s-m-r-t'er. I took a look at the counts at a bunch of powers of 10:

At 10 totaldigits=11, counts are: [1, 2, 1, 1, 1, 1, 1, 1, 1, 1]
At 100 totaldigits=192, counts are: [11, 21, 20, 20, 20, 20, 20, 20, 20, 20]
At 1000 totaldigits=2893, counts are: [192, 301, 300, 300, 300, 300, 300, 300, 300, 300]
At 10000 totaldigits=38894, counts are: [2893, 4001, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000]
At 100000 totaldigits=488895, counts are: [38894, 50001, 50000, 50000, 50000, 50000, 50000, 50000, 50000, 50000]
At 1000000 totaldigits=5888896, counts are: [488895, 600001, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000]
At 10000000 totaldigits=68888897, counts are: [5888896, 7000001, 7000000, 7000000, 7000000, 7000000, 7000000, 7000000, 7000000, 7000000]

A pattern has started to emerge! After 10^n numbers, the counts for 2,3,...,9 are equal to n * 10^(n-1), and the counts for 1 are 1 more than that, n * 10^(n-1) + 1. The counts for 0 are less than the others, and appear to be equal to the total digits at the previous power of ten! So, we can count the digits in the numbers through 10, and then for every power after that, the counts for 1 thru 9 can be computed directly, and the counts for 0 can be obtained from the previous total counts. i.e.:

total_digits_in = {}
total_digits_in[10] = 11
highest_power = 9
for cur_power in range(2, highest_power+1):
    counts = [
        total_digits_in[10**(cur_power-1)],     # zero = total counts at previous power of 10
        cur_power * (10**(cur_power - 1)) + 1,  # one = n * 10^(n-1) + 1
        cur_power * (10 ** (cur_power - 1)) ,   # 2 thru 9 = n * 10^(n-1)
        cur_power * (10 ** (cur_power - 1)),
        cur_power * (10 ** (cur_power - 1)),
        cur_power * (10 ** (cur_power - 1)),
        cur_power * (10 ** (cur_power - 1)),
        cur_power * (10 ** (cur_power - 1)),
        cur_power * (10 ** (cur_power - 1)),
        cur_power * (10 ** (cur_power - 1)),
    ]
    total_digits_in[10**cur_power] = sum(counts)
    print(f'Counts for 10^{cur_power}: {counts}')

Counts for 10^2: [11, 21, 20, 20, 20, 20, 20, 20, 20, 20]
Counts for 10^3: [192, 301, 300, 300, 300, 300, 300, 300, 300, 300]
Counts for 10^4: [2893, 4001, 4000, 4000, 4000, 4000, 4000, 4000, 4000, 4000]
Counts for 10^5: [38894, 50001, 50000, 50000, 50000, 50000, 50000, 50000, 50000, 50000]
Counts for 10^6: [488895, 600001, 600000, 600000, 600000, 600000, 600000, 600000, 600000, 600000]
Counts for 10^7: [5888896, 7000001, 7000000, 7000000, 7000000, 7000000, 7000000, 7000000, 7000000, 7000000]
Counts for 10^8: [68888897, 80000001, 80000000, 80000000, 80000000, 80000000, 80000000, 80000000, 80000000, 80000000]
Counts for 10^9: [788888898, 900000001, 900000000, 900000000, 900000000, 900000000, 900000000, 900000000, 900000000, 900000000]

This gets you the exact counts of each digit if going through the integers from 1 through a power of 10, essentially instantly. I think it will be significantly harder to get the counts for an arbitrary number between powers of 10. I don't think it's impossible, just ... difficult. Anyhow, hope you like this new solution!


问:
How to get class object by NSString
We could use [NSObject class] to get class object, but forgot how to get class object by string, something like [OBJ getClassByNSString: @"NSString"]?

Thanks.

答: Class myClass = NSClassFromString(@"ClassName");

Title: How to get class object by NSString


问:
C - Printing null character using %c in nested printf statement
Why both inner printf() functions are working different even the printing value is same for both functions ?
Here is the code -:</p>

```<code>#include<stdio.h>
int main()
{
    char ch = '\0';

    printf("%d",printf("%c", ch)) ;
    // This line will print 1.

    printf("%d",printf("\0")) ;
    // This line will print 0.
   return 0;
}
</code>```

答:
Referring to man page of printf

```<code>man 3 printf
</code>```

printf returns the following

```<code>RETURN VALUE
   Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings).
</code>```

So it does not return the count of null bytes.

In the first printf you are explicitly telling to print 1 character, so the output is 1. In the second printf there is nothing to print or NULL. So the output is 0

Body:
Why both inner printf() functions are working different even the printing value is same for both functions ?
Here is the code -:

#include<stdio.h>
int main()
{
    char ch = '\0';

    printf("%d",printf("%c", ch)) ;
    // This line will print 1.

    printf("%d",printf("\0")) ;
    // This line will print 0.
   return 0;
}

Body:
Referring to man page of printf

man 3 printf

printf returns the following

RETURN VALUE
   Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings).

So it does not return the count of null bytes.

In the first printf you are explicitly telling to print 1 character, so the output is 1. In the second printf there is nothing to print or NULL. So the output is 0


问:
What Is The Output Of This Code, I Didn't Got Any Outputn Because My Computer Is Very Slow
```<code>from decimal import Decimal

a = Decimal()
a = 2

for i in range(1, 64):
    a = a*a
print(a)
</code>```

答:
Well, looking at the question in the image, what you're actually looking to do is sum the values, not just get the largest one.

Since:

2^0 + 2^1 + ... + 2^n = 1 + 2 + ... + 2^n = 2^(n+1) - 1

all the code you really need is:

```<code>print(pow(a,64) - 1)
</code>```

Body:
Well, looking at the question in the image, what you're actually looking to do is sum the values, not just get the largest one.

Since:

2^0 + 2^1 + ... + 2^n = 1 + 2 + ... + 2^n = 2^(n+1) - 1

all the code you really need is:

print(pow(a,64) - 1)


问:
Get the signed-in Office 365 user id
How can I get the signed-in Office 365 user's id in Excel VBA?

Not the the Application.Username or Environ("username")

答:
I'm assuming by "ID" you're referring to the name of the person? The following should work</p>

```<code>Sub getLoggedInUser()

Dim olApp As Object
Dim olNS As Object

Set olApp = CreateObject("Outlook.Application")
Set olNS = olApp.GetNamespace("MAPI")

    With olNS.session.currentuser.AddressEntry.GetExchangeUser
        'some different options for getting the name
        Debug.Print .Name
        Debug.Print .FirstName
        Debug.Print .LastName
        Debug.Print .Alias
    End With

End Sub
</code>```

Title: Get the signed-in Office 365 user id

Body:
I'm assuming by "ID" you're referring to the name of the person? The following should work

Sub getLoggedInUser()

Dim olApp As Object
Dim olNS As Object

Set olApp = CreateObject("Outlook.Application")
Set olNS = olApp.GetNamespace("MAPI")

    With olNS.session.currentuser.AddressEntry.GetExchangeUser
        'some different options for getting the name
        Debug.Print .Name
        Debug.Print .FirstName
        Debug.Print .LastName
        Debug.Print .Alias
    End With

End Sub


问:
How to normalize this into 1NF?
I am trying to breakdown this table into 1NF:

```<code>STUDENT    AGE    SUBJECT
Nancy      15     Math
Nancy      15     Bio
Peter      14     Math
Hal        17     Math
</code>```

I first have a separate table of student and age,

```<code>STUDENT    AGE
Nancy      15
Peter      14
Hal        17
</code>```

I known I should have a separate table for subject as well, but how can I achieve that and makes it relational to the previous table?

答:
Since you are already maintaining the student's metadata in the second table (such as the age), there is no need to also repeat this information in the first table.  Therefore, the first table can simply look like this:

```<code>STUDENT    SUBJECT
Nancy      Math
Nancy      Bio
Peter      Math
Hal        Math
</code>```

In practice, you might not even be using the student and subject names as the primary keys here, but rather some type of general ID.  However, the above suggestion at least sets you on the right track.

Title: How to normalize this into 1NF?

Body:
I am trying to breakdown this table into 1NF:

STUDENT    AGE    SUBJECT
Nancy      15     Math
Nancy      15     Bio
Peter      14     Math
Hal        17     Math

I first have a separate table of student and age,

STUDENT    AGE
Nancy      15
Peter      14
Hal        17

I known I should have a separate table for subject as well, but how can I achieve that and makes it relational to the previous table?

Body:
Since you are already maintaining the student's metadata in the second table (such as the age), there is no need to also repeat this information in the first table.  Therefore, the first table can simply look like this:

STUDENT    SUBJECT
Nancy      Math
Nancy      Bio
Peter      Math
Hal        Math

In practice, you might not even be using the student and subject names as the primary keys here, but rather some type of general ID.  However, the above suggestion at least sets you on the right track.


问:
Crop and extract text from PDF
I have cropped a PDF using the following command.

```<code>gswin32c.exe ^
-o cropped.pdf ^
-sDEVICE=pdfwrite ^
-c "[/CropBox [64 418 348 803] /PAGE pdfmark" ^
-f original.pdf
</code>```

The PDF is getting cropped. I used the following command to extract the text from the cropped PDF.

```<code>gswin32c.exe ^
-q ^
-sFONTPATH=c:/windows/fonts ^
-dNODISPLAY ^
-dSAFER ^
-dDELAYBIND ^
-dWRITESYSTEMDICT ^
-dSIMPLE ^
-f ps2ascii.ps ^
-dFirstPage=1 ^
-dLastPage=1 ^
cropped.pdf ^
-> c:\output.txt ^
-dQUIET
</code>```

The output contains the text of the original PDF and not the cropped PDF.

Can someone help to extract the text only from the cropped PDF.

Thanks
Nazeer

答:
The result you got is exactly what is to be expected.

Cropping of a PDF page does NOT mean: cut off everything around the cropped area and delete it.

Cropping means: do only display what's inside the cropped area (and zoom to it), and hide what's around it.

So when you convert such a page to text, you'll also get the hidden content back.

Title: Crop and extract text from PDF

Body:
I have cropped a PDF using the following command.

gswin32c.exe ^
-o cropped.pdf ^
-sDEVICE=pdfwrite ^
-c "[/CropBox [64 418 348 803] /PAGE pdfmark" ^
-f original.pdf

The PDF is getting cropped. I used the following command to extract the text from the cropped PDF.

gswin32c.exe ^
-q ^
-sFONTPATH=c:/windows/fonts ^
-dNODISPLAY ^
-dSAFER ^
-dDELAYBIND ^
-dWRITESYSTEMDICT ^
-dSIMPLE ^
-f ps2ascii.ps ^
-dFirstPage=1 ^
-dLastPage=1 ^
cropped.pdf ^
-> c:\output.txt ^
-dQUIET

The output contains the text of the original PDF and not the cropped PDF.

Can someone help to extract the text only from the cropped PDF.

Thanks
Nazeer


问:
'Specified cast is not valid.' while populate ComboBoxe
I am trying to fill ComboBox in button click, but however I get the following error:

System.InvalidCastException: 'Specified cast is not valid.'

```<code>    public void FillOrgUnit()
    {
        try
        {
            using (SqlConnection conn = new SqlConnection(@"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True"))
            {
                conn.Open();
                string query = "SELECT DISTINCT OrgUnitID FROM tblZaposleni_AD ORDER BY OrgUnitID ASC";
                SqlCommand cmd = new SqlCommand(query, conn);
                using (SqlDataReader saReader = cmd.ExecuteReader())
                {
                    while (saReader.Read())
                    {
                        string name = saReader.GetInt32(0).ToString();
                        ddlStatus.Items.Add(name);
                    }
                }
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
</code>```

I tried to convert string name to int but this doesn't work. I have no idea where the mistake comes from.

BTW : OrgUnitId in database is type bigint

答:
If you install Dapper, all that code you wrote can probably be reduced to:

```<code>using(conn = new SqlConnection(...))
   ddlStatus.DataSource = conn.Query("SELECT DISTINCT OrgUnitID FROM tblZaposleni_AD ORDER BY OrgUnitID ASC").ToList();
</code>```

(And it wouldn't have thrown this error)

Life is too short to spend it writing endless GetString(1), GetString(2), GetInt(3) ... :)

Dapper's pretty neat- it can even take your queries and turn them into your classes for you so it'll just return you a Person when you "select * from person", it does all the setting of the properties for you. You can take a look at what it does/some example usage without installing it at dapper-tutorial.net (no affiliation)

Body:
I am trying to fill ComboBox in button click, but however I get the following error:

System.InvalidCastException: 'Specified cast is not valid.'

    public void FillOrgUnit()
    {
        try
        {
            using (SqlConnection conn = new SqlConnection(@"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True"))
            {
                conn.Open();
                string query = "SELECT DISTINCT OrgUnitID FROM tblZaposleni_AD ORDER BY OrgUnitID ASC";
                SqlCommand cmd = new SqlCommand(query, conn);
                using (SqlDataReader saReader = cmd.ExecuteReader())
                {
                    while (saReader.Read())
                    {
                        string name = saReader.GetInt32(0).ToString();
                        ddlStatus.Items.Add(name);
                    }
                }
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

I tried to convert string name to int but this doesn't work. I have no idea where the mistake comes from.

BTW : OrgUnitId in database is type bigint

Body:
If you install Dapper, all that code you wrote can probably be reduced to:

using(conn = new SqlConnection(...))
   ddlStatus.DataSource = conn.Query("SELECT DISTINCT OrgUnitID FROM tblZaposleni_AD ORDER BY OrgUnitID ASC").ToList();

(And it wouldn't have thrown this error)

Life is too short to spend it writing endless GetString(1), GetString(2), GetInt(3) ... :)

Dapper's pretty neat- it can even take your queries and turn them into your classes for you so it'll just return you a Person when you "select * from person", it does all the setting of the properties for you. You can take a look at what it does/some example usage without installing it at dapper-tutorial.net (no affiliation)


问:
Wide html responsive html table
My datatable has 30 - 40 columns. I need responsive table solution without horizontal scrollbar, where weighting of each columns is the same. Hiding last columns is OK.

Responsive datatables extension is good, but problem is, one of group data looks different as another. First are in one cell as list and another in common cells.

I think one solution is integration colvis extension with swipe table.

Next is scroll-horizontal, but responsiveness is worse.

Any other ideas?

Thanks.

答:
Maybe Automatic column hiding can help you:

https://datatables.net/extensions/responsive/examples/column-control/auto.html

https://datatables.net/extensions/rowreorder/examples/initialisation/responsive.html

There are samples in documentation. You have to use dataTables.responsive.min.js and responsive.dataTables.min.css

Also you can define column priority

$('#myTable').DataTable( {
    responsive: true,
    columnDefs: [
        { responsivePriority: 1, targets: 0 },
        { responsivePriority: 2, targets: -1 }
    ]
} );
```

<p>or add <code>data-priority</code> attribute html column header <code><th data-priority="1">First name</th></code></p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
    $('#example').DataTable( {

        "columns": [
         { "data": "seq" },
            { "data": "name" },
            { "data": "position" },
            { "data": "office" },
            { "data": "start_date" },
            { "data": "salary" }

        ]
    } );
} );</code>```

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.4/css/responsive.dataTables.min.css">

                Seq.
                Name
                Position
                Office
                Start date
                Salary

                2
                Tiger Nixon
                System Architect
                Edinburgh
                2011/04/25
                $320,800

                22
                Garrett Winters
                Accountant
                Tokyo
                2011/07/25
                $170,750

                6
                Ashton Cox
                Junior Technical Author
                San Francisco
                2009/01/12
                $86,000

                41
                Cedric Kelly
                Senior Javascript Developer
                Edinburgh
                2012/03/29
                $433,060

                55
                Airi Satou
                Accountant
                Tokyo
                2008/11/28
                $162,700

                21
                Brielle Williamson
                Integration Specialist
                New York
                2012/12/02
                $372,000

                46
                Herrod Chandler
                Sales Assistant
                San Francisco
                2012/08/06
                $137,500

                50
                Rhona Davidson
                Integration Specialist
                Tokyo
                2010/10/14
                $327,900

                26
                Colleen Hurst
                Javascript Developer
                San Francisco
                2009/09/15
                $205,500

                18
                Sonya Frost
                Software Engineer
                Edinburgh
                2008/12/13
                $103,600

                13
                Jena Gaines
                Office Manager
                London
                2008/12/19
                $90,560

                23
                Quinn Flynn
                Support Lead
                Edinburgh
                2013/03/03
                $342,000

                14
                Charde Marshall
                Regional Director
                San Francisco
                2008/10/16
                $470,600

                12
                Haley Kennedy
                Senior Marketing Designer
                London
                2012/12/18
                $313,500

                54
                Tatyana Fitzpatrick
                Regional Director
                London
                2010/03/17
                $385,750

                37
                Michael Silva
                Marketing Designer
                London
                2012/11/27
                $198,500

                32
                Paul Byrd
                Chief Financial Officer (CFO)
                New York
                2010/06/09
                $725,000

                Name
                Position
                Office
                Start date
                Salary
                Extn.

```
</div>
</div>
</p>

<p>Another way hiding column you can manage by class control with html column header or javascript. You can tell Responsive what columns should be visible on different devices through the use of class names on the columns. </p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
    $('#example').DataTable( {
        "columns": [
         { "data": "seq" },
            { "data": "name" },
            { "data": "position" },
            { "data": "office" },
            { "data": "start_date" },
            { "data": "salary" }

        ]
    } );
} );</code>```

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.4/css/responsive.dataTables.min.css">

                Seq.
                Name
                Position
                Office
                Start date
                Salary

                2
                Tiger Nixon
                System Architect
                Edinburgh
                2011/04/25
                $320,800

                22
                Garrett Winters
                Accountant
                Tokyo
                2011/07/25
                $170,750

                6
                Ashton Cox
                Junior Technical Author
                San Francisco
                2009/01/12
                $86,000

                41
                Cedric Kelly
                Senior Javascript Developer
                Edinburgh
                2012/03/29
                $433,060

                55
                Airi Satou
                Accountant
                Tokyo
                2008/11/28
                $162,700

                21
                Brielle Williamson
                Integration Specialist
                New York
                2012/12/02
                $372,000

                46
                Herrod Chandler
                Sales Assistant
                San Francisco
                2012/08/06
                $137,500

                50
                Rhona Davidson
                Integration Specialist
                Tokyo
                2010/10/14
                $327,900

                26
                Colleen Hurst
                Javascript Developer
                San Francisco
                2009/09/15
                $205,500

                18
                Sonya Frost
                Software Engineer
                Edinburgh
                2008/12/13
                $103,600

                13
                Jena Gaines
                Office Manager
                London
                2008/12/19
                $90,560

                23
                Quinn Flynn
                Support Lead
                Edinburgh
                2013/03/03
                $342,000

                14
                Charde Marshall
                Regional Director
                San Francisco
                2008/10/16
                $470,600

                12
                Haley Kennedy
                Senior Marketing Designer
                London
                2012/12/18
                $313,500

                54
                Tatyana Fitzpatrick
                Regional Director
                London
                2010/03/17
                $385,750

                37
                Michael Silva
                Marketing Designer
                London
                2012/11/27
                $198,500

                32
                Paul Byrd
                Chief Financial Officer (CFO)
                New York
                2010/06/09
                $725,000

                35
                Gloria Little
                Systems Administrator
                New York
                2009/04/10
                $237,500

                48
                Bradley Greer
                Software Engineer
                London
                2012/10/13
                $132,000

                45
                Dai Rios
                Personnel Lead
                Edinburgh
                2012/09/26
                $217,500

                17
                Jenette Caldwell
                Development Lead
                New York
                2011/09/03
                $345,000

                57
                Yuri Berry
                Chief Marketing Officer (CMO)
                New York
                2009/06/25
                $675,000

                29
                Caesar Vance
                Pre-Sales Support
                New York
                2011/12/12
                $106,450

                56
                Doris Wilder
                Sales Assistant
                Sydney
                2010/09/20
                $85,600

                36
                Angelica Ramos
                Chief Executive Officer (CEO)
                London
                2009/10/09
                $1,200,000

                5
                Gavin Joyce
                Developer
                Edinburgh
                2010/12/22
                $92,575

                51
                Jennifer Chang
                Regional Director
                Singapore
                2010/11/14
                $357,650

                20
                Brenden Wagner
                Software Engineer
                San Francisco
                2011/06/07
                $206,850

                7
                Fiona Green
                Chief Operating Officer (COO)
                San Francisco
                2010/03/11
                $850,000

                1
                Shou Itou
                Regional Marketing
                Tokyo
                2011/08/14
                $163,000

                Name
                Position
                Office
                Start date
                Salary
                Extn.

```

Title: Wide html responsive html table

Body:
Maybe Automatic column hiding can help you:

https://datatables.net/extensions/responsive/examples/column-control/auto.html

https://datatables.net/extensions/rowreorder/examples/initialisation/responsive.html

There are samples in documentation. You have to use dataTables.responsive.min.js and responsive.dataTables.min.css

Also you can define column priority

$('#myTable').DataTable( {
    responsive: true,
    columnDefs: [
        { responsivePriority: 1, targets: 0 },
        { responsivePriority: 2, targets: -1 }
    ]
} );

or add data-priority attribute html column header <th data-priority="1">First name</th>

$(document).ready(function() {
    $('#example').DataTable( {

        "columns": [
         { "data": "seq" },
            { "data": "name" },
            { "data": "position" },
            { "data": "office" },
            { "data": "start_date" },
            { "data": "salary" }

        ]
    } );
} );

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.4/css/responsive.dataTables.min.css">

<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.2.4/js/dataTables.responsive.min.js"></script>

<table id="example" class="display responsive nowrap" width="100%">
        <thead>
            <tr>
                <th data-priority="1">Seq.</th>
                <th data-priority="1">Name</th>
                <th data-priority="3">Position</th>
                <th >Office</th>
                <th >Start date</th>
                <th data-priority="2">Salary</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>2</td>
                <td>Tiger Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
                <td>2011/04/25</td>
                <td>$320,800</td>
            </tr>
            <tr>
                <td>22</td>
                <td>Garrett Winters</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>2011/07/25</td>
                <td>$170,750</td>
            </tr>
            <tr>
                <td>6</td>
                <td>Ashton Cox</td>
                <td>Junior Technical Author</td>
                <td>San Francisco</td>
                <td>2009/01/12</td>
                <td>$86,000</td>
            </tr>
            <tr>
                <td>41</td>
                <td>Cedric Kelly</td>
                <td>Senior Javascript Developer</td>
                <td>Edinburgh</td>
                <td>2012/03/29</td>
                <td>$433,060</td>
            </tr>
            <tr>
                <td>55</td>
                <td>Airi Satou</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>2008/11/28</td>
                <td>$162,700</td>
            </tr>
            <tr>
                <td>21</td>
                <td>Brielle Williamson</td>
                <td>Integration Specialist</td>
                <td>New York</td>
                <td>2012/12/02</td>
                <td>$372,000</td>
            </tr>
            <tr>
                <td>46</td>
                <td>Herrod Chandler</td>
                <td>Sales Assistant</td>
                <td>San Francisco</td>
                <td>2012/08/06</td>
                <td>$137,500</td>
            </tr>
            <tr>
                <td>50</td>
                <td>Rhona Davidson</td>
                <td>Integration Specialist</td>
                <td>Tokyo</td>
                <td>2010/10/14</td>
                <td>$327,900</td>
            </tr>
            <tr>
                <td>26</td>
                <td>Colleen Hurst</td>
                <td>Javascript Developer</td>
                <td>San Francisco</td>
                <td>2009/09/15</td>
                <td>$205,500</td>
            </tr>
            <tr>
                <td>18</td>
                <td>Sonya Frost</td>
                <td>Software Engineer</td>
                <td>Edinburgh</td>
                <td>2008/12/13</td>
                <td>$103,600</td>
            </tr>
            <tr>
                <td>13</td>
                <td>Jena Gaines</td>
                <td>Office Manager</td>
                <td>London</td>
                <td>2008/12/19</td>
                <td>$90,560</td>
            </tr>
            <tr>
                <td>23</td>
                <td>Quinn Flynn</td>
                <td>Support Lead</td>
                <td>Edinburgh</td>
                <td>2013/03/03</td>
                <td>$342,000</td>
            </tr>
            <tr>
                <td>14</td>
                <td>Charde Marshall</td>
                <td>Regional Director</td>
                <td>San Francisco</td>
                <td>2008/10/16</td>
                <td>$470,600</td>
            </tr>
            <tr>
                <td>12</td>
                <td>Haley Kennedy</td>
                <td>Senior Marketing Designer</td>
                <td>London</td>
                <td>2012/12/18</td>
                <td>$313,500</td>
            </tr>
            <tr>
                <td>54</td>
                <td>Tatyana Fitzpatrick</td>
                <td>Regional Director</td>
                <td>London</td>
                <td>2010/03/17</td>
                <td>$385,750</td>
            </tr>
            <tr>
                <td>37</td>
                <td>Michael Silva</td>
                <td>Marketing Designer</td>
                <td>London</td>
                <td>2012/11/27</td>
                <td>$198,500</td>
            </tr>
            <tr>
                <td>32</td>
                <td>Paul Byrd</td>
                <td>Chief Financial Officer (CFO)</td>
                <td>New York</td>
                <td>2010/06/09</td>
                <td>$725,000</td>
            </tr>

        </tbody>
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Start date</th>
                <th>Salary</th>
                <th>Extn.</th>
            </tr>
        </tfoot>
    </table>

Another way hiding column you can manage by class control with html column header or javascript. You can tell Responsive what columns should be visible on different devices through the use of class names on the columns.

$(document).ready(function() {
    $('#example').DataTable( {
        "columns": [
         { "data": "seq" },
            { "data": "name" },
            { "data": "position" },
            { "data": "office" },
            { "data": "start_date" },
            { "data": "salary" }

        ]
    } );
} );

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.4/css/responsive.dataTables.min.css">

<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.2.4/js/dataTables.responsive.min.js"></script>

<table id="example" class="display responsive" width="100%">
        <thead>
            <tr>
                <th class="all">Seq.</th>
                <th class="all">Name</th>
                <th class="min-phone-l">Position</th>
                <th class="min-tablet">Office</th>
                <th class="none">Start date</th>
                <th class="desktop">Salary</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>2</td>
                <td>Tiger Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
                <td>2011/04/25</td>
                <td>$320,800</td>
            </tr>
            <tr>
                <td>22</td>
                <td>Garrett Winters</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>2011/07/25</td>
                <td>$170,750</td>
            </tr>
            <tr>
                <td>6</td>
                <td>Ashton Cox</td>
                <td>Junior Technical Author</td>
                <td>San Francisco</td>
                <td>2009/01/12</td>
                <td>$86,000</td>
            </tr>
            <tr>
                <td>41</td>
                <td>Cedric Kelly</td>
                <td>Senior Javascript Developer</td>
                <td>Edinburgh</td>
                <td>2012/03/29</td>
                <td>$433,060</td>
            </tr>
            <tr>
                <td>55</td>
                <td>Airi Satou</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>2008/11/28</td>
                <td>$162,700</td>
            </tr>
            <tr>
                <td>21</td>
                <td>Brielle Williamson</td>
                <td>Integration Specialist</td>
                <td>New York</td>
                <td>2012/12/02</td>
                <td>$372,000</td>
            </tr>
            <tr>
                <td>46</td>
                <td>Herrod Chandler</td>
                <td>Sales Assistant</td>
                <td>San Francisco</td>
                <td>2012/08/06</td>
                <td>$137,500</td>
            </tr>
            <tr>
                <td>50</td>
                <td>Rhona Davidson</td>
                <td>Integration Specialist</td>
                <td>Tokyo</td>
                <td>2010/10/14</td>
                <td>$327,900</td>
            </tr>
            <tr>
                <td>26</td>
                <td>Colleen Hurst</td>
                <td>Javascript Developer</td>
                <td>San Francisco</td>
                <td>2009/09/15</td>
                <td>$205,500</td>
            </tr>
            <tr>
                <td>18</td>
                <td>Sonya Frost</td>
                <td>Software Engineer</td>
                <td>Edinburgh</td>
                <td>2008/12/13</td>
                <td>$103,600</td>
            </tr>
            <tr>
                <td>13</td>
                <td>Jena Gaines</td>
                <td>Office Manager</td>
                <td>London</td>
                <td>2008/12/19</td>
                <td>$90,560</td>
            </tr>
            <tr>
                <td>23</td>
                <td>Quinn Flynn</td>
                <td>Support Lead</td>
                <td>Edinburgh</td>
                <td>2013/03/03</td>
                <td>$342,000</td>
            </tr>
            <tr>
                <td>14</td>
                <td>Charde Marshall</td>
                <td>Regional Director</td>
                <td>San Francisco</td>
                <td>2008/10/16</td>
                <td>$470,600</td>
            </tr>
            <tr>
                <td>12</td>
                <td>Haley Kennedy</td>
                <td>Senior Marketing Designer</td>
                <td>London</td>
                <td>2012/12/18</td>
                <td>$313,500</td>
            </tr>
            <tr>
                <td>54</td>
                <td>Tatyana Fitzpatrick</td>
                <td>Regional Director</td>
                <td>London</td>
                <td>2010/03/17</td>
                <td>$385,750</td>
            </tr>
            <tr>
                <td>37</td>
                <td>Michael Silva</td>
                <td>Marketing Designer</td>
                <td>London</td>
                <td>2012/11/27</td>
                <td>$198,500</td>
            </tr>
            <tr>
                <td>32</td>
                <td>Paul Byrd</td>
                <td>Chief Financial Officer (CFO)</td>
                <td>New York</td>
                <td>2010/06/09</td>
                <td>$725,000</td>
            </tr>
            <tr>
                <td>35</td>
                <td>Gloria Little</td>
                <td>Systems Administrator</td>
                <td>New York</td>
                <td>2009/04/10</td>
                <td>$237,500</td>
            </tr>
            <tr>
                <td>48</td>
                <td>Bradley Greer</td>
                <td>Software Engineer</td>
                <td>London</td>
                <td>2012/10/13</td>
                <td>$132,000</td>
            </tr>
            <tr>
                <td>45</td>
                <td>Dai Rios</td>
                <td>Personnel Lead</td>
                <td>Edinburgh</td>
                <td>2012/09/26</td>
                <td>$217,500</td>
            </tr>
            <tr>
                <td>17</td>
                <td>Jenette Caldwell</td>
                <td>Development Lead</td>
                <td>New York</td>
                <td>2011/09/03</td>
                <td>$345,000</td>
            </tr>
            <tr>
                <td>57</td>
                <td>Yuri Berry</td>
                <td>Chief Marketing Officer (CMO)</td>
                <td>New York</td>
                <td>2009/06/25</td>
                <td>$675,000</td>
            </tr>
            <tr>
                <td>29</td>
                <td>Caesar Vance</td>
                <td>Pre-Sales Support</td>
                <td>New York</td>
                <td>2011/12/12</td>
                <td>$106,450</td>
            </tr>
            <tr>
                <td>56</td>
                <td>Doris Wilder</td>
                <td>Sales Assistant</td>
                <td>Sydney</td>
                <td>2010/09/20</td>
                <td>$85,600</td>
            </tr>
            <tr>
                <td>36</td>
                <td>Angelica Ramos</td>
                <td>Chief Executive Officer (CEO)</td>
                <td>London</td>
                <td>2009/10/09</td>
                <td>$1,200,000</td>
            </tr>
            <tr>
                <td>5</td>
                <td>Gavin Joyce</td>
                <td>Developer</td>
                <td>Edinburgh</td>
                <td>2010/12/22</td>
                <td>$92,575</td>
            </tr>
            <tr>
                <td>51</td>
                <td>Jennifer Chang</td>
                <td>Regional Director</td>
                <td>Singapore</td>
                <td>2010/11/14</td>
                <td>$357,650</td>
            </tr>
            <tr>
                <td>20</td>
                <td>Brenden Wagner</td>
                <td>Software Engineer</td>
                <td>San Francisco</td>
                <td>2011/06/07</td>
                <td>$206,850</td>
            </tr>
            <tr>
                <td>7</td>
                <td>Fiona Green</td>
                <td>Chief Operating Officer (COO)</td>
                <td>San Francisco</td>
                <td>2010/03/11</td>
                <td>$850,000</td>
            </tr>
            <tr>
                <td>1</td>
                <td>Shou Itou</td>
                <td>Regional Marketing</td>
                <td>Tokyo</td>
                <td>2011/08/14</td>
                <td>$163,000</td>
            </tr>

        </tbody>
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Start date</th>
                <th>Salary</th>
                <th>Extn.</th>
            </tr>
        </tfoot>
    </table>