问:
In tkinter, in python 3, how can I make a button do a command that goes to a fuction such as "def helloCallBack(a)", and allows me to give a?
If I run this , it will run the command without pressing the button. And I know I can change variable a to "hi" on the second line, but I cant on another piece of code that I am working on (I made this one to be a lot simpler and easier to explain(not because you wouldn't understand))

I have tried changing what is in between the brackets on the 4th line, that didn't help.

```<code>from tkinter import *
from tkinter import messagebox

top = Tk()
top.geometry("100x100")
def helloCallBack(a):
    msg = messagebox.showinfo( "Hello Python", a)

B = Button(top, text = "Hello", command = helloCallBack("hi"))
B.place(x = 50,y = 50)
top.mainloop()
</code>```

I was hoping, that as soon as the button was pressed, not before, the message box would appear and show "Python hi".

答:
Use a lambda to pass the entry data to the command function:</p>

```<code>from tkinter import *
from tkinter import messagebox

top = Tk()
top.geometry("100x100")
def helloCallBack(a):
    msg = messagebox.showinfo( "Hello Python", a)
B = Button(top, text = "Hello", command = lambda: helloCallBack('hi'))
B.place(x = 50,y = 50)
B.pack()
top.mainloop()
</code>```

Body:
If I run this , it will run the command without pressing the button. And I know I can change variable a to "hi" on the second line, but I cant on another piece of code that I am working on (I made this one to be a lot simpler and easier to explain(not because you wouldn't understand))

I have tried changing what is in between the brackets on the 4th line, that didn't help.

from tkinter import *
from tkinter import messagebox

top = Tk()
top.geometry("100x100")
def helloCallBack(a):
    msg = messagebox.showinfo( "Hello Python", a)

B = Button(top, text = "Hello", command = helloCallBack("hi"))
B.place(x = 50,y = 50)
top.mainloop()

I was hoping, that as soon as the button was pressed, not before, the message box would appear and show "Python hi".

Body:
Use a lambda to pass the entry data to the command function:

from tkinter import *
from tkinter import messagebox

top = Tk()
top.geometry("100x100")
def helloCallBack(a):
    msg = messagebox.showinfo( "Hello Python", a)
B = Button(top, text = "Hello", command = lambda: helloCallBack('hi'))
B.place(x = 50,y = 50)
B.pack()
top.mainloop()


来源: stackexchange

问:
Creating Xml attribute json:Array using XElement and XNamespace C# classes
I'm trying to build up Xml that looks like the following (taken from another question) but using the XElement/XNamespace classes:

```<code><person xmlns:json='http://james.newtonking.com/projects/json' id='1'>
   <name>Alan</name>
   <url>http://www.google.com</url>
   <role json:Array='true'>Admin</role>
</person>
</code>```

This is so I can serialize using Newtonsoft.Json.JsonConvert.SerializeXmlNode() and maintain correct arrays.

The problem I'm having is creating json:Array='true'.

Other examples show XmlDocument classes or raw creation of Xml string, but is there a way to achieve it using XElement? I've tried several things with XNamespace to attempt to create the "json" prefix without success.

答:
Yes, you can achieve it with XElement. For example:

```<code>XNamespace json = "http://james.newtonking.com/projects/json";
XDocument xml = new XDocument(new XElement("person",
    new XAttribute(XNamespace.Xmlns + "json", json),
    new XAttribute("id", 1),
    new XElement("name", "Alan"),
    new XElement("url", "http://www.google.com"),
    new XElement("role", new XAttribute(json + "Array", true), "Admin")));
</code>```

Will produce the following:

```<code><person xmlns:json="http://james.newtonking.com/projects/json" id="1">
  <name>Alan</name>
  <url>http://www.google.com</url>
  <role json:Array="true">Admin</role>
</person>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to build up Xml that looks like the following (taken from another question) but using the XElement/XNamespace classes:

<person xmlns:json='http://james.newtonking.com/projects/json' id='1'>
   <name>Alan</name>
   <url>http://www.google.com</url>
   <role json:Array='true'>Admin</role>
</person>

This is so I can serialize using Newtonsoft.Json.JsonConvert.SerializeXmlNode() and maintain correct arrays.

The problem I'm having is creating json:Array='true'.

Other examples show XmlDocument classes or raw creation of Xml string, but is there a way to achieve it using XElement? I've tried several things with XNamespace to attempt to create the "json" prefix without success.

Body:
Yes, you can achieve it with XElement. For example:

XNamespace json = "http://james.newtonking.com/projects/json";
XDocument xml = new XDocument(new XElement("person",
    new XAttribute(XNamespace.Xmlns + "json", json),
    new XAttribute("id", 1),
    new XElement("name", "Alan"),
    new XElement("url", "http://www.google.com"),
    new XElement("role", new XAttribute(json + "Array", true), "Admin")));

Will produce the following:

<person xmlns:json="http://james.newtonking.com/projects/json" id="1">
  <name>Alan</name>
  <url>http://www.google.com</url>
  <role json:Array="true">Admin</role>
</person>


问:
Compiler policies on destruction of temporaries
I've been playing with the following piece of code. file_string returns a temporary string that should only "live" until the end of the statement. In Visual Studio 2008, when you use pTempFolder, it contains rubbish as expected. In Linux though, with Intel compiler 11.0, pTempFolder still points to a valid string. Do compilers have different policies regarding the destruction of temporaries, kind of eager (Visual) versus lazy (Intel)? Or maybe this is just a coincidence?

```<code>boost::filesystem wpathTempFolder("/tmp");
const wchar_t* const pTempFolder = wpathTempFolder.file_string().c_str();
// use pTempFolder
</code>```

BTW, that is boost filesystem version 2. I've also seen that file_string is being deprecated in boost filesystem version 3. And that there is a new c_str method that operates over a string&, instead of over a temporary string.

```<code>/*filesystem 2*/
const string_type file_string() const;
/*filesystem 3*/
const string_type&  native() const;  // native format, encoding
const value_type*   c_str() const;   // native().c_str()
</code>```

答:
The lifetime of a temporary (with a few exceptions) is until the
end of the full expression.  The lifetime of the array object pointed to
by the return value of std::string::c_str() does not excede
that of the string object itself (and may be shorter, if any
non-const functions are called on the string).  Accessing an
object after its lifetime has ended is undefined behavior, so
you cannot draw any conclusions from what the compiler does.

ContentLicense: CC BY-SA 3.0

Body:
I've been playing with the following piece of code. file_string returns a temporary string that should only "live" until the end of the statement. In Visual Studio 2008, when you use pTempFolder, it contains rubbish as expected. In Linux though, with Intel compiler 11.0, pTempFolder still points to a valid string. Do compilers have different policies regarding the destruction of temporaries, kind of eager (Visual) versus lazy (Intel)? Or maybe this is just a coincidence?

boost::filesystem wpathTempFolder("/tmp");
const wchar_t* const pTempFolder = wpathTempFolder.file_string().c_str();
// use pTempFolder

BTW, that is boost filesystem version 2. I've also seen that file_string is being deprecated in boost filesystem version 3. And that there is a new c_str method that operates over a string&, instead of over a temporary string.

/*filesystem 2*/
const string_type file_string() const;
/*filesystem 3*/
const string_type&  native() const;  // native format, encoding
const value_type*   c_str() const;   // native().c_str()


问:
Do Azure Container Instances (Windows) support access to Table Storage
I have a container instance (Windows) running a spring-boot application that accesses azure table storage from within a spring-boot CommandLineRunner. The container runs fine locally (Docker / Win10 Pro).

When I deploy to a container instance, a StorageException is thrown at the point that an attempt is made to retrieve a DynamicTableEntity from a table. The connection to the storage account and the table appear to succeed, but the retrieve operation fails. The Tomcat server is running and responsive (I catch the exception and prepare basic error information to be returned by servlets that manage requests). I have been unable to find any examples or definitive statements about using the Java Azure storage libraries in containers, so I would like to know if there are any restrictions, or work-arounds if necessary.

Below are logs which indicate where the exception is thrown.
Log entries with "CommandLineRunner" are generated by my code.
Line 397 in my application is the line where I attempt to retrieve a DynamicTableEntity from the table (14 lines into the log). Prior to that, the connection string is parsed without error, and a reference to the table is generated without error. Although not shown, I am satisfied that the partitionKey and RowKey are correct (and the exception is because the table does not exist - but it does, and is accessible when the container is run locally). Line 562 is the entry point of the spring-boot CommandLineRunner.

```<code>    **2019-05-13 00:57:44.632  INFO 3060 --- [           main] a.c.n.sbtest.demo.DemoApplication        : CommandLineRunner: Engine Intialization Ready (status: 0)**
2019-05-13 00:57:44.670  INFO 3060 --- [           main] a.c.n.sbtest.demo.DemoApplication        : CommandLineRunner: Deployment table <Deployments> accessible
2019-05-13 00:57:44.687  INFO 3060 --- [           main] a.c.n.sbtest.demo.DemoApplication        : CommandLineRunner: User <e7c6163e-8c06-4146-b0e4-78fec93e6cce> Container accessible
2019-05-13 01:00:17.755  INFO 3060 --- [nio-8080-exec-7] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-05-13 01:00:17.755  INFO 3060 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-05-13 01:00:17.768  INFO 3060 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : Completed initialization in 13 ms
com.microsoft.azure.storage.StorageException:
        at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:87)
        at com.microsoft.azure.storage.core.ExecutionEngine.executeWithRetry(ExecutionEngine.java:209)
        at com.microsoft.azure.storage.table.QueryTableOperation.performRetrieve(QueryTableOperation.java:178)
        at com.microsoft.azure.storage.table.TableOperation.execute(TableOperation.java:694)
        at com.microsoft.azure.storage.table.CloudTable.execute(CloudTable.java:529)
        at com.microsoft.azure.storage.table.CloudTable.execute(CloudTable.java:496)
        at **ai.com.neuralstudio.sbtest.demo.DemoApplication.lambda$commandLineRunner$0(DemoApplication.java:562)**
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:813)
        at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:797)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:324)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248)
        at **ai.com.neuralstudio.sbtest.demo.DemoApplication.main(DemoApplication.java:397)**
        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.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
        at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)
