问:
Can't remotely connect to Python Socket
I have created a chat application using python sockets and Tkinter and it all works perfectly locally however the Client is unable to connect to the server remotely (when I enter my public IP address as the host) I have already fully port-forwarded my network and I know how to port forward very well and when I run an online Port Open scanner that checks if a port is open it states that the port is open!?

I have port-forwarded my router on a number of ports and updating the client and server accordingly however the client and telnet could still not connect..  I have also disabled all my windows firewalls and I disabled all of the routers firewalls.

Here is a very simple socket client and server model which I am trying to troubleshoot my problem using.

Server

```<code>import socket

s = socket.socket()
host='0.0.0.0'

port = 2000
s.bind((host,port))

s.listen(5)
while True:
    c, addr = s.accept()
    print ("Got a connection from: ", addr)
    c.send(bytes("Thanks for connecting",'utf8'))
    c.close()

</code>```

Client

```<code>import socket

s = socket.socket()
port = 2000

s.connect(("109.156.114.183", port))
print (s.recv(1024))
s.close
</code>```

Telnet

```<code>C:\Users\Maks>telnet 109.156.114.183 2000
Connecting To 109.156.114.183...Could not open connection to the host, on port 2000: Connect failed
</code>```

When I try to connect to the server on 127.0.0.1 or localhost or from within my local network the client connects perfectly and telnet can connect as well. I am 200% sure I have port forwarded correctly because when I run a Port Open scan it says that the port(2000) is open.

Please help!
Thanks-
Maks

答:
I'm at home so there's no firewalls running on my network at all.

That comment was the missing piece to solve your problem. You actually don't connect from remote as your question implies but you try to connect from inside your local network to the externally visible address of your router.

Such a setup is supported by some routers and not by others. It looks like you router does not support it. For more information on this see NAT hairpinning (or NAT loopback).

Title: Can't remotely connect to Python Socket

Body:
I have created a chat application using python sockets and Tkinter and it all works perfectly locally however the Client is unable to connect to the server remotely (when I enter my public IP address as the host) I have already fully port-forwarded my network and I know how to port forward very well and when I run an online Port Open scanner that checks if a port is open it states that the port is open!?

I have port-forwarded my router on a number of ports and updating the client and server accordingly however the client and telnet could still not connect..  I have also disabled all my windows firewalls and I disabled all of the routers firewalls.

Here is a very simple socket client and server model which I am trying to troubleshoot my problem using.

Server

import socket

s = socket.socket()
host='0.0.0.0'

port = 2000
s.bind((host,port))

s.listen(5)
while True:
    c, addr = s.accept()
    print ("Got a connection from: ", addr)
    c.send(bytes("Thanks for connecting",'utf8'))
    c.close()

Client

import socket

s = socket.socket()
port = 2000

s.connect(("109.156.114.183", port))
print (s.recv(1024))
s.close

Telnet

C:\Users\Maks>telnet 109.156.114.183 2000
Connecting To 109.156.114.183...Could not open connection to the host, on port 2000: Connect failed

When I try to connect to the server on 127.0.0.1 or localhost or from within my local network the client connects perfectly and telnet can connect as well. I am 200% sure I have port forwarded correctly because when I run a Port Open scan it says that the port(2000) is open.

Please help!
Thanks-
Maks


来源: stackexchange

问:
Does pull request in Azure devops merge the code and then runs the build definition
I have feature branch feature/feature1 and dev branch. I created a branch policy for dev branch where I have selected a build definition.

When I initiate a pull request from feature/feature1 to dev does it merge the 2 branches and then does the build? Or does it just build feature/feature1?

```<code> * [new branch]      dev                -> origin/dev
 * [new branch]      feature/feature2   -> origin/feature/feature2
 * [new branch]      feature/test       -> origin/feature/test
 * [new branch]      master             -> origin/master
 * [new branch]      release/release-1  -> origin/release/release-1
 * [new branch]      release/release-2  -> origin/release/release-2
 * [new ref]         refs/pull/37/merge -> pull/37/merge
##[command]git checkout --progress --force refs/remotes/pull/37/merge
Note: checking out 'refs/remotes/pull/37/merge'.
</code>```

答:
with branch policies when you initiate a PR build it does the merge and then does the actual build

Real merge only happens on PR completion

ContentLicense: CC BY-SA 4.0

Body:
I have feature branch feature/feature1 and dev branch. I created a branch policy for dev branch where I have selected a build definition.

When I initiate a pull request from feature/feature1 to dev does it merge the 2 branches and then does the build? Or does it just build feature/feature1?

 * [new branch]      dev                -> origin/dev
 * [new branch]      feature/feature2   -> origin/feature/feature2
 * [new branch]      feature/test       -> origin/feature/test
 * [new branch]      master             -> origin/master
 * [new branch]      release/release-1  -> origin/release/release-1
 * [new branch]      release/release-2  -> origin/release/release-2
 * [new ref]         refs/pull/37/merge -> pull/37/merge
##[command]git checkout --progress --force refs/remotes/pull/37/merge
Note: checking out 'refs/remotes/pull/37/merge'.


问:
checking if the plot hit a number or not?
How to check for any given number how many times a plot hit that number horizontally and get higher?

I have already tried:

```<code>  import os
import numpy as np
import pylab as plt
import pandas as pd
df = pd.read_csv('C:/Users/Payam/Desktop/tesla-stock-price.csv')
df['avg'] = df[['high', 'low']].mean(axis=1)
e=df['avg'].values
x = df['date'].values
y = df['close'].values
z = df['open'].values

f, ax = plt.subplots(figsize=(20,10))
ax.plot(x,y,'b')
ax.set_xticks(x[::150]);
plt.xticks(rotation=90)
ax.plot(np.arange(len(x)),np.zeros(len(x))+50,'k.')

</code>```

答:
Given some test array

```<code>test_array=np.array([1,6,8,65,4,2,5,8,9,6,4,6,9,0,8,6,4,32,])
</code>```

you can get all indices where the value is greater than a number, say 5, like so

```<code>print (np.where(test_array>5))
print (test_array[np.where(test_array>5)])
</code>```

Body:
How to check for any given number how many times a plot hit that number horizontally and get higher?

I have already tried:

  import os
import numpy as np
import pylab as plt
import pandas as pd
df = pd.read_csv('C:/Users/Payam/Desktop/tesla-stock-price.csv')
df['avg'] = df[['high', 'low']].mean(axis=1)
e=df['avg'].values
x = df['date'].values
y = df['close'].values
z = df['open'].values

f, ax = plt.subplots(figsize=(20,10))
ax.plot(x,y,'b')
ax.set_xticks(x[::150]);
plt.xticks(rotation=90)
ax.plot(np.arange(len(x)),np.zeros(len(x))+50,'k.')

Body:
Given some test array

test_array=np.array([1,6,8,65,4,2,5,8,9,6,4,6,9,0,8,6,4,32,])

you can get all indices where the value is greater than a number, say 5, like so

print (np.where(test_array>5))
print (test_array[np.where(test_array>5)])


问:
What is the quickest way from a concept to a site?
I've got a bunch of website ideas and I was wondering what is the quickest way to get from a pretty thorough concept definition (idea mind-maps, use-cases, architecture diagrams ) to a working website. The only point is to get to something that's functional, not worrying about performance. The idea is to get something out to showcase a functional site, and after worry about fine-tuning or re-writing parts if necessary.

I am familiar with quite a few web frameworks from open-source and proprietary world, but I could not find so far a swiss-army-knife of web development environments that can get you fast from a concept to a working site.  I was kinda wondering if there is such a thing, free or non-free

Looking forward to your suggestions...

UPDATE: The question might get a bit too metaphoric for the kind readers of this site, but I'm at a moment where I feel that implementation details are killing my creativity ... maybe you'll laugh or you'll feel offended, I'm just wondering if anyone can give me a useful hint..

答: There really is no quick way of doing this. If you are looking for investors or people to work on the site with then a detailed spec will have to do. If you need more then you are just going to have to start writing the real site. In this case you need to use whatever you know you can use to produce a site quickly. The framework itself is far less important than your experience with it. </p>

OwnerDisplayName: Cip

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: JayArr


问:
Dynamically select based on List of columns
I have a List of columns model as below:

```
    class ColumnSettings
    {
    public string Title { get; set; }
    public string Width { get; set; }
    public string Field { get; set; }
    public string Format { get; set;}
    public bool Hidden { get; set; }
    }
```

I have an stored procedure to return users list (GetUserList), and when I query the database, the data is returned with 30 columns.

I dynamically select visible columns in view and pass columns to controller and convert to List of ColumnSettings and set modelData variable.

I want to select those columns that are in modelData variable, something like :

GetUserList.select(s => s.???)

I make problem easier. Suppose I have a grid and I want create Excel file on sever-side. I pass columns to controller, and have a list of columns (List) and then I call SP and get 30 columns, but I don't want all columns and it should be dynamic.

答: Make your property with dynamic keyword and it will except all over the class which you want make as dynamic.</p>

Body:
I have a List of columns model as below:

    class ColumnSettings
    {
    public string Title { get; set; }
    public string Width { get; set; }
    public string Field { get; set; }
    public string Format { get; set;}
    public bool Hidden { get; set; }
    }

I have an stored procedure to return users list (GetUserList), and when I query the database, the data is returned with 30 columns.

I dynamically select visible columns in view and pass columns to controller and convert to List of ColumnSettings and set modelData variable.

I want to select those columns that are in modelData variable, something like :

GetUserList.select(s => s.???)

I make problem easier. Suppose I have a grid and I want create Excel file on sever-side. I pass columns to controller, and have a list of columns (List) and then I call SP and get 30 columns, but I don't want all columns and it should be dynamic.


问:
Uploading similar apps on Google Play and App Store
We have a company that helps people create apps for their websites, and we complately rely on webview technology, and push notifications.

We use one developer account to upload all our clients apps to both Google Play and App Store

Would this be considered illegal? Are there any restrictions on uploading similar functionality apps (webviews)?

答:
Android: I don't think there is any restriction for that.

iOS: You can't do that. As per the AppStore Review Guideline, you can't upload apps on behalf of your clients. Also if those apps have similar functionality and looks same, apple will reject those apps (I had two web-view based application for the same client with similar functionality and Apple rejected the second app when submitted for approval)

4.2.6 Apps created from a commercialized template or app generation service will be rejected unless they are submitted directly by the
  provider of the app’s content. These services should not submit apps
  on behalf of their clients and should offer tools that let their
  clients create customized, innovative apps that provide unique
  customer experiences. Another acceptable option for template providers
  is to create a single binary to host all client content in an
  aggregated or “picker” model, for example as a restaurant finder app
  with separate customized entries or pages for each client restaurant,
  or as an event app with separate entries for each client event.


