问:
Running A Bookmarklet With Autohotkey
I have this neat little bookmarklet that refreshes the stylesheet on whatever webpage you are looking at without reloading the page:

```<code>javascript:(function(){var h,a,f;a=document.getElementsByTagName('link');for(h=0;h<a.length;h++){f=a[h];if(f.rel.toLowerCase().match(/stylesheet/)&&f.href){var g=f.href.replace(/(&|%5C?)forceReload=\d+/,'');f.href=g+(g.match(/\?/)?'&':'?')+'forceReload='+(new Date().valueOf())}}})()
</code>```

I'm trying to write an AHK script to run the bookmarklet when I hit CTRL + Q. This is what I've got so far:

```<code>^q::
Clipboard:="?javascript:(function(){var h,a,f;a=document.getElementsByTagName('link');for(h=0;h<a.length;h++){f=a[h];if(f.rel.toLowerCase().match(/stylesheet/)&&f.href){var g=f.href.replace(/(&|%5C?)forceReload=\d+/,'');f.href=g+(g.match(/\?/)?'&':'?')+'forceReload='+(new Date().valueOf())}}})()"
sendinput ^l
sendinput {Right}
sendinput ^v
sendinput {enter}
return
</code>```

It doesn't help that I don't know how to execute the bookmarklet without actually clicking it in the bookmark bar. The above codes selects the URL and pastes the javascript at the end of it - but this doesn't work.

Can anyone help me out?

EDIT: here is another attempt but this just searches google for the actual string instead of running it.

```<code>^q::
Clipboard:="javascript:(function(){var h,a,f;a=document.getElementsByTagName('link');for(h=0;h<a.length;h++){f=a[h];if(f.rel.toLowerCase().match(/stylesheet/)&&f.href){var g=f.href.replace(/(&|%5C?)forceReload=\d+/,'');f.href=g+(g.match(/\?/)?'&':'?')+'forceReload='+(new Date().valueOf())}}})()"
sendinput ^l
sendinput ^v
sendinput {enter}
return
</code>```

答:
By doing a bit of research, this may well work as a workaround:

Add a custom search engine in Chrome by right clicking the address bar, and clicking add next to "other search engines"

Name it something sensible and give it a keyword (in this case I used "refreshcss")

Paste the bookmarklet in the URL field and save.

Now modify the AHK script as follows:

```<code>^q::
sendinput ^l
send refreshcss
sendinput {enter}
return
</code>```

This will take you to the URL bar, select your bookmarklet and run it :)

Title: Running A Bookmarklet With Autohotkey

Body:
I have this neat little bookmarklet that refreshes the stylesheet on whatever webpage you are looking at without reloading the page:

javascript:(function(){var h,a,f;a=document.getElementsByTagName('link');for(h=0;h<a.length;h++){f=a[h];if(f.rel.toLowerCase().match(/stylesheet/)&&f.href){var g=f.href.replace(/(&|%5C?)forceReload=\d+/,'');f.href=g+(g.match(/\?/)?'&':'?')+'forceReload='+(new Date().valueOf())}}})()

I'm trying to write an AHK script to run the bookmarklet when I hit CTRL + Q. This is what I've got so far:

^q::
Clipboard:="?javascript:(function(){var h,a,f;a=document.getElementsByTagName('link');for(h=0;h<a.length;h++){f=a[h];if(f.rel.toLowerCase().match(/stylesheet/)&&f.href){var g=f.href.replace(/(&|%5C?)forceReload=\d+/,'');f.href=g+(g.match(/\?/)?'&':'?')+'forceReload='+(new Date().valueOf())}}})()"
sendinput ^l
sendinput {Right}
sendinput ^v
sendinput {enter}
return

It doesn't help that I don't know how to execute the bookmarklet without actually clicking it in the bookmark bar. The above codes selects the URL and pastes the javascript at the end of it - but this doesn't work.

Can anyone help me out?

EDIT: here is another attempt but this just searches google for the actual string instead of running it.

^q::
Clipboard:="javascript:(function(){var h,a,f;a=document.getElementsByTagName('link');for(h=0;h<a.length;h++){f=a[h];if(f.rel.toLowerCase().match(/stylesheet/)&&f.href){var g=f.href.replace(/(&|%5C?)forceReload=\d+/,'');f.href=g+(g.match(/\?/)?'&':'?')+'forceReload='+(new Date().valueOf())}}})()"
sendinput ^l
sendinput ^v
sendinput {enter}
return

Body:
By doing a bit of research, this may well work as a workaround:

Add a custom search engine in Chrome by right clicking the address bar, and clicking add next to "other search engines"

Name it something sensible and give it a keyword (in this case I used "refreshcss")

Paste the bookmarklet in the URL field and save.

Now modify the AHK script as follows:

^q::
sendinput ^l
send refreshcss
sendinput {enter}
return

This will take you to the URL bar, select your bookmarklet and run it :)


来源: stackexchange

问:
what is the use of this sign %<-% in r
I am learning keras with r, and I am looking at this page for using Keras in classification,

https://keras.rstudio.com/articles/tutorial_basic_classification.html

but I do not quite understand what %<-% means

I have search %<-% in stackoverflow, but I did not find any answer.

fashion_mnist <- dataset_fashion_mnist()

c(train_images, train_labels) %<-% fashion_mnist$train
c(test_images, test_labels) %<-% fashion_mnist$test
```

答:
From the help page:

```<code>?keras::`%<-%`
</code>```

%<-% and %->% assign into the environment in which they are evaluated.

[..]

At its simplest, the name structure may be a single variable name, in
  which case %<-% and %->% perform regular assignment, x %<-% list(1, 2,
  3) or list(1, 2, 3) %->% x.

So, in this case, it's just like x <- list(1,2,3). The neat trick is when you want to do multiple assignments:

[..]

To specify multiple variable names use a call to c(), for example c(x,
  y, z) %<-% c(1, 2, 3).

So you can assign in one line to multiple objects multiple outputs:

```<code># basic usage
c(a, b) %<-% list(0, 1)

a  # 0
b  # 1
</code>```

This will be equal to:

```<code>a<-0
b<-1
</code>```

In your example fashion_mnist$train it's an object (I guess a list) that has two elements "train images" and "train labels", and so this one-liner lets you assign properly these two in the environment.

This behavior is similar to Python, which lets you do this "multiple-assignment" by default.

ContentLicense: CC BY-SA 4.0

Title: what is the use of this sign %<-% in r

Body:
From the help page:

?keras::`%<-%`

%<-% and %->% assign into the environment in which they are evaluated.

[..]

At its simplest, the name structure may be a single variable name, in
  which case %<-% and %->% perform regular assignment, x %<-% list(1, 2,
  3) or list(1, 2, 3) %->% x.

So, in this case, it's just like x <- list(1,2,3). The neat trick is when you want to do multiple assignments:

[..]

To specify multiple variable names use a call to c(), for example c(x,
  y, z) %<-% c(1, 2, 3).

So you can assign in one line to multiple objects multiple outputs:

# basic usage
c(a, b) %<-% list(0, 1)

a  # 0
b  # 1

This will be equal to:

a<-0
b<-1

In your example fashion_mnist$train it's an object (I guess a list) that has two elements "train images" and "train labels", and so this one-liner lets you assign properly these two in the environment.

This behavior is similar to Python, which lets you do this "multiple-assignment" by default.


问:
Two timers working on Concurrent Dictionary c#
I have two timers which are working on the application. One is firing when a new message is received and that will be added to a Concurrent Dictionary. The other one is firing to remove any message(i.e. trying to get message) from the dictionary if that message is in the dictionary for 'x' time.

```<code>public class Program
{
   static void Main()
   {
       string val;
       Console.Write("Enter Type: ");
       val = Console.ReadLine();

       int type = Convert.ToInt32(val);
       TimerExample.Start(type);
   }
}

static class TimerExample
{
   static Timer _timer;
   static Timer _timer2;
   static ConcurrentDictionary<int, Message> dict;
   static int _type;

   public static void Start(int type)
   {
       var timer = new Timer(3000);
       timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
       timer.Enabled = true;
       _timer = timer;

       var timer2 = new Timer(3000);
       timer2.Elapsed += new ElapsedEventHandler(_timer2_Elapsed);
       timer2.Enabled = true;
       _timer2 = timer2;
       _type = type;
   }

   static void _timer_Elapsed(object sender, ElapsedEventArgs e)
   {
      _dict.Add(_type,DateTime.Now);
   }

   static void _timer2_Elapsed(object sender, ElapsedEventArgs e)
   {
      //remove here if type is stuck in the dict for more than 30 secs
   }
}
</code>```

There can be multiple types as keys in the dict at one point of time so whenever the 2nd timer elapsed I have to check the time for each type in the dictionary it was there. If one or more than types are in the dict for more than 30 secs remove them from the dict.

My concern is whenever I am reading the dict the first timer can also add new time for already added type can that cause a consurrency problem? And the other question is whenever I got the message from the dict which was there for more than 30 secs for any type and at that time only timer1 also updated the new time for that type can that also cause a concurrency problem or data loss problem?

Any help?

答:
According to the comments you want to

process messages at regular intervals - collect messages for 30 seconds before processing them.

when that interval elapses, you may have received the same message twice, but you only want to process it once.

That's easier if you manage duplicate messages as you process them, not as you receive them.

As messages come in, insert them into a ConcurrentQueue<Message> instead of a dictionary. At this step it doesn't matter if there are duplicates.

Set your 30-second timer. You only need one timer. When the timer elapses, read everything from the queue. It's unclear how you recognize duplicate messages, but this is the place to do it.

For example, if Message overrides Equals so that identical messages are "equal", you could use a Hashset<Message>. It's a collection that ignores added items if they are already in the collection.

```<code>void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
    var messagesFromQueue = DequeueUniqueMessages(messageQueue);
    DoWhateverWithTheMessages(messagesFromQueue);
}

