问:
Add a delay to a for loop in swift
I have a coding 'issue'.

I have a label, which text I want to change dynamically every 2 seconds.
I've done the following:

```<code>// WELCOME STRING ARRAY
let welcomeContainer:[String] = ["Welcome","Benvenuti","Bienvenue","Willkommen","üdvözlet","Dobrodošli","добро пожаловать","Witajcie","Bienvenido","Ласкаво просимо","Vitajte","欢迎你来"]
</code>```

and then, rather than using a timerwithinterval (which seemed to be too much for this simple task), I tried with the delay method in my function inside for loop:

```<code>func welcomeLabelChange() {
for i in 0..<welcomeContainer.count {
    welcomeLabel.text = welcomeContainer[i]
    delay(delay: 2.0, closure: {})
}
</code>```

Unfortunately it's entirely skipping the delay... the for loop is executed instantly and just the last text in the array is displayed.
What am I doing wrong?

I found this OBJ-C answer, but it's suggesting an (old) NSTimer implementation.

答:
Marked answer doesn't delay loop iterations and you still get just the last value in the label.text.

You can solve it like this:

```<code>func showWelcome(_ iteration: Int = 0) {
    let i = iteration>=self.welcomeContainer.count ? 0 : iteration
    let message = self.welcomeContainer[i]
    self.delay(2){
        self.welcomeLabel.text = message
        return self.showWelcome(i + 1)
    }
}
</code>```

Usage:

```<code>    showWelcome()
</code>```

Title: Add a delay to a for loop in swift

Body:
I have a coding 'issue'.

I have a label, which text I want to change dynamically every 2 seconds.
I've done the following:

// WELCOME STRING ARRAY
let welcomeContainer:[String] = ["Welcome","Benvenuti","Bienvenue","Willkommen","üdvözlet","Dobrodošli","добро пожаловать","Witajcie","Bienvenido","Ласкаво просимо","Vitajte","欢迎你来"]

and then, rather than using a timerwithinterval (which seemed to be too much for this simple task), I tried with the delay method in my function inside for loop:

func welcomeLabelChange() {
for i in 0..<welcomeContainer.count {
    welcomeLabel.text = welcomeContainer[i]
    delay(delay: 2.0, closure: {})
}

Unfortunately it's entirely skipping the delay... the for loop is executed instantly and just the last text in the array is displayed.
What am I doing wrong?

I found this OBJ-C answer, but it's suggesting an (old) NSTimer implementation.

Body:
Marked answer doesn't delay loop iterations and you still get just the last value in the label.text.

You can solve it like this:

func showWelcome(_ iteration: Int = 0) {
    let i = iteration>=self.welcomeContainer.count ? 0 : iteration
    let message = self.welcomeContainer[i]
    self.delay(2){
        self.welcomeLabel.text = message
        return self.showWelcome(i + 1)
    }
}

Usage:

    showWelcome()


来源: stackexchange

问:
Flask form.populate_obj() keep null values
I have an edit function where I edit certain data. The form (I use flask_wtf) is the same, so I can use:

```<code>form.populate_obj(build)
</code>```

Now I see all old values and can edit them, but some fields do not have a value. These fields are null in the DB. Often I dont need to edit them so I simply ignore them.

And here is the problem, if I submit the edit form all values which should remain null become an empty string ""

Here is a precise example:

Thats an entry where I want only to edit date_added. I ignore bandits and additional_info.

After submit I expect that bandits and additional_info still are null, but they change:

Of course I could rewrite the whole code and use the same logic where I add these values to the DB, but I feel like there should be a better solution.

答:
Could you add filters to your form fields:

```<code>filters = [lambda x: x or None]
</code>```

For example like this:

```<code>birthtown = StringField("Birthtown", filters = [lambda x: x or None])
</code>```

This will either use whatever you write in the field or None. At least you will get rid of the empty strings. Or is this too much rewriting to be acceptable?

ContentLicense: CC BY-SA 3.0

Body:
I have an edit function where I edit certain data. The form (I use flask_wtf) is the same, so I can use:

form.populate_obj(build)

Now I see all old values and can edit them, but some fields do not have a value. These fields are null in the DB. Often I dont need to edit them so I simply ignore them.

And here is the problem, if I submit the edit form all values which should remain null become an empty string ""

Here is a precise example:

Thats an entry where I want only to edit date_added. I ignore bandits and additional_info.

After submit I expect that bandits and additional_info still are null, but they change:

Of course I could rewrite the whole code and use the same logic where I add these values to the DB, but I feel like there should be a better solution.

Body:
Could you add filters to your form fields:

filters = [lambda x: x or None]

For example like this:

birthtown = StringField("Birthtown", filters = [lambda x: x or None])

This will either use whatever you write in the field or None. At least you will get rid of the empty strings. Or is this too much rewriting to be acceptable?


问:
How to resolve the latest version of the referenced package in nuspec?
Is there a way resolve the latest version of the referenced package/dependency in nuspec file?

```<code><?xml version="1.0"?>
<package >
  <metadata>
    <id>Package1</id>
    <dependencies>
      <dependency id="Package2" version="LATEST_YOU_CAN_FIND"  />
    </dependencies>
  </metadata>
  <files>
    <file src="lib\" target="lib" />
  </files>
</package>
</code>```

Post build scripts/regex/substitution solutions are not what I'm looking for.

答:
Edit: This doesn't apply to a nuspec file but you can make the changes as described in this answer to always get the latest. The change specified only applies to your own machine. For any code that is yours, you could add your own nuget.config file to make this true.

There isn't a keyword for latest version today. There is however a way to say, use from this version and beyond. You can find the full reference here. Note, this does not mean that NuGet will always get the latest version for the listed dependencies.

An example (from the link provided):

```<code><!-- Accepts any version above, but not include 4.1.3. This might be
      used to guarantee a dependency with a specific bug fix. -->
<dependency id="ExamplePackage" version="(4.1.3,)" />

<!-- Accepts any version up below 5.x, which might be used to prevent
      pulling in a later version of a dependency that changed its interface.
      However, this form is not recommended because it can be difficult to
      determine the lowest version.  -->
<dependency id="ExamplePackage" version="(,5.0)" />

<!-- Accepts any 1.x or 2.x version, but no 0.x or 3.x and higher versions -->
<dependency id="ExamplePackage" version="[1,3)" />

<!-- Accepts 1.3.2 up to 1.4.x, but not 1.5 and higher. -->
<dependency id="ExamplePackage" version="[1.3.2,1.5)" />
</code>```

Body:
Is there a way resolve the latest version of the referenced package/dependency in nuspec file?

<?xml version="1.0"?>
<package >
  <metadata>
    <id>Package1</id>
    <dependencies>
      <dependency id="Package2" version="LATEST_YOU_CAN_FIND"  />
    </dependencies>
  </metadata>
  <files>
    <file src="lib\" target="lib" />
  </files>
</package>

Post build scripts/regex/substitution solutions are not what I'm looking for.

Body:
Edit: This doesn't apply to a nuspec file but you can make the changes as described in this answer to always get the latest. The change specified only applies to your own machine. For any code that is yours, you could add your own nuget.config file to make this true.

There isn't a keyword for latest version today. There is however a way to say, use from this version and beyond. You can find the full reference here. Note, this does not mean that NuGet will always get the latest version for the listed dependencies.

An example (from the link provided):

<!-- Accepts any version above, but not include 4.1.3. This might be
      used to guarantee a dependency with a specific bug fix. -->
<dependency id="ExamplePackage" version="(4.1.3,)" />

<!-- Accepts any version up below 5.x, which might be used to prevent
      pulling in a later version of a dependency that changed its interface.
      However, this form is not recommended because it can be difficult to
      determine the lowest version.  -->
<dependency id="ExamplePackage" version="(,5.0)" />

<!-- Accepts any 1.x or 2.x version, but no 0.x or 3.x and higher versions -->
<dependency id="ExamplePackage" version="[1,3)" />

<!-- Accepts 1.3.2 up to 1.4.x, but not 1.5 and higher. -->
<dependency id="ExamplePackage" version="[1.3.2,1.5)" />


问:
Why crash program by access pointer? In C
I tried to access a pointer but the program crashes. With memory access error.
I receive the pointer from a stack.  (pop- function). As a void*-pointer.
Why an I getting this behavior?

```<code>int main()
{
    int MAX = 5;
    int field[MAX];
    int i; /* for the loop */
    int *pInt = NULL;

    initStack();

    for (i = 0; i < MAX; i++)
    {
        field[i] = i;
        push((field + i));  // HERE CRASH
    }

    for (i = 0; i < MAX; i++)
    {
        pInt = pop();   /* fetch next integer */

        printf("%d\n", *pInt); /* print value */
    }

    return EXIT_SUCCESS;
}
</code>```

UPDATE:

I have tested my stack. And it works. But with for-loops it crashes.

My stack implementation.
I get the error always I access to the pointer.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#include "stack.h"

/*
   actual stack data structure
   This pointer will pointing at the actual field (of void * pointers)
   that represents the stack.
 */
void **array;

/* the current capacity of the stack */
int max = 10;

/* counter variable for counting the elements of the stack. */
int counter = 0;

/*
    offset address
    points at the top element of the stack.
*/
int offset = -1;

void initStack(void)
{

    array = malloc(sizeof(void) * max);
    assert(array); /* tests whether pointer is assigned to memory. */
}

/*
    grow: increases the stack by 10 elements.
          This utility function isn't part of the public interface
*/
void grow(void)
{
    max += 10; /* increases the capacity */

    int i; // for the loop
    void **tmp = malloc(sizeof(void) * max);

    /* copies the elements from the origin array in the new one. */
    for (i = 0; i < max - 10; i++)
    {
        *(tmp + i) = *(array + i);
    }

    array = tmp; /* setups the new one as basis */
}

/* push: pushs the argument onto the stack */
void push(void *object)
{

    assert(object); /* tests whether pointer isn't null */

    if (offset < max)
    {

        offset++; /* increases the element-pointer */

        /*
            moves pointer by the offset address
            pushes the object onto stack
         */
        *(array + offset) = object;
    }
    else /* stack is full */
    {

        /* TODO */
        grow();
        push(object); /* recursive call */
    }
}

/*
    pop: pops the top element of the stack from the stack.
*/
void *pop(void)
{
    printf("\tBEFORE\n"); //DEBUG
    void *top = *(array + offset);
    assert(top);
    assert(array + offset);
    printf("\tAFTER  void *top = *(array + offset);\n"); //DEBUG
    // int *pInt = top;
    // printf("\tpop: value= %d\n", *top); /* DEBUG */

    /* decreases the offset address for pointing of
        the new top element */
    offset--;

    return top;
}
</code>```

答:
the issue is that kind of allocation:

```<code>void initStack()
{

    array = malloc(sizeof(void) * max);
}
</code>```

sizeof(void) is illegal but some compilers consider it legal like gcc, which in that case returns 1, which isn't enough for your int pointer.

So you could fix those by passing the size of the element:

```<code>void initStack(int sz)
{
    array = malloc(sz * max);
</code>```

call by

```<code>initStack(sizeof(int *));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I tried to access a pointer but the program crashes. With memory access error.
I receive the pointer from a stack.  (pop- function). As a void*-pointer.
Why an I getting this behavior?

int main()
{
    int MAX = 5;
    int field[MAX];
    int i; /* for the loop */
    int *pInt = NULL;

    initStack();

    for (i = 0; i < MAX; i++)
    {
        field[i] = i;
        push((field + i));  // HERE CRASH
    }

    for (i = 0; i < MAX; i++)
    {
        pInt = pop();   /* fetch next integer */

        printf("%d\n", *pInt); /* print value */
    }

    return EXIT_SUCCESS;
}

UPDATE:

I have tested my stack. And it works. But with for-loops it crashes.

My stack implementation.
I get the error always I access to the pointer.

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#include "stack.h"

/*
   actual stack data structure
   This pointer will pointing at the actual field (of void * pointers)
   that represents the stack.
 */
void **array;

/* the current capacity of the stack */
int max = 10;

/* counter variable for counting the elements of the stack. */
int counter = 0;

/*
    offset address
    points at the top element of the stack.
*/
int offset = -1;

void initStack(void)
{

    array = malloc(sizeof(void) * max);
    assert(array); /* tests whether pointer is assigned to memory. */
}

/*
    grow: increases the stack by 10 elements.
          This utility function isn't part of the public interface
*/
void grow(void)
{
    max += 10; /* increases the capacity */

    int i; // for the loop
    void **tmp = malloc(sizeof(void) * max);

    /* copies the elements from the origin array in the new one. */
    for (i = 0; i < max - 10; i++)
    {
        *(tmp + i) = *(array + i);
    }

    array = tmp; /* setups the new one as basis */
}

/* push: pushs the argument onto the stack */
void push(void *object)
{

    assert(object); /* tests whether pointer isn't null */

    if (offset < max)
    {

        offset++; /* increases the element-pointer */

        /*
            moves pointer by the offset address
            pushes the object onto stack
         */
        *(array + offset) = object;
    }
    else /* stack is full */
    {

        /* TODO */
        grow();
        push(object); /* recursive call */
    }
}

/*
    pop: pops the top element of the stack from the stack.
*/
void *pop(void)
{
    printf("\tBEFORE\n"); //DEBUG
    void *top = *(array + offset);
    assert(top);
    assert(array + offset);
    printf("\tAFTER  void *top = *(array + offset);\n"); //DEBUG
    // int *pInt = top;
    // printf("\tpop: value= %d\n", *top); /* DEBUG */

    /* decreases the offset address for pointing of
        the new top element */
    offset--;

    return top;
}

Body:
the issue is that kind of allocation:

void initStack()
{

    array = malloc(sizeof(void) * max);
}

sizeof(void) is illegal but some compilers consider it legal like gcc, which in that case returns 1, which isn't enough for your int pointer.

So you could fix those by passing the size of the element:

void initStack(int sz)
{
    array = malloc(sz * max);

call by

initStack(sizeof(int *));


问:
Print elements from different size array
```<code>Integer [][] x = {{1,2,3},{4},{5,6}};
</code>```

What is the best way to print the elements in stdout like this?

```<code>1
2
3
4
5
6
</code>```

I have tried Arrays.deepToString(x) but doesnt output what I desire

答:
Try this :

```<code>public class MyClass {
    public static void main(String args[]) {

        Integer [][] x = {{1,2,3},{4},{5,6}};

        for(Integer[] y : x) {

            for(Integer i : y) {

                System.out.println(i);

            }
        }

    }
}
</code>```

Output :

```<code>1
2
3
4
5
6
</code>```

Here it is : https://ideone.com/9ywcjz

Body:
Integer [][] x = {{1,2,3},{4},{5,6}};

What is the best way to print the elements in stdout like this?

1
2
3
4
5
6

I have tried Arrays.deepToString(x) but doesnt output what I desire

Body:
Try this :

public class MyClass {
    public static void main(String args[]) {

        Integer [][] x = {{1,2,3},{4},{5,6}};

        for(Integer[] y : x) {

            for(Integer i : y) {

                System.out.println(i);

            }
        }

    }
}

Output :

1
2
3
4
5
6

Here it is : https://ideone.com/9ywcjz


问:
what is '???' in Scala?
I'm learning Scala using IntelliJ IDE.

When I subs class Element and override contents method, IDE provided default implementation for contents method with definition ???

Below code from the book Programming in Scala, 3rd edition

Element

```<code>abstract class Element {
  def contents: Array[String]

  def height = contents.length

  def width = if (height == 0) 0 else contents(0).length
}
</code>```

ArrayElement

```<code>class ArrayElement(cont: Array[String]) extends Element {
  override def contents: Array[String] = ??? // impl provided by IDE
}
</code>```

I don't see any issues in running the program but when I access the method I get below exception

```<code>Exception in thread "main" scala.NotImplementedError: an implementation is missing
    at scala.Predef$.$qmark$qmark$qmark(Predef.scala:284)
    at org.saravana.scala.ArrayElement.contents(ScalaTest.scala:65)
</code>```

Can someone explain what is ??? and use of it?

答:
??? is designed as a placeholder and is a method defined in Predef (which is automatically imported by default)

It's definition is

def ??? : Nothing = throw new NotImplementedError

So it has return type Nothing and all it does is throw NotImplementedError.  This definition allows it to used as a placeholder implementation for methods you defined but haven't implemented yet but still want to be able to compile your program.

Nothing is a subtype of every type, which makes ??? a valid implementation no matter what type is expected.

Title: what is '???' in Scala?

Body:
I'm learning Scala using IntelliJ IDE.

When I subs class Element and override contents method, IDE provided default implementation for contents method with definition ???

Below code from the book Programming in Scala, 3rd edition

Element

abstract class Element {
  def contents: Array[String]

  def height = contents.length

  def width = if (height == 0) 0 else contents(0).length
}

ArrayElement

class ArrayElement(cont: Array[String]) extends Element {
  override def contents: Array[String] = ??? // impl provided by IDE
}

I don't see any issues in running the program but when I access the method I get below exception

Exception in thread "main" scala.NotImplementedError: an implementation is missing
    at scala.Predef$.$qmark$qmark$qmark(Predef.scala:284)
    at org.saravana.scala.ArrayElement.contents(ScalaTest.scala:65)

Can someone explain what is ??? and use of it?


问:
Laravel Notifications Base Table not found
I am working on a Laravel project. I ran these commands and successfully created notifications table.

```<code>php artisan notifications:table
php artisan migrate
</code>```

All of the things were going perfectly. Later on I created a Model name "NotificationsForAdmin" with migration named "notifications_for_admin", then later on I drooped this table. Now when I am trying to generate some notifications then it is showing me this error, I dont know whats going on I have notifications table in database that is needed for laravel notifications with perfect schema. the error is :

```<code>SQLSTATE[42S02]: Base table or view not found: 1146 Table 'followup.notification_for_admins' doesn't exist (SQL: select * from `notification_for_admins` where `notification_for_admins`.`user_id` = 2 and `notification_for_admins`.`user_id` is not null)
</code>```

My notifications is :

```<code><?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use App\User;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\BroadcastMessage;
use Illuminate\Notifications\Messages\MailMessage;
use App\Events\NewEmailReceivedEvent;
use Auth;

    class NewEmailReceived extends Notification
    {
        use Queueable;

        public $sender_id, $receiver_id, $sender_name, $receiver_name, $sender_type, $receiver_type, $type, $recipient, $from_email, $subject, $message, $image, $receiver_image, $attachments, $sizesOfAttachments, $originalFileNames, $thread_id, $id_of_email;

        /**
         * Create a new notification instance.
         *
         * @return void
         */
        public function __construct($sender_id, $receiver_id, $sender_name, $receiver_name, $sender_type, $receiver_type, $type, $recipient, $from_email, $subject, $message, $image, $receiver_image, $attachments, $sizesOfAttachments, $originalFileNames, $thread_id, $id_of_email)
        {
            $this->sender_id = $sender_id;
            $this->receiver_id = $receiver_id;
            $this->sender_name = $sender_name;
            $this->receiver_name = $receiver_name;
            $this->sender_type = $sender_type;
            $this->receiver_type = $receiver_type;
            $this->type = $type;
            $this->recipient = $recipient;
            $this->from_email = $from_email;
            $this->subject = $subject;
            $this->message = $message;
            $this->image = $image;
            $this->receiver_image = $receiver_image;
            $this->attachments = $attachments;
            $this->sizesOfAttachments = $sizesOfAttachments;
            $this->originalFileNames = $originalFileNames;
            $this->thread_id = $thread_id;
            $this->id_of_email = $id_of_email;
        }

        /**
         * Get the notification's delivery channels.
         *
         * @param  mixed  $notifiable
         * @return array
         */
        public function via($notifiable)
        {
            $notifications = Auth::user()->notifications;
            if ($notifications[7]->shown == 1) {
                return ['mail', 'database'];
            }
            else{
                return ['database'];
            }
        }

        /**
         * Get the array representation of the notification.
         *
         * @param  mixed  $notifiable
         * @return array
         */
        public function toDatabase($notifiable)
        {
            return [
                'sender_id' => $this->sender_id,
                'receiver_id' => $this->receiver_id,
                'sender_name' => $this->sender_name,
                'receiver_name' => $this->receiver_name,
                'sender_type' => $this->sender_type,
                'receiver_type' => $this->receiver_type,
                'type' => $this->type,
                'recipient' => $this->recipient,
                'from_email' => $this->from_email,
                'subject' => $this->subject,
                'message' => $this->message,
                'image' => $this->image,
                'receiver_image' => $this->receiver_image,
                'attachments' => $this->attachments,
                'sizesOfAttachments' => $this->sizesOfAttachments,
                'originalFileNames' => $this->originalFileNames,
                'thread_id' => $this->thread_id,
                'id_of_email' => $this->id_of_email,
            ];
            event(new NewEmailReceivedEvent($NewEmailReceivedRequest));
            return $NewEmailReceivedRequest;
        }

        /**
         * Get the mail representation of the notification.
         *
         * @param  mixed  $notifiable
         * @return \Illuminate\Notifications\Messages\MailMessage
         */
        public function toMail($notifiable)
        {
            return (new MailMessage)
                ->subject("New email from ".$this->sender_type)
                ->greeting('Hello!')
                ->markdown('mails.NewEmailReceived' , ['recipient_name' => $this->receiver_name , 'subject' => $this->subject , 'mailMessage' => str_limit($this->message, 50) , 'avatar' => $this->image]);
        }

        /**
         * Get the array representation of the notification.
         *
         * @param  mixed  $notifiable
         * @return array
         */
        public function toArray($notifiable)
        {
            return [
                //
            ];
        }
    }
</code>```

I shall be very thankfull if someone could help me on this.

答:
It seems your notifications relation on your User object still references NotificationsForAdmin.

If you do not specify the table for a model, the table is automatically generated as a snake_case string of the model name. In the case of NotificationsForAdmin this becomes notification_for_admins.

Add the public property $table to your NotificationsForAdmin with the name of the table where your notifications are stored as the value. This should fix your problem.

Body:
I am working on a Laravel project. I ran these commands and successfully created notifications table.

php artisan notifications:table
php artisan migrate

All of the things were going perfectly. Later on I created a Model name "NotificationsForAdmin" with migration named "notifications_for_admin", then later on I drooped this table. Now when I am trying to generate some notifications then it is showing me this error, I dont know whats going on I have notifications table in database that is needed for laravel notifications with perfect schema. the error is :

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'followup.notification_for_admins' doesn't exist (SQL: select * from `notification_for_admins` where `notification_for_admins`.`user_id` = 2 and `notification_for_admins`.`user_id` is not null)

My notifications is :

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use App\User;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\BroadcastMessage;
use Illuminate\Notifications\Messages\MailMessage;
use App\Events\NewEmailReceivedEvent;
use Auth;

    class NewEmailReceived extends Notification
    {
        use Queueable;

        public $sender_id, $receiver_id, $sender_name, $receiver_name, $sender_type, $receiver_type, $type, $recipient, $from_email, $subject, $message, $image, $receiver_image, $attachments, $sizesOfAttachments, $originalFileNames, $thread_id, $id_of_email;

        /**
         * Create a new notification instance.
         *
         * @return void
         */
        public function __construct($sender_id, $receiver_id, $sender_name, $receiver_name, $sender_type, $receiver_type, $type, $recipient, $from_email, $subject, $message, $image, $receiver_image, $attachments, $sizesOfAttachments, $originalFileNames, $thread_id, $id_of_email)
        {
            $this->sender_id = $sender_id;
            $this->receiver_id = $receiver_id;
            $this->sender_name = $sender_name;
            $this->receiver_name = $receiver_name;
            $this->sender_type = $sender_type;
            $this->receiver_type = $receiver_type;
            $this->type = $type;
            $this->recipient = $recipient;
            $this->from_email = $from_email;
            $this->subject = $subject;
            $this->message = $message;
            $this->image = $image;
            $this->receiver_image = $receiver_image;
            $this->attachments = $attachments;
            $this->sizesOfAttachments = $sizesOfAttachments;
            $this->originalFileNames = $originalFileNames;
            $this->thread_id = $thread_id;
            $this->id_of_email = $id_of_email;
        }

        /**
         * Get the notification's delivery channels.
         *
         * @param  mixed  $notifiable
         * @return array
         */
        public function via($notifiable)
        {
            $notifications = Auth::user()->notifications;
            if ($notifications[7]->shown == 1) {
                return ['mail', 'database'];
            }
            else{
                return ['database'];
            }
        }

        /**
         * Get the array representation of the notification.
         *
         * @param  mixed  $notifiable
         * @return array
         */
        public function toDatabase($notifiable)
        {
            return [
                'sender_id' => $this->sender_id,
                'receiver_id' => $this->receiver_id,
                'sender_name' => $this->sender_name,
                'receiver_name' => $this->receiver_name,
                'sender_type' => $this->sender_type,
                'receiver_type' => $this->receiver_type,
                'type' => $this->type,
                'recipient' => $this->recipient,
                'from_email' => $this->from_email,
                'subject' => $this->subject,
                'message' => $this->message,
                'image' => $this->image,
                'receiver_image' => $this->receiver_image,
                'attachments' => $this->attachments,
                'sizesOfAttachments' => $this->sizesOfAttachments,
                'originalFileNames' => $this->originalFileNames,
                'thread_id' => $this->thread_id,
                'id_of_email' => $this->id_of_email,
            ];
            event(new NewEmailReceivedEvent($NewEmailReceivedRequest));
            return $NewEmailReceivedRequest;
        }

        /**
         * Get the mail representation of the notification.
         *
         * @param  mixed  $notifiable
         * @return \Illuminate\Notifications\Messages\MailMessage
         */
        public function toMail($notifiable)
        {
            return (new MailMessage)
                ->subject("New email from ".$this->sender_type)
                ->greeting('Hello!')
                ->markdown('mails.NewEmailReceived' , ['recipient_name' => $this->receiver_name , 'subject' => $this->subject , 'mailMessage' => str_limit($this->message, 50) , 'avatar' => $this->image]);
        }

        /**
         * Get the array representation of the notification.
         *
         * @param  mixed  $notifiable
         * @return array
         */
        public function toArray($notifiable)
        {
            return [
                //
            ];
        }
    }

I shall be very thankfull if someone could help me on this.


问:
Correct way to block read operations until an external event?
I am working on a devices driver for a data acquisition system. There is a pci device that provides input and output data at the same time at regular intervals. And then the linux mod manages the data in circular buffers that are read and written to through file operations.

The data throughput of the system is relatively low it receives just over 750,000 bytes/second and transmits just over 150,000 bytes per second.

There is a small user space utility that writes and reads data in a loop for testing purposes.

Here is a section of the driver code (All the code related to the circular buffers has been omitted for simplicity sake. PCI device initialization is taken care of elsewhere and pci_interupt not the real entry point for the interrupt handler)

```<code>#include <linux/sched.h>
#include <linux/wait.h>
static DECLARE_WAIT_QUEUE_HEAD(wq_head);
static ssize_t read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos)
{
    DECLARE_WAITQUEUE(wq, current);
    if(count == 0)
        return 0;
    add_wait_queue(&wq_head, &wq);
    do
    {
        set_current_state(TASK_INTERRUPTIBLE);
        if(/*There is any data in the receive buffer*/)
        {
            /*Copy Data from the receive buffer into user space*/
            break;
        }
        schedule();
    } while(1);
    set_current_state(TASK_RUNNING);
    remove_wait_queue(&wq_head, &wq);
    return count;
}
static ssize_t write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos) {
    /* Copy data from userspace into the transmit buffer*/
}
/* This procedure get's called in real time roughly once every 5 milliseconds,
It writes 4k to the receiving buffer and reads 1k from the transmit buffer*/
static void pci_interrupt() {
    /*Copy data from PCI dma buffer to receiving buffer*/
    if(/*There is enough data in the transmit buffer to fill the PCI dma buffer*/) {
        /*Copy from the transmit buffer to the PCI device*/
    } else {
        /*Copy zero's to the PCI device*/
        printk(KERN_ALERT DEVICE_NAME ": Data Underflow. Writing 0's'");
    }
    wake_up_interruptible(&wq_head);
}
</code>```

The above code works well for long periods of time however every 12-18 hours there is a data underflow error. Resulting in zeros being written.

My first thought is that due to the userspace application not being truly real-time the time delay between it's read and write operations occasionally got too large causing the failure. However I tried changing the size of the reads and writes in userspace and changing the niceness of the userspace application this had no effect on the frequency of the error.

Do to the error's nature I believe there is some form of race condition in the three methods above. I am not sure how linux kernel wait queues work.

Is there a decent alternative to the above method for blocking reads or is there something else that is wrong the could cause this behavior.

System Information:

Linux Version: Ubuntu 16.10

Linux Kernel: linux-4.8.0-lowlatency

Chipset: Intel Celeron N3150/N3160 Quad Core 2.08 GHz SoC

TL;DR: The above code hits underflow errors every 12-18 hours is there a better way to do blocking IO or some race condition in the code.

答:
One standard way used in linux can also be used in your case.

User space test program:
 1. open file in blocking mode (default in linux until you specify NONBLOCK flag)
 2. call select() to block on file descriptor.

Kernel driver:
 1. Register interrupt handler which gets invoked whenever there is data available
 2. Handler take lock to protect common buffer between reads/writes and transfer of data
Take a look at these links for source code from ldd3 book test and driver.

Body:
I am working on a devices driver for a data acquisition system. There is a pci device that provides input and output data at the same time at regular intervals. And then the linux mod manages the data in circular buffers that are read and written to through file operations.

The data throughput of the system is relatively low it receives just over 750,000 bytes/second and transmits just over 150,000 bytes per second.

There is a small user space utility that writes and reads data in a loop for testing purposes.

Here is a section of the driver code (All the code related to the circular buffers has been omitted for simplicity sake. PCI device initialization is taken care of elsewhere and pci_interupt not the real entry point for the interrupt handler)

#include <linux/sched.h>
#include <linux/wait.h>
static DECLARE_WAIT_QUEUE_HEAD(wq_head);
static ssize_t read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos)
{
    DECLARE_WAITQUEUE(wq, current);
    if(count == 0)
        return 0;
    add_wait_queue(&wq_head, &wq);
    do
    {
        set_current_state(TASK_INTERRUPTIBLE);
        if(/*There is any data in the receive buffer*/)
        {
            /*Copy Data from the receive buffer into user space*/
            break;
        }
        schedule();
    } while(1);
    set_current_state(TASK_RUNNING);
    remove_wait_queue(&wq_head, &wq);
    return count;
}
static ssize_t write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos) {
    /* Copy data from userspace into the transmit buffer*/
}
/* This procedure get's called in real time roughly once every 5 milliseconds,
It writes 4k to the receiving buffer and reads 1k from the transmit buffer*/
static void pci_interrupt() {
    /*Copy data from PCI dma buffer to receiving buffer*/
    if(/*There is enough data in the transmit buffer to fill the PCI dma buffer*/) {
        /*Copy from the transmit buffer to the PCI device*/
    } else {
        /*Copy zero's to the PCI device*/
        printk(KERN_ALERT DEVICE_NAME ": Data Underflow. Writing 0's'");
    }
    wake_up_interruptible(&wq_head);
}

The above code works well for long periods of time however every 12-18 hours there is a data underflow error. Resulting in zeros being written.

My first thought is that due to the userspace application not being truly real-time the time delay between it's read and write operations occasionally got too large causing the failure. However I tried changing the size of the reads and writes in userspace and changing the niceness of the userspace application this had no effect on the frequency of the error.

Do to the error's nature I believe there is some form of race condition in the three methods above. I am not sure how linux kernel wait queues work.

Is there a decent alternative to the above method for blocking reads or is there something else that is wrong the could cause this behavior.

System Information:

Linux Version: Ubuntu 16.10

Linux Kernel: linux-4.8.0-lowlatency

Chipset: Intel Celeron N3150/N3160 Quad Core 2.08 GHz SoC

TL;DR: The above code hits underflow errors every 12-18 hours is there a better way to do blocking IO or some race condition in the code.


问:
How should I design a program to read from multiple streams of data?
I'm writing a program which uses two different streams of data to perform certain calculations.  I currently have my code set up like this:

```<code>//pseudo c++

class Calculator
{
    //Stream is a class which contains a queue which has new messages added to it
    Stream a, b;

    bool BothQueuesHaveItems() { return !a.IsEmpty() && !b.IsEmpty(); }
    void PerformCalc() { /*Do domething with the first items in a and b*/ }

};

unsigned ThreadFunction(void *stop_event)
{
    Calculator calculator;

    while(WaitForSingleObject(stop_event) == WAIT_OBJECT_0)
    {
        if(calculator.BothQueuesHaveItems())
        {
            calculator.PerformCalc();
        }
        Sleep(5);
    }
}

int main()
{
    Event stop_event = CreateEvent(...);
    CreateThread(ThreadFunction, &stop_event, ...);

    //wait for user enter command to stop processing
    SetEvent(stop_event);
}
</code>```

This doesn't seem like a very good design (particularly the continuous looping in the ThreadFunction whether there are new items in the queues or not), but I'm not exactly sure how to improve it.  Any suggestions would be appreciated.

答:
Don't use IsEmpty, instead just read a character from the stream.  The read will block until a character is ready (at least, in *nix, not sure about Windows).

So something like

```<code>pair <char,char> nextItems() { return make_pair(a.readChar(), b.readChar()); }
</code>```

should work fine.

The only trouble is implementing your stop_event.  nextItems will wait forever, so you'll need to put the reading code in a separate thread and have stop_event exit the process directly.

ContentLicense: CC BY-SA 2.5

Body:
I'm writing a program which uses two different streams of data to perform certain calculations.  I currently have my code set up like this:

//pseudo c++

class Calculator
{
    //Stream is a class which contains a queue which has new messages added to it
    Stream a, b;

    bool BothQueuesHaveItems() { return !a.IsEmpty() && !b.IsEmpty(); }
    void PerformCalc() { /*Do domething with the first items in a and b*/ }

};

unsigned ThreadFunction(void *stop_event)
{
    Calculator calculator;

    while(WaitForSingleObject(stop_event) == WAIT_OBJECT_0)
    {
        if(calculator.BothQueuesHaveItems())
        {
            calculator.PerformCalc();
        }
        Sleep(5);
    }
}

int main()
{
    Event stop_event = CreateEvent(...);
    CreateThread(ThreadFunction, &stop_event, ...);

    //wait for user enter command to stop processing
    SetEvent(stop_event);
}

This doesn't seem like a very good design (particularly the continuous looping in the ThreadFunction whether there are new items in the queues or not), but I'm not exactly sure how to improve it.  Any suggestions would be appreciated.

Body:
Don't use IsEmpty, instead just read a character from the stream.  The read will block until a character is ready (at least, in *nix, not sure about Windows).

So something like

pair <char,char> nextItems() { return make_pair(a.readChar(), b.readChar()); }

should work fine.

The only trouble is implementing your stop_event.  nextItems will wait forever, so you'll need to put the reading code in a separate thread and have stop_event exit the process directly.


问:
display values of array in listview
After watching many tutorials and trying out a lot of code snippets, i am still confused about when and how to use ObservableArray and binding. Trying to get a listview of values from my json array - alert shows them, console displays what i thought it would. the only thing not working is my listview. any assistance by anyone please! posted my javascript and corresponding xml below.

----updated my code. shows an array of six values with one of each in the itemTemplates. how to access every instance? and the keys? need to display key: value pairs and seemingly the keys are missing in the array. anything appreciated!

listview.js

```<code>testJsonArray = {
"results": [{
  "testName": "Multiplizieren",
  "testKlasse": 3,
  "testFach": "Mathematik"
  },
            {
  "testName": "Addieren",
  "testKlasse": 3,
  "testFach": "Mathematik"
  }]
};

function onPageLoaded(args) {
var page = args.object;

var observableArray = require("data/observable-array");
var i = testJsonArray.results.length;

var tests = new observableArray.ObservableArray([]);

while (i--) {
t = testJsonArray.results[i];
tests.push([t.testName, t.testKlasse, t.testFach]);
};

var c = tests.length;
while (c--) {
console.log(c);
};

alert(tests);

page.bindingContext = {myItems: tests};

}

exports.onPageLoaded = onPageLoaded;
</code>```

listview.xml

```<code><Page xmlns="http://www.nativescript.org/tns.xsd" loaded="onPageLoaded">
<ScrollView>
 <ListView id="listview" items="{{ myItems }}">
    <ListView.itemTemplate>
        <StackLayout orientation="horizontal">
        <Label text="{{ $value }}" />
        </StackLayout>
    </ListView.itemTemplate>
</ListView>
</ScrollView>
</Page>
</code>```

答:
After reworking everything, this works now.

listview.js

```<code>data = [{
"testName": "Multiplizieren",
"testKlasse": 3,
"testFach": "Mathematik"
  },
  {
"testName": "Addieren",
"testKlasse": 3,
"testFach": "Mathematik"
  }]

var Observable = require("data/observable").Observable;
var ObservableArray = require("data/observable-array").ObservableArray;

var page;
var items = new ObservableArray([]);
var pageData = new Observable();

exports.pageLoaded = function(args) {
page = args.object;
page.bindingContext = pageData;

items.push(data);

pageData.set("items", items);

};
</code>```

listview.xml

```<code><Page xmlns="http://schemas.nativescript.org/tns.xsd" xmlns:lv="nativescript-pro-ui/listview" loaded="pageLoaded">

<ActionBar title="TableTest" class="action-bar" />

<lv:RadListView id="listview" items="{{ items }}" class="list-group" pullToRefresh="false" pullToRefreshInitiated="pullToRefreshInitiated">
    <lv:RadListView.listViewLayout>
        <lv:ListViewLinearLayout scrollDirection="Vertical"/>
    </lv:RadListView.listViewLayout>
    <lv:RadListView.itemTemplate>
    <StackLayout>
                <Label text="{{ testName }}" />
                <Label text="{{ testKlasse }}" class="list-group-item-heading"     />
                <Label text="{{ testFach }}" class="list-group-item-text" />
    </StackLayout>
    </lv:RadListView.itemTemplate>
</lv:RadListView>

</Page>
</code>```

Title: display values of array in listview

Body:
After watching many tutorials and trying out a lot of code snippets, i am still confused about when and how to use ObservableArray and binding. Trying to get a listview of values from my json array - alert shows them, console displays what i thought it would. the only thing not working is my listview. any assistance by anyone please! posted my javascript and corresponding xml below.

----updated my code. shows an array of six values with one of each in the itemTemplates. how to access every instance? and the keys? need to display key: value pairs and seemingly the keys are missing in the array. anything appreciated!

listview.js

testJsonArray = {
"results": [{
  "testName": "Multiplizieren",
  "testKlasse": 3,
  "testFach": "Mathematik"
  },
            {
  "testName": "Addieren",
  "testKlasse": 3,
  "testFach": "Mathematik"
  }]
};

function onPageLoaded(args) {
var page = args.object;

var observableArray = require("data/observable-array");
var i = testJsonArray.results.length;

var tests = new observableArray.ObservableArray([]);

while (i--) {
t = testJsonArray.results[i];
tests.push([t.testName, t.testKlasse, t.testFach]);
};

var c = tests.length;
while (c--) {
console.log(c);
};

alert(tests);

page.bindingContext = {myItems: tests};

}

exports.onPageLoaded = onPageLoaded;

listview.xml

<Page xmlns="http://www.nativescript.org/tns.xsd" loaded="onPageLoaded">
<ScrollView>
 <ListView id="listview" items="{{ myItems }}">
    <ListView.itemTemplate>
        <StackLayout orientation="horizontal">

        </StackLayout>
    </ListView.itemTemplate>
</ListView>
</ScrollView>
</Page>

Body:
After reworking everything, this works now.

listview.js

data = [{
"testName": "Multiplizieren",
"testKlasse": 3,
"testFach": "Mathematik"
  },
  {
"testName": "Addieren",
"testKlasse": 3,
"testFach": "Mathematik"
  }]

var Observable = require("data/observable").Observable;
var ObservableArray = require("data/observable-array").ObservableArray;

var page;
var items = new ObservableArray([]);
var pageData = new Observable();

exports.pageLoaded = function(args) {
page = args.object;
page.bindingContext = pageData;

items.push(data);

pageData.set("items", items);

};

listview.xml

<Page xmlns="http://schemas.nativescript.org/tns.xsd" xmlns:lv="nativescript-pro-ui/listview" loaded="pageLoaded">

<ActionBar title="TableTest" class="action-bar" />

<lv:RadListView id="listview" items="{{ items }}" class="list-group" pullToRefresh="false" pullToRefreshInitiated="pullToRefreshInitiated">
    <lv:RadListView.listViewLayout>
        <lv:ListViewLinearLayout scrollDirection="Vertical"/>
    </lv:RadListView.listViewLayout>
    <lv:RadListView.itemTemplate>
    <StackLayout>
                <Label text="{{ testName }}" />
                <Label text="{{ testKlasse }}" class="list-group-item-heading"     />
                <Label text="{{ testFach }}" class="list-group-item-text" />
    </StackLayout>
    </lv:RadListView.itemTemplate>
</lv:RadListView>

</Page>


问:
Powerpoint "Save As Picture" from C# Microsoft.Office.Interop.PowerPoint
My question is pretty similar to this one and I'm afraid the answer is the same... I want to save all the shapes/images on a slide as a single png (or jpeg). Programmatically, I get as far as

```<code>slide.Shapes.SelectAll();
</code>```

but don't see a way to save as image. Is this possible? If not, any other suggestions, hopfully w/ examples? (not VBA - I need to automate the whole conversion)

There was a reference to OpenXML in the other post, but I'm not even sure how to pull that in.

答:
I don't know how you'd do this in C# but I'd guess that you'd make use of the same methods as you would with VBA, where you can do:

```<code>Activewindow.Selection.ShapeRange.Export( "c:\temp\delete-me.jpg",ppShapeFormatJPG)
</code>```

ppShapeFormatJPG is a PowerPoint constant, a VBA Long = 1; IIRC that'd be an Integer in C#.

The method also can take two more optional parameters, scalewidth and scaleheight, which govern the width and height of the exported image in undocumented ways. By default, no parms supplied, I get exports at 72 dpi. Larger numbers result in higher pixel count exports but distorted proportions. I'm sure there's some strange logic to it, but it escapes me; all hints welcome!

There's a third optional parm, ExportMode. In my tests, it makes no difference whether you supply it or not, and if you do, which of the available values you choose.

Body:
My question is pretty similar to this one and I'm afraid the answer is the same... I want to save all the shapes/images on a slide as a single png (or jpeg). Programmatically, I get as far as

slide.Shapes.SelectAll();

but don't see a way to save as image. Is this possible? If not, any other suggestions, hopfully w/ examples? (not VBA - I need to automate the whole conversion)

There was a reference to OpenXML in the other post, but I'm not even sure how to pull that in.

Body:
I don't know how you'd do this in C# but I'd guess that you'd make use of the same methods as you would with VBA, where you can do:

Activewindow.Selection.ShapeRange.Export( "c:\temp\delete-me.jpg",ppShapeFormatJPG)

ppShapeFormatJPG is a PowerPoint constant, a VBA Long = 1; IIRC that'd be an Integer in C#.

The method also can take two more optional parameters, scalewidth and scaleheight, which govern the width and height of the exported image in undocumented ways. By default, no parms supplied, I get exports at 72 dpi. Larger numbers result in higher pixel count exports but distorted proportions. I'm sure there's some strange logic to it, but it escapes me; all hints welcome!

There's a third optional parm, ExportMode. In my tests, it makes no difference whether you supply it or not, and if you do, which of the available values you choose.


问:
Limiting Jenkins pipeline to running only on specific nodes
I'm building jobs that will be using Jenkins piplines extensively. Our nodes are designated per project by their tags, but unlike regular jobs the pipeline build does not seem to have  the "Restrict where this project can be run" checkbox. How can I specify on which node the pipeline will run the way I do for regular jobs?</p>

答:
Choosing a node which has the label X in a declarative pipeline with json format:

```<code>pipeline {
    agent { label 'X' }
...
...
}
</code>```

You also can apply multiple labels with or (||) or with and (&&) operator.

Running the job on any of the nodes which has label X or label Y:

```<code>agent { label 'X || Y' }
</code>```

Running the job only on nodes which have both label:

```<code>agent { label 'X && Y' }
</code>```

More in the Jenkins Pipeline reference guide.

ps: if you are reading this you probably have just started using Jenkins pipeline and you are not sure if you should use declarative or scripted pipeline. Short answer: it's better to start with declarative. From jenkins.io:

Declarative and Scripted Pipelines are constructed fundamentally
differently. Declarative Pipeline is a more recent feature of Jenkins
Pipeline which:

provides richer syntactical features over Scripted Pipeline syntax, and

is designed to make writing and reading Pipeline code easier.

Body:
Choosing a node which has the label X in a declarative pipeline with json format:

pipeline {
    agent { label 'X' }
...
...
}

You also can apply multiple labels with or (||) or with and (&&) operator.

Running the job on any of the nodes which has label X or label Y:

agent { label 'X || Y' }

Running the job only on nodes which have both label:

agent { label 'X && Y' }

More in the Jenkins Pipeline reference guide.

ps: if you are reading this you probably have just started using Jenkins pipeline and you are not sure if you should use declarative or scripted pipeline. Short answer: it's better to start with declarative. From jenkins.io:

Declarative and Scripted Pipelines are constructed fundamentally
differently. Declarative Pipeline is a more recent feature of Jenkins
Pipeline which:

provides richer syntactical features over Scripted Pipeline syntax, and

is designed to make writing and reading Pipeline code easier.


问:
AWS ECS tasks keep starting and stopping
I am trying to use ECS for deployment with travis.
At one point everything was working but now it stopped.

I am following this tutorial https://testdriven.io/part-five-ec2-container-service/

There are 2 tasks that keep stopping and starting.

These are the messages I see in tasks:

```<code>STOPPED (CannotStartContainerError: API error (500): oci ru)

STOPPED (Essential container in task exited)
</code>```

These are the messages I see in the logs:

```<code>FATAL: could not write to file "pg_wal/xlogtemp.28": No space left on device

container_linux.go:262: starting container process caused "exec: \"./entrypoint.sh\": permission denied"
</code>```

Why is ECS stopping and starting so many new tasks? This was not happening before.

This is my docker_deploy.sh from my main microservice which I am calling via travis.

```<code>#!/bin/sh

if [ -z "$TRAVIS_PULL_REQUEST" ] || [ "$TRAVIS_PULL_REQUEST" == "false" ];
then

    if [ "$TRAVIS_BRANCH" == "staging" ];
    then
        JQ="jq --raw-output --exit-status"

        configure_aws_cli() {
            aws --version
            aws configure set default.region us-east-1
            aws configure set default.output json
            echo "AWS Configured!"
        }

        make_task_def() {
            task_template=$(cat ecs_taskdefinition.json)
            task_def=$(printf "$task_template" $AWS_ACCOUNT_ID $AWS_ACCOUNT_ID)
            echo "$task_def"
        }

        register_definition() {
            if revision=$(aws ecs register-task-definition --cli-input-json "$task_def" --family $family | $JQ '.taskDefinition.taskDefinitionArn');
            then
                echo "Revision: $revision"
            else
                echo "Failed to register task definition"
                return 1
            fi
        }

        deploy_cluster() {

            family="testdriven-staging"
            cluster="ezasdf-staging"
            service="ezasdf-staging"

            make_task_def
            register_definition

            if [[ $(aws ecs update-service --cluster $cluster --service $service --task-definition $revision | $JQ '.service.taskDefinition') != $revision ]];
            then
                echo "Error updating service."
                return 1
            fi

        }

        configure_aws_cli
        deploy_cluster

    fi
fi
</code>```

This is my Dockerfile from my users microservice:

```<code>FROM python:3.6.2

# install environment dependencies
RUN apt-get update -yqq \
    && apt-get install -yqq --no-install-recommends \
        netcat \
    && apt-get -q clean

# set working directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# add requirements (to leverage Docker cache)
ADD ./requirements.txt /usr/src/app/requirements.txt

# install requirements
RUN pip install -r requirements.txt

# add entrypoint.sh
ADD ./entrypoint.sh /usr/src/app/entrypoint.sh
RUN chmod +x /usr/src/app/entrypoint.sh

# add app
ADD . /usr/src/app

# run server
CMD ["./entrypoint.sh"]
</code>```

entrypoint.sh:

```<code>#!/bin/sh

echo "Waiting for postgres..."

while ! nc -z users-db 5432;
do
    sleep 0.1
done

echo "PostgreSQL started"

python manage.py recreate_db
python manage.py seed_db
gunicorn -b 0.0.0.0:5000 manage:app
</code>```

I tried deleting my cluster and deregistering my tasks and restarting but ECS still continuously stops and starts new tasks now.

When it was working fine: the difference was that instead of the CMD ["./entrypoint.sh"] in my Dockerfile, I had

```<code>RUN python manage.py recreate_db
RUN python manage.py seed_db
CMD gunicorn -b 0.0.0.0:5000 manage:app
</code>```

travis is passing.

答:
The errors are right there.

You don't have enough space on your host; and the entrypoint.sh file is being denied.

Ensure your host has enough disk space (Shell in and df -h to check and expand the volume or just bring up a new instance with more space) and for the entrypoint.sh ensure that when building your image it is executable chmod +x and also is readable by the user the container is running as.

Test your containers locally first; the second error should have been caught in development instantly.

Body:
I am trying to use ECS for deployment with travis.
At one point everything was working but now it stopped.

I am following this tutorial https://testdriven.io/part-five-ec2-container-service/

There are 2 tasks that keep stopping and starting.

These are the messages I see in tasks:

STOPPED (CannotStartContainerError: API error (500): oci ru)

STOPPED (Essential container in task exited)

These are the messages I see in the logs:

FATAL: could not write to file "pg_wal/xlogtemp.28": No space left on device

container_linux.go:262: starting container process caused "exec: \"./entrypoint.sh\": permission denied"

Why is ECS stopping and starting so many new tasks? This was not happening before.

This is my docker_deploy.sh from my main microservice which I am calling via travis.

#!/bin/sh

if [ -z "$TRAVIS_PULL_REQUEST" ] || [ "$TRAVIS_PULL_REQUEST" == "false" ];
then

    if [ "$TRAVIS_BRANCH" == "staging" ];
    then
        JQ="jq --raw-output --exit-status"

        configure_aws_cli() {
            aws --version
            aws configure set default.region us-east-1
            aws configure set default.output json
            echo "AWS Configured!"
        }

        make_task_def() {
            task_template=$(cat ecs_taskdefinition.json)
            task_def=$(printf "$task_template" $AWS_ACCOUNT_ID $AWS_ACCOUNT_ID)
            echo "$task_def"
        }

        register_definition() {
            if revision=$(aws ecs register-task-definition --cli-input-json "$task_def" --family $family | $JQ '.taskDefinition.taskDefinitionArn');
            then
                echo "Revision: $revision"
            else
                echo "Failed to register task definition"
                return 1
            fi
        }

        deploy_cluster() {

            family="testdriven-staging"
            cluster="ezasdf-staging"
            service="ezasdf-staging"

            make_task_def
            register_definition

            if [[ $(aws ecs update-service --cluster $cluster --service $service --task-definition $revision | $JQ '.service.taskDefinition') != $revision ]];
            then
                echo "Error updating service."
                return 1
            fi

        }

        configure_aws_cli
        deploy_cluster

    fi
fi

This is my Dockerfile from my users microservice:

FROM python:3.6.2

# install environment dependencies
RUN apt-get update -yqq \
    && apt-get install -yqq --no-install-recommends \
        netcat \
    && apt-get -q clean

# set working directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# add requirements (to leverage Docker cache)
ADD ./requirements.txt /usr/src/app/requirements.txt

# install requirements
RUN pip install -r requirements.txt

# add entrypoint.sh
ADD ./entrypoint.sh /usr/src/app/entrypoint.sh
RUN chmod +x /usr/src/app/entrypoint.sh

# add app
ADD . /usr/src/app

# run server
CMD ["./entrypoint.sh"]

entrypoint.sh:

#!/bin/sh

echo "Waiting for postgres..."

while ! nc -z users-db 5432;
do
    sleep 0.1
done

echo "PostgreSQL started"

python manage.py recreate_db
python manage.py seed_db
gunicorn -b 0.0.0.0:5000 manage:app

I tried deleting my cluster and deregistering my tasks and restarting but ECS still continuously stops and starts new tasks now.

When it was working fine: the difference was that instead of the CMD ["./entrypoint.sh"] in my Dockerfile, I had

RUN python manage.py recreate_db
RUN python manage.py seed_db
CMD gunicorn -b 0.0.0.0:5000 manage:app

travis is passing.


问:
Running Shell Script having multiple programs dynamically in parallel
I have a shell script which captures the Process ID, CPU and Memory of the JVM every nth second and writes the output to a file. Below is my code:

```<code>JVM="aaa001_bcdefx01"
systime=$(date +"%m-%d-%y-%T")
for i in {1..10}
do
PID=`ps -auxwww | grep "jdk" |  grep $JVM | grep -v grep | cut -c -30 | awk '{print  $2}'`
MEM=`ps -auxwww | grep "jdk" |  grep $JVM | grep -v grep | cut -c -30 | awk '{print  $4 }'`
CPU=`ps -auxwww | grep "jdk" |  grep $JVM | grep -v grep | cut -c -30 | awk '{print  $3 }'`
printf '%-5s %-20s %-20s %-20s %-20s \n' "$systime $JVM $PID $CPU $MEM "  >> $LOGFILE
sleep 5
done
</code>```

This run perfectly fine when i have only one JVM in that server. How can i execute the same script in parallel and fetch the details if i have multiple JVM for a server.

I looked for some solutions and found & to be used in the script but couldn't understand how this can be implemented to my above script. Let's say I have 5 JVMs. How can i run the script and fetch the stats in parallel for all the below JVMs in parallel. Kindly guide. Any help would be appreciated.

```<code>JVM="aaa001_bcdefx01"
JVM="aaa002_bcdefx01"
JVM="aaa003_bcdefx01"
JVM="aaa004_bcdefx01"
JVM="aaa005_bcdefx01"
</code>```

答:
How about using subshell?

Each JVM shell script should go inside '(' and ')'. Put '&' at the end so that it executes in the background.

An example is given here.

```<code>#!/bin/bash
echo > testfile.txt
echo "execute subshell 1"
(
#JVM 1 should go here
sleep 10
echo "subshell 1" >> testfile
)&

echo "execute subshell 2"
(
#JVM 2 should go here
sleep 10
echo "subshell 2" >> testfile
)&

echo "execute subshell 3"
(
#JVM 3 should go here
sleep 10
echo "subhsell 3" >> testfile
)&
</code>```

Here each subshell writes data to testfile.txt after waiting for 10 seconds.

Body:
I have a shell script which captures the Process ID, CPU and Memory of the JVM every nth second and writes the output to a file. Below is my code:

JVM="aaa001_bcdefx01"
systime=$(date +"%m-%d-%y-%T")
for i in {1..10}
do
PID=`ps -auxwww | grep "jdk" |  grep $JVM | grep -v grep | cut -c -30 | awk '{print  $2}'`
MEM=`ps -auxwww | grep "jdk" |  grep $JVM | grep -v grep | cut -c -30 | awk '{print  $4 }'`
CPU=`ps -auxwww | grep "jdk" |  grep $JVM | grep -v grep | cut -c -30 | awk '{print  $3 }'`
printf '%-5s %-20s %-20s %-20s %-20s \n' "$systime $JVM $PID $CPU $MEM "  >> $LOGFILE
sleep 5
done

This run perfectly fine when i have only one JVM in that server. How can i execute the same script in parallel and fetch the details if i have multiple JVM for a server.

I looked for some solutions and found & to be used in the script but couldn't understand how this can be implemented to my above script. Let's say I have 5 JVMs. How can i run the script and fetch the stats in parallel for all the below JVMs in parallel. Kindly guide. Any help would be appreciated.

JVM="aaa001_bcdefx01"
JVM="aaa002_bcdefx01"
JVM="aaa003_bcdefx01"
JVM="aaa004_bcdefx01"
JVM="aaa005_bcdefx01"

Body:
How about using subshell?

Each JVM shell script should go inside '(' and ')'. Put '&' at the end so that it executes in the background.

An example is given here.

#!/bin/bash
echo > testfile.txt
echo "execute subshell 1"
(
#JVM 1 should go here
sleep 10
echo "subshell 1" >> testfile
)&

echo "execute subshell 2"
(
#JVM 2 should go here
sleep 10
echo "subshell 2" >> testfile
)&

echo "execute subshell 3"
(
#JVM 3 should go here
sleep 10
echo "subhsell 3" >> testfile
)&

Here each subshell writes data to testfile.txt after waiting for 10 seconds.


问:
XStream - Make a class in custom converter (unmarshal)
I'm programming a Java application and using XStream, I need to make the entire Unmarshal on my own, I could make the code to get the XML propertie but there is a problem: I can't take the other class (Agent).

I've tried "reader.getValue()" and then take the XML into the Device tag, but it does't work.

XML:

```<code><Device dev_id="99999">
    <Agent>
        <Name>PPPOOOLLL</Name>
        <Enable>1</Enable>
        <MAC>FF:FF:FF:FF:FF:FF</MAC>
        <IMEI/>
        <Addr>222.222.1.117</Addr>
        <LocalAddr>222.222.1.117</LocalAddr>
        <Port>80</Port>
        <LocalPort>80</LocalPort>
        <Username/>
        <Passwd/>
        <Mask>444.444.444.0</Mask>
        <GW>555.555.1.1</GW>
        <Model devtype_id="88">TTTYYYUUU2 3268</Model>
        <Incon incon_id="8">HWg PUSH via HTML</Incon>
        <LogPer>60</LogPer>
        <DatalogPer>3600</DatalogPer>
        <Push push_id="1">Default</Push>
        <Status>2</Status>
        <Alias>XXXYYYVVV</Alias>
        <Description/>
    </Agent>
</Device>
</code>```

Now, my code is like this, and I don't know how I could get the Agent tag and transform it into a java class.

```<code>public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        DevicePai devicePai = new DevicePai();
        devicePai.setDev_id(reader.getAttribute("dev_id"));
        devicePai.setAgent( ??? );
        return devicePai;
    }
</code>```

I can't change the way I'm programming this nor the API I'm using, I need to make the unmarshal. Every other aspect of my code is ok, I tested, but if you have something in mind I may have forgot, please tell me and I'll check asap. :)