问:
Python While Loop, also using modulo and continue commands
Attempting to finish this task that asks me to:

"Write a while loop that calculates the sum of the integers from 1 to 20 (inclusive), excluding those integers evenly divisible by 3. (Hint: You'll find the modulo operator (%) and the continue statement handy for this.)

I've attempted to construct the code myself, but the evaluation of the code times out. I'm guessing my syntax is incorrect and is causing an infinite loop

```<code>    total, x = 0, 1
    while x >=1 and x <= 20:
        if x%3==0:
            continue
        if x%3 != 0:
            print(x)
            x+=1
            total+=1
    print(total)
</code>```

The expected answer should be:

20
19
17
16
14
13
11
10
8
7
5
4
2
1

But I just get 'Timed out' errors

***Latest::

Attempted this:

```<code>total, x = 0, 1
while x>=1 and x<=20:
    if x%3 == 0:
        x+=1
        continue
    if x%3 != 0:
       print(x)
       x+=1
       total=+1
print(total)
</code>```

Received this::

```<code>Traceback (most recent call last):
   File "/usr/src/app/test_methods.py", line 23, in test
    self.assertEqual(self._output(), "147\n")
AssertionError:     '1\n2\n4\n5\n7\n8\n10\n11\n13\n14\n16\n17\n19\n20\n1\n' != '147\n'
</code>```

- 1
- 2
- 4
- 5
- 7
- 8
- 10
- 11
- 13
- 14
+ 147
?   +
- 16
- 17
- 19
- 20
- 1

答:
You are not incrementing x inside first if statement, hence it is stuck at that value and loops forever. You can try this.

```<code>total, x = 0, 1
while x >=1 and x <= 20:
    if x%3==0:
        x+=1  # incrementing x here
        continue
    elif x%3 != 0:  # using an else statement here would be recommended
        print(x)
        x+=1
        total+=x  # we are summing up all x's here
print(total)
</code>```

Alternately, you can increment x outside if statements. You can use range() as well. Here, we are simply ignoring x which are divisible by 3.

```<code>total, x = 0, 1
for x in range(1, 21):
    if x%3 != 0:
        print(x)
        x+=1
        total+=x
print(total)
</code>```

Body:
Attempting to finish this task that asks me to:

"Write a while loop that calculates the sum of the integers from 1 to 20 (inclusive), excluding those integers evenly divisible by 3. (Hint: You'll find the modulo operator (%) and the continue statement handy for this.)

I've attempted to construct the code myself, but the evaluation of the code times out. I'm guessing my syntax is incorrect and is causing an infinite loop

    total, x = 0, 1
    while x >=1 and x <= 20:
        if x%3==0:
            continue
        if x%3 != 0:
            print(x)
            x+=1
            total+=1
    print(total)

The expected answer should be:

20
19
17
16
14
13
11
10
8
7
5
4
2
1

But I just get 'Timed out' errors

***Latest::

Attempted this:

total, x = 0, 1
while x>=1 and x<=20:
    if x%3 == 0:
        x+=1
        continue
    if x%3 != 0:
       print(x)
       x+=1
       total=+1
print(total)

Received this::

Traceback (most recent call last):
   File "/usr/src/app/test_methods.py", line 23, in test
    self.assertEqual(self._output(), "147\n")
AssertionError:     '1\n2\n4\n5\n7\n8\n10\n11\n13\n14\n16\n17\n19\n20\n1\n' != '147\n'

- 1
- 2
- 4
- 5
- 7
- 8
- 10
- 11
- 13
- 14
+ 147
?   +
- 16
- 17
- 19
- 20
- 1

Body:
You are not incrementing x inside first if statement, hence it is stuck at that value and loops forever. You can try this.

total, x = 0, 1
while x >=1 and x <= 20:
    if x%3==0:
        x+=1  # incrementing x here
        continue
    elif x%3 != 0:  # using an else statement here would be recommended
        print(x)
        x+=1
        total+=x  # we are summing up all x's here
print(total)

Alternately, you can increment x outside if statements. You can use range() as well. Here, we are simply ignoring x which are divisible by 3.

total, x = 0, 1
for x in range(1, 21):
    if x%3 != 0:
        print(x)
        x+=1
        total+=x
print(total)


问:
Comparison with the previous line and summation
There is a table in dataframe:

```<code>X1  X2
1   1
1   2
1   3
2   2
2   2
1   2
</code>```

It is necessary for each line calculate the value Y, where Y = X2(previous line)+1 if X1=X1(previous line), elso 0. Result:

```<code>X1  X2  Y
1   1   0
1   2   2
1   3   3
2   2   0
2   2   3
1   2   0
</code>```

答:
Use:

```<code>m = df['X1'].shift().eq(df['X1'])
df['Y'] = np.where(m, df['X2'].shift().add(1), 0).astype(int)
print (df)
   X1  X2  Y
0   1   1  0
1   1   2  2
2   1   3  3
3   2   2  0
4   2   2  3
5   1   2  0
</code>```

Details:

First compare by Series.shifted valeus by Series.eq for equality:

```<code>m = df['X1'].shift().eq(df['X1'])
print (m)
0    False
1     True
2     True
3    False
4     True
5    False
Name: X1, dtype: bool
</code>```

Then shift column X2, add 1:

```<code>print (df['X2'].shift().add(1))
0    NaN
1    2.0
2    3.0
3    4.0
4    3.0
5    3.0
Name: X2, dtype: float64
</code>```

And set new column by numpy.where:

```<code>print (np.where(m, df['X2'].shift().add(1), 0))
[0. 2. 3. 0. 3. 0.]
</code>```

Another solution by @Divakar:

```<code>df['Y'] = df.X1.shift().eq(df.X1)*(df.X2+1).shift().fillna(0).astype(int)
#pandas 0.24+
#df['Y'] = df.X1.shift().eq(df.X1)*(df.X2+1).shift(fill_value=0)
print (df)
   X1  X2  Y
0   1   1  0
1   1   2  2
2   1   3  3
3   2   2  0
4   2   2  3
5   1   2  0
</code>```

Body:
There is a table in dataframe:

X1  X2
1   1
1   2
1   3
2   2
2   2
1   2

It is necessary for each line calculate the value Y, where Y = X2(previous line)+1 if X1=X1(previous line), elso 0. Result:

X1  X2  Y
1   1   0
1   2   2
1   3   3
2   2   0
2   2   3
1   2   0

Body:
Use:

m = df['X1'].shift().eq(df['X1'])
df['Y'] = np.where(m, df['X2'].shift().add(1), 0).astype(int)
print (df)
   X1  X2  Y
0   1   1  0
1   1   2  2
2   1   3  3
3   2   2  0
4   2   2  3
5   1   2  0

Details:

First compare by Series.shifted valeus by Series.eq for equality:

m = df['X1'].shift().eq(df['X1'])
print (m)
0    False
1     True
2     True
3    False
4     True
5    False
Name: X1, dtype: bool

Then shift column X2, add 1:

print (df['X2'].shift().add(1))
0    NaN
1    2.0
2    3.0
3    4.0
4    3.0
5    3.0
Name: X2, dtype: float64

And set new column by numpy.where:

print (np.where(m, df['X2'].shift().add(1), 0))
[0. 2. 3. 0. 3. 0.]

Another solution by @Divakar:

df['Y'] = df.X1.shift().eq(df.X1)*(df.X2+1).shift().fillna(0).astype(int)
#pandas 0.24+
#df['Y'] = df.X1.shift().eq(df.X1)*(df.X2+1).shift(fill_value=0)
print (df)
   X1  X2  Y
0   1   1  0
1   1   2  2
2   1   3  3
3   2   2  0
4   2   2  3
5   1   2  0


问:
Invalid syntax on colon
I'm writing up a program involving speed limit and whatnot with while and if statements. I'm tryna make it so that after outputting the result, it asks if I want to redo the program with a while loop.

I heard that occurs if I have one too many brackets or an open bracket. All my brackets were fine.

ques1 = int(input('What speed is the car travelling? '))
check = ques1

running = True
while running == True:
    if 0 <= check <= 50:
        print('You are clear.')

    if 51 <= check <= 60:
        print('10 demerit points')

    if 61 <= check <= 70:
        print('20 demerit points')

    if 71 <= check <= 80:
        print('30 demerit points')

    if 81 <= check <= 90:
        print('50 demerit points')

    if 91 <= check <= 1000:
        print("100 demerit points")

    dasques = input('Do you want to try again? y/n '):
        if dasques == ('n'):
            running = False

```

<p><strong>Expected output:</strong></p>

```Hoping to get :
50 demerit points
Do you want to try again? y/n
```

but I'm getting

"invalid syntax" with the colon behind:
       [ dasques = input('Do you want to try again? y/n '):]

highlighted in red.

答:
Please change below lines of code</p>

```<code>dasques = input('Do you want to try again? y/n ')
if dasques == ('n'):
   running = False