Caused by: java.net.UnknownHostException: neuralstudiotest002.table.core.windows.net
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
        at java.net.Socket.connect(Socket.java:589)
        at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:673)
        at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
        at sun.net.www.http.HttpClient.openServer(HttpClient.java:463)
        at sun.net.www.http.HttpClient.openServer(HttpClient.java:558)
        at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:264)
        at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:367)
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
        at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1156)
        at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1050)
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1564)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
        at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:347)
        at com.microsoft.azure.storage.core.ExecutionEngine.executeWithRetry(ExecutionEngine.java:115)
        ... 19 more
2019-05-13 01:00:29.420 ERROR 3060 --- [           main] a.c.n.sbtest.demo.DemoApplication        : CommandLineRunner: StorageException com.microsoft.azure.storage.StorageException:  (status: -3)
</code>```

I would greatly appreciate any insights into what might be going on.
Jack

UPDATE:
While the underlying issue is unresolved for recent Windows container images, jakaruna-MSFT responded in another forum and pointed out that an older image

```<code>mcr.microsoft.com/windows/servercore:1607-KB4505052-amd64
</code>```

would work, and it does. The underlying issue is apparently related to DNS services, and was either broken or omitted in transitions to more recent images. Presumably MS will get around to fixing the later images, with or without explanation.

答:
See UPDATE above.
While the underlying issue is unresolved for recent Windows container images, jakaruna-  MSFT responded in another forum and pointed out that an older image
    mcr.microsoft.com/windows/servercore:1607-KB4505052-amd64

would work, and it does.
The underlying issue is apparently related to DNS services, and was either broken or omitted in transitions to more recent images. Presumably MS will get around to fixing the later images, with or without explanation.

Body:
I have a container instance (Windows) running a spring-boot application that accesses azure table storage from within a spring-boot CommandLineRunner. The container runs fine locally (Docker / Win10 Pro).

When I deploy to a container instance, a StorageException is thrown at the point that an attempt is made to retrieve a DynamicTableEntity from a table. The connection to the storage account and the table appear to succeed, but the retrieve operation fails. The Tomcat server is running and responsive (I catch the exception and prepare basic error information to be returned by servlets that manage requests). I have been unable to find any examples or definitive statements about using the Java Azure storage libraries in containers, so I would like to know if there are any restrictions, or work-arounds if necessary.

Below are logs which indicate where the exception is thrown.
Log entries with "CommandLineRunner" are generated by my code.
Line 397 in my application is the line where I attempt to retrieve a DynamicTableEntity from the table (14 lines into the log). Prior to that, the connection string is parsed without error, and a reference to the table is generated without error. Although not shown, I am satisfied that the partitionKey and RowKey are correct (and the exception is because the table does not exist - but it does, and is accessible when the container is run locally). Line 562 is the entry point of the spring-boot CommandLineRunner.

    **2019-05-13 00:57:44.632  INFO 3060 --- [           main] a.c.n.sbtest.demo.DemoApplication        : CommandLineRunner: Engine Intialization Ready (status: 0)**
2019-05-13 00:57:44.670  INFO 3060 --- [           main] a.c.n.sbtest.demo.DemoApplication        : CommandLineRunner: Deployment table <Deployments> accessible
2019-05-13 00:57:44.687  INFO 3060 --- [           main] a.c.n.sbtest.demo.DemoApplication        : CommandLineRunner: User <e7c6163e-8c06-4146-b0e4-78fec93e6cce> Container accessible
2019-05-13 01:00:17.755  INFO 3060 --- [nio-8080-exec-7] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-05-13 01:00:17.755  INFO 3060 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-05-13 01:00:17.768  INFO 3060 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : Completed initialization in 13 ms
com.microsoft.azure.storage.StorageException:
        at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:87)
        at com.microsoft.azure.storage.core.ExecutionEngine.executeWithRetry(ExecutionEngine.java:209)
        at com.microsoft.azure.storage.table.QueryTableOperation.performRetrieve(QueryTableOperation.java:178)
        at com.microsoft.azure.storage.table.TableOperation.execute(TableOperation.java:694)
        at com.microsoft.azure.storage.table.CloudTable.execute(CloudTable.java:529)
        at com.microsoft.azure.storage.table.CloudTable.execute(CloudTable.java:496)
        at **ai.com.neuralstudio.sbtest.demo.DemoApplication.lambda$commandLineRunner$0(DemoApplication.java:562)**
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:813)
        at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:797)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:324)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248)
        at **ai.com.neuralstudio.sbtest.demo.DemoApplication.main(DemoApplication.java:397)**
        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.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
        at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)
Caused by: java.net.UnknownHostException: neuralstudiotest002.table.core.windows.net
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
        at java.net.Socket.connect(Socket.java:589)
        at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:673)
        at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
        at sun.net.www.http.HttpClient.openServer(HttpClient.java:463)
        at sun.net.www.http.HttpClient.openServer(HttpClient.java:558)
        at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:264)
        at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:367)
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
        at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1156)
        at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1050)
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1564)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
        at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:347)
        at com.microsoft.azure.storage.core.ExecutionEngine.executeWithRetry(ExecutionEngine.java:115)
        ... 19 more
2019-05-13 01:00:29.420 ERROR 3060 --- [           main] a.c.n.sbtest.demo.DemoApplication        : CommandLineRunner: StorageException com.microsoft.azure.storage.StorageException:  (status: -3)

I would greatly appreciate any insights into what might be going on.
Jack

UPDATE:
While the underlying issue is unresolved for recent Windows container images, jakaruna-MSFT responded in another forum and pointed out that an older image

mcr.microsoft.com/windows/servercore:1607-KB4505052-amd64

would work, and it does. The underlying issue is apparently related to DNS services, and was either broken or omitted in transitions to more recent images. Presumably MS will get around to fixing the later images, with or without explanation.


问:
Python: how to unpack lists of different lengths into a string, using .format()
Is there a way to unpack lists (of different lengths) directly into a string, using .format()?

This code works as expected:

```<code>list_of_ids = [1,2,3]

def generate_query(list_of_ids):
  list_of_ids_as_string = ', '.join(str(e) for e in list_of_ids)
  query = ('SELECT '
              'some.metrics '
              'FROM ad_group '
              'WHERE campaign.id IN ({})'.format(list_of_ids_as_string)
              )
  return query

query = generate_query(list_of_ids)
</code>```

But if I try to unpack the list directly, only the first element will show up in the query:

```<code>def generate_query(list_of_ids):
  query = ('SELECT '
              'some.metrics '
              'FROM ad_group '
              'WHERE campaign.id IN ({})'.format(*list_of_ids)
              )
  return query
</code>```

I know that I could do something like

```<code>              'WHERE campaign.id IN ({},{},{})'.format(*list_of_ids)
</code>```

... but this does not help, if the passed lists are of different lengths.

So - is there a way to unpack lists (of different lengths) directly into a string, using .format()?

答:
You cam join the list given a defined separator. </p>

```<code>“, ”.join(list_of_ids)
</code>```

<p>Which will yield a single string you can use inside your format call. </p>

Body:
Is there a way to unpack lists (of different lengths) directly into a string, using .format()?

This code works as expected:

list_of_ids = [1,2,3]

def generate_query(list_of_ids):
  list_of_ids_as_string = ', '.join(str(e) for e in list_of_ids)
  query = ('SELECT '
              'some.metrics '
              'FROM ad_group '
              'WHERE campaign.id IN ({})'.format(list_of_ids_as_string)
              )
  return query

query = generate_query(list_of_ids)

But if I try to unpack the list directly, only the first element will show up in the query:

def generate_query(list_of_ids):
  query = ('SELECT '
              'some.metrics '
              'FROM ad_group '
              'WHERE campaign.id IN ({})'.format(*list_of_ids)
              )
  return query

I know that I could do something like

              'WHERE campaign.id IN ({},{},{})'.format(*list_of_ids)

... but this does not help, if the passed lists are of different lengths.

So - is there a way to unpack lists (of different lengths) directly into a string, using .format()?

Body:
You cam join the list given a defined separator.

“, ”.join(list_of_ids)

Which will yield a single string you can use inside your format call.


问:
Bigquery data not getting inserted
I'm using python client library to insert data to big query table. The code is as follows.

```<code>client = bigquery.Client(project_id)
errors = client.insert_rows_json(table=tablename,json_rows=data_to_insert)
assert errors == []
</code>```

There are no errors, but the data is also not getting inserted.

Sample JSON rows:

```<code>[{'a':'b','c':'d'},{'a':'f','q':'r'},.....}]
</code>```

What's the problem? No exception also

答:
client.insert_rows_json method using StreamingInsert .
Inserting data to BigQuery using StreamingInsert will be cause of latency on table preview on BigQuery console.

The data is not appeared immediately. So,
You need to query them to confirm the data inserted.

Title: Bigquery data not getting inserted

Body:
I'm using python client library to insert data to big query table. The code is as follows.

client = bigquery.Client(project_id)
errors = client.insert_rows_json(table=tablename,json_rows=data_to_insert)
assert errors == []

There are no errors, but the data is also not getting inserted.

Sample JSON rows:

[{'a':'b','c':'d'},{'a':'f','q':'r'},.....}]

What's the problem? No exception also


问:
How to get only one element from collection in the view
I passed $users variable to my view and I want to get only one element of this collection by comparing it using contains() method.

It's working but I want to retrieve this element so I can show the name
how to do that?

My code:

```<code>@foreach($rqs as $rq)