答:
Source: http://x-stream.github.io/converter-tutorial.html#ComplexConverter

I could take every attribute of my class by doing moveDown() and moveUp(). I've learned that when you use moveDown(), the object moves the cursor to the next non-read child, so what I had to do was make a loop to moveDown and moveUp as many as the tag agent allows. my code is now:

```<code>public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

    DevicePai devicePai = new DevicePai();
    devicePai.setDev_id(reader.getAttribute("dev_id"));

    reader.moveDown();
    Agent agent = new Agent();
    while (reader.hasMoreChildren()) {
        reader.moveDown();
        agentFieldContructor(agent, reader.getNodeName(), reader.getValue());
        reader.moveUp();
    }

    devicePai.setAgent(agent);
    reader.moveUp();
</code>```

agentFieldConstructor() is a metod that add to agent the specified field pass through parameter, it's just a switch-case block.

Update 12/14/2017:

A second and better answer. I can tell to XStream automatcly convert the Agent tag, so I'm taking "dev_id" and after, all I need to do is call "context":

Agent newAgent = (Agent) context.convertAnother(devicePai, Agent.class);

And now I need to set the device attribute:

devicePai.setAgent(newAgent);

Nothing was done manualy, and my unmarshal method endup like this:

```<code>public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

    DevicePai devicePai = new DevicePai();
    devicePai.setDev_id(reader.getAttribute("dev_id");

    reader.moveDown();
    Agent newAgent = (Agent) context.convertAnother(devicePai, Agent.class));
    devicePai.setAgent(newAgent);
    reader.moveUp();

    return devicePai;

}
</code>```