</code>```

Title: Invalid syntax on colon

Body:
I'm writing up a program involving speed limit and whatnot with while and if statements. I'm tryna make it so that after outputting the result, it asks if I want to redo the program with a while loop.

I heard that occurs if I have one too many brackets or an open bracket. All my brackets were fine.

ques1 = int(input('What speed is the car travelling? '))
check = ques1

running = True
while running == True:
    if 0 <= check <= 50:
        print('You are clear.')

    if 51 <= check <= 60:
        print('10 demerit points')

    if 61 <= check <= 70:
        print('20 demerit points')

    if 71 <= check <= 80:
        print('30 demerit points')

    if 81 <= check <= 90:
        print('50 demerit points')

    if 91 <= check <= 1000:
        print("100 demerit points")

    dasques = input('Do you want to try again? y/n '):
        if dasques == ('n'):
            running = False

Expected output:

Hoping to get :
50 demerit points
Do you want to try again? y/n

but I'm getting

"invalid syntax" with the colon behind:
       [ dasques = input('Do you want to try again? y/n '):]

highlighted in red.

Body:
Please change below lines of code

dasques = input('Do you want to try again? y/n ')
if dasques == ('n'):
   running = False


问:
Creating JDBC functions from corresponding WSDL
I am working on building a web service from scratch with JDBC for postgreSQL. thing is that the operations given in the wsdl file do not show the corresponding database relation (Schema was provided by the client). i.e. for a message like

message name="loginRequest">

part name="in0" type="xsd:string"/>

part name="in1" type="xsd:string"/>

/message>

I cannot find out the corresponding column or what the parameters map on to.

Any solution?

P.S.I had to remove "<"

答:
JDBC is an interface for databases. It can be used for both WebService server and client, but it cannot be used to parse WebService queries etc. You will have to use other library/technology like axis2.

In axis2 there is wsdl2java utility which can create server or client code "skeleton". In those sources you can use JDBC libraries to make database queries.

ContentLicense: CC BY-SA 3.0


答:
you can use:

```<code>c1=df.X1.ne(df.X1.shift()) #checks for changes in X1 column
</code>```

Then we see wherever there is no change in X1, take previous row and add 1, else 0. Using np.where()

```<code>df['Y']=np.where(~c1,df.X2.shift()+1,0).astype(int)
print(df)
</code>```

```<code>   X1  X2  Y
0   1   1  0
1   1   2  2
2   1   3  3
3   2   2  0
4   2   2  3
5   1   2  0
</code>```

Title: Comparison with the previous line and summation

Body:
you can use:

c1=df.X1.ne(df.X1.shift()) #checks for changes in X1 column

Then we see wherever there is no change in X1, take previous row and add 1, else 0. Using np.where()

df['Y']=np.where(~c1,df.X2.shift()+1,0).astype(int)
print(df)

   X1  X2  Y
0   1   1  0
1   1   2  2
2   1   3  3
3   2   2  0
4   2   2  3
5   1   2  0


问:
How to tell if Github code repo contains malicious code?
I am considering adding this repository to my project.

Install

```<code>npm i react-shields-badge --save
yarn add react-shields-badge --save
</code>```

Getting Started

```<code>import Badge from "react-shields-badge";
import "react-shields-badge/dist/react-shields-badge.css";

<Badge data={["npm", "v1.0.0"]} />
</code>```

Before I do, how can I ensure there is no malicious code contained in that repo that might damage my app or do anything I don't intend it to do? (It only has like one download on NPM.)

Is there any web site for that? Or a script, program or command I can run, say, from my terminal?

答:
how can I ensure there is no malicious code contained in that repo that might damage my app or do anything I don't intend it to do?

That's impossible.  How could software (or even a human) know what you intend to do?

Is there any web site for that?

No, there isn't.

Or a script, program or command I can run, say, from my terminal?

Ah, yes, the magic read-my-mind.js script...

Computers just do what we tell them.  The concept of maliciousness isn't one computers and code care about.  You could have a situation where even just a README file makes otherwise harmless code into malicious code.  For example, perhaps the README says to rm -rf everything, and for whatever reason you or someone else follows it.  That's not even in the code, and is quite dangerous.

The good news is that you can audit the code yourself.  You can also check in node_modules in your version control, if you wanted to ensure that nothing changes.  (We do have NPM and Yarn lockfiles for this, but just ensuring the exact same copy of all modules is installed is another way to solve the issue of changing un-audited depencies.)

Body:
I am considering adding this repository to my project.

Install

npm i react-shields-badge --save
yarn add react-shields-badge --save

Getting Started

import Badge from "react-shields-badge";
import "react-shields-badge/dist/react-shields-badge.css";

<Badge data={["npm", "v1.0.0"]} />

Before I do, how can I ensure there is no malicious code contained in that repo that might damage my app or do anything I don't intend it to do? (It only has like one download on NPM.)

Is there any web site for that? Or a script, program or command I can run, say, from my terminal?


问:
Character to unquoted
Sometimes data files come in .rdata objects. These are annoying compared to .rds files because the objects have predefined names. In my case, I want to rename the object automatically and get rid of the wrongly named version. Simple somewhat contrived example:

```<code>#make a new iris with a bad name
badnameiris = iris
#save it to a file
save(badnameiris, file = "iris.rdata")
#rename badname version from global envir
rm(badnameiris)
#read iris from file
irisname = load("iris.rdata")
#this variable is not iris, but the name of the variable it was assigned to
irisname
[1] "badnameiris"
#it's to use the right name with get()
goodnameiris = get(irisname)
#but harder to get rid of the wrong one with rm()
rm(irisname)
</code>```

The last line does not work as intended because it requires a bare name as input and it gets a character vector. I realize one can actually use the list argument in rm(), but suppose one could not.

How does one in general convert from character to unquoted for these purposes?

I tried the rlang functions, but these are for non-standard evaluation as used in tidyverse context. I tried as.name(), as suggested here. Does not work either. Most questions I could find asking this question relate to tidyverse, but I'm trying to do base R context.

(An alternative solution above is to make a function that utilizes the destruction of the local environment to remove the unwanted copy of the object.)

答:
Just use do.call:

```<code>x <- 1
s <- "x"
do.call(rm, list(s))
ls()
#[1] "s"
</code>```

Or compute on the language:

```<code>eval(bquote(rm(.(s))))
</code>```

Title: Character to unquoted

Body:
Sometimes data files come in .rdata objects. These are annoying compared to .rds files because the objects have predefined names. In my case, I want to rename the object automatically and get rid of the wrongly named version. Simple somewhat contrived example:

#make a new iris with a bad name
badnameiris = iris
#save it to a file
save(badnameiris, file = "iris.rdata")
#rename badname version from global envir
rm(badnameiris)
#read iris from file
irisname = load("iris.rdata")
#this variable is not iris, but the name of the variable it was assigned to
irisname
[1] "badnameiris"
#it's to use the right name with get()
goodnameiris = get(irisname)
#but harder to get rid of the wrong one with rm()
rm(irisname)

The last line does not work as intended because it requires a bare name as input and it gets a character vector. I realize one can actually use the list argument in rm(), but suppose one could not.

How does one in general convert from character to unquoted for these purposes?

I tried the rlang functions, but these are for non-standard evaluation as used in tidyverse context. I tried as.name(), as suggested here. Does not work either. Most questions I could find asking this question relate to tidyverse, but I'm trying to do base R context.

(An alternative solution above is to make a function that utilizes the destruction of the local environment to remove the unwanted copy of the object.)

Body:
Just use do.call:

x <- 1
s <- "x"
do.call(rm, list(s))
ls()
#[1] "s"

Or compute on the language:

eval(bquote(rm(.(s))))


问:
basinhopping_bounds() got an unexpected keyword argument 'f_new'
I'm getting this error when using basin-hopping:
basinhopping_bounds() got an unexpected keyword argument 'f_new'

I'm trying to implement the analysis of X,F models in Python to solving a DTLZ7 problem.

So, I've started with a problem with 4 linear FO, which the result I know. When trying to solve the problem using basin-hopping for global minimization, I'm getting the error above (scipy-1.2.1.). Does anybody knows what is going wrong?

Here follows part of the code:

f1 = f_linear([0.06, 0.53, 0.18, 0.18, 0.06], "max")
f2 = f_linear([25, 70, 60, 95, 45], "max")
f3 = f_linear([0, 32.5, 300, 120, 0], "min")
f4 = f_linear([0.1, 0.1, 0.11, 0.35, 0.33], "min")
```

<pre class="lang-py prettyprint-override"><code>A_eq = np.array([[1, 1, 1, 1, 1]])
b_eq = np.array([3000])
x0_bounds = (0, 850)
x1_bounds = (0, 220)
x2_bounds = (0, 1300)
x3_bounds = (0, 1615)
x4_bounds = (0, 700)
F = [f1, f2, f3, f4]
</code>```

def mu_D(x, F):
    x = np.array(x)
    return max([f_.mu(x) for f_ in F])
```

<pre class="lang-py prettyprint-override"><code>def basinhopping_bounds(x):
    resp = True
    if np.dot(x, A_eq[0]) != b_eq[0]:
        resp = False
    if x[0] < x0_bounds[0] or x[0] > x0_bounds[1]:
        resp = False
    if x[1] < x1_bounds[0] or x[1] > x1_bounds[1]:
        resp = False
    if x[2] < x2_bounds[0] or x[2] > x2_bounds[1]:
        resp = False
    if x[3] < x3_bounds[0] or x[3] > x3_bounds[1]:
        resp = False
    if x[4] < x4_bounds[0] or x[4] > x4_bounds[1]:
        resp = False
    return resp

cobyla_constraints = [
    {"type": "ineq", "fun": lambda x: x[0]},
    {"type": "ineq", "fun": lambda x: x0_bounds[1] - x[0]},
    {"type": "ineq", "fun": lambda x: x[1]},
    {"type": "ineq", "fun": lambda x: x1_bounds[1] - x[1]},
    {"type": "ineq", "fun": lambda x: x[2]},
    {"type": "ineq", "fun": lambda x: x2_bounds[1] - x[2]},
    {"type": "ineq", "fun": lambda x: x[3]},
    {"type": "ineq", "fun": lambda x: x3_bounds[1] - x[3]},
    {"type": "ineq", "fun": lambda x: x[4]},
    {"type": "ineq", "fun": lambda x: x4_bounds[1] - x[4]},
    {"type": "eq", "fun": lambda x: np.dot(x, A_eq[0]) - b_eq[0]},
]
</code>```

minimizer_kwargs = {"args": F, "method": "SLSQP", "constraints": cobyla_constraints}
opt.basinhopping(
    mu_D,
    f1.x_max,
    minimizer_kwargs=minimizer_kwargs,
    accept_test=basinhopping_bounds,
    disp=True,
)
```

```basinhopping step 0: f 1

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-ba4f3efaec5d> in <module>
      5     minimizer_kwargs=minimizer_kwargs,
      6     accept_test=basinhopping_bounds,
----> 7     disp=True,
      8 )

~/anaconda3/lib/python3.6/site-packages/scipy/optimize/_basinhopping.py in basinhopping(func, x0, niter, T, stepsize, minimizer_kwargs, take_step, accept_test, callback, interval, disp, niter_success, seed)
    674                " successfully"]
    675     for i in range(niter):
--> 676         new_global_min = bh.one_cycle()
    677
    678         if callable(callback):

~/anaconda3/lib/python3.6/site-packages/scipy/optimize/_basinhopping.py in one_cycle(self)
    152         new_global_min = False
    153
--> 154         accept, minres = self._monte_carlo_step()
    155
    156         if accept:

~/anaconda3/lib/python3.6/site-packages/scipy/optimize/_basinhopping.py in _monte_carlo_step(self)
    127         for test in self.accept_tests:
    128             testres = test(f_new=energy_after_quench, x_new=x_after_quench,
--> 129                            f_old=self.energy, x_old=self.x)
    130             if testres == 'force accept':
    131                 accept = True

TypeError: basinhopping_bounds() got an unexpected keyword argument 'f_new'

```