IEnumerable<Message> DequeueUniqueMessages(ConcurrentQueue<Message> messageQueue)
{
    var result = new HashSet<Message>();
    while (messageQueue.TryDequeue(out Message dequeued))
        result.Add(dequeued);
    return result;
}
</code>```

Or if it doesn't or shouldn't override Equals you could define a custom IEqualityComparer<Message> and use this overload:

```<code>var result = new HashSet<Message>(new YourCustomMessageComparer());
</code>```

Pass your ConcurrentQueue to that method, and you get back a set of messages. This way they're processed first-in-first-out, and you won't get tripped up even if you're still adding new messages to the queue while you're reading from the queue.

Body:
I have two timers which are working on the application. One is firing when a new message is received and that will be added to a Concurrent Dictionary. The other one is firing to remove any message(i.e. trying to get message) from the dictionary if that message is in the dictionary for 'x' time.

public class Program
{
   static void Main()
   {
       string val;
       Console.Write("Enter Type: ");
       val = Console.ReadLine();

       int type = Convert.ToInt32(val);
       TimerExample.Start(type);
   }
}

static class TimerExample
{
   static Timer _timer;
   static Timer _timer2;
   static ConcurrentDictionary<int, Message> dict;
   static int _type;

   public static void Start(int type)
   {
       var timer = new Timer(3000);
       timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
       timer.Enabled = true;
       _timer = timer;

       var timer2 = new Timer(3000);
       timer2.Elapsed += new ElapsedEventHandler(_timer2_Elapsed);
       timer2.Enabled = true;
       _timer2 = timer2;
       _type = type;
   }

   static void _timer_Elapsed(object sender, ElapsedEventArgs e)
   {
      _dict.Add(_type,DateTime.Now);
   }

   static void _timer2_Elapsed(object sender, ElapsedEventArgs e)
   {
      //remove here if type is stuck in the dict for more than 30 secs
   }
}

There can be multiple types as keys in the dict at one point of time so whenever the 2nd timer elapsed I have to check the time for each type in the dictionary it was there. If one or more than types are in the dict for more than 30 secs remove them from the dict.

My concern is whenever I am reading the dict the first timer can also add new time for already added type can that cause a consurrency problem? And the other question is whenever I got the message from the dict which was there for more than 30 secs for any type and at that time only timer1 also updated the new time for that type can that also cause a concurrency problem or data loss problem?

Any help?

Body:
According to the comments you want to

process messages at regular intervals - collect messages for 30 seconds before processing them.

when that interval elapses, you may have received the same message twice, but you only want to process it once.

That's easier if you manage duplicate messages as you process them, not as you receive them.

As messages come in, insert them into a ConcurrentQueue<Message> instead of a dictionary. At this step it doesn't matter if there are duplicates.

Set your 30-second timer. You only need one timer. When the timer elapses, read everything from the queue. It's unclear how you recognize duplicate messages, but this is the place to do it.

For example, if Message overrides Equals so that identical messages are "equal", you could use a Hashset<Message>. It's a collection that ignores added items if they are already in the collection.

void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
    var messagesFromQueue = DequeueUniqueMessages(messageQueue);
    DoWhateverWithTheMessages(messagesFromQueue);
}

IEnumerable<Message> DequeueUniqueMessages(ConcurrentQueue<Message> messageQueue)
{
    var result = new HashSet<Message>();
    while (messageQueue.TryDequeue(out Message dequeued))
        result.Add(dequeued);
    return result;
}

Or if it doesn't or shouldn't override Equals you could define a custom IEqualityComparer<Message> and use this overload:

var result = new HashSet<Message>(new YourCustomMessageComparer());

Pass your ConcurrentQueue to that method, and you get back a set of messages. This way they're processed first-in-first-out, and you won't get tripped up even if you're still adding new messages to the queue while you're reading from the queue.


问:
Why does Thread.Sleep(0) fix my problems, and how to avoid it?
I'm working on a client server application.  At certain times, on certain machines, when there's more than 5 clients requesting data, it seems to reach a deadlock.  If I step in to debug the problem, then the program appears to be processing.  Simply setting a break point where I know the program is executing, and causing it to hit the breakpoint a few times causes it to finish. If I insert Thread.Sleep(0) at certain points in the code, mostly around some cpu intensive loops, it seems to pretty much totally resolve the problem.  The one problem that I have now is that if I call Thread.Sleep(0) too much, it can slow down the code.  If I don't call it enough, the code seems to be in deadlock.  Although I can verify that it isn't in deadlock because if I step into the code, it causes the problem to disappear, simply because I'm pausing a thread.

Is there a good way to track down exactly what is causing this.  It seems that it only happens on my laptop which is running Vista, but not on my desktop which is running Windows XP.  However, it's impossible to debug, because simply stepping into the code causes the problem to go away.  I've read comments that calling Thread.Sleep(0) is a bad practice, and shouldn't be necessary, and I don't like putting witchcraft type code into my applications that I don't understand why it has to be there.  Any pointers would be greatly appreciated.

[EDIT]
I can also verify that the code is still running when it is "deadlocked" because if I leave it long enough, it will finish, only the amount of time it takes is many orders of magnitude higher.  I mean like it's actually at least 100 times slower when it's in this "deadlocked" mode.  The CPU is pegged at 80-95%, so it is working, altough what it is doing is beyond me, because it's taking forever to complete the task.

[More Info]
Just because everybody here is insistent that it's a deadlock, I removed all the code that did any locking. There was only a couple lines of code that did any locking whatsoever. The threads work completely independantly for the most part, so it wasn't much work to remove the locking completely.  Still the problem persists.  There is no more synclocks in my code, no more mutex's no more stuff that I see see that would cause a deadlock, but the problem is still there.  And it's not deadlocked.  It runs, albeit very slowly, even though it's eating up all the processor resources.

答:
This is impossible to answer without looking at the entire codebase.

Calling Thread.Sleep is a HORRIBLE practice, and you shouldn't do it.  You are basically shifting around the timing of your code which is leading to the deadlock, as opposed to actually addressing the deadlock condition to begin with.

The reason that debugging doesn't show the problem is that when the debugger stops, all of the threads in your code stop, so that is skewing the timing of the execution of your program as well.

What you want to do here is insert logging code here to trace the path of execution of your code on different threads, and based on that, determine where the deadlock is.

OwnerDisplayName: Kibbee

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Kibbee

OwnerDisplayName: casperOne


问:
Anchor tag completely un-clickable in IE11
Hi guys so I have been researching everywhere and cannot find a solution for this problem. Here is the exact line of code.

```<code>'<a id="auto_refinance_loan_documents_save_link" ' + ((scope.styleAsBtn) ? 'class="btn btn-primary"' : '') + '>' + linkText + '</a>';
</code>```

We are using angularJS so you can pretty much ignore all the other stuff, but it is a simple anchor tag with bootstrap btn class. It works perfectly fine on all browsers, besides IE11 of course. The issue is you can not click the a tag at all. It does absolutely nothing when clicking it.

答:
If an a tag doesn't contain a href attribute, it's considered by the browser to be a placeholder for a future link, and remains unclickable. If you want to use this as a clickable link without following any URL, you can use a hash as the href:

```

It is mentioned in the W3 standard:

The href attribute on a and area elements is not required; when those elements do not have href attributes they do not create hyperlinks.

Body:
Hi guys so I have been researching everywhere and cannot find a solution for this problem. Here is the exact line of code.

'' + linkText + '';

We are using angularJS so you can pretty much ignore all the other stuff, but it is a simple anchor tag with bootstrap btn class. It works perfectly fine on all browsers, besides IE11 of course. The issue is you can not click the a tag at all. It does absolutely nothing when clicking it.

Body:
If an a tag doesn't contain a href attribute, it's considered by the browser to be a placeholder for a future link, and remains unclickable. If you want to use this as a clickable link without following any URL, you can use a hash as the href:

<a href="#"></a>

It is mentioned in the W3 standard:

The href attribute on a and area elements is not required; when those elements do not have href attributes they do not create hyperlinks.


问:
Error while using sbt-native-packager to get the docker support for my sbt project
I have added sbt-native-packager, version 1.3.15 in my plugins.sbt file.
in build.sbt file I am using enablePlugins(DockerPligin).
I am facing the below error when I am running the following command on sbt shell:

```<code>sbt>docker:publishLocal
</code>```

ERROR -->

```<code>    [error] java.io.IOException: Cannot run program "docker" (in directory "C:\Users\A674634\Desktop\Scala\playProjects\akka-cluster-playground\target\docker\stage"): CreateProcess error=2, The system cannot find the file specified
    [error]         at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    [error]         at scala.sys.process.ProcessBuilderImpl$Simple.run(ProcessBuilderImpl.scala:71)
    [error]         at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.run(ProcessBuilderImpl.scala:102)
    [error]         at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.$anonfun$runBuffered$1(ProcessBuilderImpl.scala:150)
    [error]         at scala.runtime.java8.JFunction0$mcI$sp.apply(JFunction0$mcI$sp.java:12)
    [error]         at com.typesafe.sbt.packager.docker.DockerPlugin$$anon$1.buffer(DockerPlugin.scala:348)
    [error]         at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.runBuffered(ProcessBuilderImpl.scala:150)
    [error]         at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.$bang(ProcessBuilderImpl.scala:116)
    [error]         at com.typesafe.sbt.packager.docker.DockerPlugin$.publishLocalDocker(DockerPlugin.scala:355)
    [error]         at com.typesafe.sbt.packager.docker.DockerPlugin$.$anonfun$projectSettings$30(DockerPlugin.scala:127)
    [error]         at com.typesafe.sbt.packager.docker.DockerPlugin$.$anonfun$projectSettings$30$adapted(DockerPlugin.scala:125)
    [error]         at scala.Function1.$anonfun$compose$1(Function1.scala:44)
    [error]         at sbt.internal.util.$tilde$greater.$anonfun$$u2219$1(TypeFunctions.scala:40)
    [error]         at sbt.std.Transform$$anon$4.work(System.scala:67)
    [error]         at sbt.Execute.$anonfun$submit$2(Execute.scala:269)
    [error]         at sbt.internal.util.ErrorHandling$.wideConvert(ErrorHandling.scala:16)
    [error]         at sbt.Execute.work(Execute.scala:278)
    [error]         at sbt.Execute.$anonfun$submit$1(Execute.scala:269)
    [error]         at sbt.ConcurrentRestrictions$$anon$4.$anonfun$submitValid$1(ConcurrentRestrictions.scala:178)
    [error]         at sbt.CompletionService$$anon$2.call(CompletionService.scala:37)
    [error]         at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    [error]         at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    [error]         at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    [error]         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    [error]         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    [error]         at java.lang.Thread.run(Thread.java:748)
    [error] Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    [error]         at java.lang.ProcessImpl.create(Native Method)
    [error]         at java.lang.ProcessImpl.<init>(ProcessImpl.java:386)
    [error]         at java.lang.ProcessImpl.start(ProcessImpl.java:137)
    [error]         at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
    [error]         at scala.sys.process.ProcessBuilderImpl$Simple.run(ProcessBuilderImpl.scala:71)
    [error]         at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.run(ProcessBuilderImpl.scala:102)
    [error]         at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.$anonfun$runBuffered$1(ProcessBuilderImpl.scala:150)
    [error]         at scala.runtime.java8.JFunction0$mcI$sp.apply(JFunction0$mcI$sp.java:12)
    [error]         at com.typesafe.sbt.packager.docker.DockerPlugin$$anon$1.buffer(DockerPlugin.scala:348)
    [error]         at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.runBuffered(ProcessBuilderImpl.scala:150)
    [error]         at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.$bang(ProcessBuilderImpl.scala:116)
    [error]         at com.typesafe.sbt.packager.docker.DockerPlugin$.publishLocalDocker(DockerPlugin.scala:355)
    [error]         at com.typesafe.sbt.packager.docker.DockerPlugin$.$anonfun$projectSettings$30(DockerPlugin.scala:127)
    [error]         at com.typesafe.sbt.packager.docker.DockerPlugin$.$anonfun$projectSettings$30$adapted(DockerPlugin.scala:125)
    [error]         at scala.Function1.$anonfun$compose$1(Function1.scala:44)
    [error]         at sbt.internal.util.$tilde$greater.$anonfun$$u2219$1(TypeFunctions.scala:40)
    [error]         at sbt.std.Transform$$anon$4.work(System.scala:67)
    [error]         at sbt.Execute.$anonfun$submit$2(Execute.scala:269)
    [error]         at sbt.internal.util.ErrorHandling$.wideConvert(ErrorHandling.scala:16)
    [error]         at sbt.Execute.work(Execute.scala:278)
    [error]         at sbt.Execute.$anonfun$submit$1(Execute.scala:269)
    [error]         at sbt.ConcurrentRestrictions$$anon$4.$anonfun$submitValid$1(ConcurrentRestrictions.scala:178)
    [error]         at sbt.CompletionService$$anon$2.call(CompletionService.scala:37)
    [error]         at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    [error]         at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    [error]         at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    [error]         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    [error]         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    [error]         at java.lang.Thread.run(Thread.java:748)
    [IJ]sbt:akka-cluster-playground> [error] (Docker / publishLocal) java.io.IOException: Cannot run program "docker" (in directory "C:\Users\A674634\Desktop\Scala\playProjects\akka-cluster-playground\target\docker\stage"): CreateProcess error=2, The system cannot find the file specified
</code>```