Body:
I'm programming a Java application and using XStream, I need to make the entire Unmarshal on my own, I could make the code to get the XML propertie but there is a problem: I can't take the other class (Agent).

I've tried "reader.getValue()" and then take the XML into the Device tag, but it does't work.

XML:

<Device dev_id="99999">
    <Agent>
        <Name>PPPOOOLLL</Name>
        <Enable>1</Enable>
        <MAC>FF:FF:FF:FF:FF:FF</MAC>
        <IMEI/>
        <Addr>222.222.1.117</Addr>
        <LocalAddr>222.222.1.117</LocalAddr>
        <Port>80</Port>
        <LocalPort>80</LocalPort>
        <Username/>
        <Passwd/>
        <Mask>444.444.444.0</Mask>
        <GW>555.555.1.1</GW>
        <Model devtype_id="88">TTTYYYUUU2 3268</Model>
        <Incon incon_id="8">HWg PUSH via HTML</Incon>
        <LogPer>60</LogPer>
        <DatalogPer>3600</DatalogPer>
        <Push push_id="1">Default</Push>
        <Status>2</Status>
        <Alias>XXXYYYVVV</Alias>
        <Description/>
    </Agent>
</Device>

Now, my code is like this, and I don't know how I could get the Agent tag and transform it into a java class.