<td>{{$rq->user_id}} with name:

@if($users->contains('id',$rq->user_id))
       Working  >> I want to get the user name here but only one user
@endif

</td>

@endforeach
</code>```

答:
What about:</p>

```<code>$users->where('id',$rq->user_id)->first()->name
</code>```

Body:
I passed $users variable to my view and I want to get only one element of this collection by comparing it using contains() method.

It's working but I want to retrieve this element so I can show the name
how to do that?

My code:

@foreach($rqs as $rq)

{{$rq->user_id}} with name:

@if($users->contains('id',$rq->user_id))
       Working  >> I want to get the user name here but only one user
@endif

@endforeach

Body:
What about:

$users->where('id',$rq->user_id)->first()->name


问:
Sort an array based on an index array in C
I am trying to sort many arrays in parallel. I sort one array by qsort and I return an int array which specifies the indices of their original positions. Now with this int array, I need to sort other arrays.

Array 1:

```<code> zzz
 yyy
 def
 abc
 cde
 xxx
</code>```

after sorting, I get the index array and the sorted array:Idx position array

```<code>3   :    abc
4   :    cde
2   :    def
5   :    xxx
1   :    yyy
0   :    zzz
</code>```

Now based on this index array, I need to sort another array

```<code>a
b
c
d
e
f
</code>```

so that it becomes

```<code>d
e
c
f
b
a
</code>```

Thanks a lot

答:
```<code>for (i=0; i < 6; ++i)
  SortedArray[IndexArray[i]] = AnotherArray[i];
</code>```

Body:
I am trying to sort many arrays in parallel. I sort one array by qsort and I return an int array which specifies the indices of their original positions. Now with this int array, I need to sort other arrays.

Array 1:

 zzz
 yyy
 def
 abc
 cde
 xxx

after sorting, I get the index array and the sorted array:Idx position array

3   :    abc
4   :    cde
2   :    def
5   :    xxx
1   :    yyy
0   :    zzz

Now based on this index array, I need to sort another array

a
b
c
d
e
f

so that it becomes

d
e
c
f
b
a

Thanks a lot


问:
Algorithm to filter data structure AND/OR/NOT (similar to GraphQL implementation)
I want to implement a data structure that allows for powerful filtering within my application.

The closest implementation I've found is from Prisma https://www.prisma.io/docs/1.27/prisma-graphql-api/reference/queries-qwe1/#combining-multiple-filters (which is actually from GraphQL specification, for what I understand)

Example:

```<code>{
  OR: [
    {
      AND: [
        { title_in: ["My biggest Adventure", "My latest Hobbies"] }
        { published: true }
      ]
    }
    { id: "cixnen24p33lo0143bexvr52n" }
  ]
}
</code>```

The idea is to compare a context against the filters and see if it's a match.

In the above example, the "context" would be an object with the id, title and published fields.

I'm looking for an algorithm that would perform the comparison and resolve whether it's a match or not.

As I'm not looking at reinventing the wheel (especially that it's a complex algorithm IMHO, as AND/OR/NOT conditions can be nested), I wonder if that particular algorithm already exists, or is based on some standards (as we can find that particular data structure on several apps, such as Prisma, PipeDrive and other).

I'm looking for documentation, implementation examples or even open source implementations. (I'm using JS)

答:
I was also looking for such an implementation but couldn't find one.

So I created a prototype for it: https://github.com/Errorname/logical-object-match

Body:
I want to implement a data structure that allows for powerful filtering within my application.

The closest implementation I've found is from Prisma https://www.prisma.io/docs/1.27/prisma-graphql-api/reference/queries-qwe1/#combining-multiple-filters (which is actually from GraphQL specification, for what I understand)

Example:

{
  OR: [
    {
      AND: [
        { title_in: ["My biggest Adventure", "My latest Hobbies"] }
        { published: true }
      ]
    }
    { id: "cixnen24p33lo0143bexvr52n" }
  ]
}

The idea is to compare a context against the filters and see if it's a match.

In the above example, the "context" would be an object with the id, title and published fields.

I'm looking for an algorithm that would perform the comparison and resolve whether it's a match or not.

As I'm not looking at reinventing the wheel (especially that it's a complex algorithm IMHO, as AND/OR/NOT conditions can be nested), I wonder if that particular algorithm already exists, or is based on some standards (as we can find that particular data structure on several apps, such as Prisma, PipeDrive and other).

I'm looking for documentation, implementation examples or even open source implementations. (I'm using JS)


问:
Node/Express Unhandled promise rejections are deprecated
I have been trying to resolve these unhandled Promise rejections that I continue to get in my code.

The current one I get is as follows:

[nodemon] starting mocha --recursive -R min   (node:35286)
  UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: The
  expression evaluated to a falsy value:

assert(count + 1 === newCount)

```<code>at Driver.count.then.newCount (/Users/danale/Projects/muber/test/controllers/drivers_controller.test.js:16:13)
at processTicksAndRejections (internal/process/next_tick.js:81:5) (node:35286) UnhandledPromiseRejectionWarning: Unhandled promise
</code>```

rejection. This error originated either by throwing inside of an async
  function without a catch block, or by rejecting a promise which was
  not handled with .catch(). (rejection id: 1) (node:35286) [DEP0018]
  DeprecationWarning: Unhandled promise rejections are deprecated. In
  the future, promise rejections that are not handled will terminate the
  Node.js process with a non-zero exit code.

The test that should be passing is this one:

```<code>const assert = require("assert");
const request = require("supertest");
const mongoose = require("mongoose");
const app = require("../../app");

const Driver = mongoose.model("driver");

describe("Drivers controller", () => {
  it("Post to /api/drivers create a new driver", done => {
    Driver.count().then(count => {
      request(app)
        .post("api/drivers")
        .send({ email: "test@test.com" })
        .end(() => {
          Driver.count().then(newCount => {
            assert(count + 1 === newCount);
            done();
          });
        });
    });
  });
});
</code>```

To deal with the Promise rejections that I was getting earlier I did this:

```<code>const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const routes = require("./routes/routes");
const app = express();

mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost/muber", { useMongoClient: true });

app.use(bodyParser.json());
routes(app);

module.exports = app;
</code>```

The controller I am trying to test is:

```<code>const Driver = require("../models/driver");

module.exports = {
  greeting(req, res) {
    res.send({ hi: "there" });
  },

  create(req, res) {
    console.log(req.body);
    const driverProps = req.body;

    Driver.create(driverProps).then(driver => res.send(driver));
  }
};
</code>```

I did try to add the catch() to the test like so:

```<code>describe("Drivers controller", () => {
  it("Post to /api/drivers create a new driver", done => {
    Driver.count()
      .then(count => {
        request(app)
          .post("api/drivers")
          .send({ email: "test@test.com" })
          .end((err, res) => {
            Driver.count().then(newCount => {
              assert(count + 1 === newCount);
              done();
            });
          });
      })
      .catch(error => console.log(error));
  });
});
</code>```

but it did not resolve the error.

This is my route handler:

```<code>const DriversController = require("../controllers/drivers_controller");

module.exports = app => {
  // Watch for incoming requests of method GET to the route http://localhost:3050/api
  app.get("/api", DriversController.greeting);

  app.post("/api/drivers", DriversController.create);
};
</code>```

答:
If you chain your promises properly, you will be able to catch the error:

```<code>describe("Drivers controller", () => {
    it("Post to /api/drivers create a new driver", () => {
        let oldCount;
        return Driver.count()
            .then(count => {
                oldCount = count;
                return new Promise((resolve, reject) => {
                    request(app)
                        .post("api/drivers")
                        .send({ email: "test@test.com" })
                        .end((err, res) => {
                            if (err) {
                                reject(err);
                            } else {
                                resolve(res);
                            }
                        });
                });
            }).then(() => {
                return Driver.count();
            }).then(newCount => {
                assert(oldCount + 1 === newCount);
            });
    });
});
</code>```

In your example, you had promises inside promises, but didn't return/await for these. If the assert statement throws an error, the error will not be forwarded to the outer promise.

Body:
I have been trying to resolve these unhandled Promise rejections that I continue to get in my code.

The current one I get is as follows:

[nodemon] starting mocha --recursive -R min   (node:35286)
  UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: The
  expression evaluated to a falsy value:

assert(count + 1 === newCount)

at Driver.count.then.newCount (/Users/danale/Projects/muber/test/controllers/drivers_controller.test.js:16:13)
at processTicksAndRejections (internal/process/next_tick.js:81:5) (node:35286) UnhandledPromiseRejectionWarning: Unhandled promise

rejection. This error originated either by throwing inside of an async
  function without a catch block, or by rejecting a promise which was
  not handled with .catch(). (rejection id: 1) (node:35286) [DEP0018]
  DeprecationWarning: Unhandled promise rejections are deprecated. In
  the future, promise rejections that are not handled will terminate the
  Node.js process with a non-zero exit code.

The test that should be passing is this one:

const assert = require("assert");
const request = require("supertest");
const mongoose = require("mongoose");
const app = require("../../app");

const Driver = mongoose.model("driver");

describe("Drivers controller", () => {
  it("Post to /api/drivers create a new driver", done => {
    Driver.count().then(count => {
      request(app)
        .post("api/drivers")
        .send({ email: "test@test.com" })
        .end(() => {
          Driver.count().then(newCount => {
            assert(count + 1 === newCount);
            done();
          });
        });
    });
  });
});

To deal with the Promise rejections that I was getting earlier I did this:

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const routes = require("./routes/routes");
const app = express();

mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost/muber", { useMongoClient: true });

app.use(bodyParser.json());
routes(app);

module.exports = app;

The controller I am trying to test is:

const Driver = require("../models/driver");

module.exports = {
  greeting(req, res) {
    res.send({ hi: "there" });
  },

  create(req, res) {
    console.log(req.body);
    const driverProps = req.body;

    Driver.create(driverProps).then(driver => res.send(driver));
  }
};

I did try to add the catch() to the test like so:

describe("Drivers controller", () => {
  it("Post to /api/drivers create a new driver", done => {
    Driver.count()
      .then(count => {
        request(app)
          .post("api/drivers")
          .send({ email: "test@test.com" })
          .end((err, res) => {
            Driver.count().then(newCount => {
              assert(count + 1 === newCount);
              done();
            });
          });
      })
      .catch(error => console.log(error));
  });
});

but it did not resolve the error.

This is my route handler:

const DriversController = require("../controllers/drivers_controller");

module.exports = app => {
  // Watch for incoming requests of method GET to the route http://localhost:3050/api
  app.get("/api", DriversController.greeting);

  app.post("/api/drivers", DriversController.create);
};

Body:
If you chain your promises properly, you will be able to catch the error:

describe("Drivers controller", () => {
    it("Post to /api/drivers create a new driver", () => {
        let oldCount;
        return Driver.count()
            .then(count => {
                oldCount = count;
                return new Promise((resolve, reject) => {
                    request(app)
                        .post("api/drivers")
                        .send({ email: "test@test.com" })
                        .end((err, res) => {
                            if (err) {
                                reject(err);
                            } else {
                                resolve(res);
                            }
                        });
                });
            }).then(() => {
                return Driver.count();
            }).then(newCount => {
                assert(oldCount + 1 === newCount);
            });
    });
});

In your example, you had promises inside promises, but didn't return/await for these. If the assert statement throws an error, the error will not be forwarded to the outer promise.


问:
Dockerfile, docker-compose and swarm mode lifecycle
I'm using docker 3.5. In this docker version I've got an issue with nodes dependencies at start time. I tried to resolve it as it was recommended using external sh script coping into docker file. It lead to more issues. For example `script is present but execution was not detected, executed, but program was not started. My docker-compose is up, but swarm mode is failed and so on...

