问:
springboot filter error when deployed on external tomcat
I have filter in my springboot application. When running the app in embedded tomcate 9.0.34 it works. however when I create war and deploy it on external tomcate 8.5 it throws below error.

28-May-2020 16:59:32.125 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.filterStart Exception starting filter [authenticationFilter]
    java.lang.AbstractMethodError
        at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:281)
        at org.apache.catalina.core.ApplicationFilterConfig.(ApplicationFilterConfig.java:110)
        at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4548)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5193)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:743)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:719)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:705)
        at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1720)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:287)
        at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
        at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
        at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:479)
        at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:428)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:287)
        at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
        at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
        at com.sun.jmx.remote.security.MBeanServerAccessController.invoke(MBeanServerAccessController.java:468)
        at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1468)
        at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
        at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1309)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1408)
        at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:829)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:357)
        at sun.rmi.transport.Transport$1.run(Transport.java:200)
        at sun.rmi.transport.Transport$1.run(Transport.java:197)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
        at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:573)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:834)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:688)
        at java.security.AccessController.doPrivileged(Native Method)
        at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:687)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
28-May-2020 16:59:32.126 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal One or more Filters failed to start.

答: My filter was implementing javax.servlet.Filter, not sure what was causing the issue but I eventually later extended org.springframework.web.filter.GenericFilterBean and the error vanished.</p>


来源: stackexchange

问:
Python triple quotes and percentage (%) syntax
I need to write a script to send an email using sendmail. The code that I'm looking at was found here: http://effbot.org/pyfaq/how-do-i-send-mail-from-a-python-script.htm

I am trying to figure out what this syntax means:

```<code>FROM = "sender@domain.ca"
TO = ["recipient@domain.ca"]

SUBJECT = "Hello!"

TEXT = "This message was sent via sendmail."

# Prepare actual message

message = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
</code>```

From what I can gather the triple quote is used when you need to create a very long string with keywords so that python doesn't try to interpret them. However the percentage used after the triple quote is what intrigues me. Is it some sort of concatenate operator like ampersand?

答:
I'm almost certain this is a duplicate of something but if it's not, what you're looking at is a formatted string. Triple quote is a valid way to form a string in python.

see https://www.learnpython.org/en/String_Formatting

ContentLicense: CC BY-SA 4.0

Body:
I need to write a script to send an email using sendmail. The code that I'm looking at was found here: http://effbot.org/pyfaq/how-do-i-send-mail-from-a-python-script.htm

I am trying to figure out what this syntax means:

FROM = "sender@domain.ca"
TO = ["recipient@domain.ca"]

SUBJECT = "Hello!"

TEXT = "This message was sent via sendmail."

# Prepare actual message

message = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

From what I can gather the triple quote is used when you need to create a very long string with keywords so that python doesn't try to interpret them. However the percentage used after the triple quote is what intrigues me. Is it some sort of concatenate operator like ampersand?


问:
"ORA-00600 Internal error" code when creating an OLAP cube
I'm creating an OLAP cube and I've a problem.

I'm using Oracle DB 12c and AWM 12.2 to create the cube. When I use "Maintain Cube" and load the data, I recieve an ORA-00600: Internal error code error.

The following is the log for the error:

```<code>2020-05-28T15:52:05.774911+02:00
ORCLPDB(3):ERROR: Unable to normalize symbol name for the following short stack (at offset 286):
dbgexProcessError()+398<-dbgePostErrorKGE()+2191<-dbkePostKGE_kgsf()+90<-kgeadse()+457<-kgerinv_internal()+86<-kgerinv()+63<-kgesinv()+43<-ksesin()+143<-xsTermIVX()+650<-xssqlEndAttrCB()+145<-xsldLoadDone()+216<-xsldInternalLoadQry()+3809<-xsldLoadDimQry()+2232<-xsoqLoadDimQry()+889<-?r12LoadDim@TxsOqStdFormCommand@@SAXPEAVTxsOqMdmPrimaryDimension@@PEAVTxsOqMdmDimensionLevel@@AEBVxswstring@@FW4ExsOqDimensionLoadPhase@@PEAV?$std_vector@PEAVTxsOqMdmAttributeMa()<-?runSQL@TxsOqLoadCommandProcessorDimensionContext@@QEAAXW4ExsOqDimensionLoadPhase@@PEAVTxsOqLoadCommandDimensionInfo@@AEAV?$std_vector@PEAVTxsOqMdmHierarchy@@@@PEAVTxsOqMdmBaseA()<-?loadAll@TxsOqLoadCommandProcessorDimensionContext@@QEAAXW4ExsOqDimensionLoadPhase@@AEBVxswstring@@PEAVTxsOqMdmBaseAttribute@@PEBUkscn@@@Z()+2459<-?loadDimension@TxsOqLoadCommandProcessor@@AEAAXPEBUkscn@@@Z()+531<-?run@TxsOqLoadCommandProcessor@@UEAAXXZ()+306<-?runCommand@TxsOqBuildCommandProcessor@@QEAAXXZ()+365<-?runNextCommand@TxsOqBuildItemProcessor@@QEAAFXZ()+97<-?runNextCommand@TxsOqBuildProcessor@@QEAAXXZ()+114<-?performNextAction@TxsOqBuildProcessor@@QEAAFXZ()+96<-?nextAction@TxsOqBuildProcessor@@QEAAFXZ()+63<-?performActions@TxsOqBuildProcessor@@QEAAXFPEAI0PEAUxsoqSCN@@@Z()+110<-?finishBuild@TxsOqBuildProcessor@@QEAAXFPEAI0PEAUxsoqSCN@@@Z()+178<-?execute@TxsOqBuildProcessor@@QEAAXAEBVxswstring@@PEAI@Z()+1898<-?executeBuild@TxsOqBuildProcessor@@SAXPEAVTxsOqConnection@@AEBVxswstring@@1IPEAIF11H1HPEAUxsoqSCN@@AEAVxsxmlwstring@@@Z()+493<-?executeBuild@TxsOqConnection@@QEAAXAEBVxswstring@@AEAVxsxmlwstring@@@Z()+811<-?generic@TxsOqConnection@@UEAAXPEBEPEBGAEAPEAG@Z()+1222<-?internal_cDataProvider_generic_so@@YAXPEAUOCIExtProcContext@@PEAUxsoqStreamContext@@@Z()+181<-xsoqStreamCallout()+1237<-eDataProvider_generic()+98<-spefcmpa()+323<-spefmccallstd()+303<-pextproc()+102<-peftrusted()+132<-psdexsp()+467<-kxe_push_env_internal_pp_()+786<-kkx_push_env_for_ICD_for_new_session()+151<-psdextp()+5
    Errors in file C:\USERS\USER\ORACLESUITE\ORACLEDB\diag\rdbms\orcl\orcl\trace\orcl_ora_4640.trc  (incident=64340) (PDBNAME=ORCLPDB):
    ORA-00600: codice di errore interno, argomenti: [xsTermIVX invalid position], [REVIEW_AW!DIM_BUSINESS_LEVELREL], [2], [], [], [], [], [], [], [], [], []
    ORCLPDB(3):Incident details in: C:\USERS\USER\ORACLESUITE\ORACLEDB\diag\rdbms\orcl\orcl\incident\incdir_64340\orcl_ora_4640_i64340.trc
</code>```

Can you help me solve this problem?
Thank you very much

答: By definition, ora-0600 is an "unhandled exception" (aka, "you hit a bug").  It will require Oracle Support to sort it out, and that requires a paid support contract.  If you already have that, When you log on to MOS, there is an 'ora-600 lookup tool' that will produce documents on known issues, based on the sub-codes that came with the ora-600.</p>

Body:
I'm creating an OLAP cube and I've a problem.

I'm using Oracle DB 12c and AWM 12.2 to create the cube. When I use "Maintain Cube" and load the data, I recieve an ORA-00600: Internal error code error.

The following is the log for the error:

2020-05-28T15:52:05.774911+02:00
ORCLPDB(3):ERROR: Unable to normalize symbol name for the following short stack (at offset 286):
dbgexProcessError()+398<-dbgePostErrorKGE()+2191<-dbkePostKGE_kgsf()+90<-kgeadse()+457<-kgerinv_internal()+86<-kgerinv()+63<-kgesinv()+43<-ksesin()+143<-xsTermIVX()+650<-xssqlEndAttrCB()+145<-xsldLoadDone()+216<-xsldInternalLoadQry()+3809<-xsldLoadDimQry()+2232<-xsoqLoadDimQry()+889<-?r12LoadDim@TxsOqStdFormCommand@@SAXPEAVTxsOqMdmPrimaryDimension@@PEAVTxsOqMdmDimensionLevel@@AEBVxswstring@@FW4ExsOqDimensionLoadPhase@@PEAV?$std_vector@PEAVTxsOqMdmAttributeMa()<-?runSQL@TxsOqLoadCommandProcessorDimensionContext@@QEAAXW4ExsOqDimensionLoadPhase@@PEAVTxsOqLoadCommandDimensionInfo@@AEAV?$std_vector@PEAVTxsOqMdmHierarchy@@@@PEAVTxsOqMdmBaseA()<-?loadAll@TxsOqLoadCommandProcessorDimensionContext@@QEAAXW4ExsOqDimensionLoadPhase@@AEBVxswstring@@PEAVTxsOqMdmBaseAttribute@@PEBUkscn@@@Z()+2459<-?loadDimension@TxsOqLoadCommandProcessor@@AEAAXPEBUkscn@@@Z()+531<-?run@TxsOqLoadCommandProcessor@@UEAAXXZ()+306<-?runCommand@TxsOqBuildCommandProcessor@@QEAAXXZ()+365<-?runNextCommand@TxsOqBuildItemProcessor@@QEAAFXZ()+97<-?runNextCommand@TxsOqBuildProcessor@@QEAAXXZ()+114<-?performNextAction@TxsOqBuildProcessor@@QEAAFXZ()+96<-?nextAction@TxsOqBuildProcessor@@QEAAFXZ()+63<-?performActions@TxsOqBuildProcessor@@QEAAXFPEAI0PEAUxsoqSCN@@@Z()+110<-?finishBuild@TxsOqBuildProcessor@@QEAAXFPEAI0PEAUxsoqSCN@@@Z()+178<-?execute@TxsOqBuildProcessor@@QEAAXAEBVxswstring@@PEAI@Z()+1898<-?executeBuild@TxsOqBuildProcessor@@SAXPEAVTxsOqConnection@@AEBVxswstring@@1IPEAIF11H1HPEAUxsoqSCN@@AEAVxsxmlwstring@@@Z()+493<-?executeBuild@TxsOqConnection@@QEAAXAEBVxswstring@@AEAVxsxmlwstring@@@Z()+811<-?generic@TxsOqConnection@@UEAAXPEBEPEBGAEAPEAG@Z()+1222<-?internal_cDataProvider_generic_so@@YAXPEAUOCIExtProcContext@@PEAUxsoqStreamContext@@@Z()+181<-xsoqStreamCallout()+1237<-eDataProvider_generic()+98<-spefcmpa()+323<-spefmccallstd()+303<-pextproc()+102<-peftrusted()+132<-psdexsp()+467<-kxe_push_env_internal_pp_()+786<-kkx_push_env_for_ICD_for_new_session()+151<-psdextp()+5
    Errors in file C:\USERS\USER\ORACLESUITE\ORACLEDB\diag\rdbms\orcl\orcl\trace\orcl_ora_4640.trc  (incident=64340) (PDBNAME=ORCLPDB):
    ORA-00600: codice di errore interno, argomenti: [xsTermIVX invalid position], [REVIEW_AW!DIM_BUSINESS_LEVELREL], [2], [], [], [], [], [], [], [], [], []
    ORCLPDB(3):Incident details in: C:\USERS\USER\ORACLESUITE\ORACLEDB\diag\rdbms\orcl\orcl\incident\incdir_64340\orcl_ora_4640_i64340.trc