答: I believe you should execute that command in the project root folder. Which folder are you in now?</p>

Body:
I have added sbt-native-packager, version 1.3.15 in my plugins.sbt file.
in build.sbt file I am using enablePlugins(DockerPligin).
I am facing the below error when I am running the following command on sbt shell:

sbt>docker:publishLocal

ERROR -->

    [error] java.io.IOException: Cannot run program "docker" (in directory "C:\Users\A674634\Desktop\Scala\playProjects\akka-cluster-playground\target\docker\stage"): CreateProcess error=2, The system cannot find the file specified
    [error]         at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
    [error]         at scala.sys.process.ProcessBuilderImpl$Simple.run(ProcessBuilderImpl.scala:71)
    [error]         at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.run(ProcessBuilderImpl.scala:102)
    [error]         at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.$anonfun$runBuffered$1(ProcessBuilderImpl.scala:150)
    [error]         at scala.runtime.java8.JFunction0$mcI$sp.apply(JFunction0$mcI$sp.java:12)
    [error]         at com.typesafe.sbt.packager.docker.DockerPlugin$$anon$1.buffer(DockerPlugin.scala:348)
    [error]         at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.runBuffered(ProcessBuilderImpl.scala:150)
    [error]         at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.$bang(ProcessBuilderImpl.scala:116)
    [error]         at com.typesafe.sbt.packager.docker.DockerPlugin$.publishLocalDocker(DockerPlugin.scala:355)
    [error]         at com.typesafe.sbt.packager.docker.DockerPlugin$.$anonfun$projectSettings$30(DockerPlugin.scala:127)
    [error]         at com.typesafe.sbt.packager.docker.DockerPlugin$.$anonfun$projectSettings$30$adapted(DockerPlugin.scala:125)
    [error]         at scala.Function1.$anonfun$compose$1(Function1.scala:44)
    [error]         at sbt.internal.util.$tilde$greater.$anonfun$$u2219$1(TypeFunctions.scala:40)
    [error]         at sbt.std.Transform$$anon$4.work(System.scala:67)
    [error]         at sbt.Execute.$anonfun$submit$2(Execute.scala:269)
    [error]         at sbt.internal.util.ErrorHandling$.wideConvert(ErrorHandling.scala:16)
    [error]         at sbt.Execute.work(Execute.scala:278)
    [error]         at sbt.Execute.$anonfun$submit$1(Execute.scala:269)
    [error]         at sbt.ConcurrentRestrictions$$anon$4.$anonfun$submitValid$1(ConcurrentRestrictions.scala:178)
    [error]         at sbt.CompletionService$$anon$2.call(CompletionService.scala:37)
    [error]         at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    [error]         at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    [error]         at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    [error]         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    [error]         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    [error]         at java.lang.Thread.run(Thread.java:748)
    [error] Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    [error]         at java.lang.ProcessImpl.create(Native Method)
    [error]         at java.lang.ProcessImpl.<init>(ProcessImpl.java:386)
    [error]         at java.lang.ProcessImpl.start(ProcessImpl.java:137)
    [error]         at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
    [error]         at scala.sys.process.ProcessBuilderImpl$Simple.run(ProcessBuilderImpl.scala:71)
    [error]         at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.run(ProcessBuilderImpl.scala:102)
    [error]         at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.$anonfun$runBuffered$1(ProcessBuilderImpl.scala:150)
    [error]         at scala.runtime.java8.JFunction0$mcI$sp.apply(JFunction0$mcI$sp.java:12)
    [error]         at com.typesafe.sbt.packager.docker.DockerPlugin$$anon$1.buffer(DockerPlugin.scala:348)
    [error]         at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.runBuffered(ProcessBuilderImpl.scala:150)
    [error]         at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.$bang(ProcessBuilderImpl.scala:116)
    [error]         at com.typesafe.sbt.packager.docker.DockerPlugin$.publishLocalDocker(DockerPlugin.scala:355)
    [error]         at com.typesafe.sbt.packager.docker.DockerPlugin$.$anonfun$projectSettings$30(DockerPlugin.scala:127)
    [error]         at com.typesafe.sbt.packager.docker.DockerPlugin$.$anonfun$projectSettings$30$adapted(DockerPlugin.scala:125)
    [error]         at scala.Function1.$anonfun$compose$1(Function1.scala:44)
    [error]         at sbt.internal.util.$tilde$greater.$anonfun$$u2219$1(TypeFunctions.scala:40)
    [error]         at sbt.std.Transform$$anon$4.work(System.scala:67)
    [error]         at sbt.Execute.$anonfun$submit$2(Execute.scala:269)
    [error]         at sbt.internal.util.ErrorHandling$.wideConvert(ErrorHandling.scala:16)
    [error]         at sbt.Execute.work(Execute.scala:278)
    [error]         at sbt.Execute.$anonfun$submit$1(Execute.scala:269)
    [error]         at sbt.ConcurrentRestrictions$$anon$4.$anonfun$submitValid$1(ConcurrentRestrictions.scala:178)
    [error]         at sbt.CompletionService$$anon$2.call(CompletionService.scala:37)
    [error]         at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    [error]         at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    [error]         at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    [error]         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    [error]         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    [error]         at java.lang.Thread.run(Thread.java:748)
    [IJ]sbt:akka-cluster-playground> [error] (Docker / publishLocal) java.io.IOException: Cannot run program "docker" (in directory "C:\Users\A674634\Desktop\Scala\playProjects\akka-cluster-playground\target\docker\stage"): CreateProcess error=2, The system cannot find the file specified


问:
How to temporary take out actions from actor and assign it back
I am designing my own clickListener class. When i touch down on any actor registered with my clicklistener, i would like to pause all the actions on the actor, and only call it back when touch up is trigger. I tried with the following codes but it give me a total hang everytime i triggered touchUp.

```<code>public class MyClickListener extends ClickListener {

    public Actor actor;
    Array<Action> cachedActions;

    @Override
    public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
        super.touchUp(event, x, y, pointer, button);
        actor = event.getListenerActor();
        actor.addAction(btnScaleBackActions());
        for(Action a: cachedActions)
        {
            a.reset();
            a.setTarget(actor);
            a.setActor(actor);
            actor.addAction(a); //this line give me a total hang
        }
    }

    @Override
    public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
        if(pointer==0) // avoid further trigger on other buttons while holding the selected actor
        {
            actor = event.getListenerActor();
            actor.setScale(0.9f);
            cachedActions = actor.getActions();
            actor.clearActions();
            if(autoSetSound)AudioManager.playSound(AudioManager.CLICK_IN);
            return super.touchDown(event, x, y, pointer, button);
        }
        else
        {
            return false;
        }
    }

    public static Action btnScaleBackActions(){
        float time = 0.1f;
        return sequence(
                scaleTo(1,1,time ),
                scaleTo(0.95f,0.95f,time/4),
                scaleTo(1,1,time/4)
        );
    }
}
</code>```

It shows no error but only white screen. Any help?

答:
The problem is this line:

```<code>cachedActions = actor.getActions();
</code>```

You are getting a reference to the Actor's own list of actions instead of making a copy. Incidentally, on the next line (actor.clearActions();) you are clearing the list so cachedActions is empty.

Later on touch up, the actor (and cachedActions) now have the action you added (btnScaleBackActions()). You are cycling through an array, adding the same object to it forever. The iterator can never finish because you are always adding more, so it is an infinite loop.

You need to create your own list for cached actions and copy the items over.

```<code>private final Array<Action> cachedActions = new Array<Action>();
</code>```

Then copy the actions, not the reference in touch down:

```<code>cachedActions.addAll(actor.getActions());
actor.clearActions();
</code>```

And make sure to clear cachedActions at the end of touchUp.

Body:
I am designing my own clickListener class. When i touch down on any actor registered with my clicklistener, i would like to pause all the actions on the actor, and only call it back when touch up is trigger. I tried with the following codes but it give me a total hang everytime i triggered touchUp.

public class MyClickListener extends ClickListener {

    public Actor actor;
    Array<Action> cachedActions;

    @Override
    public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
        super.touchUp(event, x, y, pointer, button);
        actor = event.getListenerActor();
        actor.addAction(btnScaleBackActions());
        for(Action a: cachedActions)
        {
            a.reset();
            a.setTarget(actor);
            a.setActor(actor);
            actor.addAction(a); //this line give me a total hang
        }
    }

    @Override
    public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
        if(pointer==0) // avoid further trigger on other buttons while holding the selected actor
        {
            actor = event.getListenerActor();
            actor.setScale(0.9f);
            cachedActions = actor.getActions();
            actor.clearActions();
            if(autoSetSound)AudioManager.playSound(AudioManager.CLICK_IN);
            return super.touchDown(event, x, y, pointer, button);
        }
        else
        {
            return false;
        }
    }

    public static Action btnScaleBackActions(){
        float time = 0.1f;
        return sequence(
                scaleTo(1,1,time ),
                scaleTo(0.95f,0.95f,time/4),
                scaleTo(1,1,time/4)
        );
    }
}

It shows no error but only white screen. Any help?

Body:
The problem is this line:

cachedActions = actor.getActions();

You are getting a reference to the Actor's own list of actions instead of making a copy. Incidentally, on the next line (actor.clearActions();) you are clearing the list so cachedActions is empty.

Later on touch up, the actor (and cachedActions) now have the action you added (btnScaleBackActions()). You are cycling through an array, adding the same object to it forever. The iterator can never finish because you are always adding more, so it is an infinite loop.

You need to create your own list for cached actions and copy the items over.

private final Array<Action> cachedActions = new Array<Action>();

Then copy the actions, not the reference in touch down:

cachedActions.addAll(actor.getActions());
actor.clearActions();

And make sure to clear cachedActions at the end of touchUp.


问:
Append Array Through If Statement
So, I am making an app that requires to select various things. You can select these by swiping to the right of the UITableView. I am using a UIContextualAction and I am using a switch statement to order out the functions and executable statements. Once the UITableView Cell is selected, it is to run off of one of my switch statements. This is from the indexPath.row chosen. Now once each object is selected, it will append the name into an array.