public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        DevicePai devicePai = new DevicePai();
        devicePai.setDev_id(reader.getAttribute("dev_id"));
        devicePai.setAgent( ??? );
        return devicePai;
    }

I can't change the way I'm programming this nor the API I'm using, I need to make the unmarshal. Every other aspect of my code is ok, I tested, but if you have something in mind I may have forgot, please tell me and I'll check asap. :)

Body:
Source: http://x-stream.github.io/converter-tutorial.html#ComplexConverter

I could take every attribute of my class by doing moveDown() and moveUp(). I've learned that when you use moveDown(), the object moves the cursor to the next non-read child, so what I had to do was make a loop to moveDown and moveUp as many as the tag agent allows. my code is now:

public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

    DevicePai devicePai = new DevicePai();
    devicePai.setDev_id(reader.getAttribute("dev_id"));

    reader.moveDown();
    Agent agent = new Agent();
    while (reader.hasMoreChildren()) {
        reader.moveDown();
        agentFieldContructor(agent, reader.getNodeName(), reader.getValue());
        reader.moveUp();
    }

    devicePai.setAgent(agent);
    reader.moveUp();

agentFieldConstructor() is a metod that add to agent the specified field pass through parameter, it's just a switch-case block.

Update 12/14/2017:

A second and better answer. I can tell to XStream automatcly convert the Agent tag, so I'm taking "dev_id" and after, all I need to do is call "context":