答:
https://docs.scipy.org/doc/scipy-0.19.0/reference/generated/scipy.optimize.basinhopping.html

This docs describes the accept_test argument.  It must be callable that recognizes a set of keyword arguments (or at least doesn't choke when given them):

```<code>accept_test : callable, accept_test(f_new=f_new, x_new=x_new, f_old=fold, x_old=x_old), optional

Define a test which will be used to judge whether or not to accept the step.
This will be used in addition to the Metropolis test based on “temperature” T.
The acceptable return values are True, False, or "force accept". If any of the
tests return False then the step is rejected. If the latter, then this will
override any other tests in order to accept the step. This can be used, for
example, to forcefully escape from a local minimum that basinhopping is
trapped in.
</code>```

Your function only takes on positional argument:

```<code>def basinhopping_bounds(x):
</code>```

You can also see how minimize calls your function in the error traceback:

```<code>testres = test(f_new=energy_after_quench, x_new=x_after_quench,
--> 129                            f_old=self.energy, x_old=self.x)
</code>```

Body:
I'm getting this error when using basin-hopping:
basinhopping_bounds() got an unexpected keyword argument 'f_new'

I'm trying to implement the analysis of X,F models in Python to solving a DTLZ7 problem.

So, I've started with a problem with 4 linear FO, which the result I know. When trying to solve the problem using basin-hopping for global minimization, I'm getting the error above (scipy-1.2.1.). Does anybody knows what is going wrong?

Here follows part of the code:

f1 = f_linear([0.06, 0.53, 0.18, 0.18, 0.06], "max")
f2 = f_linear([25, 70, 60, 95, 45], "max")
f3 = f_linear([0, 32.5, 300, 120, 0], "min")
f4 = f_linear([0.1, 0.1, 0.11, 0.35, 0.33], "min")

A_eq = np.array([[1, 1, 1, 1, 1]])
b_eq = np.array([3000])
x0_bounds = (0, 850)
x1_bounds = (0, 220)
x2_bounds = (0, 1300)
x3_bounds = (0, 1615)
x4_bounds = (0, 700)
F = [f1, f2, f3, f4]

def mu_D(x, F):
    x = np.array(x)
    return max([f_.mu(x) for f_ in F])

def basinhopping_bounds(x):
    resp = True
    if np.dot(x, A_eq[0]) != b_eq[0]:
        resp = False
    if x[0] < x0_bounds[0] or x[0] > x0_bounds[1]:
        resp = False
    if x[1] < x1_bounds[0] or x[1] > x1_bounds[1]:
        resp = False
    if x[2] < x2_bounds[0] or x[2] > x2_bounds[1]:
        resp = False
    if x[3] < x3_bounds[0] or x[3] > x3_bounds[1]:
        resp = False
    if x[4] < x4_bounds[0] or x[4] > x4_bounds[1]:
        resp = False
    return resp

cobyla_constraints = [
    {"type": "ineq", "fun": lambda x: x[0]},
    {"type": "ineq", "fun": lambda x: x0_bounds[1] - x[0]},
    {"type": "ineq", "fun": lambda x: x[1]},
    {"type": "ineq", "fun": lambda x: x1_bounds[1] - x[1]},
    {"type": "ineq", "fun": lambda x: x[2]},
    {"type": "ineq", "fun": lambda x: x2_bounds[1] - x[2]},
    {"type": "ineq", "fun": lambda x: x[3]},
    {"type": "ineq", "fun": lambda x: x3_bounds[1] - x[3]},
    {"type": "ineq", "fun": lambda x: x[4]},
    {"type": "ineq", "fun": lambda x: x4_bounds[1] - x[4]},
    {"type": "eq", "fun": lambda x: np.dot(x, A_eq[0]) - b_eq[0]},
]

minimizer_kwargs = {"args": F, "method": "SLSQP", "constraints": cobyla_constraints}
opt.basinhopping(
    mu_D,
    f1.x_max,
    minimizer_kwargs=minimizer_kwargs,
    accept_test=basinhopping_bounds,
    disp=True,
)

basinhopping step 0: f 1

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-ba4f3efaec5d> in <module>
      5     minimizer_kwargs=minimizer_kwargs,
      6     accept_test=basinhopping_bounds,
----> 7     disp=True,
      8 )

~/anaconda3/lib/python3.6/site-packages/scipy/optimize/_basinhopping.py in basinhopping(func, x0, niter, T, stepsize, minimizer_kwargs, take_step, accept_test, callback, interval, disp, niter_success, seed)
    674                " successfully"]
    675     for i in range(niter):
--> 676         new_global_min = bh.one_cycle()
    677
    678         if callable(callback):

~/anaconda3/lib/python3.6/site-packages/scipy/optimize/_basinhopping.py in one_cycle(self)
    152         new_global_min = False
    153
--> 154         accept, minres = self._monte_carlo_step()
    155
    156         if accept:

~/anaconda3/lib/python3.6/site-packages/scipy/optimize/_basinhopping.py in _monte_carlo_step(self)
    127         for test in self.accept_tests:
    128             testres = test(f_new=energy_after_quench, x_new=x_after_quench,
--> 129                            f_old=self.energy, x_old=self.x)
    130             if testres == 'force accept':
    131                 accept = True

TypeError: basinhopping_bounds() got an unexpected keyword argument 'f_new'

Body:
https://docs.scipy.org/doc/scipy-0.19.0/reference/generated/scipy.optimize.basinhopping.html

This docs describes the accept_test argument.  It must be callable that recognizes a set of keyword arguments (or at least doesn't choke when given them):

accept_test : callable, accept_test(f_new=f_new, x_new=x_new, f_old=fold, x_old=x_old), optional

Define a test which will be used to judge whether or not to accept the step.
This will be used in addition to the Metropolis test based on “temperature” T.
The acceptable return values are True, False, or "force accept". If any of the
tests return False then the step is rejected. If the latter, then this will
override any other tests in order to accept the step. This can be used, for
example, to forcefully escape from a local minimum that basinhopping is
trapped in.

Your function only takes on positional argument:

def basinhopping_bounds(x):

You can also see how minimize calls your function in the error traceback:

testres = test(f_new=energy_after_quench, x_new=x_after_quench,
--> 129                            f_old=self.energy, x_old=self.x)


答:
Try this,

```<code>>>> lst = []
>>> while x >=1 and x <= 20:
    if x%3==0:
        x+=1  # this line solve your issue
        continue
    elif x%3 != 0:   # Use elif instead of if
        lst.append(x) # As your expected output is in reverse order, store in list
        x+=1
        total+=1
</code>```

One liner: (Another way)

```<code>>>> [x for x in range(20,1,-1) if x%3 != 0]
[20, 19, 17, 16, 14, 13, 11, 10, 8, 7, 5, 4, 2]
</code>```

Output:

```<code>>>> lst[::-1] # reverse it here
[20, 19, 17, 16, 14, 13, 11, 10, 8, 7, 5, 4, 2, 1]
</code>```

Title: Python While Loop, also using modulo and continue commands

Body:
Try this,

>>> lst = []
>>> while x >=1 and x <= 20:
    if x%3==0:
        x+=1  # this line solve your issue
        continue
    elif x%3 != 0:   # Use elif instead of if
        lst.append(x) # As your expected output is in reverse order, store in list
        x+=1
        total+=1

One liner: (Another way)

>>> [x for x in range(20,1,-1) if x%3 != 0]
[20, 19, 17, 16, 14, 13, 11, 10, 8, 7, 5, 4, 2]

Output:

>>> lst[::-1] # reverse it here
[20, 19, 17, 16, 14, 13, 11, 10, 8, 7, 5, 4, 2, 1]


问:
How can i reassemble the following json using map function?
I am trying to make a json format from a given json

I use map function in nodejs but it dosen't work right. I give all the details here. I want a code that will give me that required json format.

Given Json :

```<code>var x =
[
[
    {
        "title":"My feel about shape up",
        "answer":"neutral",
        "objectives":[
            "Awareness"
        ]
    },
    {
        "title":"How good is shape up ?",
        "answer":"a",
        "objectives":[
            "Awareness"
        ]
    }
],
[
    {
        "title":"My feel about shape up",
        "answer":"neutral",
        "objectives":[
            "Awareness"
        ]
    },
    {
        "title":"How good is shape up ?",
        "answer":"Awareness",
        "objectives":[
            "Awareness"
        ]
    }
]
];
</code>```

Code i tried :

```<code>result = x.map(function(subarray) {
var data  = subarray.map(v =>{
  const wd= {[v.title ]: v.answer}
   return wd;
   })
   return data;
</code>```

})

Actual output :

```<code>[ [ { 'My feel about shape up': 'neutral' },
{ 'How good is shape up ?': 'a' } ],
[ { 'My feel about shape up': 'neutral' },
{ 'How good is shape up ?': 'Awareness' } ] ]
</code>```

Expected output :

```<code>[
{ 'My feel about shape up': 'neutral',
'How good is shape up ?': 'a' } ,
{ 'My feel about shape up': 'neutral',
'How good is shape up ?': 'Awareness' }
]
</code>```

答:
You can use .map() and .reduce() methods to get the desired output:

const data = [[
    {"title":"My feel about shape up", "answer":"neutral", "objectives":[ "Awareness"]},
    {"title":"How good is shape up ?", "answer":"a", "objectives":[ "Awareness"]}
], [
    {"title":"My feel about shape up", "answer":"neutral", "objectives":["Awareness"]},
    {"title":"How good is shape up ?", "answer":"Awareness", "objectives":["Awareness"]}
]];

const result = data.map(
    arr => arr.reduce((r, {title: k, answer: v}) => (r[k] = v, r), {})
);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I am trying to make a json format from a given json

I use map function in nodejs but it dosen't work right. I give all the details here. I want a code that will give me that required json format.

Given Json :

var x =
[
[
    {
        "title":"My feel about shape up",
        "answer":"neutral",
        "objectives":[
            "Awareness"
        ]
    },
    {
        "title":"How good is shape up ?",
        "answer":"a",
        "objectives":[
            "Awareness"
        ]
    }
],
[
    {
        "title":"My feel about shape up",
        "answer":"neutral",
        "objectives":[
            "Awareness"
        ]
    },
    {
        "title":"How good is shape up ?",
        "answer":"Awareness",
        "objectives":[
            "Awareness"
        ]
    }
]
];

Code i tried :

result = x.map(function(subarray) {
var data  = subarray.map(v =>{
  const wd= {[v.title ]: v.answer}
   return wd;
   })
   return data;

})