My problem: Once the object is appended, the array does not add on. For instance, I pick Snapchat. The array has "Snapchat" in it. If I were to also chose Instagram, the array should append "Instagram". It does, but it forgets about the "Snapchat" in it too, and when it prints, it only prints 1 selected object. (Which was the last one I picked)

How could I make an array where I can add more objects without it forgetting

I have looked at doing if statements on the tableview cell that was selected. Nothing works, and was wondering how I could fix this, or find a solution

```<code>var array = [String]()
var choice = indexPath.row
switch choice {
case 0:
    array.append("Instagram")
    print(array)
case 1:
    array.append("Snapchat")
    print(array)
case 2:
    array.append("VSCO")
    print(array)
default:
    print("Error")
    print(array)
</code>```

This is what I get when I select multiple and try to append the array.

```<code>["Instagram"]
["Snapchat"]
["VSCO"]
Error
</code>```

as you can see, they are not in the array form.

答:
This is what you have done

```<code>func someFunc() {
    var array = [String]()
    var choice = indexPath.row
    switch choice {
    case 0:
         array.append("Instagram")
         print(array)
    case 1:
         array.append("Snapchat")
         print(array)
    case 2:
         array.append("VSCO")
         print(array)
    default:
         print("Error")
         print(array)
}
</code>```

You have declared the array you want to append to inside the function that is adding the objects to the array.
What happens is everytime you add something, it overwrites the object you just entered.

Function creates array

Adds object to array

Function ends

Function creates array (overwrites old array)

Adds object to array (single object only inside array now)

Function ends

Simply move your array var array = [String]() outside of the function.

```<code> var array = [String]()

 override func viewDidLoad() {
      super.viewDidLoad()
 }

    func someFunc() {

        var choice = indexPath.row
        switch choice {
        case 0:
             self.array.append("Instagram")
             print(array)
        case 1:
             self.array.append("Snapchat")
             print(array)
        case 2:
             self.array.append("VSCO")
             print(array)
        default:
             print("Error")
             print(array)
    }
</code>```

Also, be careful when naming your array 'array', it is best practice to give the array a more meaningful name

Title: Append Array Through If Statement

Body:
So, I am making an app that requires to select various things. You can select these by swiping to the right of the UITableView. I am using a UIContextualAction and I am using a switch statement to order out the functions and executable statements. Once the UITableView Cell is selected, it is to run off of one of my switch statements. This is from the indexPath.row chosen. Now once each object is selected, it will append the name into an array.

My problem: Once the object is appended, the array does not add on. For instance, I pick Snapchat. The array has "Snapchat" in it. If I were to also chose Instagram, the array should append "Instagram". It does, but it forgets about the "Snapchat" in it too, and when it prints, it only prints 1 selected object. (Which was the last one I picked)

How could I make an array where I can add more objects without it forgetting

I have looked at doing if statements on the tableview cell that was selected. Nothing works, and was wondering how I could fix this, or find a solution