Agent newAgent = (Agent) context.convertAnother(devicePai, Agent.class);

And now I need to set the device attribute:

devicePai.setAgent(newAgent);

Nothing was done manualy, and my unmarshal method endup like this:

public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

    DevicePai devicePai = new DevicePai();
    devicePai.setDev_id(reader.getAttribute("dev_id");

    reader.moveDown();
    Agent newAgent = (Agent) context.convertAnother(devicePai, Agent.class));
    devicePai.setAgent(newAgent);
    reader.moveUp();

    return devicePai;

}


问:
how to add a class to post_class();
How can I add the bootstrap class md-col-9 to this element when the classes are being pulled through by php?</p>

```<code><li <?php post_class(); ?>>
</li>
</code>```

答:
I figured it out it's actually very simple. I added my class like this: </p>

```<code><li <?php post_class('col-md-9'); ?>>
</li>
</code>```

Title: how to add a class to post_class();

Body:
How can I add the bootstrap class md-col-9 to this element when the classes are being pulled through by php?

<li <?php post_class(); ?>>

Body:
I figured it out it's actually very simple. I added my class like this:

<li <?php post_class('col-md-9'); ?>>
</li>


问:
Get deeply nested object from JSON
Basically I'm doing some webscraping using HTMLAgilityPack and I'm getting a huge json as a string, which I then convert into a JObjectusing the json.net package.

Now somewhere deeply within said JObject there are some objects I want. But since it is very deeply nested, I wanted to know if there is actually a way to get to those objects, not knowing where exactly within the JObject they are. All I know is their name. Is there any way for me to do some kind of search within the whole JObject, just knowing the object/property names I'm looking for?

Sadly I wasn't able to find any related questions/documented methods I could make use of.

答:
This might work for you:

```<code>private JToken GetValueByKey(JObject jObject, string key)
{
    foreach (KeyValuePair<string, JToken> jProperty in jObject)
    {
        if (jProperty.Key.Equals(key))
        {
            return jProperty.Value;
        }
        else if (jProperty.Value is JObject)
        {
            return GetValueByKey((JObject)jProperty.Value, key);
        }
    }
    return null;
}
</code>```

It takes the JObject you want to search for a key in. and the key you want to search for.
It maps all the properties in the JObject to see or it matches the key, if it doesn't it will check or the current property can be cast to a JObject. in case it can be cast to a JObject it will check for all that JObjects values or your key matches.

if a match is found it will return the Value matching your key.

if no match is found after cycling through all properties in your JObject it will return null.

Title: Get deeply nested object from JSON

Body:
This might work for you:

private JToken GetValueByKey(JObject jObject, string key)
{
    foreach (KeyValuePair<string, JToken> jProperty in jObject)
    {
        if (jProperty.Key.Equals(key))
        {
            return jProperty.Value;
        }
        else if (jProperty.Value is JObject)
        {
            return GetValueByKey((JObject)jProperty.Value, key);
        }
    }
    return null;
}

