问:
Python Script POST Body Containing CRLF Characters and Malformed Headers. HTTP Request Smuggling
Lately I have been attempting Portswiggers WebSecAcademy's HTTP request smuggling labs with the additional challenge of writing a python script to complete the challenge for me.

Intended solution from Burp Repeater:

```<code>POST / HTTP/1.1
Host: ac971f2f1fe48ec180f863d5009000ed.web-security-academy.net
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: https://portswigger.net/web-security/request-smuggling/lab-basic-cl-te
Connection: close
Upgrade-Insecure-Requests: 1
Content-Length: 8
Transfer-Encoding: chunked

0

G
</code>```

If you right click and select 'Copy as curl command':

```<code>curl -i -s -k -X $'POST' \
    -H $'Host: ac011f9b1f7e242780ce2272008a009d.web-security-academy.net' -H $'User-Agent: Mozilla/5.0 (X11; Linux i686; rv:68.0) Gecko/20100101 Firefox/68.0' -H $'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' -H $'Accept-Language: en-US,en;q=0.5' -H $'Accept-Encoding: gzip, deflate' -H $'Referer: https://portswigger.net/web-security/request-smuggling/lab-basic-cl-te' -H $'Connection: close' -H $'Upgrade-Insecure-Requests: 1' -H $'Content-Length: 8' \
    --data-binary $'0\x0d\x0a\x0d\x0aG\x0d\x0a\x0d\x0a' \
    $'https://ac011f9b1f7e242780ce2272008a009d.web-security-academy.net/'
</code>```

When attempting this with Curl, it returns 500 internal server error.

I have managed to complete this using the Python requests module:

```<code>def POST_CLTE():
    url = 'https://ac011f9b1f7e242780ce2272008a009d.web-security-academy.net/'
    headers = {'Host':'ac011f9b1f7e242780ce2272008a009d.web-security-academy.net','Connection':'keep-alive',
    'Content-Type':'application/x-www-form-urlencoded','Content-Length':'8', 'Transfer-Encoding':'chunked'}

    data = '0\x0d\x0a\x0d\x0aG\x0d\x0a'

    s = requests.Session()
    r = requests.Request('POST', url, headers=headers, data=data)
    prepared = r.prepare()
    response = s.send(prepared)

    print(response.request.headers)
    print(response.status_code)
    print(response.text)
</code>```

But I don't like that I have to pass the header in as a dict and it complains when I want to include an obfuscated header such as:

```<code>X: X[\n]Transfer-Encoding: chunked
</code>```

I've attempted to reproduce the request using PyCurl:

```<code>#!/usr/bin/python

import pycurl
from StringIO import StringIO

buffer = StringIO()
c = pycurl.Curl()
c.setopt(c.POST, 1)
c.setopt(c.URL, 'https://ac011f9b1f7e242780ce2272008a009d.web-security-academy.net/')
c.setopt(c.POSTFIELDS, '0\x0d\x0a\x0d\x0aG\x0d\x0a')
#c.setopt(pycurl.POSTFIELDSIZE, 8)
c.setopt(c.HTTPHEADER, [
    'User-Agent: Mozilla/5.0 (X11; Linux i686; rv:68.0) Gecko/20100101 Firefox/68.0',
    'Host: ac011f9b1f7e242780ce2272008a009d.web-security-academy.net',
    'Content-Length: 8',
    'Transfer-Encoding: chunked',
    'Content-Type: application/x-www-form-urlencoded'
    ])
#c.setopt(c.CRLF, 1)
c.setopt(c.VERBOSE, 1)
c.setopt(c.HEADER, 1)
c.setopt(c.WRITEDATA, buffer)
c.perform()
c.close()

body = buffer.getvalue()

print(body)
</code>```

I like that I can pass the headers as an array of strings, but I unfortunately still get 500 internal server error:

```<code>*   Trying 18.200.141.238:443...
* TCP_NODELAY set
* Connected to ac561fd21ed819768081009200f2002e.web-security-academy.net (18.200.141.238) port 443 (#0)
* found 387 certificates in /etc/ssl/certs
* ALPN, offering h2
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ECDHE_RSA_AES_128_GCM_SHA256
*        server certificate verification OK
*        server certificate status verification SKIPPED
*        common name: web-security-academy.net (matched)
*        server certificate expiration date OK
*        server certificate activation date OK
*        certificate public key: RSA
*        certificate version: #3
*        subject: CN=web-security-academy.net
*        start date: Fri, 05 Jul 2019 00:00:00 GMT
*        expire date: Wed, 05 Aug 2020 12:00:00 GMT
*        issuer: C=US,O=Amazon,OU=Server CA 1B,CN=Amazon
* ALPN, server did not agree to a protocol
> POST / HTTP/1.1
Host: ac561fd21ed819768081009200f2002e.web-security-academy.net
Accept: */*
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:68.0) Gecko/20100101 Firefox/68.0
Content-Length: 8
Transfer-Encoding: chunked
Content-Type: application/x-www-form-urlencoded

8
* upload completely sent off: 15 out of 8 bytes
* Mark bundle as not supporting multiuse
< HTTP/1.1 500 Internal Server Error
< Content-Type: application/json; charset=utf-8
< Connection: close
< Content-Length: 23
<
* Closing connection 0
HTTP/1.1 500 Internal Server Error
Content-Type: application/json; charset=utf-8
Connection: close
Content-Length: 23

"Internal Server Error"
</code>```

What is the reason for this behaviour? Are there any alternatives I haven't explored? Any suggestions are much appreciated.

答:
Socket module worked perfectly for me. Feel a bit silly for not trying it to start but I learned a great deal.

Code:

```<code>import socket
import ssl

host = 'lab-id.web-security-academy.net'
port = 443
message = "POST / HTTP/1.1\r\n"
hostHeader = "Host: lab-id.web-security-academy.net\r\n"
contentLength = "Content-Length: 8\r\n"
transferEncoding = "Transfer-Encoding: chunked\r\n"
contentType = "Content-Type: application/x-www-urlencoded\r\n"
requestBody = "0\r\n\r\nG\r\n"

finalMessage = message + hostHeader + contentLength + transferEncoding + contentType + "\r\n" + requestBody

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sslWrappedSock = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_TLS)

sslWrappedSock.connect((host, port))
sslWrappedSock.sendall(finalMessage)

print(sslWrappedSock.recv(1024))

sslWrappedSock.close()
</code>```

Body:
Lately I have been attempting Portswiggers WebSecAcademy's HTTP request smuggling labs with the additional challenge of writing a python script to complete the challenge for me.

Intended solution from Burp Repeater:

POST / HTTP/1.1
Host: ac971f2f1fe48ec180f863d5009000ed.web-security-academy.net
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: https://portswigger.net/web-security/request-smuggling/lab-basic-cl-te
Connection: close
Upgrade-Insecure-Requests: 1
Content-Length: 8
Transfer-Encoding: chunked

0

G

If you right click and select 'Copy as curl command':

curl -i -s -k -X $'POST' \
    -H $'Host: ac011f9b1f7e242780ce2272008a009d.web-security-academy.net' -H $'User-Agent: Mozilla/5.0 (X11; Linux i686; rv:68.0) Gecko/20100101 Firefox/68.0' -H $'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' -H $'Accept-Language: en-US,en;q=0.5' -H $'Accept-Encoding: gzip, deflate' -H $'Referer: https://portswigger.net/web-security/request-smuggling/lab-basic-cl-te' -H $'Connection: close' -H $'Upgrade-Insecure-Requests: 1' -H $'Content-Length: 8' \
    --data-binary $'0\x0d\x0a\x0d\x0aG\x0d\x0a\x0d\x0a' \
    $'https://ac011f9b1f7e242780ce2272008a009d.web-security-academy.net/'

When attempting this with Curl, it returns 500 internal server error.

I have managed to complete this using the Python requests module:

def POST_CLTE():
    url = 'https://ac011f9b1f7e242780ce2272008a009d.web-security-academy.net/'
    headers = {'Host':'ac011f9b1f7e242780ce2272008a009d.web-security-academy.net','Connection':'keep-alive',
    'Content-Type':'application/x-www-form-urlencoded','Content-Length':'8', 'Transfer-Encoding':'chunked'}

    data = '0\x0d\x0a\x0d\x0aG\x0d\x0a'

    s = requests.Session()
    r = requests.Request('POST', url, headers=headers, data=data)
    prepared = r.prepare()
    response = s.send(prepared)

    print(response.request.headers)
    print(response.status_code)
    print(response.text)

But I don't like that I have to pass the header in as a dict and it complains when I want to include an obfuscated header such as:

X: X[\n]Transfer-Encoding: chunked

I've attempted to reproduce the request using PyCurl:

#!/usr/bin/python

import pycurl
from StringIO import StringIO

buffer = StringIO()
c = pycurl.Curl()
c.setopt(c.POST, 1)
c.setopt(c.URL, 'https://ac011f9b1f7e242780ce2272008a009d.web-security-academy.net/')
c.setopt(c.POSTFIELDS, '0\x0d\x0a\x0d\x0aG\x0d\x0a')
#c.setopt(pycurl.POSTFIELDSIZE, 8)
c.setopt(c.HTTPHEADER, [
    'User-Agent: Mozilla/5.0 (X11; Linux i686; rv:68.0) Gecko/20100101 Firefox/68.0',
    'Host: ac011f9b1f7e242780ce2272008a009d.web-security-academy.net',
    'Content-Length: 8',
    'Transfer-Encoding: chunked',
    'Content-Type: application/x-www-form-urlencoded'
    ])
#c.setopt(c.CRLF, 1)
c.setopt(c.VERBOSE, 1)
c.setopt(c.HEADER, 1)
c.setopt(c.WRITEDATA, buffer)
c.perform()
c.close()

body = buffer.getvalue()

print(body)

I like that I can pass the headers as an array of strings, but I unfortunately still get 500 internal server error:

*   Trying 18.200.141.238:443...
* TCP_NODELAY set
* Connected to ac561fd21ed819768081009200f2002e.web-security-academy.net (18.200.141.238) port 443 (#0)
* found 387 certificates in /etc/ssl/certs
* ALPN, offering h2
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ECDHE_RSA_AES_128_GCM_SHA256
*        server certificate verification OK
*        server certificate status verification SKIPPED
*        common name: web-security-academy.net (matched)
*        server certificate expiration date OK
*        server certificate activation date OK
*        certificate public key: RSA
*        certificate version: #3
*        subject: CN=web-security-academy.net
*        start date: Fri, 05 Jul 2019 00:00:00 GMT
*        expire date: Wed, 05 Aug 2020 12:00:00 GMT
*        issuer: C=US,O=Amazon,OU=Server CA 1B,CN=Amazon
* ALPN, server did not agree to a protocol
> POST / HTTP/1.1
Host: ac561fd21ed819768081009200f2002e.web-security-academy.net
Accept: */*
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:68.0) Gecko/20100101 Firefox/68.0
Content-Length: 8
Transfer-Encoding: chunked
Content-Type: application/x-www-form-urlencoded

8
* upload completely sent off: 15 out of 8 bytes
* Mark bundle as not supporting multiuse
< HTTP/1.1 500 Internal Server Error
< Content-Type: application/json; charset=utf-8
< Connection: close
< Content-Length: 23
<
* Closing connection 0
HTTP/1.1 500 Internal Server Error
Content-Type: application/json; charset=utf-8
Connection: close
Content-Length: 23

"Internal Server Error"

What is the reason for this behaviour? Are there any alternatives I haven't explored? Any suggestions are much appreciated.

Body:
Socket module worked perfectly for me. Feel a bit silly for not trying it to start but I learned a great deal.

Code:

import socket
import ssl

host = 'lab-id.web-security-academy.net'
port = 443
message = "POST / HTTP/1.1\r\n"
hostHeader = "Host: lab-id.web-security-academy.net\r\n"
contentLength = "Content-Length: 8\r\n"
transferEncoding = "Transfer-Encoding: chunked\r\n"
contentType = "Content-Type: application/x-www-urlencoded\r\n"
requestBody = "0\r\n\r\nG\r\n"

finalMessage = message + hostHeader + contentLength + transferEncoding + contentType + "\r\n" + requestBody

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sslWrappedSock = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_TLS)

sslWrappedSock.connect((host, port))
sslWrappedSock.sendall(finalMessage)

print(sslWrappedSock.recv(1024))

sslWrappedSock.close()


来源: stackexchange

问:
How to fire NSTimer when computer is asleep or user is logged out
I want to fire the timer after 6 hours. But since my computer is in sleep mode, the timer is not fired after 6 hours. It is being fired 2 minutes after I log in the computer after 6+ hours. Is it possible to fire the timer even if the user is in logout or system sleep mode?</p>

答:
This is a simple way of doing it. Create an NSDate for the upcoming event and set up a timer for comparing current time to that timestamp. This example runs once every second.

- (void) waitFor:(CGFloat)seconds {
    // Set the time to wait
    NSTimeInterval timeInSeconds = seconds;
    __block NSDate *wait = [[NSDate date] dateByAddingTimeInterval:timeInSeconds];

    [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        NSDate *time = [NSDate date];
        if ([time timeIntervalSinceDate:wait] > 0) {
            // Do something
        }
    }];
}
```

This way, the process will run immediately after waking up your computer.

EDIT: Older threads (such as NSTimer continue during sleep mode) suggest that you would need to reschedule the NSTimer after wake, but it doesn't seem to be the case anymore.

ContentLicense: CC BY-SA 4.0

Body:
This is a simple way of doing it. Create an NSDate for the upcoming event and set up a timer for comparing current time to that timestamp. This example runs once every second.

- (void) waitFor:(CGFloat)seconds {
    // Set the time to wait
    NSTimeInterval timeInSeconds = seconds;
    __block NSDate *wait = [[NSDate date] dateByAddingTimeInterval:timeInSeconds];

    [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        NSDate *time = [NSDate date];
        if ([time timeIntervalSinceDate:wait] > 0) {
            // Do something
        }
    }];
}

This way, the process will run immediately after waking up your computer.

EDIT: Older threads (such as NSTimer continue during sleep mode) suggest that you would need to reschedule the NSTimer after wake, but it doesn't seem to be the case anymore.


问:
UserControl Storyboard objects moving out of UserControl
I have a UserControl that have a storyboard that moves a control (within my UserControl) out of the usercontrol (using a TranslateX RenderTransform).

When I move the object out of the control it shows on the parent Page (that hosts my UserControl).  Is there a way to just hide it when it reaches the boundaries of my UserControl?

答:
What I finally did :

Use a Canvas (instead of a Grid) as my LayoutRoot of my UserControl

Added a Canvas.Clip that matches the size of my UserControl

On the SizeChanged of my UserControl I resize my Clip to fit the new size.

I'd like to post the XAML here but somehow the CodeSample does not work :/  Sorry

ContentLicense: CC BY-SA 3.0


问:
GIBBON::must set an api_key prior to making a call - rails
I used a tutorial to set up my app with mailchimp so that it sends a new subscriber to a mailchimp list. Everything is working just fine if you go through the flow. But when I ran Rspec Half of my test suite is red with this error Gibbon::GibbonError:You must set an api_key prior to making a call. I tried setting my api key where it says but it didn't work? I'll post some code for clarity.

Gibbon.rb:

```<code>Gibbon::API.api_key = ENV["MAILCHIMP_API_KEY"]
Gibbon::API.timeout = 15
Gibbon::API.throws_exceptions = true
</code>```

JOB

```<code>     class SubscribeUserToMailingListJob < ActiveJob::Base
  queue_as :default

  def perform(subscriber)
    gb = Gibbon::API.new(Figaro.env.mailchimp_api_key)
    gb.lists.subscribe({:id => ENV["MAILCHIMP_LIST_ID"], :email => {:email => subscriber.email}, :merge_vars => {:FNAME => subscriber.first_name, :LNAME => subscriber.last_name}, :double_optin => false})
  end
end
</code>```

MODEL:

```<code> def subscribe_user_to_mailing_list
   SubscribeUserToMailingListJob.perform_later(self)
 end
</code>```

ERROR

```<code> Create a subscriber Subscriber can sign in
  Failure/Error: gb.lists.subscribe({:id => ENV["MAILCHIMP_LIST_ID"],   :email => {:email => subscriber.email}, :merge_vars => {:FNAME =>   subscriber.first_name, :LNAME => subscriber.last_name}, :double_optin =>   false})

Gibbon::GibbonError:
You must set an api_key prior to making a call
</code>```

I'm lost on this one. Any help would be great! thank you.

答:
I think you should require the gem dotenv like this in your model</p>

```<code>class SubscribeUserToMailingListJob < ActiveJob::Base
  queue_as :default

  require 'dotenv'
  Dotenv.load

  def perform(subscriber)
    gb = Gibbon::API.new(Figaro.env.mailchimp_api_key)
    gb.lists.subscribe({:id => ENV["MAILCHIMP_LIST_ID"], :email => {:email => subscriber.email}, :merge_vars => {:FNAME => subscriber.first_name, :LNAME => subscriber.last_name}, :double_optin => false})
  end
end
</code>```

Body:
I used a tutorial to set up my app with mailchimp so that it sends a new subscriber to a mailchimp list. Everything is working just fine if you go through the flow. But when I ran Rspec Half of my test suite is red with this error Gibbon::GibbonError:You must set an api_key prior to making a call. I tried setting my api key where it says but it didn't work? I'll post some code for clarity.

Gibbon.rb:

Gibbon::API.api_key = ENV["MAILCHIMP_API_KEY"]
Gibbon::API.timeout = 15
Gibbon::API.throws_exceptions = true

JOB

     class SubscribeUserToMailingListJob < ActiveJob::Base
  queue_as :default

  def perform(subscriber)
    gb = Gibbon::API.new(Figaro.env.mailchimp_api_key)
    gb.lists.subscribe({:id => ENV["MAILCHIMP_LIST_ID"], :email => {:email => subscriber.email}, :merge_vars => {:FNAME => subscriber.first_name, :LNAME => subscriber.last_name}, :double_optin => false})
  end
end

MODEL:

 def subscribe_user_to_mailing_list
   SubscribeUserToMailingListJob.perform_later(self)
 end

ERROR

 Create a subscriber Subscriber can sign in
  Failure/Error: gb.lists.subscribe({:id => ENV["MAILCHIMP_LIST_ID"],   :email => {:email => subscriber.email}, :merge_vars => {:FNAME =>   subscriber.first_name, :LNAME => subscriber.last_name}, :double_optin =>   false})

Gibbon::GibbonError:
You must set an api_key prior to making a call

I'm lost on this one. Any help would be great! thank you.

Body:
I think you should require the gem dotenv like this in your model

class SubscribeUserToMailingListJob < ActiveJob::Base
  queue_as :default

  require 'dotenv'
  Dotenv.load

  def perform(subscriber)
    gb = Gibbon::API.new(Figaro.env.mailchimp_api_key)
    gb.lists.subscribe({:id => ENV["MAILCHIMP_LIST_ID"], :email => {:email => subscriber.email}, :merge_vars => {:FNAME => subscriber.first_name, :LNAME => subscriber.last_name}, :double_optin => false})
  end
end


问:
Is using inline-block for table with dynamic columns feasible?
Ive been toying with a pure-CSS way to create a table without needing to specify the number of columns.  A table where, when the browser is resized the number of rows and columns adjust accordingly.  This code works for the most part:

```<code><html>
<head>
<style>
.kw1 {background-color:#F00; color:#FFF; border-radius:5px; padding:3px;}
.kw2 {background-color:#0F0; color:#000; border-radius:5px; padding:3px;}
.kw3 {background-color:#DDD; color:#000; border-radius:5px; padding:3px;}
.kw4 {background-color:#000; color:#FFF; border-radius:5px; padding:3px;}
.kw5 {background-color:#00F; color:#FFF; border-radius:5px; padding:3px;}
.out {display:inline-block; border:solid 1px #999; width:245px; height:300px; }
img  {width:240px;}    /* image height will vary */
font {font-size:8pt;}
</style>
</head>

<body>
<div style="border:solid 3px #000;" >
<span class="out">
    <a href="some-location"><img src="some-image"></a><br/>
    <font class="kw1">keyword 1</font>
    <font class="kw2">keyword 2</font>
    <font class="kw3">keyword 3</font>
    </span>
<span class="out">
    <a href="some-location"><img src="some-image"></a><br/>
    <font class="kw4">keyword 4</font>
    </span>
<span class="out">
    <a href="some-location"><img src="some-image"></a><br/>
    <font class="kw3">keyword 3</font>
    </span>
<span class="out">
    <a href="some-location"><img src="some-image"></a><br/>
    <font class=""></font>
    </span>
<span class="out">
    <a href="some-location"><img src="some-image"></a><br/>
    <font class="kw5">keyword 5</font>
    <font class="kw3">keyword 3</font>
    </span>
</div>
</body>
</code>```

smaller browser window -- larger browser window

The problem is the staggered alignment of the "cells"; especially noticeable when real images with varying heights are thrown in.  I thought that specifying an exact height would correct the problem, it has not.

I tried toying with display:grid but unless I specified what row and column, items would overflow.

Im open to other pure-CSS ideas, but would love to NOT have to specify columns.  Future plans will be inserting new items in between existing ones, I dont want to be adjusting rows and columns all the time.

答:
```<code><html>
<head>
<style>
.kw1 {background-color:#F00; color:#FFF; border-radius:5px; padding:3px;}
.kw2 {background-color:#0F0; color:#000; border-radius:5px; padding:3px;}
.kw3 {background-color:#DDD; color:#000; border-radius:5px; padding:3px;}
.kw4 {background-color:#000; color:#FFF; border-radius:5px; padding:3px;}
.kw5 {background-color:#00F; color:#FFF; border-radius:5px; padding:3px;}
.out {
  display:inline-block; border:solid 1px #999; width:245px;height:400px; }
img  {
  width:240px;
  height:300px;
  }    /* image height will vary */
font {font-size:8pt;}
</style>
</head>

<body>
<div style="border:solid 3px #000;" >
<span class="out">
    <a href="some-location"><img src="https://source.unsplash.com/WLUHO9A_xik/300x400"></a><br/>
    <font class="kw1">keyword 1</font>
    <font class="kw2">keyword 2</font>
    <font class="kw3">keyword 3</font>
    </span>
<span class="out">
    <a href="some-location"><img src="https://source.unsplash.com/WLUHO9A_xik"></a><br/>
    <font class="kw4">keyword 4</font>
    </span>
<span class="out">
    <a href="some-location"><img src="https://source.unsplash.com/WLUHO9A_xik/500x600"></a><br/>
    <font class="kw3">keyword 3</font>
    </span>
<span class="out">
    <a href="some-location"><img src="https://source.unsplash.com/WLUHO9A_xik"></a><br/>
    <font class="kw3">keyword 3</font>
    </span>
<span class="out">
    <a href="some-location"><img src="https://source.unsplash.com/WLUHO9A_xik"></a><br/>
    <font class="kw5">keyword 5</font>
    <font class="kw3">keyword 3</font>
    </span>
</div>
</body>
</html>
</code>```

You need to define the height of the image otherwise it will cause problems in most cases.
here I have used images of different sizes but they fit in the specific width and height because we have defined it, if you don't give specific height and width then it will automatically take the width and height as per their needs and that will cause problems in alignment.

Body:
Ive been toying with a pure-CSS way to create a table without needing to specify the number of columns.  A table where, when the browser is resized the number of rows and columns adjust accordingly.  This code works for the most part:

    keyword 1
    keyword 2
    keyword 3

    keyword 4

    keyword 3

    keyword 5
    keyword 3

smaller browser window -- larger browser window

The problem is the staggered alignment of the "cells"; especially noticeable when real images with varying heights are thrown in.  I thought that specifying an exact height would correct the problem, it has not.

I tried toying with display:grid but unless I specified what row and column, items would overflow.

Im open to other pure-CSS ideas, but would love to NOT have to specify columns.  Future plans will be inserting new items in between existing ones, I dont want to be adjusting rows and columns all the time.

Body:
<html>
<head>
<style>
.kw1 {background-color:#F00; color:#FFF; border-radius:5px; padding:3px;}
.kw2 {background-color:#0F0; color:#000; border-radius:5px; padding:3px;}
.kw3 {background-color:#DDD; color:#000; border-radius:5px; padding:3px;}
.kw4 {background-color:#000; color:#FFF; border-radius:5px; padding:3px;}
.kw5 {background-color:#00F; color:#FFF; border-radius:5px; padding:3px;}
.out {
  display:inline-block; border:solid 1px #999; width:245px;height:400px; }
img  {
  width:240px;
  height:300px;
  }    /* image height will vary */
font {font-size:8pt;}
</style>
</head>

<body>
<div style="border:solid 3px #000;" >
<span class="out">
    <a href="some-location"><img src="https://source.unsplash.com/WLUHO9A_xik/300x400"></a><br/>
    <font class="kw1">keyword 1</font>
    <font class="kw2">keyword 2</font>
    <font class="kw3">keyword 3</font>
    </span>
<span class="out">
    <a href="some-location"><img src="https://source.unsplash.com/WLUHO9A_xik"></a><br/>
    <font class="kw4">keyword 4</font>
    </span>
<span class="out">
    <a href="some-location"><img src="https://source.unsplash.com/WLUHO9A_xik/500x600"></a><br/>
    <font class="kw3">keyword 3</font>
    </span>
<span class="out">
    <a href="some-location"><img src="https://source.unsplash.com/WLUHO9A_xik"></a><br/>
    <font class="kw3">keyword 3</font>
    </span>
<span class="out">
    <a href="some-location"><img src="https://source.unsplash.com/WLUHO9A_xik"></a><br/>
    <font class="kw5">keyword 5</font>
    <font class="kw3">keyword 3</font>
    </span>
</div>
</body>
</html>

You need to define the height of the image otherwise it will cause problems in most cases.
here I have used images of different sizes but they fit in the specific width and height because we have defined it, if you don't give specific height and width then it will automatically take the width and height as per their needs and that will cause problems in alignment.


问:
Postgresql: cannot create tablespace due to permissions
I know there has been a dozen times a similar question, but I could not find an answer that worked for me.

I have a Debian 9 machine, fresh from install on which I have installed a Postgresql 9.6 server.
I am trying to create a new tablespace but it fails. The command :

```<code>CREATE TABLESPACE newTableSPace LOCATION '/DATA/PostgreSQL/';
</code>```

Returns the following error :

```<code>ERROR: could not set permissions on directory "/DATA/PostgreSQL": Permission denied
SQL state: 42501
</code>```

So, after a few basis searches, I have already checked the following points :

The directory /DATA/PostgreSQL exists

Its owner/group is postgres:postgres

The rights on the directory are 770

SELinux is apparently not installed (in Synaptic, libselinux1 is installed, but all selinux commands that I have tried returned me "command not found". Examples : selinuxenabled, setenforce 0).

I am running out of ideas.

Anybody has a suggestion ?

答:
Hey I just found a possible solution, the thing is that you´ll have to give everyone access to the directory you to write in.

Right click in the directory ".../targetDirectory".

Properties> Security> In Group /usernames click on "edit"

Add another group or username, type "Everyone" and click "OK"

If you need to add more permisson to this group you check the permissions and press Ok.

You could see it in this video: https://www.youtube.com/watch?v=FQzBgEFkdes

This worked for me creating tablespaces and copy files from one directory to another one.

Hope this helps.

Body:
I know there has been a dozen times a similar question, but I could not find an answer that worked for me.

I have a Debian 9 machine, fresh from install on which I have installed a Postgresql 9.6 server.
I am trying to create a new tablespace but it fails. The command :

CREATE TABLESPACE newTableSPace LOCATION '/DATA/PostgreSQL/';

Returns the following error :

ERROR: could not set permissions on directory "/DATA/PostgreSQL": Permission denied
SQL state: 42501

So, after a few basis searches, I have already checked the following points :

The directory /DATA/PostgreSQL exists

Its owner/group is postgres:postgres

The rights on the directory are 770

SELinux is apparently not installed (in Synaptic, libselinux1 is installed, but all selinux commands that I have tried returned me "command not found". Examples : selinuxenabled, setenforce 0).

I am running out of ideas.

Anybody has a suggestion ?


问:
How to resend confirmation code in Cognito's sign-up process
I'm having issues with resending the confirmation code for cases where for some reason the confirmation code was not delivered to the users. This is what I have:

First, I have a sign-up step:

```<code>const cognito = new AWS.CognitoIdentityServiceProvider({region});
const params = {
    ClientId,
    Username,
    Password,
};
const result = await cognito.signUp(params).promise();
</code>```

This step (in case of success) should send an email to the user's email address (which is also their username) with their confirmation code. Now let's assume for some reason that email is not sent (the reason itself is not important). I would like to provide a chance to the user to ask for a new email to be sent. These are what I've been testing for this purpose so far:

First, I've tested the resendConfirmationCode method:

```<code>const cognito = new AWS.CognitoIdentityServiceProvider({region});
const params = {
    ClientId,
    Username,
};
const result = await cognito.resendConfirmationCode(params).promise();
</code>```

Executing this code throws this error message:

```<code>UnhandledPromiseRejectionWarning: NotAuthorizedException: Cannot resend codes. Auto verification not turned on.
</code>```

Then, I tested this approach (because of the answer given in this post):

```<code>const cognito = new AWS.CognitoIdentityServiceProvider({region});
const params = {
  UserPoolId,
  Username,
  DesiredDeliveryMediums: ["EMAIL"],
  ForceAliasCreation: false,
  MessageAction: "RESEND",
}
const result = await cognito.adminCreateUser(params).promise();
</code>```

This time, I'm getting this error:

```<code>UnhandledPromiseRejectionWarning: UnsupportedUserStateException: Resend not possible. ********-****-****-****-********** status is not FORCE_CHANGE_PASSWORD
</code>```

The retracted part is the user's sub.

So, does anyone know how I can resend the confirmation code for a user that is not confirmed yet?

答:
For anyone else who might be facing this issue, this was because the User Pool's setting was not to sent the verification code in the first place. Here's how to enable sending the verification code on User Pool:

Go to Coginto and the User Pool

Go to the page "MFA and verifications"

In the section "Which attributes do you want to verify?" select one of the items (for me it was "Email")

But the actual issue for me was that this option was initially set properly earlier. But it was reset to "No verification" when I executed this command:

```<code>aws cognito-idp update-user-pool \
    --region us-east-1 \
    --user-pool-id us-east-1_********* \
    --lambda-config CustomMessage=arn:aws:lambda:us-east-1:************:function:composeEmail
</code>```

This command is supposed to introduce a lambda function to compose the email for verification code. But for some reason, it will reset the other setting as well and I have no idea why.

In any case, once you have that setting set properly, my first solution will work:

```<code>const cognito = new AWS.CognitoIdentityServiceProvider({region});
const params = {
    ClientId,
    Username,
};
const result = await cognito.resendConfirmationCode(params).promise();
</code>```

After a chat with AWS support, you can specify verification attribute like this:

```
aws cognito-idp update-user-pool \
    --region us-east-1 \
    --user-pool-id us-east-1_********* \
    --lambda-config CustomMessage=arn:aws:lambda:us-east-1:************:function:composeEmail
    <b>--auto-verified-attributes email</b>
```

Body:
I'm having issues with resending the confirmation code for cases where for some reason the confirmation code was not delivered to the users. This is what I have:

First, I have a sign-up step:

const cognito = new AWS.CognitoIdentityServiceProvider({region});
const params = {
    ClientId,
    Username,
    Password,
};
const result = await cognito.signUp(params).promise();

This step (in case of success) should send an email to the user's email address (which is also their username) with their confirmation code. Now let's assume for some reason that email is not sent (the reason itself is not important). I would like to provide a chance to the user to ask for a new email to be sent. These are what I've been testing for this purpose so far:

First, I've tested the resendConfirmationCode method:

const cognito = new AWS.CognitoIdentityServiceProvider({region});
const params = {
    ClientId,
    Username,
};
const result = await cognito.resendConfirmationCode(params).promise();

Executing this code throws this error message:

UnhandledPromiseRejectionWarning: NotAuthorizedException: Cannot resend codes. Auto verification not turned on.

Then, I tested this approach (because of the answer given in this post):

const cognito = new AWS.CognitoIdentityServiceProvider({region});
const params = {
  UserPoolId,
  Username,
  DesiredDeliveryMediums: ["EMAIL"],
  ForceAliasCreation: false,
  MessageAction: "RESEND",
}
const result = await cognito.adminCreateUser(params).promise();

This time, I'm getting this error:

UnhandledPromiseRejectionWarning: UnsupportedUserStateException: Resend not possible. ********-****-****-****-********** status is not FORCE_CHANGE_PASSWORD

The retracted part is the user's sub.

So, does anyone know how I can resend the confirmation code for a user that is not confirmed yet?

Body:
For anyone else who might be facing this issue, this was because the User Pool's setting was not to sent the verification code in the first place. Here's how to enable sending the verification code on User Pool:

Go to Coginto and the User Pool

Go to the page "MFA and verifications"

In the section "Which attributes do you want to verify?" select one of the items (for me it was "Email")

But the actual issue for me was that this option was initially set properly earlier. But it was reset to "No verification" when I executed this command:

aws cognito-idp update-user-pool \
    --region us-east-1 \
    --user-pool-id us-east-1_********* \
    --lambda-config CustomMessage=arn:aws:lambda:us-east-1:************:function:composeEmail

This command is supposed to introduce a lambda function to compose the email for verification code. But for some reason, it will reset the other setting as well and I have no idea why.

In any case, once you have that setting set properly, my first solution will work:

const cognito = new AWS.CognitoIdentityServiceProvider({region});
const params = {
    ClientId,
    Username,
};
const result = await cognito.resendConfirmationCode(params).promise();

After a chat with AWS support, you can specify verification attribute like this:

aws cognito-idp update-user-pool \
    --region us-east-1 \
    --user-pool-id us-east-1_********* \
    --lambda-config CustomMessage=arn:aws:lambda:us-east-1:************:function:composeEmail
    --auto-verified-attributes email


问:
Java Char on actionscript
I have java class which has a variable of type "char" now I have to conver that class on AS3 side . does any one know whats the java char equivalent on actionsctipt (keeping in mind char accepty only one character )</p>

答:
This may not be what you want, but I would still use String.  I have had this same situation in the past, and I found that using String still provided everything I needed.  You could create your own special object with a member String and then control access through getters and setters to make sure that only a single char is assigned.

Technically you could use int (and I have in the past) to store a single char or bit array.  There are no 'true' primitives that you want to use for a char however.

Title: Java Char on actionscript


问:
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
I am studying spring boot and spring jpa .
I was able to successfully read and write into the database, but the problem occurs while updating the data.

```<code>There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
</code>```

I am trying to update data of table : Person ( Id, Name , Age) using a html form. It accepts the data, and using spring jpa  I am trying to update it in MySQL database.

I am getting the following at console when trying to update the data, after submitting the form

```<code>> WARN 5176 --- [nio-8080-exec-1]
> .w.s.m.s.DefaultHandlerExceptionResolver : Resolved
> [org.springframework.web.HttpRequestMethodNotSupportedException:
> Request method 'GET' not supported]
</code>```

My code is here :
updateperson form :

```<code> <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <h1>Enter new details</h1>
    <form action="updatePerson" method="post">
        Id   : <input type="number" name="id"><br>
        Name :<input type = "text" name = "name"><br>
        Age : <input type = "number" name = "age"><br>
        <input type="submit">
    </form>
    </body>
    </html>
</code>```

PersonRepository.java

```<code>package com.example.demo.repository;

import com.example.demo.model.Person;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface PersonRepository extends CrudRepository<Person , Integer> {
    List<Person> findByName(String name);
    List<Person> findByAge(int age);
    List<Person> findAll();
}
</code>```

PersonController.java

```<code>    package com.example.demo.controller;

import com.example.demo.model.Person;
import com.example.demo.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class PersonController {
    @Autowired
    PersonRepository personRepository;

    @GetMapping("update")
    public String updatePerson(){
        System.out.println("update to updateperson html");
        return "updateperson";
    }
    @PutMapping("/updatePerson")
    public String updatePerson(Person person){
        System.out.println("UPDATING TO" + person.getAge()+" : "+person.getName() + " : "+person.getPid());
        personRepository.save(person);
        return "updateperson";
    }

}
</code>```

Person.java

```<code>package com.example.demo.model;

import org.springframework.stereotype.Component;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Person {
    @Id
    @GeneratedValue
    int pid;

    String name;
    int age;

     public Person() {
    }

    public Person(int pid, String name, int age) {
        this.pid = pid;
        this.name = name;
        this.age = age;
    }

//getter and setters
}
</code>```

The URL to which I'm sending the request:

```<code>localhost:8080/updatePerson?id=4&name=personame&age=34
</code>```

答:
If you check the URL: localhost:8080/updatePerson?id=4&name=personame&age=34, the method you are trying to access (updatePerson) is a PUT, so you should send a PUT instead of a GET.
You can see the method type in the annotation:

```<code>@PutMapping("/updatePerson")
</code>```

Depending on how you are doing the request there should be someplace to set the method you are using. Also, looking at the URL, it does not seem to fit any request since in the /updatePerson you are expecting an object Person in the body but are sending: ?id=4&name=personame&age=34 as query parameters.

An example of a curl with a body that would be accepted by your method:

```<code>curl -X PUT -H "Content-Type: application/json" -d '{"name":"personame","age":"34"}' http://localhost:8080/updatePerson
</code>```

Body:
I am studying spring boot and spring jpa .
I was able to successfully read and write into the database, but the problem occurs while updating the data.

There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported

I am trying to update data of table : Person ( Id, Name , Age) using a html form. It accepts the data, and using spring jpa  I am trying to update it in MySQL database.

I am getting the following at console when trying to update the data, after submitting the form

> WARN 5176 --- [nio-8080-exec-1]
> .w.s.m.s.DefaultHandlerExceptionResolver : Resolved
> [org.springframework.web.HttpRequestMethodNotSupportedException:
> Request method 'GET' not supported]

My code is here :
updateperson form :

 <!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Title</title>

Enter new details

    <form action="updatePerson" method="post">
        Id   : <input type="number" name="id">

        Name :<input type = "text" name = "name">

        Age : <input type = "number" name = "age">

        <input type="submit">
    </form>

PersonRepository.java

package com.example.demo.repository;

import com.example.demo.model.Person;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface PersonRepository extends CrudRepository<Person , Integer> {
    List<Person> findByName(String name);
    List<Person> findByAge(int age);
    List<Person> findAll();
}

PersonController.java

    package com.example.demo.controller;

import com.example.demo.model.Person;
import com.example.demo.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class PersonController {
    @Autowired
    PersonRepository personRepository;

    @GetMapping("update")
    public String updatePerson(){
        System.out.println("update to updateperson html");
        return "updateperson";
    }
    @PutMapping("/updatePerson")
    public String updatePerson(Person person){
        System.out.println("UPDATING TO" + person.getAge()+" : "+person.getName() + " : "+person.getPid());
        personRepository.save(person);
        return "updateperson";
    }

}

Person.java

package com.example.demo.model;

import org.springframework.stereotype.Component;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Person {
    @Id
    @GeneratedValue
    int pid;

    String name;
    int age;

     public Person() {
    }

    public Person(int pid, String name, int age) {
        this.pid = pid;
        this.name = name;
        this.age = age;
    }

//getter and setters
}

The URL to which I'm sending the request:

localhost:8080/updatePerson?id=4&name=personame&age=34

Body:
If you check the URL: localhost:8080/updatePerson?id=4&name=personame&age=34, the method you are trying to access (updatePerson) is a PUT, so you should send a PUT instead of a GET.
You can see the method type in the annotation:

@PutMapping("/updatePerson")

Depending on how you are doing the request there should be someplace to set the method you are using. Also, looking at the URL, it does not seem to fit any request since in the /updatePerson you are expecting an object Person in the body but are sending: ?id=4&name=personame&age=34 as query parameters.

An example of a curl with a body that would be accepted by your method:

curl -X PUT -H "Content-Type: application/json" -d '{"name":"personame","age":"34"}' http://localhost:8080/updatePerson


问:
CS50 Pset 7 13.sql, I can't solve it, nested sqlite3 database
DataBase movies.db

tables

directors (movie_id, person_id)

movies (id, title, year)

people (id, name, birth)

ratings (movie_id, rating, votes)

stars (movie_id, person_id)

you can download the database.

Question

I'm new in programming, so I decided, to begin with, CS50 Harvard course here is the problem and the test solution:

In 13.sql, write a SQL query to list the names of all people who starred in a movie in which Kevin Bacon also starred.
Your query should output a table with a single column for the name of each person.
There may be multiple people named Kevin Bacon in the database. Be sure to only select the Kevin Bacon born in 1958.
Kevin Bacon himself should not be included in the resulting list.

solution hint

Executing 13.sql results in a table with 1 column and 176 rows.

executing code in PowerShell or bash
cat 13.sql | sqlite3 movies.db

My Code:

```<code>SELECT COUNT(name)
FROM people
JOIN stars ON stars.person_id = people.id
JOIN movies ON movies.id = stars.movie_id
WHERE people.id IN(
SELECT stars.person_id
FROM stars
GROUP BY stars.person_id
HAVING name = "Kevin Bacon");
</code>```

problem:

when I execute code it stop working, I can't choose stars with Kevin

答:
I did it without using any Join, just nesting the conditions.</p>

```<code>SELECT people.name FROM people
WHERE people.id IN
(
    SELECT stars.person_id FROM stars
    WHERE stars.movie_id IN
    (
        SELECT stars.movie_id FROM stars
        WHERE stars.person_id IN
        (
            SELECT people.id FROM people
            WHERE people.name = "Kevin Bacon" AND
            people.birth = 1958
        )
    )
)
AND people.name != "Kevin Bacon"
GROUP BY people.name
</code>```

Body:
DataBase movies.db

tables

directors (movie_id, person_id)

movies (id, title, year)

people (id, name, birth)

ratings (movie_id, rating, votes)

stars (movie_id, person_id)

you can download the database.

Question

I'm new in programming, so I decided, to begin with, CS50 Harvard course here is the problem and the test solution:

In 13.sql, write a SQL query to list the names of all people who starred in a movie in which Kevin Bacon also starred.
Your query should output a table with a single column for the name of each person.
There may be multiple people named Kevin Bacon in the database. Be sure to only select the Kevin Bacon born in 1958.
Kevin Bacon himself should not be included in the resulting list.

solution hint

Executing 13.sql results in a table with 1 column and 176 rows.

executing code in PowerShell or bash
cat 13.sql | sqlite3 movies.db

My Code:

SELECT COUNT(name)
FROM people
JOIN stars ON stars.person_id = people.id
JOIN movies ON movies.id = stars.movie_id
WHERE people.id IN(
SELECT stars.person_id
FROM stars
GROUP BY stars.person_id
HAVING name = "Kevin Bacon");

problem:

when I execute code it stop working, I can't choose stars with Kevin

Body:
I did it without using any Join, just nesting the conditions.

SELECT people.name FROM people
WHERE people.id IN
(
    SELECT stars.person_id FROM stars
    WHERE stars.movie_id IN
    (
        SELECT stars.movie_id FROM stars
        WHERE stars.person_id IN
        (
            SELECT people.id FROM people
            WHERE people.name = "Kevin Bacon" AND
            people.birth = 1958
        )
    )
)
AND people.name != "Kevin Bacon"
GROUP BY people.name


问:
Pass Vuejs Data in Style (SFA)
I have a beginner question. For example i have a componnent that have a Boolean prop. Deppending on the values of the prop i'm setting the path to which Less he should to take, but that doesn't work. Does anyone know how to do that? And if that is possible?

<template>

Text

</template>

```

答:
It's a bit of a hack, but you can achieve this by creating scss-style variables in the element's style and then using these in the actual style to set 'real' css properties. It works as the variables set in style are ignored by the browser as they are not valid css properties, but scss gets access to all previously set properties, and these appear as variables.

Code Sandbox

```<code><template>
  <div class="hello">
    <!-- Set the style to include the values from cssVars computed property -->
    <p :style="cssVars">Hello World</p>
    <!-- type in a new color name/#rgb value to dynamically change it -->
    <input v-model="color">
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String
  },
  data() {
    return {
      color: "red"
    };
  },
  computed: {
    // Return an object containing scss variables
    cssVars() {
      return {
        "--color": this.color
      };
    }
  }
};
</script>

<style scoped>
// Use the variables defined in style to set 'real' css properties
p {
  color: var(--color);
}
</style>
</code>```

Title: Pass Vuejs Data in Style (SFA)

Body:
It's a bit of a hack, but you can achieve this by creating scss-style variables in the element's style and then using these in the actual style to set 'real' css properties. It works as the variables set in style are ignored by the browser as they are not valid css properties, but scss gets access to all previously set properties, and these appear as variables.

Code Sandbox

<template>
  <div class="hello">
    <!-- Set the style to include the values from cssVars computed property -->
    <p :style="cssVars">Hello World</p>
    <!-- type in a new color name/#rgb value to dynamically change it -->
    <input v-model="color">
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String
  },
  data() {
    return {
      color: "red"
    };
  },
  computed: {
    // Return an object containing scss variables
    cssVars() {
      return {
        "--color": this.color
      };
    }
  }
};
</script>

<style scoped>
// Use the variables defined in style to set 'real' css properties
p {
  color: var(--color);
}
</style>


问:
map and filter function in selector
My selector checks all actions from array and then deletes empty elements. Can it be written better?

const makeSelectError2 = (actions) =>
  createSelector(selectError, (errorState) =>
    actions
      .map((action) =>
        errorState[action] !== undefined ? errorState[action] : null,
      )
      .filter((action) => action)
      .find((action) => true),
  );
```

答:
What is the difference between undefined and null in your case? Both are returning false, and instead of find just get first element.

So we can write much shorter code:

actions.map(action => errorState[action]).filter(Boolean)[0]
```

<p><strong>Update:</strong> Actually, if you need just first element then from the very beginning:</p>

<pre class="lang-js prettyprint-override"><code>errorState[actions.find(action => errorState[action])]
</code>```

And that's it.

Title: map and filter function in selector

Body:
What is the difference between undefined and null in your case? Both are returning false, and instead of find just get first element.

So we can write much shorter code:

actions.map(action => errorState[action]).filter(Boolean)[0]

Update: Actually, if you need just first element then from the very beginning:

errorState[actions.find(action => errorState[action])]

And that's it.


问:
XML writing tools for Python
I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of?

This is similar to what I'm actually doing:

```<code>import xml.etree.ElementTree as ET
root = ET.Element('html')
head = ET.SubElement(root,'head')
script = ET.SubElement(head,'script')
script.set('type','text/javascript')
script.text = "var a = 'I love á letters'"
body = ET.SubElement(root,'body')
h1 = ET.SubElement(body,'h1')
h1.text = "And I like the fact that 3 > 1"
tree = ET.ElementTree(root)
tree.write('foo.xhtml')

# more foo.xhtml
<html><head><script type="text/javascript">var a = 'I love á
letters'</script></head><body><h1>And I like the fact that 3 > 1</h1>
</body></html>
</code>```

答:
I ended up using saxutils.escape(str) to generate valid XML strings and then validating it with Eli's approach to be sure I didn't miss any tag</p>

```<code>from xml.sax import saxutils
from xml.dom.minidom import parseString
from xml.parsers.expat import ExpatError

xml = '''<?xml version="1.0" encoding="%s"?>\n
<contents title="%s" crawl_date="%s" in_text_date="%s"
url="%s">\n<main_post>%s</main_post>\n</contents>''' %
(self.encoding, saxutils.escape(title), saxutils.escape(time),
saxutils.escape(date), saxutils.escape(url), saxutils.escape(contents))
try:
    minidoc = parseString(xml)
catch ExpatError:
    print "Invalid xml"
</code>```

OwnerDisplayName: Vinko Vrsalovic

Title: XML writing tools for Python

Body:
I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of?

This is similar to what I'm actually doing:

import xml.etree.ElementTree as ET
root = ET.Element('html')
head = ET.SubElement(root,'head')
script = ET.SubElement(head,'script')
script.set('type','text/javascript')
script.text = "var a = 'I love á letters'"
body = ET.SubElement(root,'body')
h1 = ET.SubElement(body,'h1')
h1.text = "And I like the fact that 3 > 1"
tree = ET.ElementTree(root)
tree.write('foo.xhtml')

# more foo.xhtml

And I like the fact that 3 > 1

Body:
I ended up using saxutils.escape(str) to generate valid XML strings and then validating it with Eli's approach to be sure I didn't miss any tag

from xml.sax import saxutils
from xml.dom.minidom import parseString
from xml.parsers.expat import ExpatError

xml = '''<?xml version="1.0" encoding="%s"?>\n
<contents title="%s" crawl_date="%s" in_text_date="%s"
url="%s">\n<main_post>%s</main_post>\n</contents>''' %
(self.encoding, saxutils.escape(title), saxutils.escape(time),
saxutils.escape(date), saxutils.escape(url), saxutils.escape(contents))
try:
    minidoc = parseString(xml)
catch ExpatError:
    print "Invalid xml"

ContentLicense: CC BY-SA 2.5


问:
Testing argument using Python Click
I have a command-line script with Python-click with an argument and option:

# console.py
import click

@click.command()
@click.version_option()
@click.argument("filepath", type=click.Path(exists=True), default=".")
@click.option(
    "-m",
    "--max-size",
    type=int,
    help="Max size in megabytes.",
    default=20,
    show_default=True,
)
def main(filepath: str, max_size: int) -> None:
    max_size_bytes = max_size * 1024 * 1024  # convert to MB
    if filepath.endswith(".pdf"):
        print("success")
    else:
        print(max_size_bytes)
```

<p>Both the argument and option have default values and work on the command-line and using the CLI it behaves as expected. But when I try testing it following Click documentation and debug it, it does not enter the first line:</p>

<pre class="lang-py prettyprint-override"><code># test_console.py
from unittest.mock import Mock

import click.testing
import pytest
from pytest_mock import MockFixture

from pdf_split_tool import console

@pytest.fixture
def runner() -> click.testing.CliRunner:
    """Fixture for invoking command-line interfaces."""
    return click.testing.CliRunner()

@pytest.fixture
def mock_pdf_splitter_pdfsplitter(mocker: MockFixture) -> Mock:
    """Fixture for mocking pdf_splitter.PdfSplitter."""
    return mocker.patch("pdf_split_tool.pdf_splitter.PdfSplitter", autospec=True)

def test_main_uses_specified_filepath(
    runner: click.testing.CliRunner,
    mock_pdf_splitter_pdfsplitter: Mock,
) -> None:
    """It uses the specified filepath."""
    result = runner.invoke(console.main, ["test.pdf"])
    assert result.exit_code == 0
</code>```

I couldn't see why it is giving since the debugger did not enter the first line of function main(). Any ideas of what could be wrong?

答:
The failure is due to following error.

```<code>(pdb)print result.output
"Usage: main [OPTIONS] [FILEPATH]\nTry 'main --help' for help.\n\nError: Invalid value for '[FILEPATH]': Path 'test.pdf' does not exist.\n"
</code>```

This is happening due to following code in console.py which checks if the filepath exists.
@click.argument("filepath", type=click.Path(exists=True), default=".")

One way to test creating a temporary file is using afterburner's code:

# test_console.py
def test_main_uses_specified_filepath() -> None:
    runner = click.testing.CliRunner()
    with runner.isolated_filesystem():
        with open('test.pdf', 'w') as f:
            f.write('Hello World!')

        result = runner.invoke(main, ["test.pdf"])
    assert result.exit_code == 0
```

Title: Testing argument using Python Click

Body:
I have a command-line script with Python-click with an argument and option:

# console.py
import click

@click.command()
@click.version_option()
@click.argument("filepath", type=click.Path(exists=True), default=".")
@click.option(
    "-m",
    "--max-size",
    type=int,
    help="Max size in megabytes.",
    default=20,
    show_default=True,
)
def main(filepath: str, max_size: int) -> None:
    max_size_bytes = max_size * 1024 * 1024  # convert to MB
    if filepath.endswith(".pdf"):
        print("success")
    else:
        print(max_size_bytes)

Both the argument and option have default values and work on the command-line and using the CLI it behaves as expected. But when I try testing it following Click documentation and debug it, it does not enter the first line:

# test_console.py
from unittest.mock import Mock

import click.testing
import pytest
from pytest_mock import MockFixture

from pdf_split_tool import console

@pytest.fixture
def runner() -> click.testing.CliRunner:
    """Fixture for invoking command-line interfaces."""
    return click.testing.CliRunner()

@pytest.fixture
def mock_pdf_splitter_pdfsplitter(mocker: MockFixture) -> Mock:
    """Fixture for mocking pdf_splitter.PdfSplitter."""
    return mocker.patch("pdf_split_tool.pdf_splitter.PdfSplitter", autospec=True)

def test_main_uses_specified_filepath(
    runner: click.testing.CliRunner,
    mock_pdf_splitter_pdfsplitter: Mock,
) -> None:
    """It uses the specified filepath."""
    result = runner.invoke(console.main, ["test.pdf"])
    assert result.exit_code == 0

I couldn't see why it is giving since the debugger did not enter the first line of function main(). Any ideas of what could be wrong?

Body:
The failure is due to following error.

(pdb)print result.output
"Usage: main [OPTIONS] [FILEPATH]\nTry 'main --help' for help.\n\nError: Invalid value for '[FILEPATH]': Path 'test.pdf' does not exist.\n"

This is happening due to following code in console.py which checks if the filepath exists.
@click.argument("filepath", type=click.Path(exists=True), default=".")

One way to test creating a temporary file is using afterburner's code:

# test_console.py
def test_main_uses_specified_filepath() -> None:
    runner = click.testing.CliRunner()
    with runner.isolated_filesystem():
        with open('test.pdf', 'w') as f:
            f.write('Hello World!')

        result = runner.invoke(main, ["test.pdf"])
    assert result.exit_code == 0


问:
Empty cell counts only via F8. How to make it run correct automatically?
i'm done. Maybe I'm blind, but I can't find any reason why code is working properly only if i breakpoint or F8. I'm talking about line where, I find first empty cell in range (cell.value = ""). If it's run automatically, the value is 0. If I do a breakpoint before it and continue, it calculates properly. The weird symbols are in russian.</p>

```<code>Public Sub Prepare_OMOBUS()

Dim ReportBook As Workbook
Dim wbD As Worksheet, wbS  As Worksheet, wbO  As Worksheet, wbK As Worksheet
Dim cell As Range
Dim lRow As Long, i As Long, k As Long
Dim namestr As String

If UserForm11.ComboBox1.Value = "" Or UserForm11.ComboBox2.Value = "" Then
    MsgBox "Íå âûáðàí ãîä/ìåñÿö", 64
    Exit Sub
End If

Application.ScreenUpdating = False

UserForm11.Hide
UserForm10.Show vbModeless

UserForm10.Label1.Caption = "Ïîäãîòîâêà ÀÏ..."
UserForm10.Repaint

Set wbD = ThisWorkbook.Sheets("OMOBUS_AP_DATA")
Set wbS = ThisWorkbook.Sheets("OMOBUS_PROMO_DATA")
Set wbO = ThisWorkbook.Sheets("OMOBUS_TEMPLATE")
Set wbK = ThisWorkbook.Sheets("OMOBUS")

wbD.Range("AP_DELETE").Clear
wbS.Range("PROMO_DELETE").Clear

Range("OMOBUS_AP_QUERY").Copy Destination:=wbD.Range("A1")
Range("OMOBUS_PROMO_QUERY").Copy Destination:=wbS.Range("A1")

wbK.PivotTables("PivotTable1").ManualUpdate = True
wbK.PivotTables("PivotTable2").ManualUpdate = True

UserForm10.Label1.Caption = "Ôèëüòðàöèÿ äàííûõ..."
UserForm10.Repaint

With wbK.PivotTables("PivotTable1").PivotFields("Table2.Year")
    .ClearAllFilters
    .CurrentPage = UserForm11.ComboBox2.Value
End With

With wbK.PivotTables("PivotTable2").PivotFields("Table2.Year")
    .ClearAllFilters
    .CurrentPage = UserForm11.ComboBox2.Value
End With

With wbK.PivotTables("PivotTable1").PivotFields("Table2.MONTH")
    .ClearAllFilters
    .CurrentPage = UserForm11.ComboBox1.Value
End With

With wbK.PivotTables("PivotTable2").PivotFields("Table2.MONTH")
    .ClearAllFilters
    .CurrentPage = UserForm11.ComboBox1.Value
End With

With wbK.PivotTables("PivotTable1").PivotFields("Table2.ÄÌÏ44")
    .ClearAllFilters
    .PivotFilters. _
    Add2 Type:=xlCaptionDoesNotEqual, Value1:="0"
End With

With wbK.PivotTables("PivotTable2").PivotFields("Table2.Final Discount")
    .ClearAllFilters
    .PivotFilters. _
    Add2 Type:=xlCaptionDoesNotEqual, Value1:="0"
End With

wbK.PivotTables("PivotTable2").RefreshTable

UserForm10.Label1.Caption = "Çàïîëíåíèå ôîðìû..."
UserForm10.Repaint

Call UnProtect1

wbO.Visible = True
wbD.Visible = True
wbS.Visible = True
wbK.Visible = True

For Each cell In wbK.Range("A7:A1000000")
    If cell.Value = "" Then
        i = cell.Row
        Exit For
    End If
Next cell

For Each cell In wbK.Range("Y7:Y1000000")
    If cell.Value = "" Then
        k = cell.Row
        Exit For
    End If
Next cell

wbK.Range(wbK.Cells(7, 1), wbK.Cells(i, 16)).Copy
wbO.Range("A3").PasteSpecial xlPasteValues

lRow = wbO.Range("A3", wbO.Range("A3").End(xlDown)).Rows.Count + 3
If lRow > 1000000 Then lRow = 3

wbK.Range(wbK.Cells(7, 25), wbK.Cells(k, 40)).Copy
wbO.Range("A" & lRow).PasteSpecial xlPasteValues

lRow = wbO.Range("A3", wbO.Range("A3").End(xlDown)).Rows.Count + 3
If lRow > 1000000 Then lRow = 3

wbO.Range("A3:P3").Copy
wbO.Range("A3:P" & lRow).PasteSpecial xlPasteFormats

UserForm10.Label1.Caption = "Ïîäãîòîâêà ôàéëà..."
UserForm10.Repaint

Dim MainFolder As String

Set ReportBook = Workbooks.Add

ThisWorkbook.Sheets("REFERENCES").Visible = True
wbO.Visible = True
ThisWorkbook.Sheets("REFERENCES").Copy Before:=ReportBook.Sheets(1)
wbO.Copy Before:=ReportBook.Sheets(1)

MainFolder = CreateObject("WScript.Shell").specialfolders("Desktop") & "\PromoTool\OMOBUS Reports\"

Dim fdObj As Object
Set fdObj = CreateObject("Scripting.FileSystemObject")

If fdObj.FolderExists(MainFolder) = False Then
    fdObj.CreateFolder (MainFolder)
End If

namestr = "OMOBUS Report for (" & UserForm11.ComboBox2.Value & "-" & UserForm11.ComboBox1.Value & ") created on " & InternetTime
namestr = Replace(namestr, ":", "-")

UserForm10.Label1.Caption = "Ñîõðàíåíèå..."
UserForm10.Repaint

ReportBook.SaveAs MainFolder & namestr & ".xlsx"

wbD.Range("AP_DELETE").Clear
wbS.Range("PROMO_DELETE").Clear

ThisWorkbook.Activate
With wbO
    .Select
    .Range("A3:P3").ClearContents
    .Range("O_DELETE").Clear
End With

Call ShowRoleSheet
Call Protect1

Set wbO = Nothing
Set wbD = Nothing
Set wbS = Nothing
Set wbK = Nothing
Set fdObj = Nothing

UserForm10.Hide
ReportBook.Activate
Application.ScreenUpdating = True

MsgBox "Îò÷åò óñïåøíî ñîçäàí è ñîõðàíåí â ïàïêó " & MainFolder, 64

End Sub
</code>```

答: Looks like the issue was due to calculations referring to pivot table which was result of power query. I replaced the copy ranges with PivotTable.RowRange, added .Update to pivot table on power query refresh. This solved all problems.

Body:
i'm done. Maybe I'm blind, but I can't find any reason why code is working properly only if i breakpoint or F8. I'm talking about line where, I find first empty cell in range (cell.value = ""). If it's run automatically, the value is 0. If I do a breakpoint before it and continue, it calculates properly. The weird symbols are in russian.

Public Sub Prepare_OMOBUS()

Dim ReportBook As Workbook
Dim wbD As Worksheet, wbS  As Worksheet, wbO  As Worksheet, wbK As Worksheet
Dim cell As Range
Dim lRow As Long, i As Long, k As Long
Dim namestr As String

If UserForm11.ComboBox1.Value = "" Or UserForm11.ComboBox2.Value = "" Then
    MsgBox "Íå âûáðàí ãîä/ìåñÿö", 64
    Exit Sub
End If

Application.ScreenUpdating = False

UserForm11.Hide
UserForm10.Show vbModeless

UserForm10.Label1.Caption = "Ïîäãîòîâêà ÀÏ..."
UserForm10.Repaint

Set wbD = ThisWorkbook.Sheets("OMOBUS_AP_DATA")
Set wbS = ThisWorkbook.Sheets("OMOBUS_PROMO_DATA")
Set wbO = ThisWorkbook.Sheets("OMOBUS_TEMPLATE")
Set wbK = ThisWorkbook.Sheets("OMOBUS")

wbD.Range("AP_DELETE").Clear
wbS.Range("PROMO_DELETE").Clear

Range("OMOBUS_AP_QUERY").Copy Destination:=wbD.Range("A1")
Range("OMOBUS_PROMO_QUERY").Copy Destination:=wbS.Range("A1")

wbK.PivotTables("PivotTable1").ManualUpdate = True
wbK.PivotTables("PivotTable2").ManualUpdate = True

UserForm10.Label1.Caption = "Ôèëüòðàöèÿ äàííûõ..."
UserForm10.Repaint

With wbK.PivotTables("PivotTable1").PivotFields("Table2.Year")
    .ClearAllFilters
    .CurrentPage = UserForm11.ComboBox2.Value
End With

With wbK.PivotTables("PivotTable2").PivotFields("Table2.Year")
    .ClearAllFilters
    .CurrentPage = UserForm11.ComboBox2.Value
End With

With wbK.PivotTables("PivotTable1").PivotFields("Table2.MONTH")
    .ClearAllFilters
    .CurrentPage = UserForm11.ComboBox1.Value
End With

With wbK.PivotTables("PivotTable2").PivotFields("Table2.MONTH")
    .ClearAllFilters
    .CurrentPage = UserForm11.ComboBox1.Value
End With

With wbK.PivotTables("PivotTable1").PivotFields("Table2.ÄÌÏ44")
    .ClearAllFilters
    .PivotFilters. _
    Add2 Type:=xlCaptionDoesNotEqual, Value1:="0"
End With

With wbK.PivotTables("PivotTable2").PivotFields("Table2.Final Discount")
    .ClearAllFilters
    .PivotFilters. _
    Add2 Type:=xlCaptionDoesNotEqual, Value1:="0"
End With

wbK.PivotTables("PivotTable2").RefreshTable

UserForm10.Label1.Caption = "Çàïîëíåíèå ôîðìû..."
UserForm10.Repaint

Call UnProtect1

wbO.Visible = True
wbD.Visible = True
wbS.Visible = True
wbK.Visible = True

For Each cell In wbK.Range("A7:A1000000")
    If cell.Value = "" Then
        i = cell.Row
        Exit For
    End If
Next cell

For Each cell In wbK.Range("Y7:Y1000000")
    If cell.Value = "" Then
        k = cell.Row
        Exit For
    End If
Next cell

wbK.Range(wbK.Cells(7, 1), wbK.Cells(i, 16)).Copy
wbO.Range("A3").PasteSpecial xlPasteValues

lRow = wbO.Range("A3", wbO.Range("A3").End(xlDown)).Rows.Count + 3
If lRow > 1000000 Then lRow = 3

wbK.Range(wbK.Cells(7, 25), wbK.Cells(k, 40)).Copy
wbO.Range("A" & lRow).PasteSpecial xlPasteValues

lRow = wbO.Range("A3", wbO.Range("A3").End(xlDown)).Rows.Count + 3
If lRow > 1000000 Then lRow = 3

wbO.Range("A3:P3").Copy
wbO.Range("A3:P" & lRow).PasteSpecial xlPasteFormats

UserForm10.Label1.Caption = "Ïîäãîòîâêà ôàéëà..."
UserForm10.Repaint

Dim MainFolder As String

Set ReportBook = Workbooks.Add

ThisWorkbook.Sheets("REFERENCES").Visible = True
wbO.Visible = True
ThisWorkbook.Sheets("REFERENCES").Copy Before:=ReportBook.Sheets(1)
wbO.Copy Before:=ReportBook.Sheets(1)

MainFolder = CreateObject("WScript.Shell").specialfolders("Desktop") & "\PromoTool\OMOBUS Reports\"

Dim fdObj As Object
Set fdObj = CreateObject("Scripting.FileSystemObject")

If fdObj.FolderExists(MainFolder) = False Then
    fdObj.CreateFolder (MainFolder)
End If

namestr = "OMOBUS Report for (" & UserForm11.ComboBox2.Value & "-" & UserForm11.ComboBox1.Value & ") created on " & InternetTime
namestr = Replace(namestr, ":", "-")

UserForm10.Label1.Caption = "Ñîõðàíåíèå..."
UserForm10.Repaint

ReportBook.SaveAs MainFolder & namestr & ".xlsx"

wbD.Range("AP_DELETE").Clear
wbS.Range("PROMO_DELETE").Clear

ThisWorkbook.Activate
With wbO
    .Select
    .Range("A3:P3").ClearContents
    .Range("O_DELETE").Clear
End With

Call ShowRoleSheet
Call Protect1

Set wbO = Nothing
Set wbD = Nothing
Set wbS = Nothing
Set wbK = Nothing
Set fdObj = Nothing

UserForm10.Hide
ReportBook.Activate
Application.ScreenUpdating = True

MsgBox "Îò÷åò óñïåøíî ñîçäàí è ñîõðàíåí â ïàïêó " & MainFolder, 64

End Sub


问:
How to use background tasks with Starlette when there's no background object?
I'm hoping to avoid any use of Celery at the moment. In Starlette's docs they give two ways to add background tasks:

Via Graphene: https://www.starlette.io/graphql/

class Query(graphene.ObjectType):
    user_agent = graphene.String()

    def resolve_user_agent(self, info):
        """
        Return the User-Agent of the incoming request.
        """
        user_agent = request.headers.get("User-Agent", "<unknown>")
        background = info.context["background"]
        background.add_task(log_user_agent, user_agent=user_agent)
        return user_agent
```

<p>Via a JSON response: https://www.starlette.io/background/</p>

<pre class="lang-py prettyprint-override"><code>async def signup(request):
    data = await request.json()
    username = data['username']
    email = data['email']
    task = BackgroundTask(send_welcome_email, to_address=email)
    message = {'status': 'Signup successful'}
    return JSONResponse(message, background=task)
</code>```

Does anyone know of a way to add tasks to Starlette's background with Ariadne? I am unable to return a JSONResponse in my resolver, and I do not have access to a info.context["background"]. The only thing I have attached to my context is my request object.

答:
Solved!

Starlette Middleware:

class BackgroundTaskMiddleware(BaseHTTPMiddleware):
    async def dispatch(
            self, request: Request, call_next: RequestResponseEndpoint
    ) -> Response:
        request.state.background = None
        response = await call_next(request)
        if request.state.background:
            response.background = request.state.background
        return response
```

<p>Ariadne Resolver:</p>

<pre class="lang-py prettyprint-override"><code>@query.field("getUser")
@check_authentication
async def resolve_get_user(user, obj, info):
    task = BackgroundTasks()
    task.add_task(test_func)
    task.add_task(testing_func_two, "I work now")
    request = info.context["request"]
    request.state.background = task
    return True

async def test_func():
    await asyncio.sleep(10)
    print("once!!")

async def testing_func_two(message: str):
    print(message)
</code>```

The functions still execute synchronously, but because they're background tasks I'm not too worried.

More discussion here.

Body:
I'm hoping to avoid any use of Celery at the moment. In Starlette's docs they give two ways to add background tasks:

Via Graphene: https://www.starlette.io/graphql/

class Query(graphene.ObjectType):
    user_agent = graphene.String()

    def resolve_user_agent(self, info):
        """
        Return the User-Agent of the incoming request.
        """
        user_agent = request.headers.get("User-Agent", "<unknown>")
        background = info.context["background"]
        background.add_task(log_user_agent, user_agent=user_agent)
        return user_agent

Via a JSON response: https://www.starlette.io/background/

async def signup(request):
    data = await request.json()
    username = data['username']
    email = data['email']
    task = BackgroundTask(send_welcome_email, to_address=email)
    message = {'status': 'Signup successful'}
    return JSONResponse(message, background=task)

Does anyone know of a way to add tasks to Starlette's background with Ariadne? I am unable to return a JSONResponse in my resolver, and I do not have access to a info.context["background"]. The only thing I have attached to my context is my request object.

Body:
Solved!

Starlette Middleware:

class BackgroundTaskMiddleware(BaseHTTPMiddleware):
    async def dispatch(
            self, request: Request, call_next: RequestResponseEndpoint
    ) -> Response:
        request.state.background = None
        response = await call_next(request)
        if request.state.background:
            response.background = request.state.background
        return response

Ariadne Resolver:

@query.field("getUser")
@check_authentication
async def resolve_get_user(user, obj, info):
    task = BackgroundTasks()
    task.add_task(test_func)
    task.add_task(testing_func_two, "I work now")
    request = info.context["request"]
    request.state.background = task
    return True

async def test_func():
    await asyncio.sleep(10)
    print("once!!")

async def testing_func_two(message: str):
    print(message)

The functions still execute synchronously, but because they're background tasks I'm not too worried.

More discussion here.


问:
Class constructor in C#
I am somewhat of a C# noob, and have been looking around in documentation but have been unable to understand how to create a constructor method for my class as I would in python.

Say I have a class named Vehicle, and when I create an instance of vehicle, I need to input the number of wheels and the number of axles the vehicles has. I want the constructor to divide the total wheels by the total axles to set the property wheelsPerAxle:

```<code>public class Vehicle
{
    public int numWheels;
    public int numAxles;
    public int wheelsPerAxle;

    public Vehicle()
    {
        wheelsPerAxle = Mathf.CeilToInt(numWheels/numAxles);
    }

}
</code>```

My code example is a little ridiculous but hopefully you get the idea that I want to call the method when the object is instantiated. How can I do this?

答:
Let's go over first what actually happens with your code, so we can get an idea of how it works.

We'll use this code to make an instance of the class:

```<code>var vehicle = new Vehicle();

// set the items inside
vehicle.numWheels = 4;
vehicle.numAxles = 2;
</code>```

Well, what does this do?

When code execution runs, it starts by running your constructor, and all the code inside it, before running the last two lines to modify the properties1. Your object must be fully instantiated before you can modify it.

Problem is, you'll never be able to fully instantiate the object.

Your class has two variables which you read from in the constructor, numWheels and numAxles. Both of these are (32 bit) integeters, and are uninstantiated - meaning you never directly assign them a value before you read from them.

However, int types are Value Types in c#, which means they are never uninstantiated. If you don't set a value when you create the variable it will take the default value for that type, which in this case is 0.

And then you try to do 0/0, and an exception will be thrown.

The issue here is that you need to provide a value for your variables during creation of the class, as doing so afterwards is too late. The good news is that you can pass in values as arguments to the class's constructor.

```<code>public class Vehicle
{
    public int wheelsPerAxle;

    public Vehicle(int numWheels, int numAxels)
    {
        wheelsPerAxle = Mathf.CeilToInt(numWheels/numAxles);
    }
}
</code>```

```<code>var vehicle = new Vehicle(4, 2);
// "vehicle.wheelsPerAxel" is 2
</code>```

Note: this doesn't do any validation, and it doesn't save (scope-wise) the values for use outside of the constructor, but this should get the point across.

See Pac0's answer for a more robust solution to modifying your class.

1 These are not properties, they are fields.

Title: Class constructor in C#

Body:
I am somewhat of a C# noob, and have been looking around in documentation but have been unable to understand how to create a constructor method for my class as I would in python.

Say I have a class named Vehicle, and when I create an instance of vehicle, I need to input the number of wheels and the number of axles the vehicles has. I want the constructor to divide the total wheels by the total axles to set the property wheelsPerAxle:

public class Vehicle
{
    public int numWheels;
    public int numAxles;
    public int wheelsPerAxle;

    public Vehicle()
    {
        wheelsPerAxle = Mathf.CeilToInt(numWheels/numAxles);
    }

}

My code example is a little ridiculous but hopefully you get the idea that I want to call the method when the object is instantiated. How can I do this?

Body:
Let's go over first what actually happens with your code, so we can get an idea of how it works.

We'll use this code to make an instance of the class:

var vehicle = new Vehicle();

// set the items inside
vehicle.numWheels = 4;
vehicle.numAxles = 2;

Well, what does this do?

When code execution runs, it starts by running your constructor, and all the code inside it, before running the last two lines to modify the properties1. Your object must be fully instantiated before you can modify it.

Problem is, you'll never be able to fully instantiate the object.

Your class has two variables which you read from in the constructor, numWheels and numAxles. Both of these are (32 bit) integeters, and are uninstantiated - meaning you never directly assign them a value before you read from them.

However, int types are Value Types in c#, which means they are never uninstantiated. If you don't set a value when you create the variable it will take the default value for that type, which in this case is 0.

And then you try to do 0/0, and an exception will be thrown.

The issue here is that you need to provide a value for your variables during creation of the class, as doing so afterwards is too late. The good news is that you can pass in values as arguments to the class's constructor.

public class Vehicle
{
    public int wheelsPerAxle;

    public Vehicle(int numWheels, int numAxels)
    {
        wheelsPerAxle = Mathf.CeilToInt(numWheels/numAxles);
    }
}

var vehicle = new Vehicle(4, 2);
// "vehicle.wheelsPerAxel" is 2

Note: this doesn't do any validation, and it doesn't save (scope-wise) the values for use outside of the constructor, but this should get the point across.

See Pac0's answer for a more robust solution to modifying your class.

1 These are not properties, they are fields.


问:
Exclude paths from URL with split and merge or regex replace
My plan is to alter a URL and remove some of the paths. For instance, from this: site = "link.com/path1/path2/path3/random" I want to get this: "link.com/path1/path3/random" only if path2 exists. path2 might have slightly different name (e.g. path2_version1, path2_version2 etc)

My solution works below. I actually, get all the paths separately and then merge them:

```<code>    import re
    from urllib.parse import urljoin
    import urllib.request
    import os
    import csv

    site = "https://img.mysite.com/c_fill,g_auto,w_750,h_536/q_auto,f_auto/mysitecom/2020/05/06/w331e4787162_5/my-image-saved"

def image_graber(old_url):
    url_main = 'https://img.mysite.com/mysitecom/'

    split_url_paths = old_url.rsplit('/', 6)
    url_subfolder1 = split_url_paths[2]
    url_subfolder2 = split_url_paths[3]
    url_subfolder3 = split_url_paths[4]
    url_subfolder4 = split_url_paths[5]
    url_subfolder5 = split_url_paths[6]

    final_url = url_main + '/' + url_subfolder1 + '/' + url_subfolder2 + '/' + url_subfolder3 + '/' + url_subfolder4 + '/' + url_subfolder5

    urllib.request.urlretrieve(final_url, "C:\My Site\IMG\/"+os.path.basename(final_url))

image_graber(site)
</code>```

I tried changing the script to make it more professional. In this case one urljoin couldn't work as it can take max 3 paths. So, I used more than one but to my surprise it doesn't work as it should:

```<code>#This didn't work
url_join1 = urljoin(url_main, url_subfolder1, url_subfolder2)
print(url_join1)
url_join2 = urljoin(url_join1, url_subfolder3, url_subfolder4)
print(url_join2)
final_join = urljoin(url_join2, url_subfolder5)
print(final_join)
</code>```

My question is, why this didn't work above? A possibly easier and faster way to just extract this part using regex was also tested:

```<code>if('c_fill' or 'q_auto' in site):
    exclude_path1 = re.sub(r'/c_fill[^/]+/',r'/',site)
    exclude_path2 = re.sub(r'/q_auto[^/]+/',r'/',exclude_path1)
    print(exclude_path2)
</code>```

答:
Sample old url:

```<code>old_url = 'https://img.mysite.com/c_fill,g_auto,w_750,h_536/alsothis/q_auto,f_auto/mysitecom/2020/05/06/deletethis/w331e4787162_5/my-image-saved'
</code>```

Now you can simply split it by '/' and make a list:

```<code>splitted = old_url.split('/')
</code>```

Also, create unwanted or stuff to delete

```<code>delete = ['alsothis','w331e4787162_5', 'deletethis']
</code>```

Now you can do a quick list comprehension to get your final url.

```<code>res = '/'.join([x for x in splitted if x not in delete])
</code>```

res will give you the required output.

Body:
My plan is to alter a URL and remove some of the paths. For instance, from this: site = "link.com/path1/path2/path3/random" I want to get this: "link.com/path1/path3/random" only if path2 exists. path2 might have slightly different name (e.g. path2_version1, path2_version2 etc)

My solution works below. I actually, get all the paths separately and then merge them:

    import re
    from urllib.parse import urljoin
    import urllib.request
    import os
    import csv

    site = "https://img.mysite.com/c_fill,g_auto,w_750,h_536/q_auto,f_auto/mysitecom/2020/05/06/w331e4787162_5/my-image-saved"

def image_graber(old_url):
    url_main = 'https://img.mysite.com/mysitecom/'

    split_url_paths = old_url.rsplit('/', 6)
    url_subfolder1 = split_url_paths[2]
    url_subfolder2 = split_url_paths[3]
    url_subfolder3 = split_url_paths[4]
    url_subfolder4 = split_url_paths[5]
    url_subfolder5 = split_url_paths[6]

    final_url = url_main + '/' + url_subfolder1 + '/' + url_subfolder2 + '/' + url_subfolder3 + '/' + url_subfolder4 + '/' + url_subfolder5

    urllib.request.urlretrieve(final_url, "C:\My Site\IMG\/"+os.path.basename(final_url))

image_graber(site)

I tried changing the script to make it more professional. In this case one urljoin couldn't work as it can take max 3 paths. So, I used more than one but to my surprise it doesn't work as it should:

#This didn't work
url_join1 = urljoin(url_main, url_subfolder1, url_subfolder2)
print(url_join1)
url_join2 = urljoin(url_join1, url_subfolder3, url_subfolder4)
print(url_join2)
final_join = urljoin(url_join2, url_subfolder5)
print(final_join)

My question is, why this didn't work above? A possibly easier and faster way to just extract this part using regex was also tested:

if('c_fill' or 'q_auto' in site):
    exclude_path1 = re.sub(r'/c_fill[^/]+/',r'/',site)
    exclude_path2 = re.sub(r'/q_auto[^/]+/',r'/',exclude_path1)
    print(exclude_path2)

Body:
Sample old url:

old_url = 'https://img.mysite.com/c_fill,g_auto,w_750,h_536/alsothis/q_auto,f_auto/mysitecom/2020/05/06/deletethis/w331e4787162_5/my-image-saved'

Now you can simply split it by '/' and make a list:

splitted = old_url.split('/')

Also, create unwanted or stuff to delete

delete = ['alsothis','w331e4787162_5', 'deletethis']

Now you can do a quick list comprehension to get your final url.

res = '/'.join([x for x in splitted if x not in delete])

res will give you the required output.


问:
Position element according to body instead of the relative parent
I have a div with position relative and two children using it and both have position absolute. And I need them. But I want to make another child inside the relative div and give it the position absolute. But now the problem is that I want some part of it to appear outside of the element. So how can I do it in CSS? Thanks in advance.

Reference to what I need is: Example of what I need, check the search icon. How it is placed. I want that kind of thing.

```<code>div {
   //Parent div
    position:relative;
}
div {
   //Child div
    position:absolute;
}
div {
   //Child div
    position:absolute;
   //This is an emoji
   //But I want this to appear half outside of the parent div,
   //i.e. on the border of the parent div
}
</code>```

答:
in the given example, section is the parent div  which is relative and rest 2 child, or you can have as many as you want, all are absolute, and image is out on border as you requested

* {margin: 0; padding: 0; box-sizing: border-box;}
img {max-width: 30px;}
section {border:15px solid #ccc; border-radius: 20px; height: 100px; position: relative;}
.child {position: absolute;}
.child1 {top: 50%; left: 50%; transform: translate(-50%,-50%);}
.childEmoji {top: 0; left:0; transform: translate(-50%,-50%);}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
  <div class="child child1">Child 1</div>
  <div class="child childEmoji"><img src="https://images.macrumors.com/t/45wRHEDrpfO6dWOSqibLkzcZG-s=/800x0/filters:quality(90)/article-new/2017/11/crying-tears-of-joy-emoji-250x248.jpg"></div>
</section></code>```

Body:
I have a div with position relative and two children using it and both have position absolute. And I need them. But I want to make another child inside the relative div and give it the position absolute. But now the problem is that I want some part of it to appear outside of the element. So how can I do it in CSS? Thanks in advance.

Reference to what I need is: Example of what I need, check the search icon. How it is placed. I want that kind of thing.

div {
   //Parent div
    position:relative;
}
div {
   //Child div
    position:absolute;
}
div {
   //Child div
    position:absolute;
   //This is an emoji
   //But I want this to appear half outside of the parent div,
   //i.e. on the border of the parent div
}

Body:
in the given example, section is the parent div  which is relative and rest 2 child, or you can have as many as you want, all are absolute, and image is out on border as you requested

* {margin: 0; padding: 0; box-sizing: border-box;}
img {max-width: 30px;}
section {border:15px solid #ccc; border-radius: 20px; height: 100px; position: relative;}
.child {position: absolute;}
.child1 {top: 50%; left: 50%; transform: translate(-50%,-50%);}
.childEmoji {top: 0; left:0; transform: translate(-50%,-50%);}

<section>
  <div class="child child1">Child 1</div>
  <div class="child childEmoji"><img src="https://images.macrumors.com/t/45wRHEDrpfO6dWOSqibLkzcZG-s=/800x0/filters:quality(90)/article-new/2017/11/crying-tears-of-joy-emoji-250x248.jpg"></div>
</section>


问:
Question: BigQueryIO creates one file per input line, is it correct?
I'm new on Apache Beam and I'm developing a pipeline to get rows from JDBCIO and send them to BigQueryIO. I'm converting the rows to avro files with withAvroFormatFunction but it is creating a new file for each row returned by JDBCIO. The same for withFormatFunction with json files.

It is so slow to run locally with DirectRunner because it uploads a lot of files to Google Storage. Is this approach good for scaling on Google Dataflow? Is there a better way to deal with it?

Thanks

答: BigQueryIO will commit results to BigQuery for each bundle. The DirectRunner is known to be a bit inefficient about bundling. It never combines bundles. So whatever bundling is provided by a source is propagated to the sink. You can try using other runners such as Flink, Spark, or Dataflow. The in-process open source runners are about as easy to use as the direct runner. Just change --runner=DirectRunner to --runner=FlinkRunner and the default settings will run in local embedded mode.


问:
Creating a new Dataframe using existing data in a column
I am trying to create a new dataframe based on the data shown in the below Dataframe link. Basically I need to create 6 new columns based on the value of "Keyword Type" Which gives me each article per row and all the corresponding keyword type information. So the columns would be Article ID, Sport, Competition, Context, etc... and the first row would be Article 1's corresponding info. I need it per article so I can join it to another dataframe's article column and bring this info in. Is there an efficient way to do this? Click here to view  Dataframe

Current Structure:

```<code>Article ID  | Keyword Type | Keyword Value
Article 1   | Sport        | Football
Article 1   | Team         | Manchester United
Article 1   | Language     | English
Article 1   | Context      | News
</code>```

Expected Output:

```<code>Article ID | Sport    | Team              | Language  | Context
Article 1  | Football | Manchester United | English   | News
</code>```

答:
Do the following: </p>

```<code>res = pd.pivot_table(df, columns="Keyword Type", index="Article ID", aggfunc=lambda x:x)
res = res.droplevel(0, axis="columns")
</code>```

<p>The result is: </p>

```<code>           Context Language     Sport               Team
Article ID
Article 1     News  English  Football  Manchester United
</code>```

Body:
I am trying to create a new dataframe based on the data shown in the below Dataframe link. Basically I need to create 6 new columns based on the value of "Keyword Type" Which gives me each article per row and all the corresponding keyword type information. So the columns would be Article ID, Sport, Competition, Context, etc... and the first row would be Article 1's corresponding info. I need it per article so I can join it to another dataframe's article column and bring this info in. Is there an efficient way to do this? Click here to view  Dataframe

Current Structure:

Article ID  | Keyword Type | Keyword Value
Article 1   | Sport        | Football
Article 1   | Team         | Manchester United
Article 1   | Language     | English
Article 1   | Context      | News

Expected Output:

Article ID | Sport    | Team              | Language  | Context
Article 1  | Football | Manchester United | English   | News

Body:
Do the following:

res = pd.pivot_table(df, columns="Keyword Type", index="Article ID", aggfunc=lambda x:x)
res = res.droplevel(0, axis="columns")

The result is:

           Context Language     Sport               Team
Article ID
Article 1     News  English  Football  Manchester United


问:
Taking a list as input from user
While taking a list as an input from the user, the input is SUPPOSED to be enclosed within square brackets as opposed to just typing the numbers
This is my code for taking multiple inputs from the user for a list

```<code>a = list(map(int,input().strip().split(', ')))
</code>```

The default input is [1, 2, 3, 4].
When I run my code, I get an error as:

```<code>ValueError: invalid literal for int() with base 10: '[1'
</code>```

I know the reason it's happening is because '[1' is a an element that cannot be converted into int and it  (the square bracket and 1) is being regarded as the first element of the list at index 0.
Having the square bracket is absolutely essential for me, how can I resolve the error or just ignore the square brackets? Is there an ignore method or something similar that might work?
Cheers!

答:
You could remove it from the string before converting it to int:

```<code>a = list(map(int,
             input()
             .strip()
             .replace('[', '')
             .replace(']', '')
             .split(', ')
            )
        )
</code>```

or you could also use a regular expression to get out all the numbers:

```<code>import re
a = list(map(int, re.findall(r'\d+', input())))
</code>```

Title: Taking a list as input from user

Body:
While taking a list as an input from the user, the input is SUPPOSED to be enclosed within square brackets as opposed to just typing the numbers
This is my code for taking multiple inputs from the user for a list

a = list(map(int,input().strip().split(', ')))

The default input is [1, 2, 3, 4].
When I run my code, I get an error as:

ValueError: invalid literal for int() with base 10: '[1'

I know the reason it's happening is because '[1' is a an element that cannot be converted into int and it  (the square bracket and 1) is being regarded as the first element of the list at index 0.
Having the square bracket is absolutely essential for me, how can I resolve the error or just ignore the square brackets? Is there an ignore method or something similar that might work?
Cheers!

Body:
You could remove it from the string before converting it to int:

a = list(map(int,
             input()
             .strip()
             .replace('[', '')
             .replace(']', '')
             .split(', ')
            )
        )

or you could also use a regular expression to get out all the numbers:

import re
a = list(map(int, re.findall(r'\d+', input())))


问:
Keep getting stuck loading when ScrapySharp NavigateToPage
My browser just keeps loading when navigatetopage using scrapysharp and won't go to the next line of code. Below is my code using c# asp.net web form. May I know why? The link I use is working and can manually browse. The code just gets stuck at the Browser.NavigateToPage(new Uri("http://www.asnb.com.my/v3_/asnbv2_0index.php")); and keep loading in the browser. And I am using asp.net webform.

```<code>ScrapingBrowser Browser = new ScrapingBrowser();
Browser.AllowAutoRedirect = true;
Browser.AllowMetaRedirect = true;

WebPage PageResult = Browser.NavigateToPage(new Uri("http://www.asnb.com.my/v3_/asnbv2_0index.php"));
HtmlNode TitleNode = PageResult.Html.CssSelect(".navbar-brand").First();
</code>```

答:
Another method would be to use the async version of the NavigateToPage eg:</p>

```<code>private async Task<WebPage> LoadPage(Uri uri)
{
    WebPage page = await browser.NavigateToPageAsync(uri);
    return page;
}
</code>```

Body:
My browser just keeps loading when navigatetopage using scrapysharp and won't go to the next line of code. Below is my code using c# asp.net web form. May I know why? The link I use is working and can manually browse. The code just gets stuck at the Browser.NavigateToPage(new Uri("http://www.asnb.com.my/v3_/asnbv2_0index.php")); and keep loading in the browser. And I am using asp.net webform.

ScrapingBrowser Browser = new ScrapingBrowser();
Browser.AllowAutoRedirect = true;
Browser.AllowMetaRedirect = true;

WebPage PageResult = Browser.NavigateToPage(new Uri("http://www.asnb.com.my/v3_/asnbv2_0index.php"));
HtmlNode TitleNode = PageResult.Html.CssSelect(".navbar-brand").First();

Body:
Another method would be to use the async version of the NavigateToPage eg:

private async Task<WebPage> LoadPage(Uri uri)
{
    WebPage page = await browser.NavigateToPageAsync(uri);
    return page;
}


问:
How to send a single Ajax request instead of two
I have a JSP page which has a form with an input text. When I submit, it goes to a servlet. The servlet processes and creates some objects and sets in request using request.setAttribute(). It then forwards to a page which has some custom JSP tags which use the objects set in servlet.

I want to replace this by Ajax. I have implemented it as follows:

First, the form is submitted through Ajax using POST, the objects which were set earlier using request.setAttribute() are converted to JSON string and sent as response. On success, there is another Ajax GET call to a JSP page which has my custom tags and the JSON string is passed as parameter. The response of this Ajax call is set inside a div.

But it are two Ajax requests. How can I make it a single Ajax request instead?

答:
As per the comments, you just need to let the first request forward to the desired JSP instead of returning the JSON string which you in turn pass back to the JSP.</p>

```<code>request.getRequestDispatcher("/WEB-INF/next.jsp?jsonstring=" + jsonstring).forward(request, response);
</code>```

Body:
As per the comments, you just need to let the first request forward to the desired JSP instead of returning the JSON string which you in turn pass back to the JSP.

request.getRequestDispatcher("/WEB-INF/next.jsp?jsonstring=" + jsonstring).forward(request, response);


问:
Creating a JSON object with name of the JSON file and its content in bash
I have a few .json files in my directory. If I do:

```<code>find . -name '*.json' -exec echo "{\"filename\": \"{}\", \"content\": `cat {}` }," \;
</code>```

I get:

```<code>{"filename": "./a.json", "content":  },
{"filename": "./b.json", "content":  },
</code>```

However, if I do:

```<code>find . -name '*.json' -exec echo "{\"filename\": \"{}\", \"content\": cat {} }," \;
</code>```

I get:

```<code>{"filename": "./a.json", "content": cat ./a.json },
{"filename": "./b.json", "content": cat ./b.json },
</code>```

so how do I make the a.json and b.json contents be cated correctly ?

BTW, if I do:

```<code>find . -name '*.json' -exec cat {} \;
</code>```

the json files are correctly printed in the console, so I know that the file contents are valid.

答:
Using bash without find you can do below. You can use nullglob and globstar for recursive JSON file name traversal

```<code>shopt -s nullglob globstar
</code>```

By default jq provides a function input_filename which prints the filename being processed currently. The documentation says, it should work fine as long as the locale is UTF-8

```<code>jq '{ filename: input_filename, content: . }' **/*.json
</code>```

To have a comma between the object entries, use the -n flag with inputs and put the entire result in an array [..]

```<code>jq -n '[inputs | { filename: input_filename, content: . }]' **/*.json
</code>```

For compact output on the same line, use the -c flag as jq -c '..'

Body:
I have a few .json files in my directory. If I do:

find . -name '*.json' -exec echo "{\"filename\": \"{}\", \"content\": `cat {}` }," \;

I get:

{"filename": "./a.json", "content":  },
{"filename": "./b.json", "content":  },

However, if I do:

find . -name '*.json' -exec echo "{\"filename\": \"{}\", \"content\": cat {} }," \;

I get:

{"filename": "./a.json", "content": cat ./a.json },
{"filename": "./b.json", "content": cat ./b.json },

so how do I make the a.json and b.json contents be cated correctly ?

BTW, if I do:

find . -name '*.json' -exec cat {} \;

the json files are correctly printed in the console, so I know that the file contents are valid.

Body:
Using bash without find you can do below. You can use nullglob and globstar for recursive JSON file name traversal

shopt -s nullglob globstar

By default jq provides a function input_filename which prints the filename being processed currently. The documentation says, it should work fine as long as the locale is UTF-8

jq '{ filename: input_filename, content: . }' **/*.json

To have a comma between the object entries, use the -n flag with inputs and put the entire result in an array [..]

jq -n '[inputs | { filename: input_filename, content: . }]' **/*.json

For compact output on the same line, use the -c flag as jq -c '..'