var array = [String]()
var choice = indexPath.row
switch choice {
case 0:
    array.append("Instagram")
    print(array)
case 1:
    array.append("Snapchat")
    print(array)
case 2:
    array.append("VSCO")
    print(array)
default:
    print("Error")
    print(array)

This is what I get when I select multiple and try to append the array.

["Instagram"]
["Snapchat"]
["VSCO"]
Error

as you can see, they are not in the array form.

Body:
This is what you have done

func someFunc() {
    var array = [String]()
    var choice = indexPath.row
    switch choice {
    case 0:
         array.append("Instagram")
         print(array)
    case 1:
         array.append("Snapchat")
         print(array)
    case 2:
         array.append("VSCO")
         print(array)
    default:
         print("Error")
         print(array)
}

You have declared the array you want to append to inside the function that is adding the objects to the array.
What happens is everytime you add something, it overwrites the object you just entered.

Function creates array

Adds object to array

Function ends

Function creates array (overwrites old array)

Adds object to array (single object only inside array now)

Function ends

Simply move your array var array = [String]() outside of the function.

 var array = [String]()

 override func viewDidLoad() {
      super.viewDidLoad()
 }

    func someFunc() {

        var choice = indexPath.row
        switch choice {
        case 0:
             self.array.append("Instagram")
             print(array)
        case 1:
             self.array.append("Snapchat")
             print(array)
        case 2:
             self.array.append("VSCO")
             print(array)
        default:
             print("Error")
             print(array)
    }

Also, be careful when naming your array 'array', it is best practice to give the array a more meaningful name


问:
Troubles with ajax. How to convert javascript variable to php variable?
I want to convert javascript variable to php variable to use it in sql query,but it doesn't work.

html code :

```<code><select id = "dep_ID" name = "dep_ID" onchange="myFunction()">
</code>```

javascript code in the same file:

```<code><script>
    function myFunction(){

        var xo = document.getElementById("dep_ID").value;
        document.getElementById("demo").innerHTML = "You selected: " + xo;

        $.ajax({
            url: 'insert.php',
            data: {duration: xo},
            type: 'POST',
            success: function(data) {
            alert(data);
            document.getElementById("demo").innerHTML = "You selected: " + <?php echo @$duration;?>;
            }
        });
    }
</script>
</code>```

insert.php code:

```<code><?php
$duration = $_POST['xo'];
return $duration ;
?>
</code>```

I expect the output of dep_ID variable, but i get nothing.

答:
Javascript and PHP systax are different. In the response of ajax call you will get javascript object. So you need to do changes as follows:</p>

```<code>document.getElementById("demo").innerHTML = "You selected: " + data.duration;
</code>```

Body:
I want to convert javascript variable to php variable to use it in sql query,but it doesn't work.

html code :

<select id = "dep_ID" name = "dep_ID" onchange="myFunction()">

javascript code in the same file:

insert.php code:

<?php
$duration = $_POST['xo'];
return $duration ;
?>

I expect the output of dep_ID variable, but i get nothing.

Body:
Javascript and PHP systax are different. In the response of ajax call you will get javascript object. So you need to do changes as follows:

document.getElementById("demo").innerHTML = "You selected: " + data.duration;


问:
error from service not being caught in component.ts
Once a user logs in, I retrieve their userAccount. In the case that it is not returned, I throw an error in the service. I then proceed to catch the error in a component.ts controller.

For some reason the component.ts does not catch the error being thrown. In console, I can see the errors, but for some reason my component.ts does not catch it in the try/catch block.

I've tested it multiple times to see where it failed and it seems that the error message doesn't reach the catch statement.

This is in my service:

```<code>/* On error: */
error => {

    if (error.status === 401) {

        Helpers.logGroupedErrorObjectsToDevConsole(
            'Login Service: getCustomerAccount()',
            [
                {
                    title: 'Session Timed Out:',
                    info:  true
                }
            ]
        );
    } else {
        Helpers.logGroupedErrorObjectsToDevConsole(
            'Login Service: getCustomerAccount()',
            [
                {
                    title: 'Cannot get customer account:',
                    info: true
                }
            ]
        );
    }

    throw new Error(error);
}
</code>```

this is in my component.ts

```<code>try {
        setTimeout(() => {
           this._service.customer(this.url, this.route)
        }, 1000);
     } catch (e) {
         this.showUnknownLoginFailureMessage  = true;
     }
</code>```

What I expect is for the error to be handled in component.ts

Is it possible?
Am I doing the error handling properly or am I missing something?

I need some guidance.

Thanks in advance!

答:
You can handle the exception by moving the try... catch statement inside of the setTimeout callback:

```<code>setTimeout(() => {
  try {
    this._service.customer(this.url, this.route);
  } catch (e) {
    this.showUnknownLoginFailureMessage  = true;
  }
}, 1000);
</code>```

See this stackblitz for a demo.

Body:
Once a user logs in, I retrieve their userAccount. In the case that it is not returned, I throw an error in the service. I then proceed to catch the error in a component.ts controller.

For some reason the component.ts does not catch the error being thrown. In console, I can see the errors, but for some reason my component.ts does not catch it in the try/catch block.

I've tested it multiple times to see where it failed and it seems that the error message doesn't reach the catch statement.

This is in my service:

/* On error: */
error => {

    if (error.status === 401) {

        Helpers.logGroupedErrorObjectsToDevConsole(
            'Login Service: getCustomerAccount()',
            [
                {
                    title: 'Session Timed Out:',
                    info:  true
                }
            ]
        );
    } else {
        Helpers.logGroupedErrorObjectsToDevConsole(
            'Login Service: getCustomerAccount()',
            [
                {
                    title: 'Cannot get customer account:',
                    info: true
                }
            ]
        );
    }

    throw new Error(error);
}

this is in my component.ts

try {
        setTimeout(() => {
           this._service.customer(this.url, this.route)
        }, 1000);
     } catch (e) {
         this.showUnknownLoginFailureMessage  = true;
     }

What I expect is for the error to be handled in component.ts

Is it possible?
Am I doing the error handling properly or am I missing something?

I need some guidance.

Thanks in advance!

Body:
You can handle the exception by moving the try... catch statement inside of the setTimeout callback:

setTimeout(() => {
  try {
    this._service.customer(this.url, this.route);
  } catch (e) {
    this.showUnknownLoginFailureMessage  = true;
  }
}, 1000);

See this stackblitz for a demo.


问:
Why won't .save() use the data I tell it too
Ok so this may be kind of odd, but hear me out.
  first thing, this question is related to my issue.

In a nutshell.  I am trying to make Mongo entries, everything is communicating, but my model.save() only save id and version.

The difference in what I am trying to do is that I don't want what to send any data.

I want to send a GET request, and I want the server to generate the initial data entry.  That entry just being a timestamp and a boolean.
So my code looks like this

```<code>  const CLOCK_IN = (req ,res ) => {

      const TimeCard = new TimeCardModel({
        startTime: new Date.now(),
        clockedIn: true
     })
     TimeCard.save()
       .then(res => {
         res.json(TimeCard.toJSON())
       })
        .catch(err => {
         res.json(err)
      })
    }
</code>```

So what they say in the first question.  Is that the object is empty because the function can't read the data. So do I need to write up some code that will make the data I want before I call the entry saving function? Or is there something else that I'm missing?

答:
My schema was wrong.

The answer is in the docs

my model was defined

```<code>var animalSchema = new Schema({name: { Type: Date },
</code>```

proper syntax is

```<code>var animalSchema = new Schema({ name: String, type: String });
</code>```

Body:
Ok so this may be kind of odd, but hear me out.
  first thing, this question is related to my issue.

In a nutshell.  I am trying to make Mongo entries, everything is communicating, but my model.save() only save id and version.

The difference in what I am trying to do is that I don't want what to send any data.

I want to send a GET request, and I want the server to generate the initial data entry.  That entry just being a timestamp and a boolean.
So my code looks like this

  const CLOCK_IN = (req ,res ) => {

      const TimeCard = new TimeCardModel({
        startTime: new Date.now(),
        clockedIn: true
     })
     TimeCard.save()
       .then(res => {
         res.json(TimeCard.toJSON())
       })
        .catch(err => {
         res.json(err)
      })
    }

So what they say in the first question.  Is that the object is empty because the function can't read the data. So do I need to write up some code that will make the data I want before I call the entry saving function? Or is there something else that I'm missing?

Body:
My schema was wrong.

The answer is in the docs

my model was defined

var animalSchema = new Schema({name: { Type: Date },

proper syntax is

var animalSchema = new Schema({ name: String, type: String });


问:
I want to convert my existing complex Angular project to Mobile App using Ionic Framework. Can anyone suggest me the procedure?
By Using Angular 7 we build a webapp with all mobile responsive features, now we want to convert that Angular 7 project to Mobile App for Android & iOS using Ionic Framework. please help me with this and i am new to this field</p>

答:
This is a very broad question and this site isn't here to create something for you. We have a ton of resources, and I'm sure the community would be glad to help solve issues you're having. If you're wanting help for converting to Ionic, the Ionic support team has features for that. Check here for community.

Also, I do know The Ionic team has personal support for development teams, but that is not free. They can assist with migrations and support for plugins exclusively for your app. There is an option for that in the link as well.


问:
Writing to a read-only file using XmlWriter in .NET
I would like to write to a read-only file using XmlWriter. What is the proper way to do this?

Currently I have:

```<code>XmlWriterSettings lSettings = new XmlWriterSettings();
lSettings.Encoding = new UTF8Encoding(false);
lSettings.Indent = true;

XmlWriter lWriter = XmlWriter.Create(lPath, lSettings);
lXml.WriteContentTo(lWriter);
lWriter.Close();
</code>```

I'm wondering if there's a way to avoid clearing and re-setting the read-only flag.

答:
As I understand it  you must remove the read-only flag to write to a file given the fact that this flag is controlled directly by the operating system.

If what you want is avoid the possibility that someone else can write to the file in the time the write flag is enabled you can do a temporary copy of the file (with write permissions), write your XML to that file and finally replace the original file with yours and set the flag to read-only.

ContentLicense: CC BY-SA 3.0

Body:
I would like to write to a read-only file using XmlWriter. What is the proper way to do this?

Currently I have:

XmlWriterSettings lSettings = new XmlWriterSettings();
lSettings.Encoding = new UTF8Encoding(false);
lSettings.Indent = true;

XmlWriter lWriter = XmlWriter.Create(lPath, lSettings);
lXml.WriteContentTo(lWriter);
lWriter.Close();

I'm wondering if there's a way to avoid clearing and re-setting the read-only flag.


问:
how to disable/enable dropdown angular 4
How can I enable/disable a dropdown based on the selection of another dropdown menu?

I tried this but it doesn't seem to work:

```<code><select class="custom-select" id="abc">
    <option value="" hidden>Select</option>
    <option *ngFor="let data of datay"
            [ngValue]="data.code"
            [attr.disabled]="true">
        {{data.name}}
    </option>
</select>
</code>```

Any sample code is appreciated.

答:
We can do this by using 2-way data binding. First, we bind the first <select> element to data1. This will contain the value data.code of the selected option from the first  element.

Let's assume that we will disable the second <select> element if the user selects the option with the data.code value of '1'.

Then, on our second <select> element, we bind the disabled attribute to the condition, such that the disabled arribute will be true when data1 === '1'.

```<code><select class="custom-select" [(ngModel)]="data1" id="dropdown1">
  <option value="" hidden>Select</option>
  <option *ngFor="let data of datay" [ngValue]="data.code">
    {{data.name}}
  </option>
</select>

<select class="custom-select" [(ngModel)]="data2" [disabled]="data1==='1'">
  <option value="" hidden>Select</option>
  <option *ngFor="let data of datay2" [ngValue]="data.code">
    {{data.name}}
  </option>
</select>
</code>```

Body:
How can I enable/disable a dropdown based on the selection of another dropdown menu?

I tried this but it doesn't seem to work:

<select class="custom-select" id="abc">
    <option value="" hidden>Select</option>
    <option *ngFor="let data of datay"
            [ngValue]="data.code"
            [attr.disabled]="true">
        {{data.name}}
    </option>
</select>

Any sample code is appreciated.

Body:
We can do this by using 2-way data binding. First, we bind the first <select> element to data1. This will contain the value data.code of the selected option from the first  element.

Let's assume that we will disable the second <select> element if the user selects the option with the data.code value of '1'.

Then, on our second <select> element, we bind the disabled attribute to the condition, such that the disabled arribute will be true when data1 === '1'.

<select class="custom-select" [(ngModel)]="data1" id="dropdown1">
  <option value="" hidden>Select</option>
  <option *ngFor="let data of datay" [ngValue]="data.code">
    {{data.name}}
  </option>
</select>

<select class="custom-select" [(ngModel)]="data2" [disabled]="data1==='1'">
  <option value="" hidden>Select</option>
  <option *ngFor="let data of datay2" [ngValue]="data.code">
    {{data.name}}
  </option>
</select>


问:
clang: error: clang frontend command failed with exit code 70 (use -v to see invocation)
I don't know what causes it.

It does not happen at iPhone 5 and simulators. It have been happened only my original device iPhone 7.

```<code>fatal error: error in backend: Error while trying to spill X0 from class GPR64: Cannot scavenge register without an emergency spill slot!
clang: error: clang frontend command failed with exit code 70 (use -v to see invocation)
Apple LLVM version 9.0.0 (clang-900.0.34.1)
Target: aarch64-apple-darwin16.7.0
Thread model: posix
InstalledDir: /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
clang: note: diagnostic msg: PLEASE submit a bug report to http://developer.apple.com/bugreporter/ and include the crash backtrace, preprocessed source, and associated run script.
clang: note: diagnostic msg:
********************

PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:
Preprocessed source(s) and associated run script(s) are located at:
clang: note: diagnostic msg: /var/folders/xg/tgwkzqt15xd9jprnv9f0gn4c0000gn/T/CityArray-6e6c1e.m
clang: note: diagnostic msg: /var/folders/xg/tgwkzqt15xd9jprnv9f0gn4c0000gn/T/CityArray-6e6c1e.cache
clang: note: diagnostic msg: /var/folders/xg/tgwkzqt15xd9jprnv9f0gn4c0000gn/T/CityArray-6e6c1e.sh
clang: note: diagnostic msg: Crash backtrace is located in
clang: note: diagnostic msg: /Users/junhyun/Library/Logs/DiagnosticReports/clang_<YYYY-MM-DD-HHMMSS>_<hostname>.crash
clang: note: diagnostic msg: (choose the .crash file that corresponds to your crash)
clang: note: diagnostic msg:

********************
</code>```

答:
I used the following steps to get rid of the error:

Clean cache from Xcode Product->Clean Build Folder

npm install

run react-native run-ios

Build the app using Xcode.

Body:
I don't know what causes it.

It does not happen at iPhone 5 and simulators. It have been happened only my original device iPhone 7.

fatal error: error in backend: Error while trying to spill X0 from class GPR64: Cannot scavenge register without an emergency spill slot!
clang: error: clang frontend command failed with exit code 70 (use -v to see invocation)
Apple LLVM version 9.0.0 (clang-900.0.34.1)
Target: aarch64-apple-darwin16.7.0
Thread model: posix
InstalledDir: /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
clang: note: diagnostic msg: PLEASE submit a bug report to http://developer.apple.com/bugreporter/ and include the crash backtrace, preprocessed source, and associated run script.
clang: note: diagnostic msg:
********************

PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:
Preprocessed source(s) and associated run script(s) are located at:
clang: note: diagnostic msg: /var/folders/xg/tgwkzqt15xd9jprnv9f0gn4c0000gn/T/CityArray-6e6c1e.m
clang: note: diagnostic msg: /var/folders/xg/tgwkzqt15xd9jprnv9f0gn4c0000gn/T/CityArray-6e6c1e.cache
clang: note: diagnostic msg: /var/folders/xg/tgwkzqt15xd9jprnv9f0gn4c0000gn/T/CityArray-6e6c1e.sh
clang: note: diagnostic msg: Crash backtrace is located in
clang: note: diagnostic msg: /Users/junhyun/Library/Logs/DiagnosticReports/clang_<YYYY-MM-DD-HHMMSS>_<hostname>.crash
clang: note: diagnostic msg: (choose the .crash file that corresponds to your crash)
clang: note: diagnostic msg:

********************


问:
php and MediaWiki
I am looking to retrieve the XML of a Wikipedia page using their api. The URL I'm using is the following: http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&redirects&titles=dog

I've seen this, but it hasn't helped. No matter what I do, I'm not actually getting anything returned to $c, and I can't figure out why. I can do file_get_contents with a plain text file, and it works just fine. Can anyone else verify that this works?

```<code><?php
$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&redirects&titles=Main%20Page';
$c = file_get_contents($url);
echo $c;
?>
</code>```

EDIT I have also tried the cURL available on that page, which also doesn't work:

```<code>$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&redirects&titles=Main%20Page';
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$c = curl_exec($ch);
echo $c;
</code>```

答:
wikipedia requires you specify a descriptive user agent, by doing something like this:

```<code><?php
$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&redirects&titles=Main%20Page';
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_USERAGENT, "MyCoolTool (+http://example.com/MyCoolToolPage/)");
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$c = curl_exec($ch);
echo $c;
?>
</code>```

You should use a user-agent string that describes your site, and you shouldn't spoof a web browser's user agent or you may be blocked for appearing suspicious (source: WikiMedia User-Agent policy)

Title: php and MediaWiki

Body:
I am looking to retrieve the XML of a Wikipedia page using their api. The URL I'm using is the following: http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&redirects&titles=dog

I've seen this, but it hasn't helped. No matter what I do, I'm not actually getting anything returned to $c, and I can't figure out why. I can do file_get_contents with a plain text file, and it works just fine. Can anyone else verify that this works?

<?php
$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&redirects&titles=Main%20Page';
$c = file_get_contents($url);
echo $c;
?>

EDIT I have also tried the cURL available on that page, which also doesn't work:

$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&redirects&titles=Main%20Page';
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$c = curl_exec($ch);
echo $c;

Body:
wikipedia requires you specify a descriptive user agent, by doing something like this:

<?php
$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&redirects&titles=Main%20Page';
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_USERAGENT, "MyCoolTool (+http://example.com/MyCoolToolPage/)");
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$c = curl_exec($ch);
echo $c;
?>

You should use a user-agent string that describes your site, and you shouldn't spoof a web browser's user agent or you may be blocked for appearing suspicious (source: WikiMedia User-Agent policy)


问:
Terraform modules: correct references of variables?
I'm writing a terraform script to create an EKS cluster with its worker nodes on AWS. First time doing it so I'm a bit confused.
Here is the folder organisation:

```<code>├─── Int AWS Account
│   ├─── variables.tf
│   ├─── eks-cluster.tf (refers the modules)
│   ├─── others
│
├─── Prod AWS Account
│   ├─── (will be the same than Int with different settings in variables)
│
├─── ReadMe.md
│
├─── data sources
│
├─── Modules
│   ├─── cluster.tf
│   ├─── worker-nodes.tf
│   ├─── worker-nodes-sg.tf
</code>```

I am a bit confused regarding how to use and pass variables. Right now, what I'm doing is that I refer to ${var.name} in the module folder, in the eks-cluster.tf, I either put a direct value name = blabla (mostly avoiding it), or refer to the variable again and have a variable file in the account folder.

Is that correct?

答:
I'm not sure if I get your question correctly but in general you would want to keep your module files with variables only, as modules are intended to be generic so you can easily include them in different environments.

When including the module in eks_cluster_int.tf or eks_cluster_prod.tf you would then pass the values for all variables defined in the module itself. This way you can use the environment specific values in the same module.

```<code>module "cluster" {
  source = "..."

  var1 = value1    # directly passing value
  var2 = ${var.int_specific_var}  # can be defined in variables.tf of environment
  ...
}
</code>```

Does this answer your question?

Body:
I'm writing a terraform script to create an EKS cluster with its worker nodes on AWS. First time doing it so I'm a bit confused.
Here is the folder organisation:

├─── Int AWS Account
│   ├─── variables.tf
│   ├─── eks-cluster.tf (refers the modules)
│   ├─── others
│
├─── Prod AWS Account
│   ├─── (will be the same than Int with different settings in variables)
│
├─── ReadMe.md
│
├─── data sources
│
├─── Modules
│   ├─── cluster.tf
│   ├─── worker-nodes.tf
│   ├─── worker-nodes-sg.tf

I am a bit confused regarding how to use and pass variables. Right now, what I'm doing is that I refer to ${var.name} in the module folder, in the eks-cluster.tf, I either put a direct value name = blabla (mostly avoiding it), or refer to the variable again and have a variable file in the account folder.

Is that correct?

Body:
I'm not sure if I get your question correctly but in general you would want to keep your module files with variables only, as modules are intended to be generic so you can easily include them in different environments.

When including the module in eks_cluster_int.tf or eks_cluster_prod.tf you would then pass the values for all variables defined in the module itself. This way you can use the environment specific values in the same module.

module "cluster" {
  source = "..."

  var1 = value1    # directly passing value
  var2 = ${var.int_specific_var}  # can be defined in variables.tf of environment
  ...
}

Does this answer your question?


问:
python .xml and .csv files manipulation
I made a conversion from an .xml file to .csv. In the .xml file there were some values from the txtDescricao column of this type: "Logistics, Search and Support." Because of this, when I read the file, pandas interprets that comma after Logisticsas a column separator, and throws the rest of the text forward. I am trying to work around this with the following code:

```<code>in_file = 'dados_limpos_2018.csv'
out_file = 'dados_2018.csv'
output = open(out_file, 'w')
with open(in_file, 'r') as source:
    for line in source:
    # split by semicolon
        data = line.strip().split(';')
    # remove all quotes found
        data = [t.replace('"','') for t in data]
        for item in data[:-1]:
            item.replace(',', '')
            output.write(''.join(['', item, '',',']))
            # write the last item separately, without the trailing ';'
        output.write(''.join(['"', item, '"']))
        output.write('\n')
output.close()
</code>```

however, in the line python already interprets the comma as separator and turns it into a semicolon. Here I would like to know: Is there any way I can handle this in the .csv file, or would I have to do this in .xml to .csv conversion?
Example of .cs file

```<code>name, number, sgUF, txtDescricao, year
Romario, 15, RJ, Consultoria, 2018
Ronaldo, 9, RJ, Logistics, Search and Support, 2018
</code>```

Example .xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xml>
    <dados>
          <despesa>
                  <name>Romario</name>
                  <number>15</number>
                  <sgUF>RJ</sgUF>
                  <txtDescricao>Consultoria</txtDescricao>
                  <year>2018</year>
           </despesa>

           <despesa>
                  <name>Ronaldo</name>
                  <number>9</number>
                  <sgUF>RJ</sgUF>
                  <txtDescricao>Logistics, Search and Support</txtDescricao>
                  <year>2018</year>
           </despesa>
     </dados>
</xml>
</code>```

Note: The original file is too large to open in spreadsheet editor.

答:
I modified your function to deal with those cases in the txtDescricao column.

ncols= 5
index = 3
in_file = 'dados_limpos_2018.csv'
out_file = 'dados_2018.csv'
output = open(out_file, 'w')
with open(in_file, 'r') as source:
     for line in source:
         # split by colon
         data = line.strip().split(',')
         # Change third element
         data_len = len(data)
         if  data_len > ncols:
             # Join all elements
             data[index] = ''.join(data[index:index + 1 + (data_len - ncols)])
             data[index + 1:] = data[index + 1 + data_len - ncols:]
         # Write columns
         output.write(','.join(data[:ncols]))
         output.write('\n')
 output.close()
```

<p>Input file:</p>

```name, number, sgUF, txtDescricao, year
Romario, 15, RJ, Consultoria, 2018
Ronaldo, 9, RJ, Logistics, Search and Support, 2018
```

<p>Output file:</p>

```name, number, sgUF, txtDescricao, year
Romario, 15, RJ, Consultoria, 2018
Ronaldo, 9, RJ, Logistics Search and Support, 2018
```

OBS.: I am assuming that this problem only occurs in the txtDecricao column.

Title: python .xml and .csv files manipulation

Body:
I made a conversion from an .xml file to .csv. In the .xml file there were some values from the txtDescricao column of this type: "Logistics, Search and Support." Because of this, when I read the file, pandas interprets that comma after Logisticsas a column separator, and throws the rest of the text forward. I am trying to work around this with the following code:

in_file = 'dados_limpos_2018.csv'
out_file = 'dados_2018.csv'
output = open(out_file, 'w')
with open(in_file, 'r') as source:
    for line in source:
    # split by semicolon
        data = line.strip().split(';')
    # remove all quotes found
        data = [t.replace('"','') for t in data]
        for item in data[:-1]:
            item.replace(',', '')
            output.write(''.join(['', item, '',',']))
            # write the last item separately, without the trailing ';'
        output.write(''.join(['"', item, '"']))
        output.write('\n')
output.close()

however, in the line python already interprets the comma as separator and turns it into a semicolon. Here I would like to know: Is there any way I can handle this in the .csv file, or would I have to do this in .xml to .csv conversion?
Example of .cs file

name, number, sgUF, txtDescricao, year
Romario, 15, RJ, Consultoria, 2018
Ronaldo, 9, RJ, Logistics, Search and Support, 2018

Example .xml file:

<?xml version="1.0" encoding="UTF-8"?>
<xml>
    <dados>
          <despesa>
                  <name>Romario</name>
                  <number>15</number>
                  <sgUF>RJ</sgUF>
                  <txtDescricao>Consultoria</txtDescricao>
                  <year>2018</year>
           </despesa>

           <despesa>
                  <name>Ronaldo</name>
                  <number>9</number>
                  <sgUF>RJ</sgUF>
                  <txtDescricao>Logistics, Search and Support</txtDescricao>
                  <year>2018</year>
           </despesa>
     </dados>
</xml>

Note: The original file is too large to open in spreadsheet editor.

Body:
I modified your function to deal with those cases in the txtDescricao column.

ncols= 5
index = 3
in_file = 'dados_limpos_2018.csv'
out_file = 'dados_2018.csv'
output = open(out_file, 'w')
with open(in_file, 'r') as source:
     for line in source:
         # split by colon
         data = line.strip().split(',')
         # Change third element
         data_len = len(data)
         if  data_len > ncols:
             # Join all elements
             data[index] = ''.join(data[index:index + 1 + (data_len - ncols)])
             data[index + 1:] = data[index + 1 + data_len - ncols:]
         # Write columns
         output.write(','.join(data[:ncols]))
         output.write('\n')
 output.close()

Input file:

name, number, sgUF, txtDescricao, year
Romario, 15, RJ, Consultoria, 2018
Ronaldo, 9, RJ, Logistics, Search and Support, 2018

Output file:

name, number, sgUF, txtDescricao, year
Romario, 15, RJ, Consultoria, 2018
Ronaldo, 9, RJ, Logistics Search and Support, 2018

OBS.: I am assuming that this problem only occurs in the txtDecricao column.


问:
Users can see other users real time data who are connected to socket
The code below is to show the real-time progress bar for the downloading batches once the user is connected to the socket and it will update the details in every 5 seconds. Problem is that the when two users are connected to the socket then users can see each other batches progress on their account.

I have tried using a socket.id which is unique but it's not working.

```<code>io.on("connection", socket => {
      socketUniqueID = socket.id;
      setInterval(
         () => getApiAndEmit(socket),
         5000
      );
      socket.on("disconnect", () => console.log("Client disconnected"));
});

const getApiAndEmit = socket => {
          try {
          socket.emit(socketID, {batchdata : fetchDetail(req.user.id)});
          } catch (error) {
            console.error(`Error: ${error}`);
          }
};

function fetchDetail(id){
         //CODE TO FETCH THE DETAILS FROM DATABASE
}
</code>```

User can only view the progress of their batches and not of other users who are also logged in.

答:
If you want to send a private message to a specific socketId, you should use io.to(SocketIdOfUser).emit('message','my message')
Also, you can have a look at Socket.Io emit-cheatsheet to see other examples

Body:
The code below is to show the real-time progress bar for the downloading batches once the user is connected to the socket and it will update the details in every 5 seconds. Problem is that the when two users are connected to the socket then users can see each other batches progress on their account.

I have tried using a socket.id which is unique but it's not working.

io.on("connection", socket => {
      socketUniqueID = socket.id;
      setInterval(
         () => getApiAndEmit(socket),
         5000
      );
      socket.on("disconnect", () => console.log("Client disconnected"));
});

const getApiAndEmit = socket => {
          try {
          socket.emit(socketID, {batchdata : fetchDetail(req.user.id)});
          } catch (error) {
            console.error(`Error: ${error}`);
          }
};

function fetchDetail(id){
         //CODE TO FETCH THE DETAILS FROM DATABASE
}

User can only view the progress of their batches and not of other users who are also logged in.


问:
merge list elements which are different dimensions r
I have a df:

```<code>df= data.frame(year=c(rep(2018,4),rep(2017,3)),Area=c(1:4,1:3),P=1:7,N=1:7)
</code>```

I want to split it by years, and then merge everything together again so I can see years as columns for each area. In order to do this, I am splitting and merging:

```<code>s=split(df,df$year)
m=merge(s[[1]][,2:4],[s[[2]][,2:4],by='Area',all=1)
colnames(m)=c('area','P2018','C2018','P2017','C2017')
</code>```

I am sure there is a more efficient way, expecially as the possibility for errors is very high once I include data from other years.

Any suggestions?

答:
We can do this with dcast from data.table which can take multiple value.var columns

```<code>library(data.table)
dcast(setDT(df), Area ~ year, value.var = c("P", "N"))
#  Area P_2017 P_2018 N_2017 N_2018
#1:    1      5      1      5      1
#2:    2      6      2      6      2
#3:    3      7      3      7      3
#4:    4     NA      4     NA      4
</code>```

Body:
I have a df:

df= data.frame(year=c(rep(2018,4),rep(2017,3)),Area=c(1:4,1:3),P=1:7,N=1:7)

I want to split it by years, and then merge everything together again so I can see years as columns for each area. In order to do this, I am splitting and merging:

s=split(df,df$year)
m=merge(s[[1]][,2:4],[s[[2]][,2:4],by='Area',all=1)
colnames(m)=c('area','P2018','C2018','P2017','C2017')

I am sure there is a more efficient way, expecially as the possibility for errors is very high once I include data from other years.

Any suggestions?

Body:
We can do this with dcast from data.table which can take multiple value.var columns

library(data.table)
dcast(setDT(df), Area ~ year, value.var = c("P", "N"))
#  Area P_2017 P_2018 N_2017 N_2018
#1:    1      5      1      5      1
#2:    2      6      2      6      2
#3:    3      7      3      7      3
#4:    4     NA      4     NA      4


问:
Please teach me how to sort the data list of php by 4 to the right
I want to draw out four different lists on the right. But I don't know how to solve it because the same list is repeated vertically like this.
The form I want is

1234

4567

I want a form like this.

This is my html code.

```<code>@foreach($penpals as $penpal)
<div class="row">
<div class="col" style="border:1px solid red">
    <table border>
        <tr style="border:1px solid red">
            <td>
                @if($penpal->image != null)
                    <a href="#"><img src="{{ $penpal->image }}" alt="No Image"
                            style="max-width: none; height: 170px; display: inline; " height="170px" width="170px"
                            class="img-thumbnail"></a>
                @else
                    <a href="#"><img src="{{ asset("data/ProjectImages/master/logoImage/6.png") }}" alt="No Image"
                        style="max-width: none; height: 170px; display: inline; " height="170px" width="170px"
                        class="img-thumbnail"></a>
                @endif
            </td>
        </tr>
        <tr class="text-center">
            <td>
                    {{ $penpal->user->name  }}
                    @if($penpal->user->gender == 'men')
                        <img src="{{ asset("data/ProjectImages/master/men.png") }}" alt="men">
                    @else
                        <img src="{{ asset("data/ProjectImages/master/women.png") }}" alt="women">
                    @endif
                    {{ $penpal->user->age  }}
                    @if($penpal->user->country == 'ko')
                        <img src="{{ asset("data/ProjectImages/master/korea.png") }}" alt="men">
                    @else
                        <img src="{{ asset("data/ProjectImages/master/japan.png") }}" alt="women">
                    @endif
            </td>
        </tr>
    </table>
</div>
<div class="col" style="border:1px solid red">

</div>
<div class="col" style="border:1px solid red">
    3 of 3
</div>
<div class="col" style="border:1px solid red">
    4 of 4
</div>
 </div>
@endforeach
</code>```

I'm rotating iterations and inserting the data in the remaining one div, but I don't know how to put the data in order in the remaining three divis

答:
You could use laravel collection chunk() method (https://laravel.com/docs/5.8/collections#method-chunk).

The chunk method breaks the collection into multiple, smaller collections of a given size:

```<code>@foreach($penpals->chunk(4) as $penpalsGroup)
    <div class="row">
        @forach($penpalsGroup as $penpal)
            <div class="col" style="border:1px solid red">
                <table border>
                    <tr style="border:1px solid red">
                        <td>
                            @if($penpal->image)
                                <a href="#">
                                    <img
                                        src="{{ $penpal->image }}"
                                        alt="No Image"
                                        style="max-width: none; height: 170px; width: 170px; display: inline; "
                                        class="img-thumbnail" />
                                </a>
                            @else
                                <a href="#">
                                    <img
                                        src="{{ asset("data/ProjectImages/master/logoImage/6.png") }}"
                                        alt="No Image"
                                        style="max-width: none; height: 170px; width: 170px; display: inline;"
                                        class="img-thumbnail" />
                                </a>
                            @endif
                        </td>
                    </tr>
                    <tr class="text-center">
                        <td>
                            {{ $penpal->user->name  }}

                            @if($penpal->user->gender == 'men')
                                <img src="{{ asset("data/ProjectImages/master/men.png") }}" alt="men">
                            @else
                                <img src="{{ asset("data/ProjectImages/master/women.png") }}" alt="women">
                            @endif

                            {{ $penpal->user->age  }}

                            @if($penpal->user->country == 'ko')
                                <img src="{{ asset("data/ProjectImages/master/korea.png") }}" alt="men">
                            @else
                                <img src="{{ asset("data/ProjectImages/master/japan.png") }}" alt="women">
                            @endif
                        </td>
                    </tr>
                </table>
            </div>
        @endforeach
    </div>
@endforeach
</code>```

Body:
I want to draw out four different lists on the right. But I don't know how to solve it because the same list is repeated vertically like this.
The form I want is

1234

4567

I want a form like this.

This is my html code.

@foreach($penpals as $penpal)

                @if($penpal->image != null)
                    image }}" alt="No Image"
                            style="max-width: none; height: 170px; display: inline; " height="170px" width="170px"
                            class="img-thumbnail">
                @else

                @endif

                    {{ $penpal->user->name  }}
                    @if($penpal->user->gender == 'men')

                    @else

                    @endif
                    {{ $penpal->user->age  }}
                    @if($penpal->user->country == 'ko')

                    @else

                    @endif

    3 of 3

    4 of 4

@endforeach

I'm rotating iterations and inserting the data in the remaining one div, but I don't know how to put the data in order in the remaining three divis

Body:
You could use laravel collection chunk() method (https://laravel.com/docs/5.8/collections#method-chunk).

The chunk method breaks the collection into multiple, smaller collections of a given size:

@foreach($penpals->chunk(4) as $penpalsGroup)
    <div class="row">
        @forach($penpalsGroup as $penpal)
            <div class="col" style="border:1px solid red">
                <table border>
                    <tr style="border:1px solid red">
                        <td>
                            @if($penpal->image)
                                <a href="#">
                                    <img
                                        src="{{ $penpal->image }}"
                                        alt="No Image"
                                        style="max-width: none; height: 170px; width: 170px; display: inline; "
                                        class="img-thumbnail" />
                                </a>
                            @else
                                <a href="#">
                                    <img
                                        src="{{ asset("data/ProjectImages/master/logoImage/6.png") }}"
                                        alt="No Image"
                                        style="max-width: none; height: 170px; width: 170px; display: inline;"
                                        class="img-thumbnail" />
                                </a>
                            @endif
                        </td>
                    </tr>
                    <tr class="text-center">
                        <td>
                            {{ $penpal->user->name  }}

                            @if($penpal->user->gender == 'men')
                                <img src="{{ asset("data/ProjectImages/master/men.png") }}" alt="men">
                            @else
                                <img src="{{ asset("data/ProjectImages/master/women.png") }}" alt="women">
                            @endif

                            {{ $penpal->user->age  }}

                            @if($penpal->user->country == 'ko')
                                <img src="{{ asset("data/ProjectImages/master/korea.png") }}" alt="men">
                            @else
                                <img src="{{ asset("data/ProjectImages/master/japan.png") }}" alt="women">
                            @endif
                        </td>
                    </tr>
                </table>
            </div>
        @endforeach
    </div>
@endforeach


问:
Errors thrown within a flow are returned to the rpc client as an InternalNodeException, how do we improve error reporting?
We are trying to implement better error reporting coming out of our Corda flows, but we're seeing that any errors thrown within a flow are returned to the RPC-client as an InternalNodeException.

Is there a recommended way to return more details to the client when we need it?

答:
To improve the information provided back to the RPC-Client make the exception type implement ClientRelevantError.

This is a feature that we plan to delete: https://r3-cev.atlassian.net/browse/CORDA-2740


问:
Is there a way to add a second y axis to a matplotlib subplot?
(I think) I know about the twiny/x function in matplotlib, but I am really struggling to figure out how to use this function in a subplot context. I have a line plot like this showing rainfall data:

Generated by this code:

```<code>fig,ax = plt.subplots(3, figsize=(10,15),sharey=True)

ax[0].plot(YEAR1['pcp_1D_tot'], label='RG')
ax[0].plot(YEAR1['ppt_1D'], label='TRMM')
ax[0].set_title('Year 1',x=0.1,y=0.9)

ax[1].plot(YEAR2['pcp_1D_tot'], label='RG')
ax[1].plot(YEAR2['ppt_1D'], label='TRMM')
ax[1].set_title('Year 2',x=0.1,y=0.9)
ax[1].set_ylabel('Rainfall total (mm/day)')

ax[2].plot(YEAR3['pcp_1D_tot'], label='RG')
ax[2].plot(YEAR3['ppt_1D'], label='TRMM')
ax[2].set_title('Year 3',x=0.1,y=0.9)
ax[2].set_xlabel('Date')

fig.legend(loc=(0.8,0.9))
fig.tight_layout()
plt.show()
</code>```

But I also have data on flood magnitude I would like to add which is in categories of 1, 2, and 3, stored in a column named, e.g.

```<code>YEAR1['Size']
</code>```

I'd like to plot these as a scatter plot on top of the line plot to show their incidence relative to rainfall, and so I believe I need to add another y axis on the right, but I am very unclear how to do this.

Can anyone help?

**###########UPDATE############### **

Thanks to the contributions below, I managed to make the following, which is exactly what I was hoping for:

By using the following code:

```<code>x = YEAR1m.index #### these are referring to other data that has been filtered
y = YEAR2m.index
z = YEAR3m.index

fig,ax = plt.subplots(3, figsize=(10,15),sharey=True)

ax[0].plot(YEAR1['pcp_1D_tot'], label='RG')
ax[0].plot(YEAR1['ppt_1D'], label='TRMM')
ax[0].set_title('Year 1',x=0.1,y=0.9)
ax0 = ax[0].twinx()
ax0.scatter(x, YEAR1m['Size'], marker='*', color='r',s=100)
ax0.set_ylim([0,3.2])
ax0.set_yticklabels(['0',' ','1',' ','2',' ','3'])

ax[1].plot(YEAR2['pcp_1D_tot'], label='RG')
ax[1].plot(YEAR2['ppt_1D'], label='TRMM')
ax[1].set_title('Year 2',x=0.1,y=0.9)
ax[1].set_ylabel('Rainfall total (mm/day)')
ax1 = ax[1].twinx()
ax1.scatter(y, YEAR2m['Size'], marker='*', color='r',s=100)
ax1.set_ylim([0,3.2])
ax1.set_yticklabels(['0',' ','1',' ','2',' ','3'])

ax[2].plot(YEAR3['pcp_1D_tot'], label='RG')
ax[2].plot(YEAR3['ppt_1D'], label='TRMM')
ax[2].set_title('Year 3',x=0.1,y=0.9)
ax[2].set_xlabel('Date')
ax2 = ax[2].twinx()
ax2.scatter(z, YEAR3m['Size'], marker='*', color='r',s=100)
ax2.set_ylim([0,3.2])
ax2.set_yticklabels(['0',' ','1',' ','2',' ','3'])

# fig.legend(loc=(0.8,0.9))
fig.tight_layout()
plt.show()
</code>```

答:
In the absence of data, I can only provide a guess solution. The following should work. You will have to use individual subplot object to create a secondary y-axis using twinx

```<code>fig,ax = plt.subplots(3, figsize=(10,15),sharey=True)

ax[0].plot(YEAR1['pcp_1D_tot'], label='RG')
ax[0].plot(YEAR1['ppt_1D'], label='TRMM')
ax[0].set_title('Year 1',x=0.1,y=0.9)

ax0 = ax[0].twinx()
ax0.plot(YEAR1['Size'])

ax[1].plot(YEAR2['pcp_1D_tot'], label='RG')
ax[1].plot(YEAR2['ppt_1D'], label='TRMM')
ax[1].set_title('Year 2',x=0.1,y=0.9)
ax[1].set_ylabel('Rainfall total (mm/day)')

ax1 = ax[1].twinx()
ax1.plot(YEAR2['Size'])

ax[2].plot(YEAR3['pcp_1D_tot'], label='RG')
ax[2].plot(YEAR3['ppt_1D'], label='TRMM')
ax[2].set_title('Year 3',x=0.1,y=0.9)
ax[2].set_xlabel('Date')

ax2 = ax[2].twinx()
ax2.plot(YEAR3['Size'])
</code>```

Body:
(I think) I know about the twiny/x function in matplotlib, but I am really struggling to figure out how to use this function in a subplot context. I have a line plot like this showing rainfall data:

Generated by this code:

fig,ax = plt.subplots(3, figsize=(10,15),sharey=True)

ax[0].plot(YEAR1['pcp_1D_tot'], label='RG')
ax[0].plot(YEAR1['ppt_1D'], label='TRMM')
ax[0].set_title('Year 1',x=0.1,y=0.9)

ax[1].plot(YEAR2['pcp_1D_tot'], label='RG')
ax[1].plot(YEAR2['ppt_1D'], label='TRMM')
ax[1].set_title('Year 2',x=0.1,y=0.9)
ax[1].set_ylabel('Rainfall total (mm/day)')

ax[2].plot(YEAR3['pcp_1D_tot'], label='RG')
ax[2].plot(YEAR3['ppt_1D'], label='TRMM')
ax[2].set_title('Year 3',x=0.1,y=0.9)
ax[2].set_xlabel('Date')

fig.legend(loc=(0.8,0.9))
fig.tight_layout()
plt.show()

But I also have data on flood magnitude I would like to add which is in categories of 1, 2, and 3, stored in a column named, e.g.

YEAR1['Size']

I'd like to plot these as a scatter plot on top of the line plot to show their incidence relative to rainfall, and so I believe I need to add another y axis on the right, but I am very unclear how to do this.

Can anyone help?

**###########UPDATE############### **

Thanks to the contributions below, I managed to make the following, which is exactly what I was hoping for:

By using the following code:

x = YEAR1m.index #### these are referring to other data that has been filtered
y = YEAR2m.index
z = YEAR3m.index

fig,ax = plt.subplots(3, figsize=(10,15),sharey=True)

ax[0].plot(YEAR1['pcp_1D_tot'], label='RG')
ax[0].plot(YEAR1['ppt_1D'], label='TRMM')
ax[0].set_title('Year 1',x=0.1,y=0.9)
ax0 = ax[0].twinx()
ax0.scatter(x, YEAR1m['Size'], marker='*', color='r',s=100)
ax0.set_ylim([0,3.2])
ax0.set_yticklabels(['0',' ','1',' ','2',' ','3'])

ax[1].plot(YEAR2['pcp_1D_tot'], label='RG')
ax[1].plot(YEAR2['ppt_1D'], label='TRMM')
ax[1].set_title('Year 2',x=0.1,y=0.9)
ax[1].set_ylabel('Rainfall total (mm/day)')
ax1 = ax[1].twinx()
ax1.scatter(y, YEAR2m['Size'], marker='*', color='r',s=100)
ax1.set_ylim([0,3.2])
ax1.set_yticklabels(['0',' ','1',' ','2',' ','3'])

ax[2].plot(YEAR3['pcp_1D_tot'], label='RG')
ax[2].plot(YEAR3['ppt_1D'], label='TRMM')
ax[2].set_title('Year 3',x=0.1,y=0.9)
ax[2].set_xlabel('Date')
ax2 = ax[2].twinx()
ax2.scatter(z, YEAR3m['Size'], marker='*', color='r',s=100)
ax2.set_ylim([0,3.2])
ax2.set_yticklabels(['0',' ','1',' ','2',' ','3'])

# fig.legend(loc=(0.8,0.9))
fig.tight_layout()
plt.show()

Body:
In the absence of data, I can only provide a guess solution. The following should work. You will have to use individual subplot object to create a secondary y-axis using twinx

fig,ax = plt.subplots(3, figsize=(10,15),sharey=True)

ax[0].plot(YEAR1['pcp_1D_tot'], label='RG')
ax[0].plot(YEAR1['ppt_1D'], label='TRMM')
ax[0].set_title('Year 1',x=0.1,y=0.9)

ax0 = ax[0].twinx()
ax0.plot(YEAR1['Size'])

ax[1].plot(YEAR2['pcp_1D_tot'], label='RG')
ax[1].plot(YEAR2['ppt_1D'], label='TRMM')
ax[1].set_title('Year 2',x=0.1,y=0.9)
ax[1].set_ylabel('Rainfall total (mm/day)')

ax1 = ax[1].twinx()
ax1.plot(YEAR2['Size'])

ax[2].plot(YEAR3['pcp_1D_tot'], label='RG')
ax[2].plot(YEAR3['ppt_1D'], label='TRMM')
ax[2].set_title('Year 3',x=0.1,y=0.9)
ax[2].set_xlabel('Date')

ax2 = ax[2].twinx()
ax2.plot(YEAR3['Size'])


问:
Date changes when setting value
I'm facing a strange problem, I have a function to get the current date. It may not be the best, but it's ok. I then use the function to set the value of a hidden input:

function gettoday() {
  var d = new Date();
  var month = d.getMonth() + 1;
  var day = d.getDate();

  var out = (day < 10 ? '0' : '') + day + '/' +
    (month < 10 ? '0' : '') + month + '/' +
    d.getFullYear();
  return out;
}

something.attr('value', String(gettoday()));
```

When I do so the date becomes 31/12/1969. The gettoday() function returns the correct date. Any ideas what could be happening? I tried debugging the call but nothing happens there. The same happens in Chrome or Firefox. Thanks!

答:
You should set the value using val in yyyy-mm-dd format, try the following snippet

function gettoday() {
  var d = new Date();

  var month = d.getMonth() + 1;
  var day = d.getDate();

  var out = d.getFullYear() + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
  return out;
}

$('input').val(gettoday());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date"></code>```

Title: Date changes when setting value

Body:
I'm facing a strange problem, I have a function to get the current date. It may not be the best, but it's ok. I then use the function to set the value of a hidden input:

function gettoday() {
  var d = new Date();
  var month = d.getMonth() + 1;
  var day = d.getDate();

  var out = (day < 10 ? '0' : '') + day + '/' +
    (month < 10 ? '0' : '') + month + '/' +
    d.getFullYear();
  return out;
}

something.attr('value', String(gettoday()));

When I do so the date becomes 31/12/1969. The gettoday() function returns the correct date. Any ideas what could be happening? I tried debugging the call but nothing happens there. The same happens in Chrome or Firefox. Thanks!

Body:
You should set the value using val in yyyy-mm-dd format, try the following snippet

function gettoday() {
  var d = new Date();

  var month = d.getMonth() + 1;
  var day = d.getDate();

  var out = d.getFullYear() + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
  return out;
}

$('input').val(gettoday());

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date">


问:
How to downgrade to Angular 7 from Angular 8 or 9
So I was trying to upgrade our entire web-application earlier from Angular 6 to 7. And I was able to do that since the script I run earlier installed the most latest version available of Angular which is Angular 8 (should have been 7 though as I thought) release 2 days ago. But it turns out there are build issues in the node modules when I did the upgrade to Angular 8. So instead, I want to downgrade my project from Angular 8 to Angular 7. How do I do that?. TIA.

PS:
I did not expect that there is Angular 8 alright, so I thought it would install Angular 7 as the latest version.

答:
Try like this :

```<code>ng --version
npm uninstall -g @angular/cli
npm cache clean --force

npm install -g @angular/cli@7.2.12
ng --version
</code>```

Update

The version 7.2.12 is given the following error :

npm ERR! code ETARGET
  npm ERR! notarget No matching version found for @angular/cli@7.2.12
  npm ERR! notarget In most cases you or one of your dependencies are requesting
  npm ERR! notarget a package version that doesn't exist.

use this instead :

```<code>npm install -g @angular/cli@7.2
</code>```

Body:
Try like this :

ng --version
npm uninstall -g @angular/cli
npm cache clean --force

npm install -g @angular/cli@7.2.12
ng --version

Update

The version 7.2.12 is given the following error :

npm ERR! code ETARGET
  npm ERR! notarget No matching version found for @angular/cli@7.2.12
  npm ERR! notarget In most cases you or one of your dependencies are requesting
  npm ERR! notarget a package version that doesn't exist.

use this instead :

npm install -g @angular/cli@7.2


问:
How to run webviews in multiple threads
My assigment says to create a simple web browser where webpage is saved in a card and later on you can retrieve it.

Each card/webpage need to run on it's own thread.

I've already setted up webview and myWebViewClient to load links, and a 2nd activity where i display and can add new webpages. Selecting ListView item is calling loadUrl(url) in MainActivity on a WebView, but that's not the desireable outcome, I need to run webview in a thread, put it away on a stack, and later resume it's task somehow.

答:
You can create a new Activity for each WebView and save his task ID in a List. If the ID doesn't exists on the stack you create a new one WebView Activity and put it on the stack,  otherwise you push the existent WebView Activity from stack and resume this activity.

Launch WebView Activities using flags: Intent.FLAG_ACTIVITY_NEW_TASK and Intent.FLAG_ACTIVITY_MULTIPLE_TASK

Inside these activities call getTaskId() and make the ID available to your main activity. When you want to resume an activity, do the following:

```<code>ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
am.moveTaskToFront(taskId, 0);
</code>```

Requires permission permission android.Manifest.permission.REORDER_TASKS

this work if memory management doesn't destroy your activity, in this case the OnCreate method will call.

Title: How to run webviews in multiple threads

Body:
You can create a new Activity for each WebView and save his task ID in a List. If the ID doesn't exists on the stack you create a new one WebView Activity and put it on the stack,  otherwise you push the existent WebView Activity from stack and resume this activity.

Launch WebView Activities using flags: Intent.FLAG_ACTIVITY_NEW_TASK and Intent.FLAG_ACTIVITY_MULTIPLE_TASK

Inside these activities call getTaskId() and make the ID available to your main activity. When you want to resume an activity, do the following:

ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
am.moveTaskToFront(taskId, 0);

Requires permission permission android.Manifest.permission.REORDER_TASKS

this work if memory management doesn't destroy your activity, in this case the OnCreate method will call.