Can you help me solve this problem?
Thank you very much


问:
Updated row in table only by valid values and skip undefined values
I have next method which updates row:

```<code>  await db.query(`
    UPDATE some_table
    SET value1 = $1, value12 = $2, value2 = $3
    WHERE id $5
  `, [value1, value2, value3, id]);
</code>```

How to modify this query, that it will skip for example value2 and value3, if they are undefined and update only column value1?

答:
Shortcircuit is the way to go, basically the set is only added if value1-3 are not undefined

```<code>let sql = `UPDATE some_table
           SET ${$value1 !== undefined ? 'value1 = $value1, ' : ''}
               ${$value2 !== undefined ? 'value12 = $value2, ' : ''}
               ${$value3 !== undefined ? 'value3 = $value3, ' : ''}`;
sql.slice(0,-2); // remove last space and comma
sql += ' WHERE id ${id}';
await db.query(sql);
</code>```

Don't recommend using c style to add parameters ($1, $2 etc.) it makes it harder to read the code.

Body:
I have next method which updates row:

  await db.query(`
    UPDATE some_table
    SET value1 = $1, value12 = $2, value2 = $3
    WHERE id $5
  `, [value1, value2, value3, id]);

How to modify this query, that it will skip for example value2 and value3, if they are undefined and update only column value1?

Body:
Shortcircuit is the way to go, basically the set is only added if value1-3 are not undefined

let sql = `UPDATE some_table
           SET ${$value1 !== undefined ? 'value1 = $value1, ' : ''}
               ${$value2 !== undefined ? 'value12 = $value2, ' : ''}
               ${$value3 !== undefined ? 'value3 = $value3, ' : ''}`;
sql.slice(0,-2); // remove last space and comma
sql += ' WHERE id ${id}';
await db.query(sql);

Don't recommend using c style to add parameters ($1, $2 etc.) it makes it harder to read the code.


问:
How to retrieve added doc data in Firestore?
I have such code where I can get new inserted doc id:

```<code>db.collection("cities").add({
   name: "Tokyo",
   country: "Japan"
})
.then(function(docRef) {
   console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
   console.error("Error adding document: ", error);
});
</code>```

Is it possible to get data from ref?

答:
I found solution</p>

```<code>static async createUserPofile(uid) {
    const db = Firebase.firestore(),
        date = Firebase.firestore.FieldValue.serverTimestamp(),
        data ={
            user_id: uid,
            creation_time: date,
            update_time: date
        },
        docRef = await db.collection("user_profiles").add(data),
        get = await docRef.get();
    return get.data();
}
</code>```

Body:
I have such code where I can get new inserted doc id:

db.collection("cities").add({
   name: "Tokyo",
   country: "Japan"
})
.then(function(docRef) {
   console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
   console.error("Error adding document: ", error);
});

Is it possible to get data from ref?

Body:
I found solution

static async createUserPofile(uid) {
    const db = Firebase.firestore(),
        date = Firebase.firestore.FieldValue.serverTimestamp(),
        data ={
            user_id: uid,
            creation_time: date,
            update_time: date
        },
        docRef = await db.collection("user_profiles").add(data),
        get = await docRef.get();
    return get.data();
}


问:
Significance of "-" in place of user name in Tomcat Access Log
I have a JIRA instance running on Tomcat. I am trying to parse the Tomcat Access Log to finally display it in a Kibana Dashboard so that I can monitor the usage.

My typical access log line looks like this :

```<code>100.10.10.10 1x756917x1 collabin [12/May/2020:00:01:25 +0530] "GET /rest/api/2/project/ABC HTTP/1.1" 200 4759 466 "-" "-" "11nppm7"
</code>```

where "collabin" is the user name which is clear for me.

I noticed many other log lines where the user name is just a "-". For example when a user loads a JIRA dashboard:

```<code>100.10.10.10 1x756921x1 - [12/May/2020:00:01:38 +0530] "GET /secure/Dashboard.jspa HTTP/1.1" 200 36019 147 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)" "-"
</code>```

What can be inferred from a user name which is "-" ? Should I monitor the adjacent log lines to get the actual user who loaded the Dashboard ? Or should I treat them as JIRA internal calls and discard ?

I have searched for an answer and what I got is "it is the Remote user that has been authenticated. If there is none, it’s a hyphen (-)". I would be really grateful if you can explain in terms of JIRA.

答: The - in place of the username indicates no user has been authenticated. This will happen, for example, before the user has logged-in. This is nothing JIRA-specific.

Body:
I have a JIRA instance running on Tomcat. I am trying to parse the Tomcat Access Log to finally display it in a Kibana Dashboard so that I can monitor the usage.

My typical access log line looks like this :

100.10.10.10 1x756917x1 collabin [12/May/2020:00:01:25 +0530] "GET /rest/api/2/project/ABC HTTP/1.1" 200 4759 466 "-" "-" "11nppm7"

where "collabin" is the user name which is clear for me.

I noticed many other log lines where the user name is just a "-". For example when a user loads a JIRA dashboard:

100.10.10.10 1x756921x1 - [12/May/2020:00:01:38 +0530] "GET /secure/Dashboard.jspa HTTP/1.1" 200 36019 147 "-" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)" "-"

What can be inferred from a user name which is "-" ? Should I monitor the adjacent log lines to get the actual user who loaded the Dashboard ? Or should I treat them as JIRA internal calls and discard ?

I have searched for an answer and what I got is "it is the Remote user that has been authenticated. If there is none, it’s a hyphen (-)". I would be really grateful if you can explain in terms of JIRA.


问:
Dynamic search : Pandas data frame query
I am trying to take a string (word or phrase) user input to search for sub string in a particular column to query the results. How can i make it dynamic ? i.e. i want to keep adding the words as new queries to locate the item without having to define it.

eg. if input is - 'word1';
it returns all rows with 'word1' in df['column']

and if input is - 'word1 word2 wordn';
it returns all rows with the query as below :

```<code>x = input("Type to search for item : ")  # input phrase or word
words = x.split(' ')

query = df.loc[(df['Column'].str.contains(words[0]))
           &(df['Column'].str.contains(words[1]))
           &(df['Column'].str.contains(words[n]))
           ]
</code>```

答:
How about </p>

```<code>submasks = [df['Column'].str.contains(s) for s in words]
combined = np.vstack(submasks).all(axis=0)
df[combined]
</code>```

Body:
I am trying to take a string (word or phrase) user input to search for sub string in a particular column to query the results. How can i make it dynamic ? i.e. i want to keep adding the words as new queries to locate the item without having to define it.

eg. if input is - 'word1';
it returns all rows with 'word1' in df['column']

and if input is - 'word1 word2 wordn';
it returns all rows with the query as below :

x = input("Type to search for item : ")  # input phrase or word
words = x.split(' ')

query = df.loc[(df['Column'].str.contains(words[0]))
           &(df['Column'].str.contains(words[1]))
           &(df['Column'].str.contains(words[n]))
           ]

Body:
How about

submasks = [df['Column'].str.contains(s) for s in words]
combined = np.vstack(submasks).all(axis=0)
df[combined]


问:
How to select columns which has different value from two table?
I have two tables which are having same columns
ex, Table A and Table B

Table A:

```<code>Name  Address   Phone
A     Add1      123
</code>```

Table B:

```<code>Name  Address   Phone
A     Add1      12345
</code>```

i want to select only column which has different value

Expected Output:

```<code>Phone
123
1234
</code>```

答:
```<code>SELECT Phones.Phone
FROM A
INNER JOIN b ON A.Name = B.Name AND A.Addr = B.Addr AND A.Phone <> B.Phone
CROSS APPLY (
  SELECT Phone = A.Phone
  UNION ALL
  SELECT Phone = B.Phone
) AS Phones
</code>```

Body:
I have two tables which are having same columns
ex, Table A and Table B

Table A:

Name  Address   Phone
A     Add1      123

Table B:

Name  Address   Phone
A     Add1      12345

i want to select only column which has different value

Expected Output:

Phone
123
1234


问:
C - Adding the numbers in 2 strings together if a different length
If I had two strings:

```<code>a = "1234"
b = "4321"
</code>```

I could add the two numbers together like this:

```<code>for(i=0; i<width-1; i++){
    sum = (a[width-2-i]-48) + (b[width-2-i]-48) + carry;
    carry = 0;
    if(sum > 9){
        carry = 1;
        sum-=10;
    }
    answer[i] = sum+48;
}

if(carry) answer[i++] = carry+48;
answer[i]= 0;
</code>```

And then reverse it (width is equal to strlen(a)).

How could I do the same thing if the following?

```<code>a = "12345"
b = "4321"
</code>```

Would I need to reallocate memory? Or what?

(BTW - the problem I'm trying to solve is using many numbers all with 50 digits, so strtoul or strtoull is out of the question as I understand. Here's my code so far.)

ContentLicense: CC BY-SA 3.0

Body:
If I had two strings:

a = "1234"
b = "4321"

I could add the two numbers together like this:

for(i=0; i<width-1; i++){
    sum = (a[width-2-i]-48) + (b[width-2-i]-48) + carry;
    carry = 0;
    if(sum > 9){
        carry = 1;
        sum-=10;
    }
    answer[i] = sum+48;
}

if(carry) answer[i++] = carry+48;
answer[i]= 0;

And then reverse it (width is equal to strlen(a)).

How could I do the same thing if the following?

a = "12345"
b = "4321"

Would I need to reallocate memory? Or what?

(BTW - the problem I'm trying to solve is using many numbers all with 50 digits, so strtoul or strtoull is out of the question as I understand. Here's my code so far.)

Body:
int num(char x,int len){
    if(len <0)
        return 0;
    return ((x=='1') ? 1 :  (x=='2') ? 2 : (x=='3') ? 3 : (x=='4') ? 4 : (x=='5') ? 5 : (x=='6') ? 6 : (x=='7') ? 7 : (x=='8') ? 8 : 9);
}