I think I'm not clear with Docker life cycle. Lets imagine we have Dockerfile, docker-compose.yml and docker-swarm.yml. Each of them has an CMD and ENTRYPOINT instruction.

Starting docker-compose I can detect that my service waits for required one (because of waiting script). In case I'm using swarm mode i'm getting fails and my service can't start correctly.

Can you please help with considering lifecycle?

there are instructions:

CMD (docker file)

ENTRYPOINT (docker file)

entrypoint (docker-compose)

command (docker-compose)

entrypoint (docker-swarm)

command (docker-swarm)

Is it possible to have information about execution order of specified instructions for different scenarios?

答:
There is no "execution order" between an entrypoint and a command, regardless of whether it is defined in your image (Dockerfile) or overridden at runtime (with a compose file or cli argument). There is only one command that docker will run to start your container, and when that command exits, the container exits.

If you only define an entrypoint or a command, docker will run that. If you define both an entrypoint and a command, docker will append the command as an argument to the entrypoint. So if you have:

```<code>ENTRYPOINT ["/bin/app", "arg1"]
CMD ["script.sh", "arg2"]
</code>```

Docker will run your container with the command:

```<code>/bin/app arg1 script.sh arg2
</code>```

meaning that script.sh is passed as a cli argument to /bin/app.

If you use the shell/string syntax instead of the exec/json syntax, this can get a bit strange since the shell syntax wraps your command with a /bin/sh -c "$string", and more importantly, the -c arg to /bin/sh only takes a single argument. That means:

```<code>ENTRYPOINT /bin/app arg1
CMD script.sh arg2
</code>```

Will run:

```<code>/bin/sh -c "/bin/app arg1" /bin/sh -c "script.sh arg2"
</code>```

which will ultimately run:

```<code>/bin/app arg1
</code>```

The standard workflow to call a command after running your entrypoint script, is to include the following line a the end of the entrypoint.sh script:

```<code>exec "$@"
</code>```

which will run any cli args to the entrypoint script, typically the value of CMD, as the new pid 1.

Body:
There is no "execution order" between an entrypoint and a command, regardless of whether it is defined in your image (Dockerfile) or overridden at runtime (with a compose file or cli argument). There is only one command that docker will run to start your container, and when that command exits, the container exits.

If you only define an entrypoint or a command, docker will run that. If you define both an entrypoint and a command, docker will append the command as an argument to the entrypoint. So if you have:

ENTRYPOINT ["/bin/app", "arg1"]
CMD ["script.sh", "arg2"]

Docker will run your container with the command:

/bin/app arg1 script.sh arg2

meaning that script.sh is passed as a cli argument to /bin/app.

If you use the shell/string syntax instead of the exec/json syntax, this can get a bit strange since the shell syntax wraps your command with a /bin/sh -c "$string", and more importantly, the -c arg to /bin/sh only takes a single argument. That means:

ENTRYPOINT /bin/app arg1
CMD script.sh arg2

Will run:

/bin/sh -c "/bin/app arg1" /bin/sh -c "script.sh arg2"

which will ultimately run:

/bin/app arg1

The standard workflow to call a command after running your entrypoint script, is to include the following line a the end of the entrypoint.sh script:

exec "$@"

which will run any cli args to the entrypoint script, typically the value of CMD, as the new pid 1.


问:
Unable to check if field exists on MongoDB using NodeJs
I am using NodeJs and MongoDb as a backend service from my android app.I am checking if Phone field exists in my database.
My problem is everytime I check for the field it sends response field exists even if Phone field is not present in document.

Here is my code:

```<code>const express = require('express');
const bodyParser = require('body-parser');
const env = require('dotenv').config();
const router = express.Router();
const MongoClient = require('mongodb').MongoClient;

var dburl = process.env.URL;

router.use(bodyParser.json());
router.use(bodyParser.urlencoded({extended:true}));

router.post('/checkPhone',(req,res) => {

        var data = req.body.uId;

MongoClient.connect(dburl,{useNewUrlParser:true},(err,client) => {

              if(err){

                console.log("Error:" +err);
              }
              else{

                var collect = client.db('Bookbudi_db').collection('Users');

                collect.find({_id:data,Phone:{$exists:true}},(err,doc) => {

                             if(err){

                                console.log("Error:" +err);
                             }
                             if(doc){

                                res.send("Exist");
                             }
                             else{

                                res.send("Doesn't exist");
                             }

                });

              }

     });

 });

module.exports = router;
</code>```

Someone please let me know what I am doing wrong in above code. Any help would be appreciated.

THANKS

答:
if { $exists:true } returns the document - it means that the field is there.

It is possible that your schema defines this field and initiates it w/ null - note that $exists will still return those fields.

References:
$exists

Body:
I am using NodeJs and MongoDb as a backend service from my android app.I am checking if Phone field exists in my database.
My problem is everytime I check for the field it sends response field exists even if Phone field is not present in document.

Here is my code:

const express = require('express');
const bodyParser = require('body-parser');
const env = require('dotenv').config();
const router = express.Router();
const MongoClient = require('mongodb').MongoClient;

var dburl = process.env.URL;

router.use(bodyParser.json());
router.use(bodyParser.urlencoded({extended:true}));

router.post('/checkPhone',(req,res) => {

        var data = req.body.uId;

MongoClient.connect(dburl,{useNewUrlParser:true},(err,client) => {

              if(err){

                console.log("Error:" +err);
              }
              else{

                var collect = client.db('Bookbudi_db').collection('Users');

                collect.find({_id:data,Phone:{$exists:true}},(err,doc) => {

                             if(err){

                                console.log("Error:" +err);
                             }
                             if(doc){

                                res.send("Exist");
                             }
                             else{

                                res.send("Doesn't exist");
                             }

                });

              }

     });

 });

module.exports = router;

Someone please let me know what I am doing wrong in above code. Any help would be appreciated.

THANKS


问:
Can numerical values be assigned to alphabetic elements of a list and then added using the sum() function?
I am  trying the following problem and I don't know what's wrong. Can somebody help me through it?

```<code>java=10
python=10
sql=5
unix=5
javascript=5
framework=10
i=eval(input("Enter courses done in a list"))
if sum(i)>=30:
    print("eligible since the score is", sum(i))
else:
    print("Not eligible since the score is",sum(i))
</code>```

But I am getting the following error,

```<code>Traceback (most recent call last):
  File "E:/Python Notes/Python Programs/Eligible for placement.py", line 8, in <module>
    if sum(i)>=30:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code>```

Thanks in advance!!

答:
I can't help but open with saying you should never just eval() raw user input. It looks like you've manually entered strings, or a variable that stores a string, at your own prompt, since the error message is saying that, on line 8 (if sum(i)>=30:) that the + operator can't work with both strings and integers at the same time. For example, sum('foo', 1) gives the same error.

Check out https://stackoverflow.com/help/minimal-reproducible-example . It's just as good for OPs as it is for responders.

Body:
I am  trying the following problem and I don't know what's wrong. Can somebody help me through it?

java=10
python=10
sql=5
unix=5
javascript=5
framework=10
i=eval(input("Enter courses done in a list"))
if sum(i)>=30:
    print("eligible since the score is", sum(i))
else:
    print("Not eligible since the score is",sum(i))

But I am getting the following error,

Traceback (most recent call last):
  File "E:/Python Notes/Python Programs/Eligible for placement.py", line 8, in <module>
    if sum(i)>=30:
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Thanks in advance!!


问:
How to set a background for whole application in Android?
In my application I have a lot of layers and instead of setting a background image to each of them, I want to set a background once and for all. How can I do that? </p>

答: Take a look at Apply a theme to an Activity or application to apply the background image across the whole application.</p>


问:
Tracking Google Analytics Page Views in Angular2
I have built a new site using Angular 2 as the front-end. As everything is done via push state, there are no page loads which typically trigger the Google Analytics code to send a page view to Google's servers.

How can I manually send page view events to Google so that I can track what users of my site are viewing?