Actual output :

[ [ { 'My feel about shape up': 'neutral' },
{ 'How good is shape up ?': 'a' } ],
[ { 'My feel about shape up': 'neutral' },
{ 'How good is shape up ?': 'Awareness' } ] ]

Expected output :

[
{ 'My feel about shape up': 'neutral',
'How good is shape up ?': 'a' } ,
{ 'My feel about shape up': 'neutral',
'How good is shape up ?': 'Awareness' }
]

Body:
You can use .map() and .reduce() methods to get the desired output:

const data = [[
    {"title":"My feel about shape up", "answer":"neutral", "objectives":[ "Awareness"]},
    {"title":"How good is shape up ?", "answer":"a", "objectives":[ "Awareness"]}
], [
    {"title":"My feel about shape up", "answer":"neutral", "objectives":["Awareness"]},
    {"title":"How good is shape up ?", "answer":"Awareness", "objectives":["Awareness"]}
]];

const result = data.map(
    arr => arr.reduce((r, {title: k, answer: v}) => (r[k] = v, r), {})
);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
android.support.v4.widget.CircleImageView does not work
when I try to use :
android.support.v4.widget.CircleImageView

```<code>        <android.support.v4.widget.CircleImageView
                android:id="@+id/picture"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_gravity="center_vertical"
                android:src="@drawable/ic_bg" />
</code>```

it makes my app crash

how to support new Material Design Widget CircleImageView

is there any example use this new widget

Logcat

```<code>  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.vogella.android.recyclerview/com.vogella.android.recyclerview.MainActivity}: android.view.InflateException: Binary XML file line #9: Error inflating class android.support.v4.widget.CircleImageView
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2255)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2309)
        at android.app.ActivityThread.access$700(ActivityThread.java:157)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1289)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:176)
        at android.app.ActivityThread.main(ActivityThread.java:5317)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: android.view.InflateException: Binary XML file line #9: Error inflating class android.support.v4.widget.CircleImageView
        at
</code>```

答:
Just Rebuild the project

Build ===> Clear Project

Build ===> Rebuild Project

and if not works

File ===> Invaildate Cahses / Restart

Then it will Work.

Body:
when I try to use :
android.support.v4.widget.CircleImageView

        <android.support.v4.widget.CircleImageView
                android:id="@+id/picture"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_gravity="center_vertical"
                android:src="@drawable/ic_bg" />

it makes my app crash

how to support new Material Design Widget CircleImageView

is there any example use this new widget

Logcat

  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.vogella.android.recyclerview/com.vogella.android.recyclerview.MainActivity}: android.view.InflateException: Binary XML file line #9: Error inflating class android.support.v4.widget.CircleImageView
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2255)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2309)
        at android.app.ActivityThread.access$700(ActivityThread.java:157)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1289)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:176)
        at android.app.ActivityThread.main(ActivityThread.java:5317)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: android.view.InflateException: Binary XML file line #9: Error inflating class android.support.v4.widget.CircleImageView
        at


答:
You should use reduce for the subarrays to get one object for each subarray;

var x = [[{"title":"My feel about shape up","answer":"neutral","objectives":["Awareness"]},{"title":"How good is shape up ?","answer":"a","objectives":["Awareness"]}],[{"title":"My feel about shape up","answer":"neutral","objectives":["Awareness"]},{"title":"How good is shape up ?","answer":"Awareness","objectives":["Awareness"]}]];
const res = x.map(e => e.reduce((acc, { title, answer }) => ({ ...acc, [title]: answer }), {}));
console.log(res);```
</div>
</div>
</p>

<p>ES5 syntax:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var x = [[{"title":"My feel about shape up","answer":"neutral","objectives":["Awareness"]},{"title":"How good is shape up ?","answer":"a","objectives":["Awareness"]}],[{"title":"My feel about shape up","answer":"neutral","objectives":["Awareness"]},{"title":"How good is shape up ?","answer":"Awareness","objectives":["Awareness"]}]];
var res = x.map(function(e) {
  return e.reduce(function(acc, curr) {
    return Object.assign({}, acc, { [curr.title]: curr.answer });
  }, {});
});
console.log(res);</code>```

Title: How can i reassemble the following json using map function?

Body:
You should use reduce for the subarrays to get one object for each subarray;

var x = [[{"title":"My feel about shape up","answer":"neutral","objectives":["Awareness"]},{"title":"How good is shape up ?","answer":"a","objectives":["Awareness"]}],[{"title":"My feel about shape up","answer":"neutral","objectives":["Awareness"]},{"title":"How good is shape up ?","answer":"Awareness","objectives":["Awareness"]}]];
const res = x.map(e => e.reduce((acc, { title, answer }) => ({ ...acc, [title]: answer }), {}));
console.log(res);

ES5 syntax:

var x = [[{"title":"My feel about shape up","answer":"neutral","objectives":["Awareness"]},{"title":"How good is shape up ?","answer":"a","objectives":["Awareness"]}],[{"title":"My feel about shape up","answer":"neutral","objectives":["Awareness"]},{"title":"How good is shape up ?","answer":"Awareness","objectives":["Awareness"]}]];
var res = x.map(function(e) {
  return e.reduce(function(acc, curr) {
    return Object.assign({}, acc, { [curr.title]: curr.answer });
  }, {});
});
console.log(res);


答:
You're returning an array from inside loop instead you need to create an object to get desired result,

let data = [[{"title":"My feel about shape up","answer":"neutral","objectives":["Awareness"]},{"title":"How good is shape up ?","answer":"a","objectives":["Awareness"]}],[{"title":"My feel about shape up","answer":"neutral","objectives":["Awareness"]},{"title":"How good is shape up ?","answer":"Awareness","objectives":["Awareness"]}]];

let final = data.map(value =>
  value.reduce((op, {title, answer}) => {
    op[title] = answer
    return op
  },{})
)
console.log(final)```


问:
Question about the processing of synchronous functions wrapped in a promise
For the most part, I understand how to wrap asynchronous and synchronous functions in a promise and the benefits and reasons for doing so.  However, I don't understand something about how they are processed in the browser.

For example, if two synchronous functions are invoked in turn (two consecutive statements), the second does not commence until the first returns.  If each synchronous function is instead wrapped in a promise and then invoked one after another (not one in the then statement of the other but two consecutive statements), are the synchronous functions going to process concurrently now instead of in order?

I have a good reason for asking other than just interest in a hypothetical scenario. I'm working on an extension that opens a tabbed display within a single local HTML page. When the page is opened, the injected script opens the indexedDB database and kicks off a set of promises that retrieve the data for each tab and populate the various sections of each tab with the appropriate data.  Placing these within a Promise.all gives the impression that all of this work is taking place concurrently and populating the tabs as the data is retrieved, as opposed to populating each tab in succession.

Within a number of the individual promises(one promise per tab), when the transaction completes, synchronous functions are invoked to display the data in different sections of that tab. As coded now, the synchronous functions for display are invoked one after another in consecutive statements, such that the second section of the tab is populated only after the first completes and returns.  The data has already been retrieved for all sections because the entire transaction has completed; so, the second function for display doesn't have to wait for the first to complete.  If those display functions are wrapped in a promise and invoked as such, will the two sections of the tab be populated concurrently?

The transactions could be split such that there is one transaction per tab section, and the synchronous display functions will each commence as soon as their specific data has been retrieved; but, I'd like to keep one transaction per tab.

Either way, the loading process will be sufficient; but I'd like to understand whether or not, even if not perceptible to user, wrapping the display functions in promises will result in the concurrent population of the separate sections within a tab.

Perhaps, I'm just confused and, although promises and Promise.all give the impression of concurrent processes, there really is no such thing in JavaScript and all that happens is that the asynchronous functions are processed in turn as their events complete.  If so, wrapping synchronous functions in a promise, as described above, has no benefit in terms of speeding up the population of data in the sections of the tabs.

If that is correct, then the only way to increase the loading speed would be to split the transactions; and that would help only if one of the data retrieval steps within a transaction was taking longer than the others and delaying the completion of the transaction and the commencement of the functions displaying that data.

I apologize for the length of this question and if it is considered inappropriate because there is no code to review, I'll certainly have no issue in deleting it.  But, if you can explain where I am wrong in my understanding I'd appreciate it.
Thank you.

答:
Javascript is single-threaded, so there's no concurrency within the javascript environment itself. Your synchronous section-populating functions will execute on a first-come, first-served basis.

When you invoke an asynchronous operation like a network request promise (or even a setTimeout call), that execution is dispatched to be handled outside the javascript environment, out in kernel-land, where where it can run without blocking js execution and possibly run on a separate thread.

When it returns, the container (the browser) pushes the result back into synchronous javascript-land by adding the callback to a message queue. When the javascript call stack is empty, the event loop checks the message queue for pending callbacks. If it finds one it pushes it onto the call stack to be executed on the next execution loop.

Whichever section call comes back first will be executed first, and any other asynchronous calls that return will have to wait until the first one finishes before they run.

There's a really great article somewhere that explains how all of this works far better (and more authoritatively) than I can. I'll try to find it and update my answer with a link.

Update: This post explains it quite well.


问:
responsive web design video container whitespace
I am trying to make a responsive web site and the problem I am facing currently is that when I minimize the browser size, my background video leaves a chunk of whitespace. It does not fill the size of the header and the following div after that is displayed after the whitespace.

As far as getting rid of video-container and using 100vw and 100vh on video-bg, I have tried and it does not work because my video is zoomed in at that point and does not display the entirety of the video.

https://www.videezy.com/urban/3951-top-to-bottom-panning-shot-of-downtown-los-angeles-4k

The above link is to download the video I am using.

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<style>
body {
    margin: 0;
    padding: 0;
}
#block {
    background-color: black;
    height: 500px;
}
.embed-container {
    position: relative;
    padding-bottom: 56.25%;
    height: 0; overflow:
    hidden;
    max-width: 100%;
}
.embed-container video, /*.embed-container object, .embed-container embed*/ {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
</style>
<body>
<!DOCTYPE html>
<html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" href="styles.css">
    </head>
    <body>
        <div class='embed-container'>
            <video autoplay muted allowfullscreen>
                <source src="downtownla.mp4" type="video/mp4">
            </video>
        </div>
        <div id="block">
            1
        </div>
    </body>
</html>
</body>
</html>
</code>```

My expected goal is to be able to have a video that is responsive and allows for the following div to be displayed immediately after without any whitespace.

答:
Not sure what exactly you are looking for as you have not mentioned details about if you want to link YouTube or the one mentioned in the link.