int main(){

    int result[100];
    int i=0;
    char num1[] = "123456789123456789";
    char num2[] = "1234567811111111111111111111";
    int carry = 0;
    int l1= strlen(num1)-1;
    int l2 = strlen(num2)-1;
    int result1;

    while(1){
        if(l1 < 0  && l2 <0 && carry == 0)
            break;
        result1 = num(num1[l1],l1) + num(num2[l2],l2);
        l1--;
        l2--;
        if(carry>0){
            result1 +=carry;
            carry = 0;
        }
        carry = result1 / 10;
        result[i] = (result1 % 10);
        i++;
    }

    i--;
    printf("\n");

    while(i>=0){
            printf("%d",result[i]);
            i--;
    }

}


问:
Replace everything from a string when it reaches a match
Given:

```<code>path = 'abc/dfg/zxc'
</code>```

Is there a way to replace the string before the first '/' with '.' ?

Expected result:

```<code>'./dfg/zxc'
</code>```

What i have tried, this approah is messy and i am wondering if there is a cleaner one to solving this issue?:

```<code> lst = path.split()

from_index = lst[0].index('/')
to_index = len(lst[0])

new_list = lst[0][from_index -1 + 1:to_index]
new_str = ''.join(new_list)
new_str2 = '.' + new_str
</code>```

答:
You should do like this:</p>

```<code>path = path.replace(path[0:path.find("/")], ".")
</code>```

Body:
Given:

path = 'abc/dfg/zxc'

Is there a way to replace the string before the first '/' with '.' ?

Expected result:

'./dfg/zxc'

What i have tried, this approah is messy and i am wondering if there is a cleaner one to solving this issue?:

 lst = path.split()

from_index = lst[0].index('/')
to_index = len(lst[0])

new_list = lst[0][from_index -1 + 1:to_index]
new_str = ''.join(new_list)
new_str2 = '.' + new_str

Body:
You should do like this:

path = path.replace(path[0:path.find("/")], ".")


问:
Can I plot/filter just the peak value per day in excel
I have a dataset which is amount (parts per million) against time (every minute)