答:
```<code>this.router.events.subscribe(event => {
    if (event instanceof NavigationEnd) {
        ga('set','page', event.urlAfterRedirects);
        ga('send', 'pageview');
    }
});
</code>```


问:
How can I convert this for loop to java 8 stream analog
How can I convert this code to java 8 stream.

Tried to use for each, but failed. For loop code is working.

```<code>for(RestrictedInstrument restrictedInstrument : restrictedInstruments){
    List<Identifier> identifierList = restrictedInstrument.getIdentifier();
    setTicker(matrix, identifierList);
}
</code>```

setTicker() method should be called with matrix Object and identifierList.

答:
Assuming restrictedInstruments is list, first you map to identifierList, then you use Stream.forEach() to execute setTicker(...) method

```<code>restrictedInstruments
  .stream()
  .map( RestrictedInstrument::getIdentifier )
  .forEach( identifierList -> setTicker(matrix, identifierList) )
</code>```

For arrays just use Arrays.stream( restrictedInstruments )

Body:
How can I convert this code to java 8 stream.

Tried to use for each, but failed. For loop code is working.

for(RestrictedInstrument restrictedInstrument : restrictedInstruments){
    List<Identifier> identifierList = restrictedInstrument.getIdentifier();
    setTicker(matrix, identifierList);
}

setTicker() method should be called with matrix Object and identifierList.

Body:
Assuming restrictedInstruments is list, first you map to identifierList, then you use Stream.forEach() to execute setTicker(...) method

restrictedInstruments
  .stream()
  .map( RestrictedInstrument::getIdentifier )
  .forEach( identifierList -> setTicker(matrix, identifierList) )

For arrays just use Arrays.stream( restrictedInstruments )


问:
Organizing tasks review (inspection, verification) in Jira
I'm new to Jira and I'm currently using it in a software development project. And one of the activities on the project is a code review process. A developer creates a new code and then two or more other developers (usually senior developers) inspect that code.

I'm thinking of a way to organize this process in Jira.

The Code Review task is logically a sub-task of the main task (a sub-task of a task). So making the code review task to be a sub-task mean we can't create sub-tasks in it, and that means we can only assign one reviewer.

I'd like to know is there an approach to conducting code review (i.e. a kind of inspection, verification of the work done) process in Jira?

答:
You can e.g. represent it in a workflow (see e.g. here)

You can create a state for Review1 and one state for Review2. But if you want to have dynamic number of reviews, this will not work.


问:
How do I use tryNext() in Gremlin with Node.js?
The following example does not work for me in Node.js using the 'gremlin' 3.4.1 npm package:

```<code>g.V().has('person','name','bill').tryNext().orElseGet{g.addV('person').property('name','bill').next()}
</code>```

I am getting a TypeError saying tryNext() is not a function. What am I doing wrong?

```<code>import {driver, structure} from 'gremlin';
import DriverRemoteConnection = driver.DriverRemoteConnection;
import Graph = structure.Graph;

const g = new Graph().traversal().withRemote(new DriverRemoteConnection('ws://localhost:8182/gremlin'));

console.log(g.V().toList());    <= working
</code>```

Now using the line from above in that code will not work, but it does work using the Gremlin console.

答:
Trying to call a function that doesn't exist, which appears to be as stated in the Gremlin docs, to wit:

tryNext() will return an Optional and thus, is a composite of hasNext()/next() (only supported for JVM languages).

http://tinkerpop.apache.org/docs/current/reference/#terminal-steps

Caveat: Never used TinkerPop, never used Gremlin. But I know how to use the web. Could be this is wrong, but the docs do seem fairly clear.

Body:
The following example does not work for me in Node.js using the 'gremlin' 3.4.1 npm package:

g.V().has('person','name','bill').tryNext().orElseGet{g.addV('person').property('name','bill').next()}

I am getting a TypeError saying tryNext() is not a function. What am I doing wrong?

import {driver, structure} from 'gremlin';
import DriverRemoteConnection = driver.DriverRemoteConnection;
import Graph = structure.Graph;

const g = new Graph().traversal().withRemote(new DriverRemoteConnection('ws://localhost:8182/gremlin'));

console.log(g.V().toList());    <= working

Now using the line from above in that code will not work, but it does work using the Gremlin console.


问:
How to snap data first and second level data from firebase at the same time?
I want to snap the key of data in the second level and the value of data in first level at the same time in order to get something like this:

```<code>{"jasper"}
{"526"}
 {"地理"}
</code>```

what should I do?

答:
I don't think this is possible as is.

What I would recommend would be to store datas as you need them on the requested node. So no values for the second lvl.

Then adding a second node wich will contain the values behind the same key, and request it with the keys that the first request bring back.

Body:
I want to snap the key of data in the second level and the value of data in first level at the same time in order to get something like this:

{"jasper"}
{"526"}
 {"地理"}

what should I do?


问:
origin 'http://localhost:4200' has been blocked by CORS policy in Angular7
I want to use of http://5.160.2.148:8091/api/trainTicketing/city/findAll rest for get cities in my angular project.

I used version 7.2.15 of angular in my project.

when get this url with httpClient throw following error :

```<code> Access to XMLHttpRequest at 'http://5.160.2.148:8091/api/trainTicketing/city/findAll' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

While at work correctly when enter url in browser and postman.

why ?

答:
Solution 1 - you need to change your backend to accept your incoming requests

Solution 2 - using Angular proxy see here

Please note this is only for ng serve, you can't use proxy in ng build

Solution 3 - IF your backend accepts requests from a wildcard domanin like *.mydomain.example then you can edit your hosts file and add 127.0.0.1 local.mydomain.example in there, then in your browser instead of localhost:4200 enter local.mydomain.example:4200

Note: the reason it's working via postman is postman doesn't send preflight requests while your browser does.

Body:
I want to use of http://5.160.2.148:8091/api/trainTicketing/city/findAll rest for get cities in my angular project.

I used version 7.2.15 of angular in my project.

when get this url with httpClient throw following error :

 Access to XMLHttpRequest at 'http://5.160.2.148:8091/api/trainTicketing/city/findAll' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

While at work correctly when enter url in browser and postman.

why ?


问:
How to tune random forest code for quality prediction
I am new to machine learning.I have got this dataset - http://archive.ics.uci.edu/ml/datasets/Wine+Quality. I have to predict Quality of wine which is the last column on the dataset.I thought about applying Neural network or random forest for this, where as NN gave around 55% accuracy, with random forest I managed to get 73% so far. I want to improve the accuracy further.Below is code I have written.

```<code>wineq <- read.csv("wine-quality.csv",header = TRUE)
str(wineq)

wineq$taste <- ifelse(wineq$quality < 6, 'bad', 'good')
wineq$taste[wineq$quality == 6] <- 'normal'
wineq$taste <- as.factor(wineq$taste)
set.seed(54321)
train <- sample(1:nrow(wineq), .75 * nrow(wineq))
wineq_train <- wineq[train, ]
wineq_test  <- wineq[-train, ]

library(randomForest)

rf=randomForest(taste~.-
quality,data=wineq_train,importance=TRUE,ntree=100)

rf_preds = predict(rf,wineq_test)
rf_preds
table(rf_preds, wineq_test$taste)
</code>```

Output:

table(rf_preds, wineq_test$taste)

```<code>rf_preds bad good normal
bad    302   11     81
good     7  163     36
normal  93  101    431
</code>```

If I want to use tuneRF it gives me below error:

```<code>   fgl.res <- tuneRF(x = wineq[train, ], y= wineq[-train, ],
   stepFactor=1.5)
</code>```

Error in randomForest.default(x, y, mtry = mtryStart, ntree =
  ntreeTry,

         :
         length of response must be the same as predictors

答:
You need to pass to tuneRF the feature variables as x and the response variable as y.

So, first find the column position of your response variable (taste):

```<code>resp_pos <- which(colnames(wineq) == "taste")
</code>```

Then:

```<code>fgl.res <- tuneRF(x = wineq[train, -resp_pos ], y= wineq[-train, resp_pos],
   stepFactor=1.5)