Below website will help you setup responsive videos from different platforms

https://embedresponsively.com/

YouTube Embedded video example

```<code><style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }</style><div class='embed-container'><iframe src='https://www.youtube.com/embed/QILiHiTD3uc' frameborder='0' allowfullscreen></iframe></div>
</code>```

Also look at this link

Body:
I am trying to make a responsive web site and the problem I am facing currently is that when I minimize the browser size, my background video leaves a chunk of whitespace. It does not fill the size of the header and the following div after that is displayed after the whitespace.

As far as getting rid of video-container and using 100vw and 100vh on video-bg, I have tried and it does not work because my video is zoomed in at that point and does not display the entirety of the video.

https://www.videezy.com/urban/3951-top-to-bottom-panning-shot-of-downtown-los-angeles-4k

The above link is to download the video I am using.

<!DOCTYPE html>

    <title></title>

<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" href="styles.css">

            <video autoplay muted allowfullscreen>
                <source src="downtownla.mp4" type="video/mp4">
            </video>

            1

My expected goal is to be able to have a video that is responsive and allows for the following div to be displayed immediately after without any whitespace.

Body:
Not sure what exactly you are looking for as you have not mentioned details about if you want to link YouTube or the one mentioned in the link.

Below website will help you setup responsive videos from different platforms

https://embedresponsively.com/

YouTube Embedded video example

<style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }</style><div class='embed-container'><iframe src='https://www.youtube.com/embed/QILiHiTD3uc' frameborder='0' allowfullscreen></iframe></div>

Also look at this link


问:
Capitalizing Vowels in a String with Ruby
I have a method that takes in a string as an argument, replaces each letter with the next letter in the alphabet and then capitalizes every vowel. I have gotten both of those to work individually (the replacing and capitalization), but at this point, I just don't know how to make them work together.</p>

```<code>def LetterChanges(str)
    new_str = str.downcase.split("")
    new_str.each do |x|
        x.next!
    end
    new_str.to_s.tr!('aeiou','AEIOU')
    return new_str.join("")
end

LetterChanges("abcdef")
</code>```

答:
This can be achieved with the combination of gsub and tr:

"abcdef".gsub(/[A-z]/) { |char| char.next }.tr('aeiou', 'AEIOU')
#=> "bcdEfg"
"Fun times!".gsub(/[A-z]/) { |char| char.next }.tr('aeiou', 'AEIOU')
#=> "GvO Ujnft!"
```

Body:
I have a method that takes in a string as an argument, replaces each letter with the next letter in the alphabet and then capitalizes every vowel. I have gotten both of those to work individually (the replacing and capitalization), but at this point, I just don't know how to make them work together.

def LetterChanges(str)
    new_str = str.downcase.split("")
    new_str.each do |x|
        x.next!
    end
    new_str.to_s.tr!('aeiou','AEIOU')
    return new_str.join("")
end

LetterChanges("abcdef")


问:
How to apply width and height and other styles to a modal created using material ui in React JS
I am not able to create a material-ui modal in my React app. I could see that a modal is rendering in the browser but its not pop up as how a modal should behave. I checked the material-ui api https://material-ui.com/api/modal/ but I could not find it helpful.

Note: I do want to use a class component and NOT a functional component.

Below is the code I tried,

Here is the code sandbox: code sandbox

index.js

```<code>import React from "react";
import ReactDOM from "react-dom";
import Modal from "@material-ui/core/Modal";
import Typography from "@material-ui/core/Typography";

import "./styles.css";