I need to find the peak for each day, so that I can plot that against other data, I can manually do this using =MAX( but I have a lot of data points and I am sure there is a better way

Many Thanks for the help

答:
I don't know where and how you want show this data, but, if you want get a max value amount per day, you can try add an array formula, like that:

```<code>=MAX(IF($COL_DATES = $DAY, $COL_VALUE, 0))
</code>```

Replace $COL_DATES to your column of day date, replace $DAY to value of day what you want get max value and replace $COL_VALUE to your column of values.

After press CTRL + SHIFT + Enter

Body:
I don't know where and how you want show this data, but, if you want get a max value amount per day, you can try add an array formula, like that:

=MAX(IF($COL_DATES = $DAY, $COL_VALUE, 0))

Replace $COL_DATES to your column of day date, replace $DAY to value of day what you want get max value and replace $COL_VALUE to your column of values.

After press CTRL + SHIFT + Enter


问:
How do I do an IF in Microsoft SQL SELECT query?
I am an absolute beginner in SQL.
Example:
I want to do a query to select people whose names begin with X if the result is 0, I want to select people whose names begin with Y.

How do I do this? Thanks.

答:
I interpret the question as: show names starting with Y if no names starting with X are found.
This solution will be fast as it will short-cut the exists from the moment 1 record is found

```<code>if exists(select * from table where name like 'X%')
  begin
    select * from table where name like 'X%'
  end
else
  begin
    select * from table where name like 'Y%'
  end
</code>```

Ideally the name column is indexed for this to work well.

Body:
I interpret the question as: show names starting with Y if no names starting with X are found.
This solution will be fast as it will short-cut the exists from the moment 1 record is found

if exists(select * from table where name like 'X%')
  begin
    select * from table where name like 'X%'
  end
else
  begin
    select * from table where name like 'Y%'
  end

Ideally the name column is indexed for this to work well.


问:
pip3: command not found but python3-pip is already installed
I can't use pip3 though python3-pip has already been installed. How to solve the problem?</p>

```<code>sudo pip3 install virtualenv
sudo: pip3: command not found

sudo apt-get install python3-pip
Reading package lists... Done
Building dependency tree
Reading state information... Done
python3-pip is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 11 not upgraded.
</code>```

答:
For Kali, you must use this code after the update.

```<code>$sudo python3 get-pip.py
</code>```

or if you write this, it also works but not supported anymore. So don't use:

```<code>$sudo python get-pip.py
</code>```

Body:
I can't use pip3 though python3-pip has already been installed. How to solve the problem?

sudo pip3 install virtualenv
sudo: pip3: command not found

sudo apt-get install python3-pip
Reading package lists... Done
Building dependency tree
Reading state information... Done
python3-pip is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 11 not upgraded.

Body:
For Kali, you must use this code after the update.

$sudo python3 get-pip.py

or if you write this, it also works but not supported anymore. So don't use:

$sudo python get-pip.py


问:
How to get List<Object[]> from a query using Spring Jdbc
I use Spring Jdbc for queries. I need to execute select from the database, but I don't know how many columns in the table to get the result from resultset (for example, for RowMapper).I would like to get List<Object[]>. Is it possible? And how can I get data without knowing the number of columns in the database?

答:
If you want a List as the result, you should definitely question your conceptual approach for what you are trying to achieve.
Ask yourself if you really can't or don't want to know in advance what colums you will receive, and how will you handle the unknown types of these columns?
You would make your life way easier if you have static model classes with statically typed fields that neatly map to your result set; and if you do this, you can even skip jdbc alltoghter and let Spring Data all the query and Resultset mapping work.

But if this really is not an option for you, then at least don't map your result rows to an Object array, but rather to simple JSON objector a Map, unless you don't care much about what value belonged to what column.


问:
Segue to new View Controller from button on table view navigation bar
I would like to add a button on navigation bar of a UITableViewController that will segue to a new UIViewController.

Control-dragging a button from one VC to a new VC (VC-A to VC-B) works perfectly, even providing a button on VC-B's navigation bar to return to VC-A.

However, putting a button on the navigation bar of a Table VC, then control-dragging it to the new VC (TVC-C to VC-D), appears to do the same thing, providing the return button on VC-D in storyboard, but when I run it, it does not open VC-D.

I noticed that putting a button on the Table View's navigation bar turns it into a Bar Button, whereas placing one on a VC does not.  Does this have something to do with it?  How do I get around that?

(Using XCode 10, Swift 4)

答: Instead of a Table View Controller, I used a TableView on a View Controller.</p>


问:
How to find acrued billing charges for Windows Azure
Is there a way or place to go to find out how much usage and ultimately costs have accrued against your Windows Azure account ? I am really interested in usage details so that I can get an estimate of costs for our application in test and try to predict when I scale it out.</p>

答:
You cannot get a complete picture of metering / billing info programatically. However, your Windows Azure account has detailed monthly billing statements that break everything down: compute time per role, bandwidth, storage consumption, etc.

Here's the link on the portal, at windows.azure.com:

Then, sign in:

Finally: view your bills:

EDIT: If you need a tool to generate load on your system, for metering/billing purposes, you can easily do so with something like LoadStorm, as it's Testing-as-a-Service with nothing to install. Alternatively, you can use Visual Studio's test agents, but then you'll be throttled by local resources (load generation machines and bandwidth).


问:
How to add a list of tags to a Flask > WTForms > Jinja2 form?
I'm building a web form and trying to allow users to autocomplete a list of tags (much like StackOverflow uses here) without reloading the form, which can then be submitted en masse with a click of the Submit button.

The engine is a simple python function that appends an empty list of tags but I can't seem to integrate the function correctly.

I suspect the issue is that the page is reloading when I click the 'Add' button but I'm not sure and even less sure how to prevent it.

Thanks for your help. Code below:

HTML:

```<code><form class="centered" action="" method="post" role="form" autocomplete=off>
    {{ form.hidden_tag() }}
    <p>{{ form.toppings(type="text", list="topps", placeholder="| e.g. cheese, tomato, etc.", **{"onchange":"addTag(tag,tags)"}) }}
    <datalist id="topps">
        {% for top in topps %}
        <option value={{ top }}>
        {% endfor %}
    </datalist>
    <span>{{ form.add(**{"onchange":"addTag(tag,tags)"}) }}</span></p><br>
    <p>
        {% for tag in tags %}
        <span>{{ tag }} {{ form.remove(value="x",**{"onchange":"tags.pop(0)"}) }}</span>
        {% endfor %}
    </p><br>
    <p>{{ form.submit(type="submit", value="Submit") }}</p>
    <p>{{ form.reset(type="reset", value="Reset", **{"onchange":"tags=[]"}) }}</p>
</form>
</code>```

FLASK PYTHON:

```<code>@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    form = ToppingsForm()
    topps = Topps.query.all()
    tag = ''
    tags = []
    def addTag(tag,tags):
        if tag not in tags:
            tags.append(tag)
        else:
            tag = ''
    addTag = addTag(tag,tags)
    return render_template('index.html', title='Home', form=form, topps=topps, tag=tag,
tags=tags, addTag=addTag)
</code>```

FORMS.py:

```<code>from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired

class ToppingsForm(FlaskForm):
    toppings = StringField('Toppings', validators=[DataRequired()])
    agree = BooleanField('Agree', validators=[DataRequired()])
    add = SubmitField('Add')
    remove = SubmitField('x')
    reset = SubmitField('Reset')
    submit = SubmitField('Submit')
</code>```

答:
So I believe what you are looking for is "SelectMultipleField" provided by wtfform.
You want something like this:

```<code>class ToppingsForm(FlaskForm):
    #toppings = StringField('Toppings', validators=[DataRequired()])
    toppings = SelectMultipleField('Toppings', choices=[],validators=[DataRequired()])
    #agree = BooleanField('Agree', validators=[DataRequired()])
    #add = SubmitField('Add')
    #remove = SubmitField('x')
    #reset = SubmitField('Reset')
    submit = SubmitField('Submit')
</code>```

```<code>@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    form = ToppingsForm()
    choices = [("cheese","cheese"), ("tomato","tomato"),("anchovies","anchovies"),("anchovies","mozarella")]
    form.toppings.choices = choices #you would change this to something like this[(c.id, c.name) for c in Topps.query.all()]

    if form.validate_on_submit():
        print(form.toppings.data)
        return "success"
    return render_template('base.html', title='Home', form=form)
</code>```

Look into how to use SelectMultipleFields for more example

Body:
I'm building a web form and trying to allow users to autocomplete a list of tags (much like StackOverflow uses here) without reloading the form, which can then be submitted en masse with a click of the Submit button.

The engine is a simple python function that appends an empty list of tags but I can't seem to integrate the function correctly.

I suspect the issue is that the page is reloading when I click the 'Add' button but I'm not sure and even less sure how to prevent it.

Thanks for your help. Code below:

HTML:

<form class="centered" action="" method="post" role="form" autocomplete=off>
    {{ form.hidden_tag() }}

{{ form.toppings(type="text", list="topps", placeholder="| e.g. cheese, tomato, etc.", **{"onchange":"addTag(tag,tags)"}) }}
    <datalist id="topps">
        {% for top in topps %}
        <option value={{ top }}>
        {% endfor %}
    </datalist>
    {{ form.add(**{"onchange":"addTag(tag,tags)"}) }}

        {% for tag in tags %}
        {{ tag }} {{ form.remove(value="x",**{"onchange":"tags.pop(0)"}) }}
        {% endfor %}

{{ form.submit(type="submit", value="Submit") }}

{{ form.reset(type="reset", value="Reset", **{"onchange":"tags=[]"}) }}

</form>

FLASK PYTHON:

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    form = ToppingsForm()
    topps = Topps.query.all()
    tag = ''
    tags = []
    def addTag(tag,tags):
        if tag not in tags:
            tags.append(tag)
        else:
            tag = ''
    addTag = addTag(tag,tags)
    return render_template('index.html', title='Home', form=form, topps=topps, tag=tag,
tags=tags, addTag=addTag)

FORMS.py:

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired

class ToppingsForm(FlaskForm):
    toppings = StringField('Toppings', validators=[DataRequired()])
    agree = BooleanField('Agree', validators=[DataRequired()])
    add = SubmitField('Add')
    remove = SubmitField('x')
    reset = SubmitField('Reset')
    submit = SubmitField('Submit')

Body:
So I believe what you are looking for is "SelectMultipleField" provided by wtfform.
You want something like this:

class ToppingsForm(FlaskForm):
    #toppings = StringField('Toppings', validators=[DataRequired()])
    toppings = SelectMultipleField('Toppings', choices=[],validators=[DataRequired()])
    #agree = BooleanField('Agree', validators=[DataRequired()])
    #add = SubmitField('Add')
    #remove = SubmitField('x')
    #reset = SubmitField('Reset')
    submit = SubmitField('Submit')

@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    form = ToppingsForm()
    choices = [("cheese","cheese"), ("tomato","tomato"),("anchovies","anchovies"),("anchovies","mozarella")]
    form.toppings.choices = choices #you would change this to something like this[(c.id, c.name) for c in Topps.query.all()]

    if form.validate_on_submit():
        print(form.toppings.data)
        return "success"
    return render_template('base.html', title='Home', form=form)

Look into how to use SelectMultipleFields for more example


问:
Emacs Configuration
I am trying to get started with Emacs/Clojure. What is the proper way to install emacs extensions. I am trying to install the the following plugin:

https://bitbucket.org/kotarak/vimclojure

I have placed it in ~/.emacs/plugins but it does not work.

答: Straight from the horse's mouth: Getting Started with Emacs</p>

Title: Emacs Configuration


问:
Select Date and Numeric columns only
Is there an efficient way to select Date and numeric columns in R?

```<code>df <- data.frame(
    Date=c("10/11/2012","10/12/2012"),
    AE=c(1211,100),
    Percent=c(0.03,0.43),
    Name = c("A", "B")
)
</code>```

As such I can use is.numeric function to check if a column is numeric or not and then use one of several ways to subset, but is there a function to check if a column is date and how to use multiple conditions for subseting.

I found that there is a funciton is.Date in lubridate package but it did not work

```<code>#does not work
df <- df %>%
    select_if(is.numeric|is.Date)
</code>```

答:
dplyr verbs for selection allow various methods of providing the conditionals>

raw functions, as in is.numeric, which will be called with the column data (a vector) as its one argument;

anonymous functions (R style), as in function(x) is.numeric(x) | inherits(x, "Date");

what is called a "purrr style lambda" using R formulas (~), which seems to be just a more compact form of the base R anon-func, but there are a some differences, namely you use . or .x as a placeholder for the column data, as in the answer below

df %>%
  select_if(~ is.numeric(.) | inherits(., "Date"))
#     AE Percent
# 1 1211    0.03
# 2  100    0.43
```

<p>Since your first column is not actually a date, let's fix that</p>

<pre class="lang-r prettyprint-override"><code># df$Date <- as.Date(df$Date, format="%m/%d/%Y")
df %>%
  mutate(Date = as.Date(Date, format="%m/%d/%Y")) %>%
  select_if(~ is.numeric(.x) | inherits(.x, "Date"))
#         Date   AE Percent
# 1 2012-10-11 1211    0.03
# 2 2012-10-12  100    0.43
</code>```

Title: Select Date and Numeric columns only

Body:
Is there an efficient way to select Date and numeric columns in R?

df <- data.frame(
    Date=c("10/11/2012","10/12/2012"),
    AE=c(1211,100),
    Percent=c(0.03,0.43),
    Name = c("A", "B")
)

As such I can use is.numeric function to check if a column is numeric or not and then use one of several ways to subset, but is there a function to check if a column is date and how to use multiple conditions for subseting.

I found that there is a funciton is.Date in lubridate package but it did not work

#does not work
df <- df %>%
    select_if(is.numeric|is.Date)

Body:
dplyr verbs for selection allow various methods of providing the conditionals>

raw functions, as in is.numeric, which will be called with the column data (a vector) as its one argument;

anonymous functions (R style), as in function(x) is.numeric(x) | inherits(x, "Date");

what is called a "purrr style lambda" using R formulas (~), which seems to be just a more compact form of the base R anon-func, but there are a some differences, namely you use . or .x as a placeholder for the column data, as in the answer below

df %>%
  select_if(~ is.numeric(.) | inherits(., "Date"))
#     AE Percent
# 1 1211    0.03
# 2  100    0.43

Since your first column is not actually a date, let's fix that

# df$Date <- as.Date(df$Date, format="%m/%d/%Y")
df %>%
  mutate(Date = as.Date(Date, format="%m/%d/%Y")) %>%
  select_if(~ is.numeric(.x) | inherits(.x, "Date"))
#         Date   AE Percent
# 1 2012-10-11 1211    0.03
# 2 2012-10-12  100    0.43


问:
Queryselector() returns null inside javascript module pattern
I have created a module containing a variable that looks up a html element via DOM's querySelector. However, the var expoElement returns 'null'. Any thoughts?</p>

```<code>var test = (function(){

    //find components
    var expoElement = document.querySelector(".expo");

    return {

        returnJow:function(){alert("the return = " + expoElement)}

    }

})();

test.returnJow();
</code>```

答:
The issue is at the HTML end.

While adding your javascript file in the HTML file make sure that you add  tag   after the .

Body:
I have created a module containing a variable that looks up a html element via DOM's querySelector. However, the var expoElement returns 'null'. Any thoughts?

var test = (function(){

    //find components
    var expoElement = document.querySelector(".expo");

    return {

        returnJow:function(){alert("the return = " + expoElement)}

    }

})();

test.returnJow();

Body:
The issue is at the HTML end.

While adding your javascript file in the HTML file make sure that you add <script src="YOURFILE.js"></script> tag   after the </body>.


问:
Get gradients with respect to inputs in Keras ANN model
```<code>bce = tf.keras.losses.BinaryCrossentropy()
ll=bce(y_test[0], model.predict(X_test[0].reshape(1,-1)))
print(ll)
<tf.Tensor: shape=(), dtype=float32, numpy=0.04165391>
print(model.input)
<tf.Tensor 'dense_1_input:0' shape=(None, 195) dtype=float32>
model.output
<tf.Tensor 'dense_3/Sigmoid:0' shape=(None, 1) dtype=float32>
grads=K.gradients(ll, model.input)[0]
print(grads)
None
</code>```

So here i have Trained a 2 hidden layer neural network, input has 195 features and output is 1 size. I wanted to feed the neural network with validation instances  named as X_test one by one with their correct labels in y_test and for each instance calculate the gradients of the output with respect to input, the grads upon printing gives me a None. Your help is appreciated.

答:
One can do this using tf.GradientTape. I wrote the following code to learn a sin wave, and get its derivative in the spirit of this question. I think, it should be possible to extend the following codes in order to compute partial derivatives.

Importing the needed libraries:

```<code>import numpy as np
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.optimizers import Adam
from tensorflow.keras import losses
import tensorflow as tf
</code>```

Create the data:

```<code>x = np.linspace(0, 6*np.pi, 2000)
y = np.sin(x)
</code>```

Defining a Keras NN:

```<code>def model_gen(Input_shape):
    X_input = Input(shape=Input_shape)
    X = Dense(units=64, activation='sigmoid')(X_input)
    X = Dense(units=64, activation='sigmoid')(X)
    X = Dense(units=1)(X)
    model = Model(inputs=X_input, outputs=X)
    return model
</code>```

Training the model:

```<code>model = model_gen(Input_shape=(1,))
opt = Adam(lr=0.01, beta_1=0.9, beta_2=0.999, decay=0.001)
model.compile(loss=losses.mean_squared_error, optimizer=opt)
model.fit(x,y, epochs=200)
</code>```

To obtain the gradient of the network w.r.t. the input:

```<code>x = list(x)
x = tf.constant(x)
with tf.GradientTape() as t:
  t.watch(x)
  y = model(x)

dy_dx = t.gradient(y, x)

dy_dx.numpy()
</code>```

One can further visualise dy_dx to make sure of how smooth the derivative is. Finally, note that one get a smoother derivative when one uses a smooth activation (e.g. sigmoid) instead of Relu as noted here.

Body:
bce = tf.keras.losses.BinaryCrossentropy()
ll=bce(y_test[0], model.predict(X_test[0].reshape(1,-1)))
print(ll)
<tf.Tensor: shape=(), dtype=float32, numpy=0.04165391>
print(model.input)
<tf.Tensor 'dense_1_input:0' shape=(None, 195) dtype=float32>
model.output
<tf.Tensor 'dense_3/Sigmoid:0' shape=(None, 1) dtype=float32>
grads=K.gradients(ll, model.input)[0]
print(grads)
None

So here i have Trained a 2 hidden layer neural network, input has 195 features and output is 1 size. I wanted to feed the neural network with validation instances  named as X_test one by one with their correct labels in y_test and for each instance calculate the gradients of the output with respect to input, the grads upon printing gives me a None. Your help is appreciated.

Body:
One can do this using tf.GradientTape. I wrote the following code to learn a sin wave, and get its derivative in the spirit of this question. I think, it should be possible to extend the following codes in order to compute partial derivatives.

Importing the needed libraries:

import numpy as np
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.optimizers import Adam
from tensorflow.keras import losses
import tensorflow as tf

Create the data:

x = np.linspace(0, 6*np.pi, 2000)
y = np.sin(x)

Defining a Keras NN:

def model_gen(Input_shape):
    X_input = Input(shape=Input_shape)
    X = Dense(units=64, activation='sigmoid')(X_input)
    X = Dense(units=64, activation='sigmoid')(X)
    X = Dense(units=1)(X)
    model = Model(inputs=X_input, outputs=X)
    return model

Training the model:

model = model_gen(Input_shape=(1,))
opt = Adam(lr=0.01, beta_1=0.9, beta_2=0.999, decay=0.001)
model.compile(loss=losses.mean_squared_error, optimizer=opt)
model.fit(x,y, epochs=200)

To obtain the gradient of the network w.r.t. the input:

x = list(x)
x = tf.constant(x)
with tf.GradientTape() as t:
  t.watch(x)
  y = model(x)

dy_dx = t.gradient(y, x)

dy_dx.numpy()

One can further visualise dy_dx to make sure of how smooth the derivative is. Finally, note that one get a smoother derivative when one uses a smooth activation (e.g. sigmoid) instead of Relu as noted here.


问:
No space left on device when pulling an image
Using Docker 1.13.0 (9795) under Windows 10 Build 14393, I'm getting "no space left on device" when trying to run the latest python image (which would be 3.6):

```<code>> docker run -it python
Unable to find image 'python:latest' locally
latest: Pulling from library/python
5040bd298390: Pull complete
fce5728aad85: Pull complete
76610ec20bf5: Pull complete
52f3db4b5710: Extracting [==================================================>] 129.8 MB/129.8 MB
45b2a7e03e44: Download complete
75ef15b2048b: Download complete
e41da2f0bac3: Download complete
C:\Program Files\Docker\Docker\Resources\bin\docker.exe: failed to register layer: Error processing tar file(exit status
 1): write /usr/share/doc/libfreetype6/reference/ft2-type1_tables.html: no space left on device.
See 'C:\Program Files\Docker\Docker\Resources\bin\docker.exe run --help'.
</code>```

There's over 20 GB free on the hard drive, so I assume the problem is inside Docker's virtual machine. How do I access it to investigate disk usage and clean up if needed?

docker images and docker ps -a didn't identify anything large:

```<code>> docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu              latest              f49eec89601e        2 days ago          129 MB
d4w/nsenter         latest              9e4f13a0901e        4 months ago        83.8 kB
> docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
ae1e7c7b11ed        ubuntu              "/bin/bash"         10 minutes ago      Exited (0) 9 minutes ago                       quirky_rosalind
</code>```

Pulling separately didn't help:

```<code>> docker pull python
Using default tag: latest
latest: Pulling from library/python
5040bd298390: Pull complete
fce5728aad85: Pull complete
76610ec20bf5: Pull complete
52f3db4b5710: Extracting [==================================================>] 129.8 MB/129.8 MB
45b2a7e03e44: Download complete
75ef15b2048b: Download complete
e41da2f0bac3: Download complete
failed to register layer: Error processing tar file(exit status 1): write /usr/bin/g++-4.9: no space left on device
</code>```

答: If you're using Docker Desktop on OSX (or similar), you can get around this by accessing the Preferences, increasing the base image size, and click "Apply and Restart"

Body:
Using Docker 1.13.0 (9795) under Windows 10 Build 14393, I'm getting "no space left on device" when trying to run the latest python image (which would be 3.6):

> docker run -it python
Unable to find image 'python:latest' locally
latest: Pulling from library/python
5040bd298390: Pull complete
fce5728aad85: Pull complete
76610ec20bf5: Pull complete
52f3db4b5710: Extracting [==================================================>] 129.8 MB/129.8 MB
45b2a7e03e44: Download complete
75ef15b2048b: Download complete
e41da2f0bac3: Download complete
C:\Program Files\Docker\Docker\Resources\bin\docker.exe: failed to register layer: Error processing tar file(exit status
 1): write /usr/share/doc/libfreetype6/reference/ft2-type1_tables.html: no space left on device.
See 'C:\Program Files\Docker\Docker\Resources\bin\docker.exe run --help'.

There's over 20 GB free on the hard drive, so I assume the problem is inside Docker's virtual machine. How do I access it to investigate disk usage and clean up if needed?

docker images and docker ps -a didn't identify anything large:

> docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu              latest              f49eec89601e        2 days ago          129 MB
d4w/nsenter         latest              9e4f13a0901e        4 months ago        83.8 kB
> docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
ae1e7c7b11ed        ubuntu              "/bin/bash"         10 minutes ago      Exited (0) 9 minutes ago                       quirky_rosalind

Pulling separately didn't help:

> docker pull python
Using default tag: latest
latest: Pulling from library/python
5040bd298390: Pull complete
fce5728aad85: Pull complete
76610ec20bf5: Pull complete
52f3db4b5710: Extracting [==================================================>] 129.8 MB/129.8 MB
45b2a7e03e44: Download complete
75ef15b2048b: Download complete
e41da2f0bac3: Download complete
failed to register layer: Error processing tar file(exit status 1): write /usr/bin/g++-4.9: no space left on device


问:
asp button event inside foundation modal not firing
I have tried searching for a solution for this, but nothing seems to be working for me. My problem is pretty straightforward though (so, I think).

I am using foundation with asp webforms and have a reveal modal window that fires when the page is loaded.

Code:

```<code>$(document).ready(function () { $('#myModal').foundation('reveal', 'open') });
</code>```

The above works fine, however, any time I put an ASP button inside the modal (the one I am using, btnReset, redirects to a new page), clicking on it will not fire the event attached to it.

Code:

```<code><div id="reset">
    <div class="large-2 columns">
        <asp:Button ID="btnReset" runat="server" Text="Reset"
                    OnClick="btnReset_Click" OnClientClick="btnReset_Click"
                    CssClass="button small radius alert" />
    </div>
</div>
</code>```

Code for btnReset:

```<code>protected void btnReset_Click(object sender, EventArgs e)
{
     HttpCookie cookie = Request.Cookies["userInfo"];
     cookie.Expires = DateTime.Now.AddDays(-1);
     Response.Cookies.Add(cookie);
     Response.Redirect("LogIn.aspx");
     //Server.Transfer("LogIn.aspx");
}
</code>```

I'm sure I am missing some here, but I'm just stumped on what I am doing wrong. How can I get an ASP button and have it fire it's event when it is inside a modal?

答:
For anyone new stumbling across this issue you can now add this to your reveal modal and your webforms buttons will work as intended inside the modal.

```<code>data-append-to="form"
</code>```

The documentation is here. And the credit goes to this old forum post by Lars Jensen at the bottom of the thread here

Body:
I have tried searching for a solution for this, but nothing seems to be working for me. My problem is pretty straightforward though (so, I think).

I am using foundation with asp webforms and have a reveal modal window that fires when the page is loaded.

Code:

$(document).ready(function () { $('#myModal').foundation('reveal', 'open') });

The above works fine, however, any time I put an ASP button inside the modal (the one I am using, btnReset, redirects to a new page), clicking on it will not fire the event attached to it.

Code:

        <asp:Button ID="btnReset" runat="server" Text="Reset"
                    OnClick="btnReset_Click" OnClientClick="btnReset_Click"
                    CssClass="button small radius alert" />

Code for btnReset:

protected void btnReset_Click(object sender, EventArgs e)
{
     HttpCookie cookie = Request.Cookies["userInfo"];
     cookie.Expires = DateTime.Now.AddDays(-1);
     Response.Cookies.Add(cookie);
     Response.Redirect("LogIn.aspx");
     //Server.Transfer("LogIn.aspx");
}

I'm sure I am missing some here, but I'm just stumped on what I am doing wrong. How can I get an ASP button and have it fire it's event when it is inside a modal?

Body:
For anyone new stumbling across this issue you can now add this to your reveal modal and your webforms buttons will work as intended inside the modal.

data-append-to="form"

The documentation is here. And the credit goes to this old forum post by Lars Jensen at the bottom of the thread here


问:
Error while creating a new app in reactjs
PS D:\React\counter-app> create-react-app tower
create-react-app : File C:\Users\ee209495\AppData\Roaming\npm\create-react-app.ps1 cannot be loaded because running scripts is disabled on this system.
For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ create-react-app tower
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess</p>

答:
this problem because of security feature in your system.
 1. Open powershell as an administrator.
 2. Run the following command set-executionpolicy remotesigned
 3. Try again.</p>


问:
urllib and "SSL: CERTIFICATE_VERIFY_FAILED" Error
I am getting the following error:

```<code>Exception in thread Thread-3:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in        __bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in  run
self.__target(*self.__args, **self.__kwargs)
File "/Users/Matthew/Desktop/Skypebot 2.0/bot.py", line 271, in process
info = urllib2.urlopen(req).read()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 431, in open
response = self._open(req, data)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 449, in _open
'_open', req)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 409, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1240, in https_open
context=self._context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1197, in do_open
raise URLError(err)
URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)>
</code>```

This is the code that is causing this error:

```<code>if input.startswith("!web"):
    input = input.replace("!web ", "")
    url = "https://domainsearch.p.mashape.com/index.php?name=" + input
    req = urllib2.Request(url, headers={ 'X-Mashape-Key': 'XXXXXXXXXXXXXXXXXXXX' })
    info = urllib2.urlopen(req).read()
    Message.Chat.SendMessage ("" + info)
</code>```

The API I'm using requires me to use HTTPS. How can I make it bypass the verification?

答:
There are cases when you can not use insecure connections or pass ssl context into urllib request. Here my solution based on
https://stackoverflow.com/a/28052583/6709778

In a case if you want use your own cert file

import ssl

def new_ssl_context_decorator(*args, **kwargs):
    kwargs['cafile'] = '/etc/ssl/certs/ca-certificates.crt'
    return ssl.create_default_context(*args, **kwargs)

ssl._create_default_https_context = ssl._create_unverified_context
```

<p>or you can use shared file from certifi</p>

<pre class="lang-py prettyprint-override"><code>def new_ssl_context_decorator(*args, **kwargs):
    import certifi
    kwargs['cafile'] = certifi.where()
    return ssl.create_default_context(*args, **kwargs)
</code>```

Body:
I am getting the following error:

Exception in thread Thread-3:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in        __bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in  run
self.__target(*self.__args, **self.__kwargs)
File "/Users/Matthew/Desktop/Skypebot 2.0/bot.py", line 271, in process
info = urllib2.urlopen(req).read()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 431, in open
response = self._open(req, data)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 449, in _open
'_open', req)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 409, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1240, in https_open
context=self._context)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1197, in do_open
raise URLError(err)
URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)>