</code>```

I noticed also that you use wineq$taste <- ifelse(wineq$quality < 6, 'bad', 'good') to find your "new" response (taste), based on the column quality. Note that this is perfectly fine, but you need to remove the column quality before training.

If you don't do this, your model will be overly optimistic, since it'll pick up that for example:

quality < 6 will always mean taste=="bad"

Body:
I am new to machine learning.I have got this dataset - http://archive.ics.uci.edu/ml/datasets/Wine+Quality. I have to predict Quality of wine which is the last column on the dataset.I thought about applying Neural network or random forest for this, where as NN gave around 55% accuracy, with random forest I managed to get 73% so far. I want to improve the accuracy further.Below is code I have written.

wineq <- read.csv("wine-quality.csv",header = TRUE)
str(wineq)

wineq$taste <- ifelse(wineq$quality < 6, 'bad', 'good')
wineq$taste[wineq$quality == 6] <- 'normal'
wineq$taste <- as.factor(wineq$taste)
set.seed(54321)
train <- sample(1:nrow(wineq), .75 * nrow(wineq))
wineq_train <- wineq[train, ]
wineq_test  <- wineq[-train, ]

library(randomForest)

rf=randomForest(taste~.-
quality,data=wineq_train,importance=TRUE,ntree=100)

rf_preds = predict(rf,wineq_test)
rf_preds
table(rf_preds, wineq_test$taste)

Output:

table(rf_preds, wineq_test$taste)

rf_preds bad good normal
bad    302   11     81
good     7  163     36
normal  93  101    431

If I want to use tuneRF it gives me below error:

   fgl.res <- tuneRF(x = wineq[train, ], y= wineq[-train, ],
   stepFactor=1.5)

Error in randomForest.default(x, y, mtry = mtryStart, ntree =
  ntreeTry,

         :
         length of response must be the same as predictors

Body:
You need to pass to tuneRF the feature variables as x and the response variable as y.

So, first find the column position of your response variable (taste):

resp_pos <- which(colnames(wineq) == "taste")

Then:

fgl.res <- tuneRF(x = wineq[train, -resp_pos ], y= wineq[-train, resp_pos],
   stepFactor=1.5)

I noticed also that you use wineq$taste <- ifelse(wineq$quality < 6, 'bad', 'good') to find your "new" response (taste), based on the column quality. Note that this is perfectly fine, but you need to remove the column quality before training.

If you don't do this, your model will be overly optimistic, since it'll pick up that for example:

quality < 6 will always mean taste=="bad"


问:
Atomic Design Pattern - Business Logic
I am implementing Atomic Design pattern in my project. Just a quick question, in where distinct stage should i put the business logic if i implement atomic design pattern?</p>

答:
Atoms and Molecules shouldnt have any business logic. Maybe the molecules can have some event handlers for there buttons, but they shouldnt. Organisms can have logic, if needed. But if you really want to implement that pattern, than the container should handle all the logic (pages/templates) so called HOC, higher order components.

If you read more about it, this article helped me a while ago.
You could also read the book Atomic Design from Brad Frost, i used it in my master thesis as literature review.

Title: Atomic Design Pattern - Business Logic


答:
You can just use List.forEach():

```<code>restrictedInstruments.forEach(i -> setTicker(matrix, i.getIdentifier()));
</code>```

Title: How can I convert this for loop to java 8 stream analog

Body:
You can just use List.forEach():

restrictedInstruments.forEach(i -> setTicker(matrix, i.getIdentifier()));


问:
BeautifulSoup getText from between
, not picking up subsequent paragraphs
Firstly, I am a complete newbie when it comes to Python. However, I have written a piece of code to look at an RSS feed, open the link and extract the text from the article. This is what I have so far:

```<code>from BeautifulSoup import BeautifulSoup
import feedparser
import urllib

# Dictionaries
links = {}
titles = {}

# Variables
n = 0

rss_url = "feed://www.gfsc.gg/_layouts/GFSC/GFSCRSSFeed.aspx?Division=ALL&Article=All&Title=News&Type=doc&List=%7b66fa9b18-776a-4e91-9f80-    30195001386c%7d%23%7b679e913e-6301-4bc4-9fd9-a788b926f565%7d%23%7b0e65f37f-1129-4c78-8f59-3db5f96409fd%7d%23%7bdd7c290d-5f17-43b7-b6fd-50089368e090%7d%23%7b4790a972-c55f-46a5-8020-396780eb8506%7d%23%7b6b67c085-7c25-458d-8a98-373e0ac71c52%7d%23%7be3b71b9c-30ce-47c0-8bfb-f3224e98b756%7d%23%7b25853d98-37d7-4ba2-83f9-78685f2070df%7d%23%7b14c41f90-c462-44cf-a773-878521aa007c%7d%23%7b7ceaf3bf-d501-4f60-a3e4-2af84d0e1528%7d%23%7baf17e955-96b7-49e9-ad8a-7ee0ac097f37%7d%23%7b3faca1d0-be40-445c-a577-c742c2d367a8%7d%23%7b6296a8d6-7cab-4609-b7f7-b6b7c3a264d6%7d%23%7b43e2b52d-e4f1-4628-84ad-0042d644deaf%7d"

# Parse the RSS feed
feed = feedparser.parse(rss_url)

# view the entire feed, one entry at a time
for post in feed.entries:
    # Create variables from posts
    link = post.link
    title = post.title
    # Add the link to the dictionary
    n += 1
    links[n] = link

for k,v in links.items():
    # Open RSS feed
    page = urllib.urlopen(v).read()
    page = str(page)
    soup = BeautifulSoup(page)

    # Find all of the text between paragraph tags and strip out the html
    page = soup.find('p').getText()

    # Strip ampersand codes and WATCH:
    page = re.sub('&\w+;','',page)
    page = re.sub('WATCH:','',page)

    # Print Page
    print(page)
    print(" ")

    # To stop after 3rd article, just whilst testing ** to be removed **
    if (k >= 3):
        break
</code>```

This produces the following output:

```<code>>>> (executing lines 1 to 45 of "RSS_BeautifulSoup.py")
Total deposits held with Guernsey banks at the end of June 2012 increased 2.1% in sterling terms by £2.1 billion from the end of March 2012 level of £101 billion, up to £103.1 billion. This is 9.4% lower than the same time a year ago.  Total assets and liabilities increased by £2.9 billion to £131.2 billion representing a 2.3% increase over the quarter though this was 5.7% lower than the level a year ago.  The higher figures reflected the effects both of volume and exchange rate factors.

The net asset value of total funds under management and administration has increased over the quarter ended 30 June 2012 by £711 million (0.3%) to reach £270.8 billion.For the year since 30 June 2011, total net asset values decreased by £3.6 billion (1.3%).

The Commission has updated the warranties on the Form REG, Form QIF and Form FTL to take into account the Commission’s Guidance Notes on Personal Questionnaires and Personal Declarations.  In particular, the following warranty (varies slightly dependent on the application) has been inserted in the aforementioned forms,

>>>
</code>```

The problem is that this is the first paragraph of each article, however I need to show the entire article. Any help would be gratefully received.

答:
This works well for specific articles where the text is all wrapped in
 tags.  Since the web is an ugly place, it's not always the case.

Often, websites will have text scattered all over, wrapped in different types of tags (e.g. maybe in a  or a
, or an
).

To find all text nodes in the DOM, you can use soup.find_all(text=True).

This is going to return some undesired text, like the contents of

Title: BeautifulSoup getText from between <p>, not picking up subsequent paragraphs

Body:
Firstly, I am a complete newbie when it comes to Python. However, I have written a piece of code to look at an RSS feed, open the link and extract the text from the article. This is what I have so far:

from BeautifulSoup import BeautifulSoup
import feedparser
import urllib

# Dictionaries
links = {}
titles = {}

# Variables
n = 0

rss_url = "feed://www.gfsc.gg/_layouts/GFSC/GFSCRSSFeed.aspx?Division=ALL&Article=All&Title=News&Type=doc&List=%7b66fa9b18-776a-4e91-9f80-    30195001386c%7d%23%7b679e913e-6301-4bc4-9fd9-a788b926f565%7d%23%7b0e65f37f-1129-4c78-8f59-3db5f96409fd%7d%23%7bdd7c290d-5f17-43b7-b6fd-50089368e090%7d%23%7b4790a972-c55f-46a5-8020-396780eb8506%7d%23%7b6b67c085-7c25-458d-8a98-373e0ac71c52%7d%23%7be3b71b9c-30ce-47c0-8bfb-f3224e98b756%7d%23%7b25853d98-37d7-4ba2-83f9-78685f2070df%7d%23%7b14c41f90-c462-44cf-a773-878521aa007c%7d%23%7b7ceaf3bf-d501-4f60-a3e4-2af84d0e1528%7d%23%7baf17e955-96b7-49e9-ad8a-7ee0ac097f37%7d%23%7b3faca1d0-be40-445c-a577-c742c2d367a8%7d%23%7b6296a8d6-7cab-4609-b7f7-b6b7c3a264d6%7d%23%7b43e2b52d-e4f1-4628-84ad-0042d644deaf%7d"

# Parse the RSS feed
feed = feedparser.parse(rss_url)

# view the entire feed, one entry at a time
for post in feed.entries:
    # Create variables from posts
    link = post.link
    title = post.title
    # Add the link to the dictionary
    n += 1
    links[n] = link

for k,v in links.items():
    # Open RSS feed
    page = urllib.urlopen(v).read()
    page = str(page)
    soup = BeautifulSoup(page)

    # Find all of the text between paragraph tags and strip out the html
    page = soup.find('p').getText()

    # Strip ampersand codes and WATCH:
    page = re.sub('&\w+;','',page)
    page = re.sub('WATCH:','',page)

    # Print Page
    print(page)
    print(" ")

    # To stop after 3rd article, just whilst testing ** to be removed **
    if (k >= 3):
        break

This produces the following output:

>>> (executing lines 1 to 45 of "RSS_BeautifulSoup.py")
Total deposits held with Guernsey banks at the end of June 2012 increased 2.1% in sterling terms by £2.1 billion from the end of March 2012 level of £101 billion, up to £103.1 billion. This is 9.4% lower than the same time a year ago.  Total assets and liabilities increased by £2.9 billion to £131.2 billion representing a 2.3% increase over the quarter though this was 5.7% lower than the level a year ago.  The higher figures reflected the effects both of volume and exchange rate factors.

The net asset value of total funds under management and administration has increased over the quarter ended 30 June 2012 by £711 million (0.3%) to reach £270.8 billion.For the year since 30 June 2011, total net asset values decreased by £3.6 billion (1.3%).

The Commission has updated the warranties on the Form REG, Form QIF and Form FTL to take into account the Commission’s Guidance Notes on Personal Questionnaires and Personal Declarations.  In particular, the following warranty (varies slightly dependent on the application) has been inserted in the aforementioned forms,

>>>

The problem is that this is the first paragraph of each article, however I need to show the entire article. Any help would be gratefully received.

Body:
This works well for specific articles where the text is all wrapped in <p> tags.  Since the web is an ugly place, it's not always the case.

Often, websites will have text scattered all over, wrapped in different types of tags (e.g. maybe in a <span> or a <div>, or an <li>).

To find all text nodes in the DOM, you can use soup.find_all(text=True).

This is going to return some undesired text, like the contents of <script> and <style> tags.  You'll need to filter out the text contents of elements you don't want.

blocklist = [
  'style',
  'script',
  # other elements,
]

text_elements = [t for t in soup.find_all(text=True) if t.parent.name not in blocklist]

If you are working with a known set of tags, you can tag the opposite approach:

allowlist = [
  'p'
]

text_elements = [t for t in soup.find_all(text=True) if t.parent.name in allowlist]


问:
How Can I Create JNI Interface for Traceroute C File
I'm working on Android application which is a network utility. One of the utility is traceroute implementation using activity and xml file. Implementing traceroute in java is kind of a pain, so I looked to JNI and C code. There's a utility that include many linux tools called busybox. It is open source and has traceroute. here's the code on github https://raw.githubusercontent.com/mirror/busybox/master/networking/traceroute.c
My question is how can I implement JNI interface in java for this file. The file one compiled acts as a command line tool which you run and pass the parameter of the host you want to traceroute. Does that mean I have to implement only the main method in JNI. Also, this file doesn't have the JNI type methods so I wont be able to interface directly with it. Do I need to create another C file that calls traceroute main method using JNI C code. Any input appreciated</p>

答:
You want to call this method: common_traceroute_main(int op, char **argv)

You have to create shared library using the code from github. Take a look here

http://jnicookbook.owsiak.org/recipe-No-001/

Once you have your library, you have to prepare parameters inside Java and pass them to JNI code, where you need to unpack them and convert to what is expected by common_traceroute_main.

For example. You can pass array of String and convert them to char **argv.

http://jnicookbook.owsiak.org/recipe-No-009/

Then, all you have to do is to call common_traceroute_main from your JNI wrapper.

Solution draft

You will need Java code, for example, something like this

```<code>public class TraceCaller {
  public static native callTraceRoute(int op, String[] args);
}
</code>```

once you compile it using javac -h headers TraceCaller you will find C header file.

Inside this header file, you will have to extract values from array of strings. Take a look here (https://github.com/mkowsiak/jnicookbook/blob/master/recipes/recipeNo038/java/recipeNo038/PassHashMap.java) to get the feeling of how to retrieve String objects from array inside JNI code and turn them into char*.

Once you have (inside JNI) both: int op and array of char * you can simply call routine: common_traceroute_main.

Once it's finished, you have to pass data back (either as return value or via object passed to JNI).

Take a look here on sample that shows how to pass String back to Java:

https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo010

And, you are done :)

Body:
You want to call this method: common_traceroute_main(int op, char **argv)

You have to create shared library using the code from github. Take a look here

http://jnicookbook.owsiak.org/recipe-No-001/

Once you have your library, you have to prepare parameters inside Java and pass them to JNI code, where you need to unpack them and convert to what is expected by common_traceroute_main.

For example. You can pass array of String and convert them to char **argv.

http://jnicookbook.owsiak.org/recipe-No-009/

Then, all you have to do is to call common_traceroute_main from your JNI wrapper.

Solution draft

You will need Java code, for example, something like this

public class TraceCaller {
  public static native callTraceRoute(int op, String[] args);
}

once you compile it using javac -h headers TraceCaller you will find C header file.

Inside this header file, you will have to extract values from array of strings. Take a look here (https://github.com/mkowsiak/jnicookbook/blob/master/recipes/recipeNo038/java/recipeNo038/PassHashMap.java) to get the feeling of how to retrieve String objects from array inside JNI code and turn them into char*.

Once you have (inside JNI) both: int op and array of char * you can simply call routine: common_traceroute_main.

Once it's finished, you have to pass data back (either as return value or via object passed to JNI).

Take a look here on sample that shows how to pass String back to Java:

https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo010

And, you are done :)


问:
Random CSS animation time on each iteration
Trying to set a random animation time on each iteration. I set a CSS custom property --animation-time changed randomly each animation iteration with JS.

let square = document.getElementById('square');
let time;

square.addEventListener('animationiteration', duration);

function duration() {
  time = Math.random() + 1;
  square.style.setProperty('--animation-time', time + 's');
  console.log(time);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>:root {
  --animation-time: 5s;
  --color-1: #ff0000;
  --color-2: #ffee00;
}

@keyframes fire {
  0% {
    background-color: var(--color-1);
  }
  100% {
    background-color: var(--color-2);
  }
}

#square {
  width: 100px;
  height: 100px;
  animation: fire var(--animation-time) ease alternate infinite;
}</code>```