It takes the JObject you want to search for a key in. and the key you want to search for.
It maps all the properties in the JObject to see or it matches the key, if it doesn't it will check or the current property can be cast to a JObject. in case it can be cast to a JObject it will check for all that JObjects values or your key matches.

if a match is found it will return the Value matching your key.

if no match is found after cycling through all properties in your JObject it will return null.


问:
Is there a setting on JSON Covert to throw any error if json is malformed
I have the following json which is malformed, which has missing property value, I want JSON.Convert to throw an error while deserializing, but instead phoneNumber is replaced with null when deserialize to strongly typed Object Person, and with dynamic type the value of phoneNumber  is replaced with {}, I have tried various JsonSerializerSettings but doesn't seem to help throw an error, is there a way to do this

```<code>var json=    {
      "firstName": "joe",
      "lastName": "doe",
      "phoneNumber": ,
      "email": "joe.doe@test.com"
    }
JsonConvert.DeserializeObject<Person>(json);
JsonConvert.DeserializeObject<Dynamic>(json);
</code>```

答:
This might be a bit of a work around, but you can mark it with an attribute that a value is required. Which migh or might not work for you depending on your exact case:</p>

```<code>public class Videogame
{
    [JsonProperty(Required = Required.Always)]
    public string Name { get; set; }

    [JsonProperty(Required = Required.AllowNull)]
    public DateTime? ReleaseDate { get; set; }
}
</code>```

Body:
I have the following json which is malformed, which has missing property value, I want JSON.Convert to throw an error while deserializing, but instead phoneNumber is replaced with null when deserialize to strongly typed Object Person, and with dynamic type the value of phoneNumber  is replaced with {}, I have tried various JsonSerializerSettings but doesn't seem to help throw an error, is there a way to do this

var json=    {
      "firstName": "joe",
      "lastName": "doe",
      "phoneNumber": ,
      "email": "joe.doe@test.com"
    }
JsonConvert.DeserializeObject<Person>(json);
JsonConvert.DeserializeObject<Dynamic>(json);

Body:
This might be a bit of a work around, but you can mark it with an attribute that a value is required. Which migh or might not work for you depending on your exact case:

public class Videogame
{
    [JsonProperty(Required = Required.Always)]
    public string Name { get; set; }

    [JsonProperty(Required = Required.AllowNull)]
    public DateTime? ReleaseDate { get; set; }
}


问:
Git checkout: updating paths is incompatible with switching branches
My problem is related to Fatal Git error when switching branch.

I try to fetch a remote branch with the command

```<code>git checkout -b local-name origin/remote-name
</code>```

but I get this error message:

fatal: git checkout: updating paths is incompatible with switching branches.

  Did you intend to checkout 'origin/remote-name' which can not be resolved as commit?

If I manually create a branch and then pull the remote branch, it works, just as making a new clone and checking the branch out.

Why does it not work on the repository I work with?

答:
For me I had a typo and my remote branch didn't exist

Use git branch -a to list remote branches

Body:
My problem is related to Fatal Git error when switching branch.

I try to fetch a remote branch with the command

git checkout -b local-name origin/remote-name

but I get this error message:

fatal: git checkout: updating paths is incompatible with switching branches.

  Did you intend to checkout 'origin/remote-name' which can not be resolved as commit?

If I manually create a branch and then pull the remote branch, it works, just as making a new clone and checking the branch out.

Why does it not work on the repository I work with?


答:
There is an error in your stack implementation.  In both initStack and grow, you do this:

```<code>malloc(sizeof(void) * max);
</code>```

This is invalid, as void doesn't have a size, although some compilers will evaluate this to 1.  So you aren't allocating enough space for an array of void *.  As a result, you write past the end of allocated memory which invokes undefined behavior.

Change the type you're getting the size of to void * in both places.

```<code>malloc(sizeof(void *) * max);
</code>```

Title: Why crash program by access pointer? In C

Body:
I tried to access a pointer but the program crashes. With memory access error.
I receive the pointer from a stack.  (pop- function). As a void*-pointer.
Why an I getting this behavior?

int main()
{
    int MAX = 5;
    int field[MAX];
    int i; /* for the loop */
    int *pInt = NULL;

    initStack();

    for (i = 0; i < MAX; i++)
    {
        field[i] = i;
        push((field + i));  // HERE CRASH
    }

    for (i = 0; i < MAX; i++)
    {
        pInt = pop();   /* fetch next integer */

        printf("%d\n", *pInt); /* print value */
    }

    return EXIT_SUCCESS;
}

UPDATE:

I have tested my stack. And it works. But with for-loops it crashes.

My stack implementation.
I get the error always I access to the pointer.

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#include "stack.h"

/*
   actual stack data structure
   This pointer will pointing at the actual field (of void * pointers)
   that represents the stack.
 */
void **array;

/* the current capacity of the stack */
int max = 10;

/* counter variable for counting the elements of the stack. */
int counter = 0;

/*
    offset address
    points at the top element of the stack.
*/
int offset = -1;

void initStack(void)
{

    array = malloc(sizeof(void) * max);
    assert(array); /* tests whether pointer is assigned to memory. */
}

/*
    grow: increases the stack by 10 elements.
          This utility function isn't part of the public interface
*/
void grow(void)
{
    max += 10; /* increases the capacity */

    int i; // for the loop
    void **tmp = malloc(sizeof(void) * max);

    /* copies the elements from the origin array in the new one. */
    for (i = 0; i < max - 10; i++)
    {
        *(tmp + i) = *(array + i);
    }

    array = tmp; /* setups the new one as basis */
}

/* push: pushs the argument onto the stack */
void push(void *object)
{

    assert(object); /* tests whether pointer isn't null */

    if (offset < max)
    {

        offset++; /* increases the element-pointer */

        /*
            moves pointer by the offset address
            pushes the object onto stack
         */
        *(array + offset) = object;
    }
    else /* stack is full */
    {

        /* TODO */
        grow();
        push(object); /* recursive call */
    }
}

/*
    pop: pops the top element of the stack from the stack.
*/
void *pop(void)
{
    printf("\tBEFORE\n"); //DEBUG
    void *top = *(array + offset);
    assert(top);
    assert(array + offset);
    printf("\tAFTER  void *top = *(array + offset);\n"); //DEBUG
    // int *pInt = top;
    // printf("\tpop: value= %d\n", *top); /* DEBUG */

    /* decreases the offset address for pointing of
        the new top element */
    offset--;

    return top;
}

Body:
There is an error in your stack implementation.  In both initStack and grow, you do this:

malloc(sizeof(void) * max);

This is invalid, as void doesn't have a size, although some compilers will evaluate this to 1.  So you aren't allocating enough space for an array of void *.  As a result, you write past the end of allocated memory which invokes undefined behavior.

Change the type you're getting the size of to void * in both places.

malloc(sizeof(void *) * max);


问:
PHP Echo SUM session value & form select
I have a PHP echo statement of a session value like this:

<?php echo $userinfo['RenewAgreementAmount'] ;?>

I have a form select element like this:

```<code><select id="Lock" name="Lock">
                      <option value="1" selected="selected">1 Year</option>
                      <option value="2">2 Years</option>
                      <option value="3">3 Years</option>
                      <option value="4">4 Years</option>
                    </select>
</code>```

I'm trying to update the <?php echo $userinfo['RenewAgreementAmount'] ;?> output by taking what the user selects in the select value id Lock with this session value while interacting with the form?

I've tried <?php echo ($userinfo['RenewAgreementAmount'] * #Lock) ;?> with no luck.

What is the easiest way to update this value as the user interacts with the select form input in real time?

答:
it's because your PHP is interpretted before your HTML. That's the whole point of PHP. One way you can work around that is to store your $userinfo['RenewAgreementAmount'] into a Javascript variable and works with this variable. EX:

```<code><script>var RenewAgreementAmount = <?php echo $userinfo['RenewAgreementAmount'] ?></script>
</code>```

And then, you can put the value of the newly created RenewAgreementAmount javascript variable where you want to show it using :

```<code><span id="renewAgreementAmountField"></span>
<script>
    document.getElementById("renewAgreementAmountField").innerHTML = RenewAgreementAmount
</script>
</code>```

You can then work with your variable and change the value.

```<code>RenewAgreementAmount = RenewAgreementAmount * document.getElementById("Lock").value;
</code>```

If you want to update the value on the server side, you can use an AJAX request ( XMLHttpRequest in plain Javascript) with your new variable.

Body:
I have a PHP echo statement of a session value like this:

<?php echo $userinfo['RenewAgreementAmount'] ;?>

I have a form select element like this:

<select id="Lock" name="Lock">
                      <option value="1" selected="selected">1 Year</option>
                      <option value="2">2 Years</option>
                      <option value="3">3 Years</option>
                      <option value="4">4 Years</option>
                    </select>

I'm trying to update the <?php echo $userinfo['RenewAgreementAmount'] ;?> output by taking what the user selects in the select value id Lock with this session value while interacting with the form?

I've tried <?php echo ($userinfo['RenewAgreementAmount'] * #Lock) ;?> with no luck.

What is the easiest way to update this value as the user interacts with the select form input in real time?

Body:
it's because your PHP is interpretted before your HTML. That's the whole point of PHP. One way you can work around that is to store your $userinfo['RenewAgreementAmount'] into a Javascript variable and works with this variable. EX:

<script>var RenewAgreementAmount = <?php echo $userinfo['RenewAgreementAmount'] ?></script>

And then, you can put the value of the newly created RenewAgreementAmount javascript variable where you want to show it using :

<span id="renewAgreementAmountField"></span>
<script>
    document.getElementById("renewAgreementAmountField").innerHTML = RenewAgreementAmount
</script>

You can then work with your variable and change the value.

RenewAgreementAmount = RenewAgreementAmount * document.getElementById("Lock").value;

If you want to update the value on the server side, you can use an AJAX request ( XMLHttpRequest in plain Javascript) with your new variable.


问:
Google Firestore a subset or superset of Google Cloud Datastore?
Google announced Firestore, the new document datastore on the block.

I have been developing an application using Google Cloud Datastore for over six months now and after reading the blog, I feel Firestore seems to be a better choice.

The concept of the alternate collection-document-subcollection looks excellent to me because while designing schema for datastore I was aware I will be unable to query nested fields. Now with firestore subcollections, I get full query capabilities which is a game changer for me (I can get maximum data with minimum queries).

As a counter argument, the flowchart suggests me to use datastore because I do not have any mobile clients.

Will it be a good idea to use Firestore just like Datastore ?
(I will conveniently ignore the mobile client/realtime updates/syncing features!)

答:
Update 2 (01/31/19)

As of today, Cloud Firestore is no longer in Beta and is Generally Available:
https://cloud.google.com/blog/products/databases/announcing-cloud-firestore-general-availability-and-updates

This means that Cloud Datastore is no longer an option for new projects (you can keep using it on existing projects).  New projects that want to use the Datastore API can use Cloud Firestore in Datastore mode.

Update 1