This is the code that is causing this error:

if input.startswith("!web"):
    input = input.replace("!web ", "")
    url = "https://domainsearch.p.mashape.com/index.php?name=" + input
    req = urllib2.Request(url, headers={ 'X-Mashape-Key': 'XXXXXXXXXXXXXXXXXXXX' })
    info = urllib2.urlopen(req).read()
    Message.Chat.SendMessage ("" + info)

The API I'm using requires me to use HTTPS. How can I make it bypass the verification?

Body:
There are cases when you can not use insecure connections or pass ssl context into urllib request. Here my solution based on
https://stackoverflow.com/a/28052583/6709778

In a case if you want use your own cert file

import ssl

def new_ssl_context_decorator(*args, **kwargs):
    kwargs['cafile'] = '/etc/ssl/certs/ca-certificates.crt'
    return ssl.create_default_context(*args, **kwargs)

ssl._create_default_https_context = ssl._create_unverified_context

or you can use shared file from certifi

def new_ssl_context_decorator(*args, **kwargs):
    import certifi
    kwargs['cafile'] = certifi.where()
    return ssl.create_default_context(*args, **kwargs)


问:
Angular TinyMCE icons disappeared
I have an Angular 8 project with tinymce editor. It works locally, but at some point toolbar icons disappeared in production deployed using CI/CD pipeline.