```

The duration of animation is set to time = Math.random() + 1; so, the iterations should never have less than 1 second. However, it hapens sometimes very quickly. Why?

Here is a CodePen: https://codepen.io/aitormendez/pen/YbvvKw

答:
When you change the animation-duration you will not simply change how each iteration will take but you will change the whole animation. If for example you have 3s as a duration so the first iteration will take 3s and if at 3s (iterationend) you change to 5s it's like you create another animation where the iteration will last 5s and you jump to a new state of that new animation which is 3s of 5s.

Here is an example to better illustrate the issue. I will keep increasing the duration and you will notice that once you reach the end of the iteration you will get back to a previous state because you increased the duration then you will reach again the last state and you will get back and so on.

It's like someone is running to the 100% state and you keep increasing that state.

let square = document.getElementById('square');
let time = 1;

square.addEventListener('animationiteration', duration);

function duration() {
  time*=2;
  square.style.setProperty('--animation-time', time + 's');
  console.log(time);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>:root {
  --animation-time: 1s;
}

@keyframes fire {
  0% {
    background-color: red;
  }
  50% {
    background:yellow;
  }
  100% {
    background-color: black;
  }
}

#square {
  width: 100px;
  height: 100px;
  animation: fire var(--animation-time) ease infinite alternate;
}</code>```

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

<p>In the above example I am multiplying the duration by 2 so each time I jump back to start from the <code>50%</code> state and once I reach the <code>100%</code> I will repeat the same again.</p>

<hr>

<p>The same is happening with your code but in a more complex way since you are increasing/decreasing the duration. Decreasing the duration will make you jump to the next iteration and the alternate state. </p>

<p>In other words, You will end with a random flickering animation.</p>

<p>To visually illustrate what is happening here is an animation where I will animate the timeline of <em>your animation</em></p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
  height:50px;
  border:1px solid;
  background:
    /* This will illustrate the current state */
    linear-gradient(green,green) left/2px 100% no-repeat,
    /* This is our animation with a duration of 5s (50px) intially*/
    linear-gradient(to right,yellow,red,red,yellow) left/100px 100%;

  animation:
    move 10s linear infinite, /* This is the current state*/
    change 2s steps(3) infinite /* this is the change of the animation duration*/
  ; /**/
}

@keyframes move {
  to {
    background-position:right,left;
  }
}
@keyframes change {
  to {
    background-size:2px 100%,40px 100%;
  }
}</code>```

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

<p>You can see that we aren't changing the current state (illustrated by the green line) but we are changing the whole animation making the current state jumping in different color randomly.</p>

<hr>

<p>One idea to obtain what you want is to consider transition and class toggling:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let square = document.getElementById('square');
let time;

/* We intially add the class to trigger the transition*/
setTimeout(function(){square.classList.toggle('change')},10);

square.addEventListener('transitionend', duration);

/* When the transition is done we toggle the class to start another one*/
function duration() {
  time = Math.random() + 1;
  square.style.setProperty('--animation-time', time + 's');
  square.classList.toggle('change');
  console.log(time);
}</code>```

:root {
  --animation-time: 1s;
  --color-1: #ff0000;
  --color-2: #ffee00;
}

#square {
  width: 100px;
  height: 100px;
  transition: var(--animation-time) ease;
  background-color: var(--color-1);
}