class App extends React.Component {
  render() {
    return (
      <Modal open={true} aria-labelledby="simple-modal-title">
        <div className="modal-size">
          <Typography variant="h6" id="modal-title">
            My Title
          </Typography>
        </div>
      </Modal>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
</code>```

styles.css

```<code>.App {
  font-family: sans-serif;
  text-align: center;
}
.modal-size {
  width: 50%;
  height: 50%;

  top: 50%;
  left: 50%;
  right: auto;
  bottom: auto;

  transform: translate(-50%, -50%);
}
</code>```

The expected result is something like below. A modal should pop up as below.

答:
Add the css rule position: absolute; or position: fixed; to your model-size class.

```<code>.modal-size {
  position: absolute;
  width: 50%;
  height: 50%;

  top: 50%;
  left: 50%;
  right: auto;
  bottom: auto;

  transform: translate(-50%, -50%);
}
</code>```

codesandbox

Body:
I am not able to create a material-ui modal in my React app. I could see that a modal is rendering in the browser but its not pop up as how a modal should behave. I checked the material-ui api https://material-ui.com/api/modal/ but I could not find it helpful.

Note: I do want to use a class component and NOT a functional component.

Below is the code I tried,

Here is the code sandbox: code sandbox

index.js

import React from "react";
import ReactDOM from "react-dom";
import Modal from "@material-ui/core/Modal";
import Typography from "@material-ui/core/Typography";

import "./styles.css";

class App extends React.Component {
  render() {
    return (
      <Modal open={true} aria-labelledby="simple-modal-title">

          <Typography variant="h6" id="modal-title">
            My Title
          </Typography>

      </Modal>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

styles.css

.App {
  font-family: sans-serif;
  text-align: center;
}
.modal-size {
  width: 50%;
  height: 50%;

  top: 50%;
  left: 50%;
  right: auto;
  bottom: auto;

  transform: translate(-50%, -50%);
}

The expected result is something like below. A modal should pop up as below.

Body:
Add the css rule position: absolute; or position: fixed; to your model-size class.

.modal-size {
  position: absolute;
  width: 50%;
  height: 50%;

  top: 50%;
  left: 50%;
  right: auto;
  bottom: auto;

  transform: translate(-50%, -50%);
}

codesandbox


问:
In Django, the button url is called unexpectedly, The url request is excuted differently
In Django, the button url is called unexpectedly, so I can not find the page

I tried click below button but it's not work

```<code><button type="button"
        class="btn btn-outline-info btn-sm float-right"
        name="button"
        onclick="location.href='{{fn_id}}/finisher/new'">
            post
</button>
</code>```

result of url request is

It seems that there is a problem because I made the url request when I was on the detail page.

and below buuton is work

```<code><button
    type="button"
    class="btn btn-outline-info btn-sm float-right"
    name="button" onclick="location.href='http://127.0.0.1:8000/bestlec/{{fn_id}}/finisher/new'"
    >
        post
</button>
</code>```

but That causes problem Because it requests a local address

do you know how to slove it?? thanks for let me know~!

答:
In your first example, I expect you're on page http://127.0.0.1:8000/bestlec/1.  You've then given a relative url of 1/finisher/new which has been added to the current url to give http://127.0.0.1:8000/bestlec/1/1/finisher/new.

If you want to give a relative url use finisher/new.  If you need to go to other ids use /bestlec/{{fn_id}}/finisher/new or better still, use {% url 'url-name' fn_id %}

Body:
In Django, the button url is called unexpectedly, so I can not find the page

I tried click below button but it's not work

<button type="button"
        class="btn btn-outline-info btn-sm float-right"
        name="button"
        onclick="location.href='{{fn_id}}/finisher/new'">
            post
</button>

result of url request is

It seems that there is a problem because I made the url request when I was on the detail page.

and below buuton is work

<button
    type="button"
    class="btn btn-outline-info btn-sm float-right"
    name="button" onclick="location.href='http://127.0.0.1:8000/bestlec/{{fn_id}}/finisher/new'"
    >
        post
</button>

but That causes problem Because it requests a local address

do you know how to slove it?? thanks for let me know~!


问:
Save list of records and fields into django model
I receive this list from my website admin:

```<code>[['present', '2'],['present', '1'], ['study', '1'], ['study', '3'], ['present', '4'], ['study', '4'],
</code>```

The first option is actually the field name that needs to be edit in Rollcall model and the second option is the user ID.

Now I want to save this list to the Rollcall model:

```<code>#models.py
class Rollcall(models.Model):
    student = models.ForeignKey(User)
    present = models.BooleanField(default=False)
    study = models.BooleanField(default=False)
</code>```

So I first check and find the various fields that a particular user has in the list,
 and then I will save all those fields for one user in my model. How can I do this?

--Update 1:
this is HTML file:

```<code>{% forstudent in students %}
                            <tr>
                                <td>{{student}} </td>
                                <td> <input type="radio" name="present_{{student.id}}" value="1"></td>
                                <td> <input type="radio" name="study_{{student.id}}" value="1"></td>
                            </tr>
                        {% endfor %}
</code>```

I get the data in this way and put them into the list that I explain in the first of this question:

```<code>data_list = [key.split('_') for key in request.POST.keys()][1:]
</code>```

Each student can be present or absent or can study or not.my exactly question is: How can save data of all my student?Is there another way to solve this problem without data_list or any other way to create better data_list?

答:
Try something like this:

```<code>l=[['present', '2'], ['present', '3'], ['present', '4'], ['study', '2']]
dic={}
for arr in l:
    dic.setdefault(arr[1], []).append(arr[0])
for key in dic:
    Rollcall.objects.create(present=True if 'present' in dic[key] else False,\
    student=True if 'student' in dic[key] else False, \
    study=User.objects.get(id=int(key)))
</code>```

or to make it in bulk after creating the dictionary (dic):

```<code>final_objects = [Rollcall(is_present=True if 'present' in final_dic[key] else False,
                          is_study=True if 'study' in final_dic[key] else False,
                          student=User.objects.get(id=int(key)),
                          ) for key in final_dic]
Rollcall.objects.bulk_create(final_objects)
</code>```

Body:
I receive this list from my website admin:

[['present', '2'],['present', '1'], ['study', '1'], ['study', '3'], ['present', '4'], ['study', '4'],

The first option is actually the field name that needs to be edit in Rollcall model and the second option is the user ID.

Now I want to save this list to the Rollcall model:

#models.py
class Rollcall(models.Model):
    student = models.ForeignKey(User)
    present = models.BooleanField(default=False)
    study = models.BooleanField(default=False)

So I first check and find the various fields that a particular user has in the list,
 and then I will save all those fields for one user in my model. How can I do this?

--Update 1:
this is HTML file:

{% forstudent in students %}

                                {{student}}
                                 <input type="radio" name="present_{{student.id}}" value="1">
                                 <input type="radio" name="study_{{student.id}}" value="1">

                        {% endfor %}

I get the data in this way and put them into the list that I explain in the first of this question:

data_list = [key.split('_') for key in request.POST.keys()][1:]

Each student can be present or absent or can study or not.my exactly question is: How can save data of all my student?Is there another way to solve this problem without data_list or any other way to create better data_list?

Body:
Try something like this:

l=[['present', '2'], ['present', '3'], ['present', '4'], ['study', '2']]
dic={}
for arr in l:
    dic.setdefault(arr[1], []).append(arr[0])
for key in dic:
    Rollcall.objects.create(present=True if 'present' in dic[key] else False,\
    student=True if 'student' in dic[key] else False, \
    study=User.objects.get(id=int(key)))

or to make it in bulk after creating the dictionary (dic):

final_objects = [Rollcall(is_present=True if 'present' in final_dic[key] else False,
                          is_study=True if 'study' in final_dic[key] else False,
                          student=User.objects.get(id=int(key)),
                          ) for key in final_dic]
Rollcall.objects.bulk_create(final_objects)


问:
New Function constructor in Angular how to reference imported scripts in revived object
I have a json with function stored in it as strings and when I revive it using new Function and try to use the method which happens to use a library imported by angular like lodash I get a reference error. Here is the code the ZombieLoader will revive the json object and in the angular class test will try to run it i will get the error _ not found.

```<code>// This class takes a json and produces an object with methods
export class ZombieLoader {
  static revive(st: string): object {
    const result = {};
    const obj = JSON.parse(st);
    for (const key of Object.keys(obj)) {
      if (key.startsWith('@')) {
        result[key.substring(1)] = new Function('return ' + obj[key])();
        continue;
      }
      result[key] = obj[key];
    }
    return result;
  }
}

// the json with function in string form that will be hydrated back for use
{
script: '{"@run":"function () { return _.chunk(['a', 'b', 'c', 'd'], 2); };}'
}

// here I test the method which fails because it cant find _
import * as _ from 'lodash';
import {ZombieLoader} from './zombie-loader';

export class Test {
    constructor(script: string) {
         const sceneScript = ZombieLoader.revive(script);
         sceneScript.run();
    }
}
</code>```

Why does the reconstructed object not have reference to Angular loaded scripts is there a way to reconstruct the object and bind it to an angular.
If I add the lodash to the index.html file it works but I don't want to have to do this to several other libraries

答:
It seems like _ library is not loaded by Angular because it is not used directly at the time of component creation . A small solution , try using _ library in constructor or Oninit like this
console.log(typeof _ );
than you won't get reference error.

Body:
I have a json with function stored in it as strings and when I revive it using new Function and try to use the method which happens to use a library imported by angular like lodash I get a reference error. Here is the code the ZombieLoader will revive the json object and in the angular class test will try to run it i will get the error _ not found.

// This class takes a json and produces an object with methods
export class ZombieLoader {
  static revive(st: string): object {
    const result = {};
    const obj = JSON.parse(st);
    for (const key of Object.keys(obj)) {
      if (key.startsWith('@')) {
        result[key.substring(1)] = new Function('return ' + obj[key])();
        continue;
      }
      result[key] = obj[key];
    }
    return result;
  }
}

// the json with function in string form that will be hydrated back for use
{
script: '{"@run":"function () { return _.chunk(['a', 'b', 'c', 'd'], 2); };}'
}

// here I test the method which fails because it cant find _
import * as _ from 'lodash';
import {ZombieLoader} from './zombie-loader';

export class Test {
    constructor(script: string) {
         const sceneScript = ZombieLoader.revive(script);
         sceneScript.run();
    }
}

Why does the reconstructed object not have reference to Angular loaded scripts is there a way to reconstruct the object and bind it to an angular.
If I add the lodash to the index.html file it works but I don't want to have to do this to several other libraries


问:
Ionic 4 loading until images in page loaded
enter image description hereI am using ionic 4 so i need to a loader untill the page loaded completely. Now i am using loadingController and dismiss it when api res, loading finished but images still loading. I want loading untill all loading finished.

Like ionic 3 ionViewDidLoad() works
Below is the Answer i found on Ionic Documentation an event called ionImgWillLoad but dont know how to use it.

答:
Ionic 4 relies more on Angular lifecycle hooks and instead of ionViewDidLoad you should now use ngAfterViewInit hook.

View initialization means views’ layout and rendering of components has been finished, but images async loading can still be ongoing.

ionViewDidLoad in Ionic 3 was also not awaiting for images to load. To have such a "hook" one needs to to custom implementation.

In typescript something like the below would do the trick:

```<code>counter: number;
maxImagesCount: number = document.images.length;

updateCounter() {
    this.counter++;
    if ( this.counter === this.maxImagesCount ) {
        console.log( 'All images loaded!' );
    }
}
</code>```

In the template you could attach load event listener to images templates:

```<code><img src="url" (load)="updateCounter()">
</code>```

Body:
Ionic 4 relies more on Angular lifecycle hooks and instead of ionViewDidLoad you should now use ngAfterViewInit hook.

View initialization means views’ layout and rendering of components has been finished, but images async loading can still be ongoing.

ionViewDidLoad in Ionic 3 was also not awaiting for images to load. To have such a "hook" one needs to to custom implementation.

In typescript something like the below would do the trick:

counter: number;
maxImagesCount: number = document.images.length;

updateCounter() {
    this.counter++;
    if ( this.counter === this.maxImagesCount ) {
        console.log( 'All images loaded!' );
    }
}

In the template you could attach load event listener to images templates:

<img src="url" (load)="updateCounter()">


问:
How to handle a persisted/state-dependent pod start failure in Kubernetes?
I have the following issue with on Kubernetes pod accessing a persistent volume exclusively where apparently a file has not been removed upon shutdown of the previous pod using it:

```<code>[2019-05-25 09:11:33,980] ERROR [KafkaServer id=0] Fatal error during KafkaServer startup. Prepare to shutdown (kafka.server.KafkaServer)
org.apache.kafka.common.KafkaException: Failed to acquire lock on file .lock in /opt/kafka/data/logs. A Kafka instance in another process or thread is using this directory.
    at kafka.log.LogManager$$anonfun$lockLogDirs$1.apply(LogManager.scala:240)
    at kafka.log.LogManager$$anonfun$lockLogDirs$1.apply(LogManager.scala:236)
    at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
    at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at scala.collection.TraversableLike$class.flatMap(TraversableLike.scala:241)
    at scala.collection.AbstractTraversable.flatMap(Traversable.scala:104)
    at kafka.log.LogManager.lockLogDirs(LogManager.scala:236)
    at kafka.log.LogManager.<init>(LogManager.scala:97)
    at kafka.log.LogManager$.apply(LogManager.scala:953)
    at kafka.server.KafkaServer.startup(KafkaServer.scala:237)
    at io.confluent.support.metrics.SupportedServerStartable.startup(SupportedServerStartable.java:114)
    at io.confluent.support.metrics.SupportedKafka.main(SupportedKafka.java:66)
</code>```

I installed Kafka using the official helm chart, so I assume that the setup of Kafka and zookeeper pods as well as either assignment to persistent volumes and claims is suited for Kubernetes.

First of all: Is this a good idea to persist the running state on the persistent volume? Since pods are supposed to be not reliable and can crash or be evicted at any point in time this method is very prone to errors. Should I consider this a bug or flaw which is worth reporting to the helm chart authors?

Since bugs exist and other software might persist it's running state on the persistent volume, I'm interested in a general best practices approach how to bring the persistent volume into a state where the pod using it can start again (in this case it sould be deleting the lock file from /opt/kafka/data/logs afaik).

So far I attempted to start a console in a container shell and try to run the command to remove the file before the pod crashes. This takes some tries and is very annoying.

I'm experiencing this with microk8s 1.14.2 (608) on Ubuntu 19.10, but I think it could happen on any Kubernetes implementation.

答:
To solve this bug, I think we just need a PreStart and PreStop Hook in Kafka pod specification like other offical helm charts.

```<code>containers:
  - name: kafka-broker
    ...
    lifecycle:
      preStart:
        exec:
          command:
            - "/bin/sh"
            - "-ec"
            - |
              rm -rf ${KAFKA_LOG_DIRS}/.lock
      preStop:
        exec:
          command:
          - "/bin/sh"
          - "-ec"
          - "/usr/bin/kafka-server-stop"
</code>```

Body:
I have the following issue with on Kubernetes pod accessing a persistent volume exclusively where apparently a file has not been removed upon shutdown of the previous pod using it:

[2019-05-25 09:11:33,980] ERROR [KafkaServer id=0] Fatal error during KafkaServer startup. Prepare to shutdown (kafka.server.KafkaServer)
org.apache.kafka.common.KafkaException: Failed to acquire lock on file .lock in /opt/kafka/data/logs. A Kafka instance in another process or thread is using this directory.
    at kafka.log.LogManager$$anonfun$lockLogDirs$1.apply(LogManager.scala:240)
    at kafka.log.LogManager$$anonfun$lockLogDirs$1.apply(LogManager.scala:236)
    at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
    at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at scala.collection.TraversableLike$class.flatMap(TraversableLike.scala:241)
    at scala.collection.AbstractTraversable.flatMap(Traversable.scala:104)
    at kafka.log.LogManager.lockLogDirs(LogManager.scala:236)
    at kafka.log.LogManager.<init>(LogManager.scala:97)
    at kafka.log.LogManager$.apply(LogManager.scala:953)
    at kafka.server.KafkaServer.startup(KafkaServer.scala:237)
    at io.confluent.support.metrics.SupportedServerStartable.startup(SupportedServerStartable.java:114)
    at io.confluent.support.metrics.SupportedKafka.main(SupportedKafka.java:66)

I installed Kafka using the official helm chart, so I assume that the setup of Kafka and zookeeper pods as well as either assignment to persistent volumes and claims is suited for Kubernetes.

First of all: Is this a good idea to persist the running state on the persistent volume? Since pods are supposed to be not reliable and can crash or be evicted at any point in time this method is very prone to errors. Should I consider this a bug or flaw which is worth reporting to the helm chart authors?

Since bugs exist and other software might persist it's running state on the persistent volume, I'm interested in a general best practices approach how to bring the persistent volume into a state where the pod using it can start again (in this case it sould be deleting the lock file from /opt/kafka/data/logs afaik).

So far I attempted to start a console in a container shell and try to run the command to remove the file before the pod crashes. This takes some tries and is very annoying.

I'm experiencing this with microk8s 1.14.2 (608) on Ubuntu 19.10, but I think it could happen on any Kubernetes implementation.

Body:
To solve this bug, I think we just need a PreStart and PreStop Hook in Kafka pod specification like other offical helm charts.

containers:
  - name: kafka-broker
    ...
    lifecycle:
      preStart:
        exec:
          command:
            - "/bin/sh"
            - "-ec"
            - |
              rm -rf ${KAFKA_LOG_DIRS}/.lock
      preStop:
        exec:
          command:
          - "/bin/sh"
          - "-ec"
          - "/usr/bin/kafka-server-stop"


问:
In Swift, how do you detect which UIControlEvents triggered the action?
I currently have 4 UITextField's

```<code>@IBOutlet weak var fNameTextField: UITextField!
@IBOutlet weak var lNameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var phoneTextField: UITextField!
</code>```

and I want to keep track of their various events:

```<code>[UIControlEvents.EditingChanged, UIControlEvents.EditingDidBegin, UIControlEvents.EditingDidEnd ]
</code>```

but I don't want to have 3 event separate event handlers so I created a single function like this. This function does a great job of telling me which UITextField fired an event but it doesn't tell me which event was triggered.:

```<code>fNameTextField.addTarget(self, action: "onChangeTextField:", forControlEvents: UIControlEvents.AllTouchEvents)
lNameTextField.addTarget(self, action: "onChangeTextField:", forControlEvents: UIControlEvents.AllTouchEvents)
emailTextField.addTarget(self, action: "onChangeTextField:", forControlEvents: UIControlEvents.AllTouchEvents)
phoneTextField.addTarget(self, action: "onChangeTextField:", forControlEvents: UIControlEvents.AllTouchEvents)

func onChangeTextField(sender:UITextField){
    switch(sender){
        case fNameTextField:
            print("First Name")
        case lNameTextField:
            print("Last Name")
        case emailTextField:
            print("E-mail")
        case phoneTextField:
            print("Phone")
        default: break
    }
}
</code>```

How can I print both the name of the sender and the name of the event triggered (ex: .EditingDidEnd, .EditingDidEnd, .EditingDidEnd)?

Ideally, I do not want to write multiple event handlers, I'd prefer a single function.

Something like this:

```<code>func onChangeTextField(sender:UITextField){
    switch(sender.eventTriggerd){
        case UIControlEvents.EditingChanged:
            println("EditingChanged")
        case UIControlEvents.EditingDidBegin:
            println("EditingDidBegin")
        case UIControlEvents.EditingDidEnd:
            println("EditingDidEnd")
        default: break
    }
}
</code>```

答:
As matt said, this is not possible (and is indeed very irritating!). I've been using this little helper class to relieve myself of some of the typing.

Each UIControl.Event has a corresponding optional Selector. You can set only the selectors you need, and ignore the ones you don't.

```<code>class TargetActionMaker<T: UIControl> {

    var touchDown: Selector?
    var touchDownRepeat: Selector?
    var touchDragInside: Selector?
    var touchDragOutside: Selector?
    var touchDragEnter: Selector?
    var touchDragExit: Selector?
    var touchUpInside: Selector?
    var touchUpOutside: Selector?
    var touchCancel: Selector?
    var valueChanged: Selector?
    var primaryActionTriggered: Selector?
    var editingDidBegin: Selector?
    var editingChanged: Selector?
    var editingDidEnd: Selector?
    var editingDidEndOnExit: Selector?
    var allTouchEvents: Selector?
    var allEditingEvents: Selector?
    var applicationReserved: Selector?
    var systemReserved: Selector?
    var allEvents: Selector?

    func addActions(_ sender: T, target: Any?) {
        for selectorAndEvent in self.selectorsAndEvents() {
            if let action = selectorAndEvent.0 {
                sender.addTarget(target, action: action, for: selectorAndEvent.1)
            }
        }
    }

    private func selectorsAndEvents() -> [(Selector?, UIControl.Event)] {
        return [
            (self.touchDown, .touchDown),
            (self.touchDownRepeat, .touchDownRepeat),
            (self.touchDragInside, .touchDragInside),
            (self.touchDragOutside, .touchDragOutside),
            (self.touchDragEnter, .touchDragEnter),
            (self.touchDragExit, .touchDragExit),
            (self.touchUpInside, .touchUpInside),
            (self.touchUpOutside, .touchUpOutside),
            (self.touchCancel, .touchCancel),
            (self.valueChanged, .valueChanged),
            (self.primaryActionTriggered, .primaryActionTriggered),
            (self.editingDidBegin, .editingDidBegin),
            (self.editingChanged, .editingChanged),
            (self.editingDidEnd, .editingDidEnd),
            (self.editingDidEndOnExit, .editingDidEndOnExit),
            (self.allTouchEvents, .allTouchEvents),
            (self.allEditingEvents, .allEditingEvents),
            (self.applicationReserved, .applicationReserved),
            (self.systemReserved, .systemReserved),
            (self.allEvents, .allEvents)
        ]
    }
}
</code>```

Use it like so:

```<code>class MyControl: UIControl {

    func setupSelectors() {
        let targetActionMaker = TargetActionMaker<MyControl>()
        targetActionMaker.touchDown = #selector(self.handleTouchDown(_:))
        targetActionMaker.touchUpInside = #selector(self.handleTouchUpInside(_:))
        targetActionMaker.touchUpOutside = #selector(self.handleTouchUpOutside(_:))
        targetActionMaker.addActions(self, target: self)
    }

    @objc func handleTouchDown(_ sender: MyControl) {
        print("handleTouchDown")
    }

    @objc func handleTouchUpInside(_ sender: MyControl) {
        print("handleTouchUpInside")
    }

    @objc func handleTouchUpOutside(_ sender: MyControl) {
        print("handleTouchUpOutside")
    }
}
</code>```

Though, to be honest, in the end it really doesn't save you that much typing.

Body:
I currently have 4 UITextField's

@IBOutlet weak var fNameTextField: UITextField!
@IBOutlet weak var lNameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var phoneTextField: UITextField!

and I want to keep track of their various events:

[UIControlEvents.EditingChanged, UIControlEvents.EditingDidBegin, UIControlEvents.EditingDidEnd ]

but I don't want to have 3 event separate event handlers so I created a single function like this. This function does a great job of telling me which UITextField fired an event but it doesn't tell me which event was triggered.:

fNameTextField.addTarget(self, action: "onChangeTextField:", forControlEvents: UIControlEvents.AllTouchEvents)
lNameTextField.addTarget(self, action: "onChangeTextField:", forControlEvents: UIControlEvents.AllTouchEvents)
emailTextField.addTarget(self, action: "onChangeTextField:", forControlEvents: UIControlEvents.AllTouchEvents)
phoneTextField.addTarget(self, action: "onChangeTextField:", forControlEvents: UIControlEvents.AllTouchEvents)

func onChangeTextField(sender:UITextField){
    switch(sender){
        case fNameTextField:
            print("First Name")
        case lNameTextField:
            print("Last Name")
        case emailTextField:
            print("E-mail")
        case phoneTextField:
            print("Phone")
        default: break
    }
}

How can I print both the name of the sender and the name of the event triggered (ex: .EditingDidEnd, .EditingDidEnd, .EditingDidEnd)?

Ideally, I do not want to write multiple event handlers, I'd prefer a single function.

Something like this:

func onChangeTextField(sender:UITextField){
    switch(sender.eventTriggerd){
        case UIControlEvents.EditingChanged:
            println("EditingChanged")
        case UIControlEvents.EditingDidBegin:
            println("EditingDidBegin")
        case UIControlEvents.EditingDidEnd:
            println("EditingDidEnd")
        default: break
    }
}

Body:
As matt said, this is not possible (and is indeed very irritating!). I've been using this little helper class to relieve myself of some of the typing.

Each UIControl.Event has a corresponding optional Selector. You can set only the selectors you need, and ignore the ones you don't.

class TargetActionMaker<T: UIControl> {

    var touchDown: Selector?
    var touchDownRepeat: Selector?
    var touchDragInside: Selector?
    var touchDragOutside: Selector?
    var touchDragEnter: Selector?
    var touchDragExit: Selector?
    var touchUpInside: Selector?
    var touchUpOutside: Selector?
    var touchCancel: Selector?
    var valueChanged: Selector?
    var primaryActionTriggered: Selector?
    var editingDidBegin: Selector?
    var editingChanged: Selector?
    var editingDidEnd: Selector?
    var editingDidEndOnExit: Selector?
    var allTouchEvents: Selector?
    var allEditingEvents: Selector?
    var applicationReserved: Selector?
    var systemReserved: Selector?
    var allEvents: Selector?

    func addActions(_ sender: T, target: Any?) {
        for selectorAndEvent in self.selectorsAndEvents() {
            if let action = selectorAndEvent.0 {
                sender.addTarget(target, action: action, for: selectorAndEvent.1)
            }
        }
    }

    private func selectorsAndEvents() -> [(Selector?, UIControl.Event)] {
        return [
            (self.touchDown, .touchDown),
            (self.touchDownRepeat, .touchDownRepeat),
            (self.touchDragInside, .touchDragInside),
            (self.touchDragOutside, .touchDragOutside),
            (self.touchDragEnter, .touchDragEnter),
            (self.touchDragExit, .touchDragExit),
            (self.touchUpInside, .touchUpInside),
            (self.touchUpOutside, .touchUpOutside),
            (self.touchCancel, .touchCancel),
            (self.valueChanged, .valueChanged),
            (self.primaryActionTriggered, .primaryActionTriggered),
            (self.editingDidBegin, .editingDidBegin),
            (self.editingChanged, .editingChanged),
            (self.editingDidEnd, .editingDidEnd),
            (self.editingDidEndOnExit, .editingDidEndOnExit),
            (self.allTouchEvents, .allTouchEvents),
            (self.allEditingEvents, .allEditingEvents),
            (self.applicationReserved, .applicationReserved),
            (self.systemReserved, .systemReserved),
            (self.allEvents, .allEvents)
        ]
    }
}

Use it like so:

class MyControl: UIControl {

    func setupSelectors() {
        let targetActionMaker = TargetActionMaker<MyControl>()
        targetActionMaker.touchDown = #selector(self.handleTouchDown(_:))
        targetActionMaker.touchUpInside = #selector(self.handleTouchUpInside(_:))
        targetActionMaker.touchUpOutside = #selector(self.handleTouchUpOutside(_:))
        targetActionMaker.addActions(self, target: self)
    }

    @objc func handleTouchDown(_ sender: MyControl) {
        print("handleTouchDown")
    }

    @objc func handleTouchUpInside(_ sender: MyControl) {
        print("handleTouchUpInside")
    }

    @objc func handleTouchUpOutside(_ sender: MyControl) {
        print("handleTouchUpOutside")
    }
}

Though, to be honest, in the end it really doesn't save you that much typing.