I'm getting 404 for /tinymce/icons/default/icons.min.js.

What the heck is icons.min.js??

My angular.json assets looks like this:

```<code>{
                "glob": "**/*",
                "input": "node_modules/tinymce/skins",
                "output": "/tinymce/skins/"
              },
              {
                "glob": "**/*",
                "input": "node_modules/tinymce/themes",
                "output": "/tinymce/themes/"
              },
              {
                "glob": "**/*",
                "input": "node_modules/tinymce/plugins",
                "output": "/tinymce/plugins/"
              }
</code>```

答:
TinyMCE 5 contains an icons folder with two JavaScript files.  It would appear that you have not included that content in what you deployed to production.

Based on your example json you likely need to add something like this:

```<code>{
  "glob": "**/*",
  "input": "node_modules/tinymce/icons",
  "output": "/tinymce/icons/"
},
</code>```

Title: Angular TinyMCE icons disappeared

Body:
I have an Angular 8 project with tinymce editor. It works locally, but at some point toolbar icons disappeared in production deployed using CI/CD pipeline.

I'm getting 404 for /tinymce/icons/default/icons.min.js.

What the heck is icons.min.js??

My angular.json assets looks like this:

{
                "glob": "**/*",
                "input": "node_modules/tinymce/skins",
                "output": "/tinymce/skins/"
              },
              {
                "glob": "**/*",
                "input": "node_modules/tinymce/themes",
                "output": "/tinymce/themes/"
              },
              {
                "glob": "**/*",
                "input": "node_modules/tinymce/plugins",
                "output": "/tinymce/plugins/"
              }

Body:
TinyMCE 5 contains an icons folder with two JavaScript files.  It would appear that you have not included that content in what you deployed to production.

Based on your example json you likely need to add something like this:

{
  "glob": "**/*",
  "input": "node_modules/tinymce/icons",
  "output": "/tinymce/icons/"
},


问:
Understanding "VOLUME" instruction in DockerFile
Below is the content of my "Dockerfile"

```<code>FROM node:boron

# Create app directory
RUN mkdir -p /usr/src/app

# Change working dir to /usr/src/app
WORKDIR /usr/src/app

VOLUME . /usr/src/app

RUN npm install

EXPOSE 8080

CMD ["node" , "server" ]
</code>```

In this file I am expecting VOLUME . /usr/src/app instruction to mount
contents of present working directory in host to be mounted on /usr/src/app
folder of container.

Please let me know if this is the correct way?

答:
I don't consider the use of VOLUME good in any case, except if you are creating an image for yourself and no one else is going to use it.

I was impacted negatively due to VOLUME exposed in base images that I extended and only came up to know about the problem after the image was already running, like wordpress that declares the /var/www/html folder as a VOLUME, and this meant that any files added or changed during the build stage aren't considered, and live changes persist, even if you don't know. There is an ugly workaround to define web directory in another place, but this is just a bad solution to a much simpler one: just remove the VOLUME directive.

You can achieve the intent of volume easily using the -v option, this not only make it clear what will be the volumes of the container (without having to take a look at the Dockerfile and parent Dockerfiles), but this also gives the consumer the option to use the volume or not.

It's also bad to use VOLUMES due to the following reasons, as said by this answer:

However, the VOLUME instruction does come at a cost.

Users might not be aware of the unnamed volumes being created, and    continuing to take up storage space on their Docker host after containers are removed.

There is no way to remove a volume declared    in a Dockerfile. Downstream images cannot add data to paths where    volumes exist.

The latter issue results in problems like these.

How to “undeclare” volumes in docker image?

GitLab on Docker: how to persist user data between deployments?

Having the option to undeclare a volume would help, but only if you know the volumes defined in the dockerfile that generated the image (and the parent dockerfiles!). Furthermore, a VOLUME could be added in newer versions of a Dockerfile and break things unexpectedly for the consumers of the image.

Another good explanation (about the oracle image having VOLUME, which was removed): https://github.com/oracle/docker-images/issues/640#issuecomment-412647328

More cases in which VOLUME broke stuff for people:

https://github.com/datastax/docker-images/issues/31

https://github.com/docker-library/wordpress/issues/232

https://github.com/docker-library/ghost/issues/195

https://github.com/samos123/docker-drupal/issues/10

A pull request to add options to reset properties the parent image (including VOLUME), was closed and is being discussed here (and you can see several cases of people affected adversely due to volumes defined in dockerfiles), which has a comment with a good explanation against VOLUME:

Using VOLUME in the Dockerfile is worthless. If a user needs
persistence, they will be sure to provide a volume mapping when
running the specified container. It was very hard to track down that
my issue of not being able to set a directory's ownership
(/var/lib/influxdb) was due to the VOLUME declaration in InfluxDB's
Dockerfile. Without an UNVOLUME type of option, or getting rid of it
altogether, I am unable to change anything related to the specified
folder. This is less than ideal, especially when you are
security-aware and desire to specify a certain UID the image should be
ran as, in order to avoid a random user, with more permissions than
necessary, running software on your host.

The only good thing I can see about VOLUME is about documentation, and I would consider it good if it only did that (without any side effects).

Update (2021-10-19)

One more related issue with the mysql official image: https://github.com/docker-library/mysql/issues/255

Update (2022-01-26)

I found a good article explaining about the issues with VOLUME. It's already several years old, but the same issues remain:

https://boxboat.com/2017/01/23/volumes-and-dockerfiles-dont-mix/

TL;DR

I consider that the best use of VOLUME is to be deprecated.

Body:
Below is the content of my "Dockerfile"

FROM node:boron

# Create app directory
RUN mkdir -p /usr/src/app

# Change working dir to /usr/src/app
WORKDIR /usr/src/app

VOLUME . /usr/src/app

RUN npm install

EXPOSE 8080

CMD ["node" , "server" ]

In this file I am expecting VOLUME . /usr/src/app instruction to mount
contents of present working directory in host to be mounted on /usr/src/app
folder of container.

Please let me know if this is the correct way?


问:
How to resize a cropped image?
Goal:

My current goal is to crop the original image from pictureBox1 and show it in pictureBox2 and increase it's size (Height & Width) by 0.8.

Current Code:

```<code>//...
private Point LocationXY;
private Point LocationX1Y1;

private void button1_Click(object sender, EventArgs e)
{
    if (Clipboard.ContainsImage())
    {
        pictureBox1.Image?.Dispose();
        pictureBox1.Image = Clipboard.GetImage();
    }
}

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Left)
        LocationXY = e.Location;
}

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        LocationX1Y1 = e.Location;
        pictureBox1.Invalidate();
    }
}

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Left)
    {
        LocationX1Y1 = e.Location;

        pictureBox1.Invalidate();
        pictureBox2.Invalidate();
    }
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    if (MouseButtons == MouseButtons.Left)
        e.Graphics.DrawRectangle(Pens.Red, GetRect());
}

private void pictureBox2_Paint(object sender, PaintEventArgs e)
{
    var src = GetRect();

    if (src == Rectangle.Empty) return;

    var des = new Rectangle(0, 0, src.Width, src.Height);

    e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
    e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
    e.Graphics.CompositingQuality = CompositingQuality.HighQuality;

    e.Graphics.DrawImage(pictureBox1.Image,
        des, src, GraphicsUnit.Pixel);
}

private Rectangle GetRect()
{
    return new Rectangle(
        Math.Min(LocationXY.X, LocationX1Y1.X),
        Math.Min(LocationXY.Y, LocationX1Y1.Y),
        Math.Abs(LocationXY.X - LocationX1Y1.X),
        Math.Abs(LocationXY.Y - LocationX1Y1.Y)
        );
}
//...
</code>```

Cropping the image:

```<code>//...
private Bitmap GetCroppedImage()
{
    var src = GetRect();

    if (src == Rectangle.Empty) return null;

    var des = new Rectangle(0, 0, src.Width, src.Height);
    var b = new Bitmap(src.Width, src.Height);

    using (var g = Graphics.FromImage(b))
    {
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.CompositingQuality = CompositingQuality.HighQuality;

        g.DrawImage(pictureBox1.Image, des, src, GraphicsUnit.Pixel);
    }
    return b;
}
//...
</code>```

Current code - what does it do

Currently this code is able to mark an red area in pictureBox1 and show the cropped image in pictureBox2.

Question:

How do I increase/resize the cropped image height and width by 0.8?

答:
Calculate the ratio of the scale up against the source size and use it to calculate the new size of the image. Accordingly, the pictureBox2.Paint event code:

private void pictureBox2_Paint(object sender, PaintEventArgs e)
{
    var src = GetRect();

    if (src == Rectangle.Empty || src.Width == 0 || src.Height == 0) return;

    e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
    e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
    e.Graphics.CompositingQuality = CompositingQuality.HighQuality;

    var widthScale = 0.8;
    var heightScale = 0.8;
    var widthRatio = (src.Width * widthScale + src.Width) / src.Width;
    var heightRatio = (src.Height * heightScale + src.Height) / src.Height;
    var newWidth = (int)(src.Width * widthRatio);
    var newHeight = (int)(src.Height * heightRatio);
    var des = new Rectangle(0, 0, newWidth, newHeight);

    e.Graphics.DrawImage(pictureBox1.Image,
        des, src, GraphicsUnit.Pixel);
}
```

<p>To apply that on the <code>GetCroppedImage()</code> function:</p>

<pre class="lang-cs prettyprint-override"><code>private Image GetCroppedImage(double scale = 0)
{
    var src = GetRect();

    if (src == Rectangle.Empty || src.Width == 0 || src.Height == 0) return null;

    var widthRatio = (src.Width * scale + src.Width) / src.Width;
    var heightRatio = (src.Height * scale + src.Height) / src.Height;
    var newWidth = (int)(src.Width * widthRatio);
    var newHeight = (int)(src.Height * heightRatio);

    if (newWidth == 0 || newHeight == 0) return null;

    var des = new Rectangle(0, 0, newWidth, newHeight);
    var b = new Bitmap(newWidth, newHeight);

    using (var g = Graphics.FromImage(b))
    {
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.CompositingQuality = CompositingQuality.HighQuality;
        g.DrawImage(pictureBox1.Image, des, src, GraphicsUnit.Pixel);
    }

    return b;
}
</code>```

Also, you could use the Image.GetThumbnailImage to get small sizes from the main image. Not recommended if you need to return large ones. Read the Remarks for more information.