As you we have noticed, we've expanded Cloud Firestore since this question was posted.

This means Cloud Firestore now has 2 modes:

The original launch was 'Native mode'

The new launch adds 'Datastore mode'

'Datastore mode' is the 3rd gen of Cloud Datastore. 1st was called Master/Slave Datastore, 2nd was High-Replication Datastore (HRD) that was rebranded as Cloud Datastore in 2013.

The below answer is still largely relevant since both modes are currently mutually exclusive, so you need to pick one or the other.

The main differences are the improves of Cloud Firestore in Datastore mode over Cloud Datastore. The biggest ones are:

Write through-put per entity group now unbounded (was 1 write/second)

Transactions no longer limited to 25 entity groups

All queries now strongly consistent.

Also note Cloud Firestore regardless of mode is beta, so the new Service-Level Agreement (SLA) doesn't go into effect until the product reaches General Availability (GA).

Original Answer

Cloud Datastore (CD) and Cloud Firestore (CF) are similar, however different in significant ways.

CF is mobile-centric with direct from mobile client functionality with the Firebase SDKs and Rules functionality. CD is server-centric with a wider range of server client libraries, as well as some mature frameworks on App Engine Standard that bundle in memcache functionality.

CF has a newer storage layer that is strongly consistency in the same way as Cloud Spanner, however, it's still in beta without an SLA. CD's storage layer is only strongly consistent within entity-groups and eventually consistent across entity-groups, however, it is GA with a 99.95% SLA for the Multi-Region locations.

CF is only available in the US Multi-Region at this time. CD is available Cloud across a dozen locations including places in the Americas, Europe, Asia, and Australia.

CF during beta has a guideline limit of 2500 writes/second while we build experience monitoring and tuning the system prior to GA, whereas CD will happily handle >1M writes/second (please reach out to your account rep first though).

CF and CD's set of query capabilities are overlapping but not the same. Overall CD has a broader set of query capabilities we haven't built in CF yet, so you'd have more flexibility in CD.

Overall, I'd consider this list to see if any of the differences make or break what you're trying to build then pick the DB that fits closest to your needs.


问:
how to add a image to camera overlay view (swift4)
My code right here displays a red line on the top of the imagePicker when taking a photo. I want to do the same thing but add a image in the middle of the red line. See pic. I added the word image in a yellow box as a example of what I am trying to code.

```<code>    @IBAction func takePhoto(_ sender: UIButton) {
    imagePicker =  UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = .camera
    present(imagePicker, animated: true, completion: nil)
    let mainView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height-150))
    let blockView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: 150))
    blockView.backgroundColor = UIColor.red
    mainView.addSubview(blockView)
    imagePicker.cameraOverlayView = mainView
}
</code>```

答:
Just do:

```<code>let frame             = CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: 150)
let blockView         = UIImageView.init(frame: frame)
blockView.contentMode = .scaleAspectFit
blockView.image       = UIImage(named: "NameOfYourImage")  // Just an example.
</code>```

See UIImageView.

The frame above needs adjustment of course, to allow for top and bottom margins you show in your screenshot.

Body:
My code right here displays a red line on the top of the imagePicker when taking a photo. I want to do the same thing but add a image in the middle of the red line. See pic. I added the word image in a yellow box as a example of what I am trying to code.

    @IBAction func takePhoto(_ sender: UIButton) {
    imagePicker =  UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = .camera
    present(imagePicker, animated: true, completion: nil)
    let mainView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height-150))
    let blockView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: 150))
    blockView.backgroundColor = UIColor.red
    mainView.addSubview(blockView)
    imagePicker.cameraOverlayView = mainView
}

Body:
Just do:

let frame             = CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: 150)
let blockView         = UIImageView.init(frame: frame)
blockView.contentMode = .scaleAspectFit
blockView.image       = UIImage(named: "NameOfYourImage")  // Just an example.

See UIImageView.

The frame above needs adjustment of course, to allow for top and bottom margins you show in your screenshot.


问:
Uncompilable source code - Erroneous tree type error and cannot find symbol error
I was getting "Uncompilable source code - Erroneous tree type" error and "cannot
find symbol" error I turned off compile on save and now get cannot find symbol. The area that seems to be breaking it is where I initialize Asteroid() in AsteroidFields generate method, so I feel like my initialization is incorrect but I haven't been able to figure out how.</p>

```<code>package asteroidfield;
import java.util.TreeSet;
import blobzx.BlobGUI;
import blobzx.SandBox;
import blobzx.SandBoxMode;

public class AsteroidField implements BlobGUI {

    SandBox ast;

    public static void main (String [] Args){
        new AsteroidField();
    }

    public AsteroidField (){
        ast = new SandBox();

        ast.setSandBoxMode(SandBoxMode.FLOW);
        ast.setFrameRate(15);
        ast.init(this);

    }

    @Override
    public void generate() {
       // This is the line that is breaking the code.
         Asteroid asteroid = new Asteroid();

    }

}

    package AsteroidField;

    import blobzx.BlobUtils;
    import blobzx.PolyBlob;
    import java.awt.Point;

    import java.util.Random;

    public class Asteroid extends PolyBlob{

    // private static Random random = new Random();

    public Asteroid(int velX, int velY, double rot) {

       super(-100, -100, rot);

       setDelta(velX, velY);

       Random sides = new Random();
       Random dist = new Random();
       int si = sides.nextInt(9 - 5 + 1) + 5;

       int di =  dist.nextInt(15 - 5 + 1) + 5;

       double region = (2 * Math.PI) / si;
       double []angle = new double [si];

       int [] xInt = new int[si];
       int [] yInt = new int[si];
       double [] x = new double [si];
       double [] y = new double [si];
       System.out.print("m");

       for(int i = 0; i < si; i++){

        angle[i] = (i*region)+(Math.random()*region);
        Point cord = BlobUtils.rotatePoint(di, angle[i]);

        x[i] = cord.getX();
        y[i] = cord.getY();
       }
       for (int i = 0; i > x.length; i ++){
        xInt[i] = (int) x[i];
        yInt[i] = (int) y[i];
       }

       setPolygon(xInt, yInt);

       }
      }
</code>```

答:
Recheck the package declarations in all your classes!

This behaviour has been observed in NetBeans, when the package declaration in one of the classes of the package refers to a non-existent or wrong package. NetBeans normally detects and highlights this error but has been known to fail and misleadingly report the package as free of errors when this is not the case.

Body:
I was getting "Uncompilable source code - Erroneous tree type" error and "cannot
find symbol" error I turned off compile on save and now get cannot find symbol. The area that seems to be breaking it is where I initialize Asteroid() in AsteroidFields generate method, so I feel like my initialization is incorrect but I haven't been able to figure out how.

package asteroidfield;
import java.util.TreeSet;
import blobzx.BlobGUI;
import blobzx.SandBox;
import blobzx.SandBoxMode;

public class AsteroidField implements BlobGUI {

    SandBox ast;

    public static void main (String [] Args){
        new AsteroidField();
    }

    public AsteroidField (){
        ast = new SandBox();

        ast.setSandBoxMode(SandBoxMode.FLOW);
        ast.setFrameRate(15);
        ast.init(this);

    }

    @Override
    public void generate() {
       // This is the line that is breaking the code.
         Asteroid asteroid = new Asteroid();

    }

}

    package AsteroidField;

    import blobzx.BlobUtils;
    import blobzx.PolyBlob;
    import java.awt.Point;

    import java.util.Random;

    public class Asteroid extends PolyBlob{

    // private static Random random = new Random();

    public Asteroid(int velX, int velY, double rot) {

       super(-100, -100, rot);

       setDelta(velX, velY);

       Random sides = new Random();
       Random dist = new Random();
       int si = sides.nextInt(9 - 5 + 1) + 5;

       int di =  dist.nextInt(15 - 5 + 1) + 5;

       double region = (2 * Math.PI) / si;
       double []angle = new double [si];

       int [] xInt = new int[si];
       int [] yInt = new int[si];
       double [] x = new double [si];
       double [] y = new double [si];
       System.out.print("m");

       for(int i = 0; i < si; i++){

        angle[i] = (i*region)+(Math.random()*region);
        Point cord = BlobUtils.rotatePoint(di, angle[i]);

        x[i] = cord.getX();
        y[i] = cord.getY();
       }
       for (int i = 0; i > x.length; i ++){
        xInt[i] = (int) x[i];
        yInt[i] = (int) y[i];
       }

       setPolygon(xInt, yInt);

       }
      }


问:
Why must the copy assignment operator return a reference/const reference?
In C++, the concept of returning reference from the copy assignment operator is unclear to me. Why can't the copy assignment operator return a copy of the new object? In addition, if I have class A, and the following:

```<code>A a1(param);
A a2 = a1;
A a3;

a3 = a2; //<--- this is the problematic line
</code>```

The operator= is defined as follows:

```<code>A A::operator=(const A& a)
{
    if (this == &a)
    {
        return *this;
    }
    param = a.param;
    return *this;
}
</code>```

答:
A bit of clarification as to why it's preferable to return by reference for operator= versus return by value --- as the chain a = b = c will work fine if a value is returned.

If you return a reference, minimal work is done. The values from one object are copied to another object.

However, if you return by value for operator=, you will call a constructor AND destructor EACH time that the assignment operator is called!!

So, given:

```<code>A& operator=(const A& rhs) { /* ... */ };
</code>```

Then,

```<code>a = b = c; // calls assignment operator above twice. Nice and simple.
</code>```

But,

```<code>A operator=(const A& rhs) { /* ... */ };

a = b = c; // calls assignment operator twice, calls copy constructor twice, calls destructor type to delete the temporary values! Very wasteful and nothing gained!
</code>```

In sum, there is nothing gained by returning by value, but a lot to lose.

(Note: This isn't meant to address the advantages of having the assignment operator return an lvalue.  Read the other posts for why that might be preferable)

Body:
In C++, the concept of returning reference from the copy assignment operator is unclear to me. Why can't the copy assignment operator return a copy of the new object? In addition, if I have class A, and the following:

A a1(param);
A a2 = a1;
A a3;

a3 = a2; //<--- this is the problematic line

The operator= is defined as follows:

A A::operator=(const A& a)
{
    if (this == &a)
    {
        return *this;
    }
    param = a.param;
    return *this;
}

Body:
A bit of clarification as to why it's preferable to return by reference for operator= versus return by value --- as the chain a = b = c will work fine if a value is returned.

If you return a reference, minimal work is done. The values from one object are copied to another object.

However, if you return by value for operator=, you will call a constructor AND destructor EACH time that the assignment operator is called!!

So, given:

A& operator=(const A& rhs) { /* ... */ };

Then,

a = b = c; // calls assignment operator above twice. Nice and simple.

But,

A operator=(const A& rhs) { /* ... */ };

a = b = c; // calls assignment operator twice, calls copy constructor twice, calls destructor type to delete the temporary values! Very wasteful and nothing gained!

In sum, there is nothing gained by returning by value, but a lot to lose.

(Note: This isn't meant to address the advantages of having the assignment operator return an lvalue.  Read the other posts for why that might be preferable)