#square.change {
  background-color: var(--color-2);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="square"></div></code>```

Body:
Trying to set a random animation time on each iteration. I set a CSS custom property --animation-time changed randomly each animation iteration with JS.

let square = document.getElementById('square');
let time;

square.addEventListener('animationiteration', duration);

function duration() {
  time = Math.random() + 1;
  square.style.setProperty('--animation-time', time + 's');
  console.log(time);
}

:root {
  --animation-time: 5s;
  --color-1: #ff0000;
  --color-2: #ffee00;
}

@keyframes fire {
  0% {
    background-color: var(--color-1);
  }
  100% {
    background-color: var(--color-2);
  }
}

#square {
  width: 100px;
  height: 100px;
  animation: fire var(--animation-time) ease alternate infinite;
}

The duration of animation is set to time = Math.random() + 1; so, the iterations should never have less than 1 second. However, it hapens sometimes very quickly. Why?

Here is a CodePen: https://codepen.io/aitormendez/pen/YbvvKw

Body:
When you change the animation-duration you will not simply change how each iteration will take but you will change the whole animation. If for example you have 3s as a duration so the first iteration will take 3s and if at 3s (iterationend) you change to 5s it's like you create another animation where the iteration will last 5s and you jump to a new state of that new animation which is 3s of 5s.

Here is an example to better illustrate the issue. I will keep increasing the duration and you will notice that once you reach the end of the iteration you will get back to a previous state because you increased the duration then you will reach again the last state and you will get back and so on.

It's like someone is running to the 100% state and you keep increasing that state.

let square = document.getElementById('square');
let time = 1;

square.addEventListener('animationiteration', duration);

function duration() {
  time*=2;
  square.style.setProperty('--animation-time', time + 's');
  console.log(time);
}

:root {
  --animation-time: 1s;
}

@keyframes fire {
  0% {
    background-color: red;
  }
  50% {
    background:yellow;
  }
  100% {
    background-color: black;
  }
}

#square {
  width: 100px;
  height: 100px;
  animation: fire var(--animation-time) ease infinite alternate;
}

<div id="square"></div>

In the above example I am multiplying the duration by 2 so each time I jump back to start from the 50% state and once I reach the 100% I will repeat the same again.

The same is happening with your code but in a more complex way since you are increasing/decreasing the duration. Decreasing the duration will make you jump to the next iteration and the alternate state.

In other words, You will end with a random flickering animation.

To visually illustrate what is happening here is an animation where I will animate the timeline of your animation

.box {
  height:50px;
  border:1px solid;
  background:
    /* This will illustrate the current state */
    linear-gradient(green,green) left/2px 100% no-repeat,
    /* This is our animation with a duration of 5s (50px) intially*/
    linear-gradient(to right,yellow,red,red,yellow) left/100px 100%;

  animation:
    move 10s linear infinite, /* This is the current state*/
    change 2s steps(3) infinite /* this is the change of the animation duration*/
  ; /**/
}

@keyframes move {
  to {
    background-position:right,left;
  }
}
@keyframes change {
  to {
    background-size:2px 100%,40px 100%;
  }
}

<div class="box">

</div>

You can see that we aren't changing the current state (illustrated by the green line) but we are changing the whole animation making the current state jumping in different color randomly.

One idea to obtain what you want is to consider transition and class toggling:

let square = document.getElementById('square');
let time;

/* We intially add the class to trigger the transition*/
setTimeout(function(){square.classList.toggle('change')},10);

square.addEventListener('transitionend', duration);

/* When the transition is done we toggle the class to start another one*/
function duration() {
  time = Math.random() + 1;
  square.style.setProperty('--animation-time', time + 's');
  square.classList.toggle('change');
  console.log(time);
}

:root {
  --animation-time: 1s;
  --color-1: #ff0000;
  --color-2: #ffee00;
}

#square {
  width: 100px;
  height: 100px;
  transition: var(--animation-time) ease;
  background-color: var(--color-1);
}

#square.change {
  background-color: var(--color-2);
}

<div id="square"></div>


问:
Iphone dev : how can I get a result from google currency converter?
Sorry for my english ^^
I would know how I can have a result from the google converter tool for currency, available on http://www.google.com/finance/converter?a=1&from=USD&to=GBP for example.

I have already tried something like that :

```<code>    -(IBAction)getResponse:(id) sender{

     NSString *myURLString = @"http://www.google.com/finance/converter?a=1&from=USD&to=GBP";

     NSURL *myURL =  [NSURL URLWithString: myURLString];

     NSData *data = [NSData alloc];

     data=[NSData dataWithContentsOfURL:myURL];

     if(data!=nil && data != ""){

          NSString *response = [[[NSString alloc] initWithData:data]]

          [label setText: response];

     }

     else [label setText:@"not working"];
}
</code>```

But when I click on my button, the label does not have a text (it is like it is empty).
Am I doing something wrong ?
Is it possible what I want to do ?
Thank you very much for your futures answers !
Olivier.

答:
Try...

NSData *data = [[NSData alloc] init];

Then check you've got something in response

```<code>NSLog(@"%@", response);
</code>```

Better yet, remove the NSData alloc/init

Replace with

```<code>NSData *data=[NSData dataWithContentsOfURL:myURL];
</code>```

And, you'll need to parse the return result, because you're not going to get back what you expect. Response will contain HTML page.

Body:
Sorry for my english ^^
I would know how I can have a result from the google converter tool for currency, available on http://www.google.com/finance/converter?a=1&from=USD&to=GBP for example.

I have already tried something like that :

    -(IBAction)getResponse:(id) sender{

     NSString *myURLString = @"http://www.google.com/finance/converter?a=1&from=USD&to=GBP";

     NSURL *myURL =  [NSURL URLWithString: myURLString];

     NSData *data = [NSData alloc];

     data=[NSData dataWithContentsOfURL:myURL];

     if(data!=nil && data != ""){

          NSString *response = [[[NSString alloc] initWithData:data]]

          [label setText: response];

     }

     else [label setText:@"not working"];
}

But when I click on my button, the label does not have a text (it is like it is empty).
Am I doing something wrong ?
Is it possible what I want to do ?
Thank you very much for your futures answers !
Olivier.

Body:
Try...

NSData *data = [[NSData alloc] init];

Then check you've got something in response

NSLog(@"%@", response);

Better yet, remove the NSData alloc/init

Replace with

NSData *data=[NSData dataWithContentsOfURL:myURL];

And, you'll need to parse the return result, because you're not going to get back what you expect. Response will contain HTML page.


问:
How to generate a random value and its result from a list?
What I want is, generate a random value displayed in a h tag, and also, display the good value relative to the random one, in an other tag.

```<code>var first = ['1+2', '10+20', '100+200'];
var second = ['3', '30', '300'];

var first_value = first[Math.floor(Math.random()*first.length)];
var second_value = second[Math.floor(Math.random()*second.length)];

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

At the moment, everything is generated randomly, there is no relation between the 2 values generated.

If "10+20" is randomly selected, I want to display "30" in the second html tag.

答:
Why not only get a random number for the first array like below.

```<code>var first = ['1+2', '10+20', '100+200'];
var index = Math.floor(Math.random() * first.length);
</code>```

And then with the result you get, calculate the actual outcome with the evaluation method like below

```<code>document.getElementById('first_value').innerHTML = eval(first[index])
</code>```

Then you don't need the second array

And if the first value is the sum, and the second value the outcome, you could do this:

```<code>document.getElementById('first_value').innerHTML = first[index]
document.getElementById('second_value').innerHTML = eval(first[index])
</code>```

Body:
What I want is, generate a random value displayed in a h tag, and also, display the good value relative to the random one, in an other tag.

var first = ['1+2', '10+20', '100+200'];
var second = ['3', '30', '300'];

var first_value = first[Math.floor(Math.random()*first.length)];
var second_value = second[Math.floor(Math.random()*second.length)];

document.getElementById('first_value').innerHTML = first_value;
document.getElementById('second_value').innerHTML = second_value;

At the moment, everything is generated randomly, there is no relation between the 2 values generated.

If "10+20" is randomly selected, I want to display "30" in the second html tag.

Body:
Why not only get a random number for the first array like below.

var first = ['1+2', '10+20', '100+200'];
var index = Math.floor(Math.random() * first.length);

And then with the result you get, calculate the actual outcome with the evaluation method like below

document.getElementById('first_value').innerHTML = eval(first[index])

Then you don't need the second array

And if the first value is the sum, and the second value the outcome, you could do this:

document.getElementById('first_value').innerHTML = first[index]
document.getElementById('second_value').innerHTML = eval(first[index])


问:
Execute SQL query when/if X
I have the following INSERT:

```<code>        $id = \DB::table('log')
      ->insert(array(
        "account_id" => $this->get("account_id"),
        "type" => "Edit info",
        "done" => "0"
      ));
</code>```

How could I adapt it in order to be executed only when there are no previous entries like this inside log table?

account_id: 1 //
type: Edit info //
done: 0

I need to avoid repeating entries (no same entries if the user already requested edit his/her info and it wasn't done by an admin yet).

答:
You can use updateOrInsert method.

```<code>$id = \DB::table('log')->updateOrInsert(array(
  "account_id" => $this->get("account_id"),
  "type" => "Edit info",
  "done" => "0"
));
</code>```

Title: Execute SQL query when/if X

Body:
I have the following INSERT:

        $id = \DB::table('log')
      ->insert(array(
        "account_id" => $this->get("account_id"),
        "type" => "Edit info",
        "done" => "0"
      ));

How could I adapt it in order to be executed only when there are no previous entries like this inside log table?

account_id: 1 //
type: Edit info //
done: 0

I need to avoid repeating entries (no same entries if the user already requested edit his/her info and it wasn't done by an admin yet).

Body:
You can use updateOrInsert method.

$id = \DB::table('log')->updateOrInsert(array(
  "account_id" => $this->get("account_id"),
  "type" => "Edit info",
  "done" => "0"
));


问:
Calling a child object in the parent object
I want to know if I can create a child object in a parent object an use it...

I mean is it posible?

Is it a good    idea?

What do I have to care if I do    so?

I am using the child classes on their own and i want to use them in a private function of the parent class as well.

thanks

here some source to imagine what I am meaning:

```<code>class A{
    private $child_class1;
    private $child_class2;

    private function somefunction(){
        $this->child_class1 = new B();
        $this->child_class1->do_something();

        $this->child_class2 = new C();
        $this->child_class2->do_something();
    }
}

class B extends A{
    public function do_something(){
...
    }
}

class C extends A{
    public function do_something(){
...
    }
}
</code>```

答:
You could use abstract methods to delegate certain actions to derived classes:

```<code>class A {
    public function __construct() {
        $this->do_something();
    }

    protected abstract function do_something();
}

class B extends A {
    protected function do_something() {
        // ...
    }
}
</code>```

It is not certainly a good idea to do so. It depends on what you want to achieve, and why. Creating derived classes in the parents constructor (like your previous example stated) is impossible. The language might allow it, but it will lead to an endless loop of instantiation. You will definitely need to explain why you are doing this. Otherwise nobody will be able to help you sufficiently.

Body:
I want to know if I can create a child object in a parent object an use it...

I mean is it posible?

Is it a good    idea?

What do I have to care if I do    so?

I am using the child classes on their own and i want to use them in a private function of the parent class as well.

thanks

here some source to imagine what I am meaning:

class A{
    private $child_class1;
    private $child_class2;

    private function somefunction(){
        $this->child_class1 = new B();
        $this->child_class1->do_something();

        $this->child_class2 = new C();
        $this->child_class2->do_something();
    }
}

class B extends A{
    public function do_something(){
...
    }
}

class C extends A{
    public function do_something(){
...
    }
}

Body:
You could use abstract methods to delegate certain actions to derived classes:

class A {
    public function __construct() {
        $this->do_something();
    }

    protected abstract function do_something();
}

class B extends A {
    protected function do_something() {
        // ...
    }
}

It is not certainly a good idea to do so. It depends on what you want to achieve, and why. Creating derived classes in the parents constructor (like your previous example stated) is impossible. The language might allow it, but it will lead to an endless loop of instantiation. You will definitely need to explain why you are doing this. Otherwise nobody will be able to help you sufficiently.