Title: How to resize a cropped image?

Body:
Goal:

My current goal is to crop the original image from pictureBox1 and show it in pictureBox2 and increase it's size (Height & Width) by 0.8.

Current Code:

//...
private Point LocationXY;
private Point LocationX1Y1;

private void button1_Click(object sender, EventArgs e)
{
    if (Clipboard.ContainsImage())
    {
        pictureBox1.Image?.Dispose();
        pictureBox1.Image = Clipboard.GetImage();
    }
}

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Left)
        LocationXY = e.Location;
}

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        LocationX1Y1 = e.Location;
        pictureBox1.Invalidate();
    }
}

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Left)
    {
        LocationX1Y1 = e.Location;

        pictureBox1.Invalidate();
        pictureBox2.Invalidate();
    }
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    if (MouseButtons == MouseButtons.Left)
        e.Graphics.DrawRectangle(Pens.Red, GetRect());
}

private void pictureBox2_Paint(object sender, PaintEventArgs e)
{
    var src = GetRect();

    if (src == Rectangle.Empty) return;

    var des = new Rectangle(0, 0, src.Width, src.Height);

    e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
    e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
    e.Graphics.CompositingQuality = CompositingQuality.HighQuality;

    e.Graphics.DrawImage(pictureBox1.Image,
        des, src, GraphicsUnit.Pixel);
}

private Rectangle GetRect()
{
    return new Rectangle(
        Math.Min(LocationXY.X, LocationX1Y1.X),
        Math.Min(LocationXY.Y, LocationX1Y1.Y),
        Math.Abs(LocationXY.X - LocationX1Y1.X),
        Math.Abs(LocationXY.Y - LocationX1Y1.Y)
        );
}
//...

Cropping the image:

//...
private Bitmap GetCroppedImage()
{
    var src = GetRect();

    if (src == Rectangle.Empty) return null;

    var des = new Rectangle(0, 0, src.Width, src.Height);
    var b = new Bitmap(src.Width, src.Height);

    using (var g = Graphics.FromImage(b))
    {
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.CompositingQuality = CompositingQuality.HighQuality;

        g.DrawImage(pictureBox1.Image, des, src, GraphicsUnit.Pixel);
    }
    return b;
}
//...

Current code - what does it do

Currently this code is able to mark an red area in pictureBox1 and show the cropped image in pictureBox2.

Question:

How do I increase/resize the cropped image height and width by 0.8?

Body:
Calculate the ratio of the scale up against the source size and use it to calculate the new size of the image. Accordingly, the pictureBox2.Paint event code:

private void pictureBox2_Paint(object sender, PaintEventArgs e)
{
    var src = GetRect();

    if (src == Rectangle.Empty || src.Width == 0 || src.Height == 0) return;

    e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
    e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
    e.Graphics.CompositingQuality = CompositingQuality.HighQuality;

    var widthScale = 0.8;
    var heightScale = 0.8;
    var widthRatio = (src.Width * widthScale + src.Width) / src.Width;
    var heightRatio = (src.Height * heightScale + src.Height) / src.Height;
    var newWidth = (int)(src.Width * widthRatio);
    var newHeight = (int)(src.Height * heightRatio);
    var des = new Rectangle(0, 0, newWidth, newHeight);

    e.Graphics.DrawImage(pictureBox1.Image,
        des, src, GraphicsUnit.Pixel);
}

To apply that on the GetCroppedImage() function:

private Image GetCroppedImage(double scale = 0)
{
    var src = GetRect();

    if (src == Rectangle.Empty || src.Width == 0 || src.Height == 0) return null;

    var widthRatio = (src.Width * scale + src.Width) / src.Width;
    var heightRatio = (src.Height * scale + src.Height) / src.Height;
    var newWidth = (int)(src.Width * widthRatio);
    var newHeight = (int)(src.Height * heightRatio);

    if (newWidth == 0 || newHeight == 0) return null;

    var des = new Rectangle(0, 0, newWidth, newHeight);
    var b = new Bitmap(newWidth, newHeight);

    using (var g = Graphics.FromImage(b))
    {
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.CompositingQuality = CompositingQuality.HighQuality;
        g.DrawImage(pictureBox1.Image, des, src, GraphicsUnit.Pixel);
    }

    return b;
}

Also, you could use the Image.GetThumbnailImage to get small sizes from the main image. Not recommended if you need to return large ones. Read the Remarks for more information.


问:
kubectl apply vs kubernetes deployment - Terraform
I am trying to use Kubernetes Deployment , i would like to know whether this is same as kubectl apply -f deployment.yaml or does this wait for the deployments to be up and running . because when i used kubernetes deployment to create a basic pod which i know will not work, i got this error

Error: Waiting for rollout to finish: 0 of 1 updated replicas are available...

Is this just giving me the error from kubernetes or the entire terraform script fails because of this?

答:
According to the documentation

A Deployment ensures that a specified number of pod “replicas” are running at any one time. In other words, a Deployment makes sure that a pod or homogeneous set of pods are always up and available. If there are too many pods, it will kill some. If there are too few, the Deployment will start more.

So, It will wait to ensure number of expected replicas are up


问:
Delegate is logging non-public events through my app: can those events be detected?
These notices are being logged on behalf of my app (which implements GKSessionDelegate), and I could really make use of these events to help users with connection difficulties. Is there any way I can detect them? There aren't any public instance methods for the delegate that directly refer to these events.

I'm hoping there's some sort of generic event catch-all for delegates that I could rig up.

```<code>GKSessionTester[79766:307] BTM: attaching to BTServer
GKSessionTester[79766:307] <<< Session >>> +[GKBluetoothSupport _determineBluetoothStatus]: BT not available - try again later.
GKSessionTester[79766:307] BTM: posting notification BluetoothAvailabilityChangedNotification
</code>```

答:
As Gonzalo mentions in the comments, it looks like a notification is being posted with the name BluetoothAvailabilityChangedNotification.

Cocoa's notifications system is based around NSNotificationCenter, which maintains a list of observers and forwards notifications based on names, which are simply NSStrings. It is very likely that you can receive notifications if you call:

```<code>[[NSNotificationCenter defaultCenter]
    addObserver:self
    selector:@selector(bluetoothAvailabilityChanged:)
    name:@"BluetoothAvailabilityChangedNotification"
    object:nil];
</code>```

And implement the method:

```<code>- (void)bluetoothAvailabilityChanged:(NSNotification *)notification
{
    // maybe [notification userInfo] has some useful info...
}
</code>```

You might not receive any notifications if GameKit is using a separate notification center object.

Does this count as private API? I would say it's no worse than parsing your console output. You are not calling methods on undocumented classes, you are passively observing notifications posted with a given name.

Of course, Apple's opinion is the only one that matters. If I were in your shoes, I would make sure that:

your app functions correctly if the notification is never posted (because a future iOS might not post it, or you might have to remove the code and resubmit without it);

your app makes no assumptions about the NSNotification's object or contents of its userInfo dictionary (because whatever they contain today might change in the future).

Alternatively, you could figure out a way to intercept your own app's STDOUT and STDERR (any solution that works on generic UNIX may work on iOS) and watch the text for relevant log messages.

Body:
These notices are being logged on behalf of my app (which implements GKSessionDelegate), and I could really make use of these events to help users with connection difficulties. Is there any way I can detect them? There aren't any public instance methods for the delegate that directly refer to these events.

I'm hoping there's some sort of generic event catch-all for delegates that I could rig up.

GKSessionTester[79766:307] BTM: attaching to BTServer
GKSessionTester[79766:307] <<< Session >>> +[GKBluetoothSupport _determineBluetoothStatus]: BT not available - try again later.
GKSessionTester[79766:307] BTM: posting notification BluetoothAvailabilityChangedNotification

Body:
As Gonzalo mentions in the comments, it looks like a notification is being posted with the name BluetoothAvailabilityChangedNotification.

Cocoa's notifications system is based around NSNotificationCenter, which maintains a list of observers and forwards notifications based on names, which are simply NSStrings. It is very likely that you can receive notifications if you call:

[[NSNotificationCenter defaultCenter]
    addObserver:self
    selector:@selector(bluetoothAvailabilityChanged:)
    name:@"BluetoothAvailabilityChangedNotification"
    object:nil];

And implement the method:

- (void)bluetoothAvailabilityChanged:(NSNotification *)notification
{
    // maybe [notification userInfo] has some useful info...
}

You might not receive any notifications if GameKit is using a separate notification center object.

Does this count as private API? I would say it's no worse than parsing your console output. You are not calling methods on undocumented classes, you are passively observing notifications posted with a given name.

Of course, Apple's opinion is the only one that matters. If I were in your shoes, I would make sure that:

your app functions correctly if the notification is never posted (because a future iOS might not post it, or you might have to remove the code and resubmit without it);

your app makes no assumptions about the NSNotification's object or contents of its userInfo dictionary (because whatever they contain today might change in the future).

Alternatively, you could figure out a way to intercept your own app's STDOUT and STDERR (any solution that works on generic UNIX may work on iOS) and watch the text for relevant log messages.


问:
iOS 13 webaudio is totally broken for html audio elements within a webview
I'm building a mobile game using cordova, using wkwebview, and I'm having a major issue with audio not working on iOS 13 (specifically iPadOS 13.2.2). I have several html audio elements connected to an AudioContext, and when I play one after the context has been resumed, there are no js errors and everything looks good from the js side. However, it doesn't play any sound, and on the native iOS side, it throws this error:

```<code>2019-11-15 18:27:09.610800-0500 MyApp[9045:99562] [assertion] Error acquiring assertion: <NSError: 0x2811ddfe0; domain: RBSAssertionErrorDomain; code: 2; reason: "Client is missing required entitlement"> {
    userInfo = {
        RBSAssertionAttribute = <RBSLegacyAttribute: 0x111048cf0; requestedReason: MediaPlayback; reason: MediaPlayback; flags: PreventTaskSuspend | PreventTaskThrottleDown | WantsForegroundResourcePriority>;
    }
}
2019-11-15 18:27:09.610840-0500 MyApp[9045:99562] [ProcessSuspension]  0x108ee7138 - ProcessAssertion() PID 9045 Unable to acquire assertion for process with PID 9045
2019-11-15 18:27:09.610894-0500 MyApp[9045:99269] [ProcessSuspension] 0x108ee7138 - ProcessAssertion::processAssertionWasInvalidated()
</code>```

I've tried adding the "Audio, AirPlay, and Picture in Picture" and "Background processing" flags in the Background Modes tab of xcode, but they had no effect. Other things to note: it plays audio in the simulator even though it still throws the error, but fails to play on an actual device. Also, audio does play correctly using AudioBuffer's, it's just Audio elements that are affected. Unfortunately, I can't use AudioBuffers for my soundtrack because they're only designed for short sounds, and take way too long to load for full length songs.

I've filed this as a webkit bug: https://bugs.webkit.org/show_bug.cgi?id=204261

Has anyone been able to get html audio working on iOS 13, or know any workarounds?

答:
I had the same issue, I solved adding these to config.xml:

```<code><preference name="AllowInlineMediaPlayback" value="true" />
</code>```

This allows media playback to appear inline within the screen layout, using browser-supplied controls rather than native controls.

For more details read:

https://cordova.apache.org/docs/en/5.1.1/guide/platforms/ios/config.html

Body:
I'm building a mobile game using cordova, using wkwebview, and I'm having a major issue with audio not working on iOS 13 (specifically iPadOS 13.2.2). I have several html audio elements connected to an AudioContext, and when I play one after the context has been resumed, there are no js errors and everything looks good from the js side. However, it doesn't play any sound, and on the native iOS side, it throws this error:

2019-11-15 18:27:09.610800-0500 MyApp[9045:99562] [assertion] Error acquiring assertion: <NSError: 0x2811ddfe0; domain: RBSAssertionErrorDomain; code: 2; reason: "Client is missing required entitlement"> {
    userInfo = {
        RBSAssertionAttribute = <RBSLegacyAttribute: 0x111048cf0; requestedReason: MediaPlayback; reason: MediaPlayback; flags: PreventTaskSuspend | PreventTaskThrottleDown | WantsForegroundResourcePriority>;
    }
}
2019-11-15 18:27:09.610840-0500 MyApp[9045:99562] [ProcessSuspension]  0x108ee7138 - ProcessAssertion() PID 9045 Unable to acquire assertion for process with PID 9045
2019-11-15 18:27:09.610894-0500 MyApp[9045:99269] [ProcessSuspension] 0x108ee7138 - ProcessAssertion::processAssertionWasInvalidated()

I've tried adding the "Audio, AirPlay, and Picture in Picture" and "Background processing" flags in the Background Modes tab of xcode, but they had no effect. Other things to note: it plays audio in the simulator even though it still throws the error, but fails to play on an actual device. Also, audio does play correctly using AudioBuffer's, it's just Audio elements that are affected. Unfortunately, I can't use AudioBuffers for my soundtrack because they're only designed for short sounds, and take way too long to load for full length songs.

I've filed this as a webkit bug: https://bugs.webkit.org/show_bug.cgi?id=204261

Has anyone been able to get html audio working on iOS 13, or know any workarounds?

Body:
I had the same issue, I solved adding these to config.xml:

<preference name="AllowInlineMediaPlayback" value="true" />

This allows media playback to appear inline within the screen layout, using browser-supplied controls rather than native controls.

For more details read:

https://cordova.apache.org/docs/en/5.1.1/guide/platforms/ios/config.html


问:
How to use a user as a ForeignKey in a Django model
I've got this model in my Django application:

class ClubSession(models.Model):
    location = models.CharField(max_length=200)
    coach = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    date = models.DateTimeField(default=now)
    details = models.TextField()

    def __str__(self):
        return self.title
```

<p>I can run <code>python manage.py makemigrations club_sessions</code> without issue but when I thn run <code>python manage.py migrate club_sessions</code> I get <code>ValueError: Field 'id' expected a number but got 'username'</code>. <code>username</code> is a superuser and already exists.</p>

<p>How do I resolve this?</p>

<p>This is the latest migration:</p>

<pre class="lang-py prettyprint-override"><code># Generated by Django 3.0.6 on 2020-05-28 15:07

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('club_sessions', '0004_auto_20200528_1450'),
    ]

    operations = [
        migrations.AlterField(
            model_name='clubsession',
            name='coach',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
        ),
        migrations.AlterField(
            model_name='clubsession',
            name='location',
            field=models.CharField(max_length=200),
        ),
    ]
</code>```

答:
By default Django lets a ForeignKey refer to the primary key of the target model. This also has some advantages to make relations more uniform.

If you really want to save the username in the ForeignKey, you can specify a to_field=… parameter [Django-doc] and let it refer to a column that is unique (the username of the default User model is unique), so we can refer to it with:

```<code>from django.conf import settings

class ClubSession(models.Model):
    location = models.CharField(max_length=200)
    coach = models.ForeignKey(
        <b>settings.AUTH_USER_MODEL</b>,
        on_delete=models.CASCADE,
        <b>to_field='username'</b>
    )
    date = models.DateTimeField(default=now)
    details = models.TextField()

    def __str__(self):
        return self.title</code>```

You will need to remove the already existing migration and make a new one in order to migrate the database properly.

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Body:
I've got this model in my Django application:

class ClubSession(models.Model):
    location = models.CharField(max_length=200)
    coach = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    date = models.DateTimeField(default=now)
    details = models.TextField()

    def __str__(self):
        return self.title

I can run python manage.py makemigrations club_sessions without issue but when I thn run python manage.py migrate club_sessions I get ValueError: Field 'id' expected a number but got 'username'. username is a superuser and already exists.

How do I resolve this?

This is the latest migration:

# Generated by Django 3.0.6 on 2020-05-28 15:07

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('club_sessions', '0004_auto_20200528_1450'),
    ]

    operations = [
        migrations.AlterField(
            model_name='clubsession',
            name='coach',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
        ),
        migrations.AlterField(
            model_name='clubsession',
            name='location',
            field=models.CharField(max_length=200),
        ),
    ]

Body:
By default Django lets a ForeignKey refer to the primary key of the target model. This also has some advantages to make relations more uniform.

If you really want to save the username in the ForeignKey, you can specify a to_field=… parameter [Django-doc] and let it refer to a column that is unique (the username of the default User model is unique), so we can refer to it with:

from django.conf import settings

class ClubSession(models.Model):
    location = models.CharField(max_length=200)
    coach = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        to_field='username'
    )
    date = models.DateTimeField(default=now)
    details = models.TextField()

    def __str__(self):
        return self.title

You will need to remove the already existing migration and make a new one in order to migrate the database properly.

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.


问:
How to randomly mutate 5 values in a binary list?
I'm writing a genetic algorithm in which I need to select 5 numbers from the binary list genotype and flip them, so a 1→0 and 0→1. I tried putting my code in a loop with a range(1,6) however when I do this it still only changes one of the numbers. Below is my original code without the loop which randomly selects one of the binary values and mutates it. Does anyone know a better way of doing this but for 5 of the elements in the list?

genotype = [1,0,0,1,0,0,1,1,1,0]

def mutate(self):
  gene = random.choice(genotype)
  if genotype[gene] == 1:
    genotype[gene] = 0
  else:
    genotype[gene] = 1
  return genotype

```

答:
Your question is more towards the software engineering problem, and not towards the EA side. But, I would like to give some suggestions towards your design decision of choosing 5 genes from the genome. You are restricting EA to explore the search space for your solutions, and your EA could definitely get stuck in local optima and might not be able to escape as mutated solutions will be changed around just 5 genes (If the limitation is from a problem itself, can't do anything about it). As an example, EA might find a near-optimal solution by just changing 3 genes or by changing 7 genes. If it is a design choice, you might like to revisit your design decision for EA.

In general, the EA community uses mutation probability for genes. When one would like to mutate offsprings, it is based on hyperparameter mutation probability (Also, as this is hyperparameter, you also can tune this for your problem to achieve good results later).

Let's say if your design decision of mutating 5 genes is a constraint, and also you would like to use tunable hyper-parameter mutation probability. You can have your solution like below:

```<code>import random

def mutate(genotype, m_probe):
  mutated_offspring = []
  mutated_genes_indexes = set()
  for index, gene in enumerate(genotype):
    if random.uniform(0, 1) >= m_probe and len(mutated_genes_indexes) < 5:
      mutated_offspring.append(int(not gene))
      mutated_genes_indexes.add(index)
    else:
      mutated_offspring.append(int(gene))
  print("Mutated genes indexes: ", mutated_genes_indexes)
  return mutated_offspring

# Each genes have 20% probability to get mutated! NOTE: with higher probability you might not find 5 genes mutated, 20 is chosen based on the constraint and can be tuned later with this constraint.
genotype = [1,0,0,1,0,0,1,1,1,0]
print(mutate(genotype, 0.20))
</code>```

My preferred design decision would be an equal chance for all genes to get mutated without constraint. In that case, a solution might look like below:

```<code>import random

def mutate(genotype, m_probe):
  mutated_offspring = []
  mutated_genes_indexes = set()
  for index, gene in enumerate(genotype):
    if random.uniform(0, 1) >= m_probe:
      mutated_offspring.append(int(not gene))
      mutated_genes_indexes.add(index)
    else:
      mutated_offspring.append(int(gene))
  print("Mutated genes indexes: ", mutated_genes_indexes)
  return mutated_offspring

genotype = [1,0,0,1,0,0,1,1,1,0]
print(mutate(genotype, 0.50))
</code>```

Body:
Your question is more towards the software engineering problem, and not towards the EA side. But, I would like to give some suggestions towards your design decision of choosing 5 genes from the genome. You are restricting EA to explore the search space for your solutions, and your EA could definitely get stuck in local optima and might not be able to escape as mutated solutions will be changed around just 5 genes (If the limitation is from a problem itself, can't do anything about it). As an example, EA might find a near-optimal solution by just changing 3 genes or by changing 7 genes. If it is a design choice, you might like to revisit your design decision for EA.

In general, the EA community uses mutation probability for genes. When one would like to mutate offsprings, it is based on hyperparameter mutation probability (Also, as this is hyperparameter, you also can tune this for your problem to achieve good results later).

Let's say if your design decision of mutating 5 genes is a constraint, and also you would like to use tunable hyper-parameter mutation probability. You can have your solution like below:

import random

def mutate(genotype, m_probe):
  mutated_offspring = []
  mutated_genes_indexes = set()
  for index, gene in enumerate(genotype):
    if random.uniform(0, 1) >= m_probe and len(mutated_genes_indexes) < 5:
      mutated_offspring.append(int(not gene))
      mutated_genes_indexes.add(index)
    else:
      mutated_offspring.append(int(gene))
  print("Mutated genes indexes: ", mutated_genes_indexes)
  return mutated_offspring

# Each genes have 20% probability to get mutated! NOTE: with higher probability you might not find 5 genes mutated, 20 is chosen based on the constraint and can be tuned later with this constraint.
genotype = [1,0,0,1,0,0,1,1,1,0]
print(mutate(genotype, 0.20))

My preferred design decision would be an equal chance for all genes to get mutated without constraint. In that case, a solution might look like below:

import random

def mutate(genotype, m_probe):
  mutated_offspring = []
  mutated_genes_indexes = set()
  for index, gene in enumerate(genotype):
    if random.uniform(0, 1) >= m_probe:
      mutated_offspring.append(int(not gene))
      mutated_genes_indexes.add(index)
    else:
      mutated_offspring.append(int(gene))
  print("Mutated genes indexes: ", mutated_genes_indexes)
  return mutated_offspring

genotype = [1,0,0,1,0,0,1,1,1,0]
print(mutate(genotype, 0.50))