问:
How to bind the content first before sending an email as one message?
I have a problem with regards to sending email as one message. The code  reads all of the content from the database but it doesn't send the message as one in the email. It sends repeatedly by how much row/s or data in the database. How can i bind first the content and send it to the email as one? </p>

```<code>  int Quantity = 0;
    string JobName;
    string OrderType;
    DateTime DueDate;

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);

    string cmdText = "SELECT * FROM Shopping_Cart WHERE UID=@UIDD";

    SqlCommand cmd = new SqlCommand(cmdText, con);

    cmd.Parameters.AddWithValue("@UIDD", hfUserID.Value);

    if (con.State == ConnectionState.Closed)
    {
        con.Open();
    }
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[4] {
                        new DataColumn("QUANTITY", typeof(int)),
                        new DataColumn("JOB NAME", typeof(string)),
                        new DataColumn("ORDER TYPE", typeof(string)),
                        new DataColumn("DUE DATE", typeof(DateTime))});

    //===== Execute Query.
    SqlDataReader dr = cmd.ExecuteReader();
    if (Session["UID"] != null)
    {
        while (dr.Read())
        {
            Quantity = dr.GetInt32(4);
            JobName = dr.GetString(10);
            OrderType = dr.GetString(17);
            DueDate = dr.GetDateTime(9);

            dt.Rows.Add(Quantity, JobName, OrderType, DueDate);
        }
        StringBuilder YourTable = new StringBuilder();
        YourTable.Append("Thank you for choosing Junand's Labels Inc. Your order will be evaluated by the manager with the maximum of (3 days). Please wait for the confirmation of the manager in your email whether your order will be acceptable or not. The price will be announced once the order has been accepted. ");
        YourTable.Append("<br>");
        YourTable.Append("<br>");
        YourTable.Append("Order Review");
        YourTable.Append("<table border = '1'>");
        YourTable.Append("<tr>");
        foreach (DataColumn column in dt.Columns)
        {
            YourTable.Append("<th style = 'background-color: #0bd2d1;color:#ffffff'>");
            YourTable.Append(column.ColumnName);
            YourTable.Append("</th>");
        }
        YourTable.Append("</tr>");

        foreach (DataRow row in dt.Rows)
        {
            YourTable.Append("<tr>");
            foreach (DataColumn column in dt.Columns)
            {
                YourTable.Append("<td>");
                YourTable.Append(row[column]);
                YourTable.Append("</td>");

            }
            YourTable.Append("</tr>");
            MailMessage message = new MailMessage();
            message.Body += YourTable;
            message.To.Add(Session["Email"].ToString());
            message.From = new MailAddress("junandscontactus@gmail.com");
            message.Subject = "View your Orders";

            message.IsBodyHtml = true;

            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            client.EnableSsl = true;
            client.Credentials = new System.Net.NetworkCredential("u@gmail.com", "password");

            client.Send(message);

        }

    }
</code>```

<p> Here is the sample output in the email</p>

答:
move the sending of the email

```<code>  client.Send(message);
</code>```

outside of the

```<code>foreach (DataRow row in dt.Rows)
</code>```

loop.

Body:
I have a problem with regards to sending email as one message. The code  reads all of the content from the database but it doesn't send the message as one in the email. It sends repeatedly by how much row/s or data in the database. How can i bind first the content and send it to the email as one?

  int Quantity = 0;
    string JobName;
    string OrderType;
    DateTime DueDate;

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);

    string cmdText = "SELECT * FROM Shopping_Cart WHERE UID=@UIDD";

    SqlCommand cmd = new SqlCommand(cmdText, con);

    cmd.Parameters.AddWithValue("@UIDD", hfUserID.Value);

    if (con.State == ConnectionState.Closed)
    {
        con.Open();
    }
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[4] {
                        new DataColumn("QUANTITY", typeof(int)),
                        new DataColumn("JOB NAME", typeof(string)),
                        new DataColumn("ORDER TYPE", typeof(string)),
                        new DataColumn("DUE DATE", typeof(DateTime))});

    //===== Execute Query.
    SqlDataReader dr = cmd.ExecuteReader();
    if (Session["UID"] != null)
    {
        while (dr.Read())
        {
            Quantity = dr.GetInt32(4);
            JobName = dr.GetString(10);
            OrderType = dr.GetString(17);
            DueDate = dr.GetDateTime(9);

            dt.Rows.Add(Quantity, JobName, OrderType, DueDate);
        }
        StringBuilder YourTable = new StringBuilder();
        YourTable.Append("Thank you for choosing Junand's Labels Inc. Your order will be evaluated by the manager with the maximum of (3 days). Please wait for the confirmation of the manager in your email whether your order will be acceptable or not. The price will be announced once the order has been accepted. ");
        YourTable.Append("
");
        YourTable.Append("
");
        YourTable.Append("Order Review");
        YourTable.Append("
");
        YourTable.Append("
");
        foreach (DataColumn column in dt.Columns)
        {
            YourTable.Append("");
            YourTable.Append(column.ColumnName);
            YourTable.Append("	");
        }
        YourTable.Append("
");

        foreach (DataRow row in dt.Rows)
        {
            YourTable.Append("
");
            foreach (DataColumn column in dt.Columns)
            {
                YourTable.Append("");
                YourTable.Append(row[column]);
                YourTable.Append("	");

            }
            YourTable.Append("
");
            MailMessage message = new MailMessage();
            message.Body += YourTable;
            message.To.Add(Session["Email"].ToString());
            message.From = new MailAddress("junandscontactus@gmail.com");
            message.Subject = "View your Orders";

            message.IsBodyHtml = true;

            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            client.EnableSsl = true;
            client.Credentials = new System.Net.NetworkCredential("u@gmail.com", "password");

            client.Send(message);

        }

    }

 Here is the sample output in the email

Body:
move the sending of the email

  client.Send(message);

outside of the

foreach (DataRow row in dt.Rows)

loop.


来源: stackexchange

问:
Having Trouble Removing Singular Sprites from Groups
right now I'm trying to do two things that involve removing sprites from groups. I want to accomplish two things:

First, I have bullets and powerups. Once my bullet collides with my powerup, I want those specific bullets and powerups to be removed.

Second, if my powerups are not hit after a certain amount of time, then I want them to be removed.

Problem with Goal 1: Once of my bullets collides with a powerup, all my bullets freeze.

Problem with Goal 2: All of my powerups are removed, rather than one powerup at a time.

Here is my Bullet Class:

```<code>class Bullet(Image):

    def __init__(self, screen_size, width, height, filename, color = (255, 0, 0)):

        super().__init__(screen_size, width, height, filename, color = (255, 0, 0))

    def checkCollision(self, powerup):

        return pygame.sprite.collide_mask(self, powerup)

    def removeBullet(self, powerup):
        if self.checkCollision(powerup):
            self.kill()

    def update(self, powerup):
        self.rect.centerx += 3
        self.removeBullet(powerup)
</code>```

Here is my PowerUp Class

```<code>class PowerUp(Image):

    def __init__(self, screen_size, width, height, filename,  color = (255, 0, 0)):

        super().__init__(screen_size, width, height, filename, color = (255, 0 , 0))

        _centerx = random.randint(20, 1100) # <-- local variable _centerx (don't need it in other methods)
        _centery = random.randint(20, 700) # <-- local variable _centery (don't need it in other methods)
        self.radius = 10
        self.rect = pygame.Rect(_centerx-self.radius,
                                _centery-self.radius,
                                self.radius*2, self.radius*2)

    def update(self):

        pass
</code>```

And here is where I run everything:

```<code>class GameScreen(SceneBase):

    def __init__(self):
        SceneBase.__init__(self)

        self.my_font = pygame.font.SysFont("Arial", 50)

        self.bullets_group = pygame.sprite.Group()
        self.powerup_group = pygame.sprite.Group()
        self.player_paddle = classes.PlayerPaddle(screen_size, 20, 100, "naruto.png", self.bullets_group)
        self.ai_paddle = classes.AIPaddle(screen_size, 20, 100, "naruto.png")
        self.pong = classes.Pong(screen_size, 20, 20, "pokeball.png")

        self.now1 = pygame.time.get_ticks()
        self.now2 = pygame.time.get_ticks()

    def ProcessInput(self, events, pressed_keys):
        for event in events:
            self.player_paddle.handle_event(event)

    def Update(self):
        self.player_paddle.update()
        self.ai_paddle.update(self.pong, self.player_paddle)
        self.pong.update(self.player_paddle, self.ai_paddle)

        for powerup in self.powerup_group:
            self.bullets_group.update(powerup)
        self.powerup_group.update()

        # if someone reaches a score of 2, then exit the game
        if self.player_paddle.score == 2 or self.ai_paddle.score == 2:
            SceneBase.is_game_over = True
            self.SwitchToScene(GameOverScreen())

        time_difference1 = pygame.time.get_ticks() - self.now1
        time_difference2 = pygame.time.get_ticks() - self.now2

        if time_difference1 >= 2000:
            self.powerup_group.add(classes.PowerUp(screen_size, 40, 40, "ramen.png"))
            self.now1 = pygame.time.get_ticks()

        for powerup in self.powerup_group:
            if time_difference2 >= 5000:
                self.powerup_group.remove(powerup)
</code>```

if my PlayerPaddle class, if I click on a key, the bullet gets launched from it. However, the bullet is not moving towards the right (like I asked it to do in the Bullet's update function).

```<code>def handle_event(self, event):
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_UP:
            self.direction = -1
        elif event.key == pygame.K_DOWN:
            self.direction = 1
        elif event.key == pygame.K_LEFT:
            self.turnLeft()
        elif event.key == pygame.K_RIGHT:
            self.turnRight()
        elif event.key == pygame.K_u:
            bullet = Bullet(screen_size, 25, 25, "naruto.png", color = (255, 0 , 0))
            bullet.rect.centerx = self.rect.centerx
            bullet.rect.centery = self.rect.centery

            self.bullet_group.add(bullet)
</code>```

答:
Goal 2: You use the same timer for all powerups in

```<code> time_difference2 = pygame.time.get_ticks() - self.now2

 ...

 if time_difference2 >= 5000:
</code>```

so it removes all powerups in the same time.

Every powerup needs own timer inside class. I use name kill_time with current_time+5000

```<code>    time_difference1 = pygame.time.get_ticks() - self.now1

    # ---

    current_time = pygame.time.get_ticks()

    if time_difference1 >= 2000:
        powerup = classes.PowerUp(screen_size, 40, 40, "ramen.png")
        powerup.kill_time = current_time + 5000
        self.powerup_group.add(power)
        self.now1 = pygame.time.get_ticks()

    # ----

    current_time = pygame.time.get_ticks()

    for powerup in self.powerup_group:
        if powerup.kill_time <= current_time:
            self.powerup_group.remove(powerup)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
right now I'm trying to do two things that involve removing sprites from groups. I want to accomplish two things:

First, I have bullets and powerups. Once my bullet collides with my powerup, I want those specific bullets and powerups to be removed.

Second, if my powerups are not hit after a certain amount of time, then I want them to be removed.

Problem with Goal 1: Once of my bullets collides with a powerup, all my bullets freeze.

Problem with Goal 2: All of my powerups are removed, rather than one powerup at a time.

Here is my Bullet Class:

class Bullet(Image):

    def __init__(self, screen_size, width, height, filename, color = (255, 0, 0)):

        super().__init__(screen_size, width, height, filename, color = (255, 0, 0))

    def checkCollision(self, powerup):

        return pygame.sprite.collide_mask(self, powerup)

    def removeBullet(self, powerup):
        if self.checkCollision(powerup):
            self.kill()

    def update(self, powerup):
        self.rect.centerx += 3
        self.removeBullet(powerup)

Here is my PowerUp Class

class PowerUp(Image):

    def __init__(self, screen_size, width, height, filename,  color = (255, 0, 0)):

        super().__init__(screen_size, width, height, filename, color = (255, 0 , 0))

        _centerx = random.randint(20, 1100) # <-- local variable _centerx (don't need it in other methods)
        _centery = random.randint(20, 700) # <-- local variable _centery (don't need it in other methods)
        self.radius = 10
        self.rect = pygame.Rect(_centerx-self.radius,
                                _centery-self.radius,
                                self.radius*2, self.radius*2)

    def update(self):

        pass

And here is where I run everything:

class GameScreen(SceneBase):

    def __init__(self):
        SceneBase.__init__(self)

        self.my_font = pygame.font.SysFont("Arial", 50)

        self.bullets_group = pygame.sprite.Group()
        self.powerup_group = pygame.sprite.Group()
        self.player_paddle = classes.PlayerPaddle(screen_size, 20, 100, "naruto.png", self.bullets_group)
        self.ai_paddle = classes.AIPaddle(screen_size, 20, 100, "naruto.png")
        self.pong = classes.Pong(screen_size, 20, 20, "pokeball.png")

        self.now1 = pygame.time.get_ticks()
        self.now2 = pygame.time.get_ticks()

    def ProcessInput(self, events, pressed_keys):
        for event in events:
            self.player_paddle.handle_event(event)

    def Update(self):
        self.player_paddle.update()
        self.ai_paddle.update(self.pong, self.player_paddle)
        self.pong.update(self.player_paddle, self.ai_paddle)

        for powerup in self.powerup_group:
            self.bullets_group.update(powerup)
        self.powerup_group.update()

        # if someone reaches a score of 2, then exit the game
        if self.player_paddle.score == 2 or self.ai_paddle.score == 2:
            SceneBase.is_game_over = True
            self.SwitchToScene(GameOverScreen())

        time_difference1 = pygame.time.get_ticks() - self.now1
        time_difference2 = pygame.time.get_ticks() - self.now2

        if time_difference1 >= 2000:
            self.powerup_group.add(classes.PowerUp(screen_size, 40, 40, "ramen.png"))
            self.now1 = pygame.time.get_ticks()

        for powerup in self.powerup_group:
            if time_difference2 >= 5000:
                self.powerup_group.remove(powerup)

if my PlayerPaddle class, if I click on a key, the bullet gets launched from it. However, the bullet is not moving towards the right (like I asked it to do in the Bullet's update function).

def handle_event(self, event):
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_UP:
            self.direction = -1
        elif event.key == pygame.K_DOWN:
            self.direction = 1
        elif event.key == pygame.K_LEFT:
            self.turnLeft()
        elif event.key == pygame.K_RIGHT:
            self.turnRight()
        elif event.key == pygame.K_u:
            bullet = Bullet(screen_size, 25, 25, "naruto.png", color = (255, 0 , 0))
            bullet.rect.centerx = self.rect.centerx
            bullet.rect.centery = self.rect.centery

            self.bullet_group.add(bullet)

Body:
Goal 2: You use the same timer for all powerups in

 time_difference2 = pygame.time.get_ticks() - self.now2

 ...

 if time_difference2 >= 5000:

so it removes all powerups in the same time.

Every powerup needs own timer inside class. I use name kill_time with current_time+5000

    time_difference1 = pygame.time.get_ticks() - self.now1

    # ---

    current_time = pygame.time.get_ticks()

    if time_difference1 >= 2000:
        powerup = classes.PowerUp(screen_size, 40, 40, "ramen.png")
        powerup.kill_time = current_time + 5000
        self.powerup_group.add(power)
        self.now1 = pygame.time.get_ticks()

    # ----

    current_time = pygame.time.get_ticks()

    for powerup in self.powerup_group:
        if powerup.kill_time <= current_time:
            self.powerup_group.remove(powerup)


问:
Unable to click button on Mobile App in android
I am new of mobile app automation tested using Appium with TestNG.Am practicing to automate amazon app, App was launching successfully but when I try to click login option, it's getting:

"FAILED: login org.openqa.selenium.NoSuchElementException: An
  element could not be located on the page using the given search
  parameters. (WARNING: The server did not provide any stacktrace
  information) Command duration or timeout: 0 milliseconds"

```<code>    public void login() throws InterruptedException{

        System.out.println("Login check");
        Thread.sleep(3000);
//      String sample = driver.findElementByXPath("//*[@class='android.widget.Button' and @index='5']").getText();
        System.out.println("Next sleep");

//      driver.findElement(By.xpath("//[@class='android.widget.Button' and @index='5']')]")).click();
//      driver.findElement(By.id("in.amazon.mShop.android.shopping:id/sign_in_button")).click();
        driver.findElement(By.xpath("//android.widget.Button[@index='5']")).click();
        Thread.sleep(3000);
        System.out.println("Pass");

    }
</code>```

Image:

答:
Please try this code:</p>

```<code>MobileElement el1 = (MobileElement) driver.findElementById("in.amazon.mShop.android.shopping:id/sign_in_button");

el1.click();
</code>```

Body:
I am new of mobile app automation tested using Appium with TestNG.Am practicing to automate amazon app, App was launching successfully but when I try to click login option, it's getting:

"FAILED: login org.openqa.selenium.NoSuchElementException: An
  element could not be located on the page using the given search
  parameters. (WARNING: The server did not provide any stacktrace
  information) Command duration or timeout: 0 milliseconds"

    public void login() throws InterruptedException{

        System.out.println("Login check");
        Thread.sleep(3000);
//      String sample = driver.findElementByXPath("//*[@class='android.widget.Button' and @index='5']").getText();
        System.out.println("Next sleep");

//      driver.findElement(By.xpath("//[@class='android.widget.Button' and @index='5']')]")).click();
//      driver.findElement(By.id("in.amazon.mShop.android.shopping:id/sign_in_button")).click();
        driver.findElement(By.xpath("//android.widget.Button[@index='5']")).click();
        Thread.sleep(3000);
        System.out.println("Pass");

    }

Image:

Body:
Please try this code:

MobileElement el1 = (MobileElement) driver.findElementById("in.amazon.mShop.android.shopping:id/sign_in_button");

el1.click();


问:
Unable to debug .NET core projects in Visual Studio 2017
I have a Service Fabric application with several services - some .NET core, some not. The target framework for all projects is .NET 4.6.2. Other members of my team are able to hit breakpoints in the core projects, but on my machine the symbols are never loaded. Breakpoints in the non-core projects are hit OK.

I have tried cleaning the solution, rebuilding, restarting Visual Studio and upgrading Visual Studio to 15.5.0 (from 15.3).

I am running a Debug build (x64).

I have also tried explicitly adding the output folders as symbol locations in the debugging settings.

答:
Turned out it was the "Use Managed Compatibility Mode" setting (it was switched on for me). Turning that off allows debugging of .NET core Service Fabric services (it has no effect on normal .NET core projects).

Thanks patutin!


问:
Date minus date is not giving desired answer - IONIC 2
When I try to subtract

Wed Dec 06 2017 15:58:59 GMT+0530 (India Standard Time)  minus Tue Nov 28 2017 00:00:00 GMT+0530 (India Standard Time)  , the answer which is coming is -22

But the answer should be 6

What is going wrong and where, below is my page.ts code:

```<code>  this.tt = new Date();
  this.tt1 = this.datePipe.transform(this.tt,'dd/mm/yyyy');

  console.log(this.ent[0],"server DATE");
  // in console we see this - 28-NOV-17 server DATE

  var firstDate= new Date(this.ent[0]);  //Jan 01 2017 00:00:00

  var secondDate = new Date();//Jan 04 2017 00:00:00

  console.log(firstDate);
 // answer in console - Tue Nov 28 2017 00:00:00 GMT+0530 (India Standard Time)

  console.log(secondDate);
 //answer in console - Wed Dec 06 2017 15:58:59 GMT+0530 (India Standard Time)

  console.log(secondDate.getDate() - firstDate.getDate() );
 //answer in console -  -22
</code>```

答:
Date.getDate() gives the "dd" of the date (in your case 6 and 28 which explains the result being -22).
I'm a bit confused with the expected result being 6. So maybe my answer won't fit you. What I would do however is convert the date in time, do the substraction and convert it back to number of days.

So

```<code>Math.Floor((secondDate.getTime() - firstDate.getTime()) / 86400000);

(86400000 being 1000 (milliseconds) * 3600 (seconds in an hour) * 24 (number of hours in a day)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When I try to subtract

Wed Dec 06 2017 15:58:59 GMT+0530 (India Standard Time)  minus Tue Nov 28 2017 00:00:00 GMT+0530 (India Standard Time)  , the answer which is coming is -22

But the answer should be 6

What is going wrong and where, below is my page.ts code:

  this.tt = new Date();
  this.tt1 = this.datePipe.transform(this.tt,'dd/mm/yyyy');

  console.log(this.ent[0],"server DATE");
  // in console we see this - 28-NOV-17 server DATE

  var firstDate= new Date(this.ent[0]);  //Jan 01 2017 00:00:00

  var secondDate = new Date();//Jan 04 2017 00:00:00

  console.log(firstDate);
 // answer in console - Tue Nov 28 2017 00:00:00 GMT+0530 (India Standard Time)

  console.log(secondDate);
 //answer in console - Wed Dec 06 2017 15:58:59 GMT+0530 (India Standard Time)

  console.log(secondDate.getDate() - firstDate.getDate() );
 //answer in console -  -22

Body:
Date.getDate() gives the "dd" of the date (in your case 6 and 28 which explains the result being -22).
I'm a bit confused with the expected result being 6. So maybe my answer won't fit you. What I would do however is convert the date in time, do the substraction and convert it back to number of days.

So

Math.Floor((secondDate.getTime() - firstDate.getTime()) / 86400000);

(86400000 being 1000 (milliseconds) * 3600 (seconds in an hour) * 24 (number of hours in a day)


问:
Docker mount to folder overriding content
I have a .net Core web Api having configurations files under a folder called Config.
I created the image and a container from it, and I correctly see using the terminal, that the container contains the folder and the configuration files inside.

My problem is that so far I couldn't find a way to create the same container mounting/binding the Config folder to a physical path, following the requirements:

1) Mount Config folder to a specific host location

2) On container creation, the Config folder should be filled with the files in the image

3) On container creation, override any existing file already present in the folder with those in the image

4) Be able to customize the config files in the folder from the host

My create command:

```<code>    docker --tls -H="$containerUrl" `
        create `
        --hostname $hostname `
        --name $containerName `
        --mac-address=$containerMacAddress `
        --ip $containerIpAddress `
        --net "bridged-network" `
        --workdir '/app' `
        --mount type=bind,src=$configVolumePath,target=/app/Config `
        --publish "0.0.0.0::80" `
        -t `
        -i $imageName":"$script:buildversion
</code>```

Using --mount with type bind, as specified in the documentation, if there is any file in the folder, those hare hidden from within the container and the application will see the deployed files.
The problem of this solution is that I cannot update the files in the config folder from the host.

Now, removing type=bind I get the same result, and it is confusing.

I tried to use volume --volume $configVolumePath":/app/Config:rw", but doing so the pre exising files in the host directory are not overridden and those are the one that will be used within the container.

Additional notes, I don't specify anything in the Dockerfile or compose related to volume mounting, and I didn't try to create a volume to then use it as a source, but I don't think that would make a difference.

The container server is running on a NAS and this is the version:

```<code> Version:      1.11.2
 API version:  1.23
 Go version:   go1.5.4
 Git commit:   781516c
 Built:        Thu Aug  3 16:04:05 2017
 OS/Arch:      linux/amd64
</code>```

Clearly I'm missing something and I have to learn more about docker, can anyone help?

My references:

1) https://docs.docker.com/engine/admin/volumes/bind-mounts/

2) https://docs.docker.com/engine/admin/volumes/volumes/

答:
First of all, docker volumes or bind mounts behave like linux mounts.

If the host volume/mount exists and contains files it will "override" whatever is in the container. If not the container files will be mirrored onto the host volume/mount and the container folder and the host will be in sync.
In both cases editing the files on the host will ALWAYS be reflected inside the container.

In your case, you can do the following:

```<code>docker volume create --driver local \
    --opt type=none \
    --opt device=$configVolumePath \
    --opt o=bind \
    config_vol
</code>```

This will create a volume which will be persisted in $configVolumePath on the host.

When creating the container use that volume:

```<code>docker create --volume config_vol:/app/Config
</code>```

What you will get is on startup, the host folder will be empty and the files from the image will be "copied" onto the host folder. Editing files in $configVolumePath will be reflected inside the container and similarly
files edited inside the container /app/Config will be reflected in $configVolumePath on the host.

Body:
I have a .net Core web Api having configurations files under a folder called Config.
I created the image and a container from it, and I correctly see using the terminal, that the container contains the folder and the configuration files inside.

My problem is that so far I couldn't find a way to create the same container mounting/binding the Config folder to a physical path, following the requirements:

1) Mount Config folder to a specific host location

2) On container creation, the Config folder should be filled with the files in the image

3) On container creation, override any existing file already present in the folder with those in the image

4) Be able to customize the config files in the folder from the host

My create command:

    docker --tls -H="$containerUrl" `
        create `
        --hostname $hostname `
        --name $containerName `
        --mac-address=$containerMacAddress `
        --ip $containerIpAddress `
        --net "bridged-network" `
        --workdir '/app' `
        --mount type=bind,src=$configVolumePath,target=/app/Config `
        --publish "0.0.0.0::80" `
        -t `
        -i $imageName":"$script:buildversion

Using --mount with type bind, as specified in the documentation, if there is any file in the folder, those hare hidden from within the container and the application will see the deployed files.
The problem of this solution is that I cannot update the files in the config folder from the host.

Now, removing type=bind I get the same result, and it is confusing.

I tried to use volume --volume $configVolumePath":/app/Config:rw", but doing so the pre exising files in the host directory are not overridden and those are the one that will be used within the container.

Additional notes, I don't specify anything in the Dockerfile or compose related to volume mounting, and I didn't try to create a volume to then use it as a source, but I don't think that would make a difference.

The container server is running on a NAS and this is the version:

 Version:      1.11.2
 API version:  1.23
 Go version:   go1.5.4
 Git commit:   781516c
 Built:        Thu Aug  3 16:04:05 2017
 OS/Arch:      linux/amd64

Clearly I'm missing something and I have to learn more about docker, can anyone help?

My references:

1) https://docs.docker.com/engine/admin/volumes/bind-mounts/

2) https://docs.docker.com/engine/admin/volumes/volumes/

Body:
First of all, docker volumes or bind mounts behave like linux mounts.

If the host volume/mount exists and contains files it will "override" whatever is in the container. If not the container files will be mirrored onto the host volume/mount and the container folder and the host will be in sync.
In both cases editing the files on the host will ALWAYS be reflected inside the container.

In your case, you can do the following:

docker volume create --driver local \
    --opt type=none \
    --opt device=$configVolumePath \
    --opt o=bind \
    config_vol

This will create a volume which will be persisted in $configVolumePath on the host.

When creating the container use that volume:

docker create --volume config_vol:/app/Config

What you will get is on startup, the host folder will be empty and the files from the image will be "copied" onto the host folder. Editing files in $configVolumePath will be reflected inside the container and similarly
files edited inside the container /app/Config will be reflected in $configVolumePath on the host.


问:
Excluding module level comments from folding
I am trying to add some comments starting on the first column of my module, in order to categorise the functions within the code and improve readability.

The issue I have is that Pydev seems to include these comments within the folding of the function above the comment (see the picture below). Is there a way that I can exclude these comments that are on the same level as the function from the function folding?

答:
There's currently no way to customize this behavior (comments are a bit tricky because they don't appear as actual nodes in the grammar).

The related code in PyDev is in:

org.python.pydev.parser.visitors.scope.CodeFoldingVisitor
org.python.pydev.editor.codefolding.CodeFoldingSetter

I guess the place which creates the folding marks could check whether a comment is in the last lines of a folding mark in the same level when right next to the declaration of a different class/method and exclude it (there are cases where that comment should enter as I've seen people add comments in the end of a class related to it -- for instance I've seen comments as # end if or #end class on big if statements or classes, but those are usually not "glued" to the next declaration -- as a note, the endLine is explicitly set to include the comments after in org.python.pydev.parser.visitors.scope.EasyAstIteratorBase.after(ASTEntry), but this is probably not fixable there).

You can report that at https://www.brainwy.com/tracker/PyDev -- although I don't know when I'll be able to tackle it, so, if you're up to provide a pull request -- see: http://www.pydev.org/developers.html for how to get the code -- it could be integrated much sooner ;)


问:
Keras - Input a 3 channel image into LSTM
I have read a sequence of images into a numpy array with shape (7338, 225, 1024, 3) where 7338 is the sample size, 225 are the time steps and 1024 (32x32) are flattened image pixels, in 3 channels (RGB).

I have a sequential model with an LSTM layer:

```<code>model = Sequential()
model.add(LSTM(128, input_shape=(225, 1024, 3))
</code>```

But this results in the error:

```<code>Input 0 is incompatible with layer lstm_1: expected ndim=3, found ndim=4
</code>```

The documentation mentions that the input tensor for LSTM layer should be a 3D tensor with shape (batch_size, timesteps, input_dim), but in my case my input_dim is 2D.

What is the suggested way to input a 3 channel image into an LSTM layer  in Keras?

答:
If you want the number of images to be a sequence (like a movie with frames), you need to put pixels AND channels as features:

```<code>input_shape = (225,3072)  #a 3D input where the batch size 7338 wasn't informed
</code>```

If you want more processing before throwing 3072 features into an LSTM, you can combine or interleave 2D convolutions and LSTMs for a more refined model (not necessarily better, though, each application has its particular behavior).

You can also try to use the new ConvLSTM2D, which will take the five dimensional input:

```<code>input_shape=(225,32,32,3) #a 5D input where the batch size 7338 wasn't informed
</code>```

I'd probably create a convolutional net with several TimeDistributed(Conv2D(...)) and TimeDistributed(MaxPooling2D(...)) before adding a TimeDistributed(Flatten()) and finally the LSTM(). This will very probably improve both your image understanding and the performance of the LSTM.

Body:
I have read a sequence of images into a numpy array with shape (7338, 225, 1024, 3) where 7338 is the sample size, 225 are the time steps and 1024 (32x32) are flattened image pixels, in 3 channels (RGB).

I have a sequential model with an LSTM layer:

model = Sequential()
model.add(LSTM(128, input_shape=(225, 1024, 3))

But this results in the error:

Input 0 is incompatible with layer lstm_1: expected ndim=3, found ndim=4

The documentation mentions that the input tensor for LSTM layer should be a 3D tensor with shape (batch_size, timesteps, input_dim), but in my case my input_dim is 2D.

What is the suggested way to input a 3 channel image into an LSTM layer  in Keras?

Body:
If you want the number of images to be a sequence (like a movie with frames), you need to put pixels AND channels as features:

input_shape = (225,3072)  #a 3D input where the batch size 7338 wasn't informed

If you want more processing before throwing 3072 features into an LSTM, you can combine or interleave 2D convolutions and LSTMs for a more refined model (not necessarily better, though, each application has its particular behavior).

You can also try to use the new ConvLSTM2D, which will take the five dimensional input:

input_shape=(225,32,32,3) #a 5D input where the batch size 7338 wasn't informed

I'd probably create a convolutional net with several TimeDistributed(Conv2D(...)) and TimeDistributed(MaxPooling2D(...)) before adding a TimeDistributed(Flatten()) and finally the LSTM(). This will very probably improve both your image understanding and the performance of the LSTM.


问:
Javascript executing when jQuery not ready
The following scenario is a problem I am having. I came to the conclusion that jQuery must not be ready when Javascript is executing by observing this scenario.

Scenario:

I have a Java application which injects Javascript script tags into the currently loaded DOM page. The following Java code runs inline Javascript which inserts jquery.js and myCode.js. myCode.js holds my Javascript codes.

```<code> browser.executeJavaScript("var head= document.getElementsByTagName('head')[0];" +
                                "var script= document.createElement('script');script.type= 'text/javascript';script.src= 'jquery.js';head.appendChild(script);" +
                                "var script4= document.createElement('script');script4.type= 'text/javascript';script4.src= 'http://myCode.js';head.appendChild(script4);");
</code>```

In this Java application, I also have a buttonListener that fires a function in myCode.js in ActionPerformed();

```<code>executedJS = browser.executeJavaScript("replaceAllLinks()");
</code>```

The problem that is encountered is nullPointerException at the above line when button is clicked. Accomodating for null case results in endless loop without any changes.

```<code>while(executedJS == null) browser.executeJavaScript("replaceAllLinks()");
</code>```

The cause of the problem was pinpointed down to when jQuery functions, methods are present inside replaceAllLinks(); javascript function. when jQuery, methods were absent, no problems could be observed. There was not one instance of nullPointerException raised.

The only possible underlying issue would be that somehow jQuery library is not fully loaded while replaceAllLinks(); is being executed. If jQuery methods and functions were not in use, it doesn't matter and everything runs okay.

My question is then, how can I make sure that jQuery is fully loaded and available for use?

答:
Declare some global variable at the end jquery.js, e.g.

```<code>window.jQueryIsLoaded=true;
</code>```

and check this variable before using jQuery.

<edit>Forget this, see  Salman A's comment below, should be the right answer.</edit>

ContentLicense: CC BY-SA 2.5

Body:
The following scenario is a problem I am having. I came to the conclusion that jQuery must not be ready when Javascript is executing by observing this scenario.

Scenario:

I have a Java application which injects Javascript script tags into the currently loaded DOM page. The following Java code runs inline Javascript which inserts jquery.js and myCode.js. myCode.js holds my Javascript codes.

 browser.executeJavaScript("var head= document.getElementsByTagName('head')[0];" +
                                "var script= document.createElement('script');script.type= 'text/javascript';script.src= 'jquery.js';head.appendChild(script);" +
                                "var script4= document.createElement('script');script4.type= 'text/javascript';script4.src= 'http://myCode.js';head.appendChild(script4);");

In this Java application, I also have a buttonListener that fires a function in myCode.js in ActionPerformed();

executedJS = browser.executeJavaScript("replaceAllLinks()");

The problem that is encountered is nullPointerException at the above line when button is clicked. Accomodating for null case results in endless loop without any changes.

while(executedJS == null) browser.executeJavaScript("replaceAllLinks()");

The cause of the problem was pinpointed down to when jQuery functions, methods are present inside replaceAllLinks(); javascript function. when jQuery, methods were absent, no problems could be observed. There was not one instance of nullPointerException raised.

The only possible underlying issue would be that somehow jQuery library is not fully loaded while replaceAllLinks(); is being executed. If jQuery methods and functions were not in use, it doesn't matter and everything runs okay.

My question is then, how can I make sure that jQuery is fully loaded and available for use?

Body:
Declare some global variable at the end jquery.js, e.g.

window.jQueryIsLoaded=true;

and check this variable before using jQuery.

<edit>Forget this, see  Salman A's comment below, should be the right answer.</edit>


问:
php code that adds a number to the current number or do nothing at it
My question is very simple
i'm programming some sort of an earning site and what i want to add to my php is:

when the user type the captcha wrong , number of user coins doesn't increase or decrease
but when he types it right , it increases by 100

but the problem i faced is that however the user types it right it doesn't increase after the first time i mean it doesn't go to 200 or more .. and when he types it wrong it turns back into 0 again
note: i'm using solve media for the captcha service

this is my code

```<code>$current n = 0;
if (!$solvemedia_response->is_valid) {
    print "<div class='alert alert-danger'> Captcha wrong try again!: ".$solvemedia_response->error."</div>";
    $currentn +=0;
    echo $currentn;
}else {
    print "<div class='alert alert-success'> 100 satoshis have been earned successfuly </div>";
    $currentn +=100;
    echo $currentn;
}
</code>```

答:
You're not storing the value anywhere.  All the code ever does is declare a variable to 0 and then maybe add 100 to it.  So all the variable will ever be is 0 or 100.

Persist the value somewhere.  For example, in session state.  Something like this:

```<code>$currentn = 0;
if (isset($_SESSION['currentn'])) {
    $currentn = $_SESSION['currentn'];
}
</code>```

And when you set the value:

```<code>$currentn += 100;
$_SESSION['currentn'] = $currentn;
</code>```

You can refactor where you store and retrieve session data depending on how you want to organize your code.  But the point is that you need to store the value somewhere.  Otherwise every time you load the page it starts again at zero.

Edit: I almost forgot, in PHP you also need to start the session service manually before using it.  So at the top of any script that uses it you’d need this:

```<code>session_start();
</code>```

Body:
My question is very simple
i'm programming some sort of an earning site and what i want to add to my php is:

when the user type the captcha wrong , number of user coins doesn't increase or decrease
but when he types it right , it increases by 100

but the problem i faced is that however the user types it right it doesn't increase after the first time i mean it doesn't go to 200 or more .. and when he types it wrong it turns back into 0 again
note: i'm using solve media for the captcha service

this is my code

$current n = 0;
if (!$solvemedia_response->is_valid) {
    print "
 Captcha wrong try again!: ".$solvemedia_response->error."
";
    $currentn +=0;
    echo $currentn;
}else {
    print "
 100 satoshis have been earned successfuly
";
    $currentn +=100;
    echo $currentn;
}

Body:
You're not storing the value anywhere.  All the code ever does is declare a variable to 0 and then maybe add 100 to it.  So all the variable will ever be is 0 or 100.

Persist the value somewhere.  For example, in session state.  Something like this:

$currentn = 0;
if (isset($_SESSION['currentn'])) {
    $currentn = $_SESSION['currentn'];
}

And when you set the value:

$currentn += 100;
$_SESSION['currentn'] = $currentn;

You can refactor where you store and retrieve session data depending on how you want to organize your code.  But the point is that you need to store the value somewhere.  Otherwise every time you load the page it starts again at zero.

Edit: I almost forgot, in PHP you also need to start the session service manually before using it.  So at the top of any script that uses it you’d need this:

session_start();


问:
ArrayList Not Replying Proper Result in jsp Page
Following is my java code, where arraylist not replying proper result.

Proper Result [Should Display on screen]

2016/04
2016/05
2016/06
2016/07
2016/08
2016/09
2016/10
2016/11
2016/12
2017/01
2017/02
2017/03
2017/04
2017/05
2017/06
2017/07
2017/08
2017/09

But Result Appearing

v_p_DataCont@183d59c
v_p_DataCont@3cfaab
v_p_DataCont@16d3046
v_p_DataCont@17c4779
v_p_DataCont@3861e6
v_p_DataCont@1a37fac
v_p_DataCont@1132e76
v_p_DataCont@4f71a3
v_p_DataCont@1ad9b0f
v_p_DataCont@9effe0
v_p_DataCont@b101cf
v_p_DataCont@edf4c8
v_p_DataCont@61a414
v_p_DataCont@5b55a9
v_p_DataCont@54f169
v_p_DataCont@b524aa
v_p_DataCont@7a3a30
v_p_DataCont@825cf3

rnssp-report1.jsp

```<code><html>
<style>
label
{
width: 23em;
float: left;
text-align: left;
margin-left: 0em;
color: red;
background: #FFFF00;
display: block
}

.submit input
{
margin-left: 2.5em;
}
input
{
color: #781351;
background: #fee3ad;
border: 1px solid #781351
}
.submit input
{
margin-left: 0em;
color: #000;
background: #ffa20f;
border: 2px outset #d7b9c9
}
fieldset
{
margin-left: 10.5em;
border: 1px solid #781351;
width: 60em
}
legend
{
margin-left: 20.5em;
color: #fff;
background: #ffa20c;
border: 1px solid #781351;
padding: 2px 6px
}
</style>
    <head>
        <title>XXXXXXXXXXXXXXXXXXXXXXXXXXXX</title>
    </head>

    <body>

    <%
     String action="v_p_Search1";
     String method="get";
     String method1="post";
    %>

    <form name="myForm1"  method= "<%=method%>" action="<%=action%>">

    <h1><center><color : blue> YYYYYYYYYYYYYYYYY</center></h1>
 <fieldset>
 <legend>Please Input Voucher Period</legend>
 <br />
 <p>
 <label for="name">Click on Search Button Bellow To Select Voucher Period</label>
 </p>
 <br />
 <p class="submit">
 <input type="submit" name="submit" value="Search" action="#{v_p_Search1.get}">
 </p>
</fieldset>
    </form>
    </body>
</html>
</code>```

v_p_Search1.java

```<code>import java.util.Date;
import java.util.*;
import java.io.*;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileWriter;
import java.sql.*;
import java.text.*;
import java.io.Console;
import java.math.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.lang.String;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.FileOutputStream;
import java.io.IOException;

import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class v_p_Search1 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

String t_date_year = " ";
int t_date_year_n = 0;
int t_date_year_n1 = 0;
String inp_year_mon = " ";
String s_date1 = "          ";
String s_date2 = "          ";
String Field1 = " ";

             DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MMM-dd");
             Date s_date = new Date();
             s_date1 = (dateFormat2.format(s_date));
             s_date2 = s_date1.substring(0, 11);
             t_date_year = s_date2.substring(0, 4);
             t_date_year_n=Integer.parseInt(t_date_year);
             t_date_year_n1 = t_date_year_n - 1;
             inp_year_mon =  t_date_year_n1+"/04";

        List<v_p_DataCont> list=v_p_DataAction.getSelectedVouPeriod(inp_year_mon);

            request.setAttribute("vpList", list);
            RequestDispatcher view = request.getRequestDispatcher("/searchview1.jsp");
            view.forward(request, response);

        out.close();
    }
}
</code>```

v_p_DataAction.java

```<code>import java.util.Date;
import java.util.*;
import java.io.*;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileWriter;
import java.sql.*;
import java.text.*;
import java.io.Console;
import java.math.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.lang.String;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.FileOutputStream;
import java.io.IOException;

import java.util.Date;
import java.text.*;
import java.io.FileOutputStream;
import java.io.*;
import java.util.*;
import java.sql.*;

public class v_p_DataAction {

            public static Connection getConnection(){
            Connection con=null;

        try{
            Class.forName("oracle.jdbc.OracleDriver");
            con = DriverManager.getConnection("jdbc:oracle:thin:@00.000.0.000:0000:xxx","yyyy", "zzzz");
           }
            catch(Exception e)
            {System.out.println(e);}
             return con;
                                                    }

    public static List<v_p_DataCont> getSelectedVouPeriod(String inp_year_mon){
        List<v_p_DataCont> list=new ArrayList<v_p_DataCont>();

           try{
                 Connection con=v_p_DataAction.getConnection();

                   PreparedStatement ps=con.prepareStatement("SELECT X.Voucher_Period FROM com_agent_comm_dtl X where X.Voucher_Period >= '" + inp_year_mon + "' group by X.VOUCHER_PERIOD ORDER BY X.VOUCHER_PERIOD");
                   ResultSet rs=ps.executeQuery();
                   while (rs.next()) {
                       v_p_DataCont s=new v_p_DataCont();
                             s.setVoucher_Period(rs.getString(1));
                             list.add(s);
                                     }

                           con.close();

              }
             catch (Exception e) {e.printStackTrace();}

           return list;

                                                         }
}
</code>```

v_p_DataCont.java

```<code>public class v_p_DataCont {
private String voucher_period;

public String getVoucher_Period() {
    return voucher_period;
                                  }
public void setVoucher_Period(String voucher_period) {
    this.voucher_period = voucher_period;
                                                     }

}
</code>```

web.xml

following part added in web.xml

```<code><!-- JSPC servlet mappings start -->

    <servlet>
        <servlet-name>org.apache.jsp.index_jsp</servlet-name>
        <servlet-class>org.apache.jsp.index_jsp</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>org.apache.jsp.index_jsp</servlet-name>
        <url-pattern>/index.jsp</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>v_p_Search1</servlet-name>
        <servlet-class>v_p_Search1</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>v_p_Search1</servlet-name>
        <url-pattern>/v_p_Search1</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>rnssp-report1.jsp</welcome-file>
    </welcome-file-list>

<!-- JSPC servlet mappings end -->
</code>```

searchview1.jsp

```<code><%@ page import="java.util.*" %>
 <%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
    <head>
    </head>
    <body>
        <table width="1000px" align="center"
               style="border:1px solid #000000;">
            <tr>
                <td colspan=16 align="center"
                    style="background-color:teal">
                    <b>XXXXXXXXXXXXX</b></td>
            </tr>
            <tr style="background-color:lightgrey;">
                <td><b>Voucher Period</b></td>
            </tr>
            <td>
            <select name="database1">
            <option value="" selected>select</option>
            <%

                String color = "#F9EBB3";
                if (request.getAttribute("vpList") != null) {
                        ArrayList list = (ArrayList) request.getAttribute("vpList");
                            for(int i=0;i<list.size();i++) {
                            String Field=list.get(i).toString();

            %>
             <option value="<%=Field %>"><%=Field %></option>

            <%
                    }
                }
            %>
                </select>
              </td>
        </table>
    </body>
</html>
</code>```

Please Help Me, How Proper Result will appear in searchview1.jsp?

答:
You should override toString() method in v_p_DataCont class

add this following code in v_p_DataCont class

```<code>@Override
public String toString()
{
return voucher_period;
}
</code>```

Body:
Following is my java code, where arraylist not replying proper result.

Proper Result [Should Display on screen]

2016/04
2016/05
2016/06
2016/07
2016/08
2016/09
2016/10
2016/11
2016/12
2017/01
2017/02
2017/03
2017/04
2017/05
2017/06
2017/07
2017/08
2017/09

But Result Appearing

v_p_DataCont@183d59c
v_p_DataCont@3cfaab
v_p_DataCont@16d3046
v_p_DataCont@17c4779
v_p_DataCont@3861e6
v_p_DataCont@1a37fac
v_p_DataCont@1132e76
v_p_DataCont@4f71a3
v_p_DataCont@1ad9b0f
v_p_DataCont@9effe0
v_p_DataCont@b101cf
v_p_DataCont@edf4c8
v_p_DataCont@61a414
v_p_DataCont@5b55a9
v_p_DataCont@54f169
v_p_DataCont@b524aa
v_p_DataCont@7a3a30
v_p_DataCont@825cf3

rnssp-report1.jsp

        <title>XXXXXXXXXXXXXXXXXXXXXXXXXXXX</title>

    <%
     String action="v_p_Search1";
     String method="get";
     String method1="post";
    %>

    <form name="myForm1"  method= "<%=method%>" action="<%=action%>">

<color : blue> YYYYYYYYYYYYYYYYY

 <fieldset>
 <legend>Please Input Voucher Period</legend>

 Click on Search Button Bellow To Select Voucher Period

 <input type="submit" name="submit" value="Search" action="#{v_p_Search1.get}">

</fieldset>
    </form>

v_p_Search1.java

import java.util.Date;
import java.util.*;
import java.io.*;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileWriter;
import java.sql.*;
import java.text.*;
import java.io.Console;
import java.math.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.lang.String;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.FileOutputStream;
import java.io.IOException;

import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class v_p_Search1 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

String t_date_year = " ";
int t_date_year_n = 0;
int t_date_year_n1 = 0;
String inp_year_mon = " ";
String s_date1 = "          ";
String s_date2 = "          ";
String Field1 = " ";

             DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MMM-dd");
             Date s_date = new Date();
             s_date1 = (dateFormat2.format(s_date));
             s_date2 = s_date1.substring(0, 11);
             t_date_year = s_date2.substring(0, 4);
             t_date_year_n=Integer.parseInt(t_date_year);
             t_date_year_n1 = t_date_year_n - 1;
             inp_year_mon =  t_date_year_n1+"/04";

        List<v_p_DataCont> list=v_p_DataAction.getSelectedVouPeriod(inp_year_mon);

            request.setAttribute("vpList", list);
            RequestDispatcher view = request.getRequestDispatcher("/searchview1.jsp");
            view.forward(request, response);

        out.close();
    }
}

v_p_DataAction.java

import java.util.Date;
import java.util.*;
import java.io.*;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileWriter;
import java.sql.*;
import java.text.*;
import java.io.Console;
import java.math.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.lang.String;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.FileOutputStream;
import java.io.IOException;

import java.util.Date;
import java.text.*;
import java.io.FileOutputStream;
import java.io.*;
import java.util.*;
import java.sql.*;

public class v_p_DataAction {

            public static Connection getConnection(){
            Connection con=null;

        try{
            Class.forName("oracle.jdbc.OracleDriver");
            con = DriverManager.getConnection("jdbc:oracle:thin:@00.000.0.000:0000:xxx","yyyy", "zzzz");
           }
            catch(Exception e)
            {System.out.println(e);}
             return con;
                                                    }

    public static List<v_p_DataCont> getSelectedVouPeriod(String inp_year_mon){
        List<v_p_DataCont> list=new ArrayList<v_p_DataCont>();

           try{
                 Connection con=v_p_DataAction.getConnection();

                   PreparedStatement ps=con.prepareStatement("SELECT X.Voucher_Period FROM com_agent_comm_dtl X where X.Voucher_Period >= '" + inp_year_mon + "' group by X.VOUCHER_PERIOD ORDER BY X.VOUCHER_PERIOD");
                   ResultSet rs=ps.executeQuery();
                   while (rs.next()) {
                       v_p_DataCont s=new v_p_DataCont();
                             s.setVoucher_Period(rs.getString(1));
                             list.add(s);
                                     }

                           con.close();

              }
             catch (Exception e) {e.printStackTrace();}

           return list;

                                                         }
}

v_p_DataCont.java

public class v_p_DataCont {
private String voucher_period;

public String getVoucher_Period() {
    return voucher_period;
                                  }
public void setVoucher_Period(String voucher_period) {
    this.voucher_period = voucher_period;
                                                     }

}

web.xml

following part added in web.xml

    <servlet>
        <servlet-name>org.apache.jsp.index_jsp</servlet-name>
        <servlet-class>org.apache.jsp.index_jsp</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>org.apache.jsp.index_jsp</servlet-name>
        <url-pattern>/index.jsp</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>v_p_Search1</servlet-name>
        <servlet-class>v_p_Search1</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>v_p_Search1</servlet-name>
        <url-pattern>/v_p_Search1</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>rnssp-report1.jsp</welcome-file>
    </welcome-file-list>

searchview1.jsp

<%@ page import="java.util.*" %>
 <%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>

                    XXXXXXXXXXXXX

                Voucher Period

            <select name="database1">
            <option value="" selected>select</option>
            <%

                String color = "#F9EBB3";
                if (request.getAttribute("vpList") != null) {
                        ArrayList list = (ArrayList) request.getAttribute("vpList");
                            for(int i=0;i<list.size();i++) {
                            String Field=list.get(i).toString();

            %>
             <option value="<%=Field %>"><%=Field %></option>

            <%
                    }
                }
            %>
                </select>

Please Help Me, How Proper Result will appear in searchview1.jsp?

Body:
You should override toString() method in v_p_DataCont class

add this following code in v_p_DataCont class

@Override
public String toString()
{
return voucher_period;
}


问:
Pressing enter in form does not execute js function properly
I am using Django to create a form where users will have to enter their email to get notified in the future. I have added a js function to handle submiting the form, because I want to display a modal.

While clicking to submit the form behaves as expected, when I press enter it does not.

This is the view that handles the form:

```<code>def add_notify_email(request):
    if request.method == "POST":
        form = NotifyEmailForm(request.POST)
        if form.is_valid():
            form.save(commit=True)
            return JsonResponse({"status": "success"})
        else:
            return JsonResponse({"status": "error"})
    else:
        form = NotifyEmailForm()
    return render(request, "landing/home.html", {"form": form})
</code>```

The html code for the form is below:

```<code><form action="{% url "notify:notify_email_add" %}" method="post" id="notify_email_form_in_hero">
    {% csrf_token %}
    <div class="form-group row">
        <div class="col-sm-10 input-group" id="email_input_in_hero">
            <div class="input-group-addon" id="coming_soon_email_icon_in_hero"><i class="fa fa-envelope fa fa-2x" aria-hidden="true" id="email_icon_in_hero"></i></div>
            <input class="form-control" type="email" name="email" onkeypress="if(event.keyCode === 13){addNotifyEmailInHero()}" placeholder="If you want to get notified when we go live, please enter your email...." maxlength="255" required id="id_email"/>
        </div>
        <div class="col-sm-2" id="notify_email_button_in_hero">
            <button type="button" class="btn btn-block btn-primary" onclick="addNotifyEmailInHero()" id="submit_notify_email_in_hero"><i class="fa fa-bell nav-icon" aria-hidden="true"></i>Notify Me</button>
        </div>
    </div>
</form>

<script src="coming_soon.js"></script>
</code>```

When the button submit_notify_email_in_hero is clicked, the script coming_soon.js is executed:

```<code>function addNotifyEmailInHero(e){
    var notifyEmailForm = $("#notify_email_form_in_hero");
    var thanksModal = $("#thanks");

    $.ajax({
    type: 'POST',
    url: '/notify-email/add/',
    data: notifyEmailForm.serialize(),
    success: function(res){
               alert(res.status);
               if(res.status === "success") {
                    thanksModal.modal('show');
                        }

                else {$("#id_email").val("");
                      $("#id_email").attr("placeholder", "Please Enter A Valid Email Address");
                        }
    }
})}

$("#id_email").keyup(function (e) {
    if (e.which === 13) {
       addNotifyEmailInHero();
}});
</code>```

The form works perfecly by clicking the button, the issues come when you press enter to submit it.

If you press enter, from what I understand the function addNotifyEmailInHero is executed but instead of getting the json response and handle it, it just displays it: {"status": "success"}

Update:

I followed geebro's answer, leaving everything the except the suggested changes. This is by html code:

```<code><div class="container" id="notify_email_container_in_hero">
    <form onsubmit="addNotifyEmailInHero()" method="post" id="notify_email_form_in_hero">
        {% csrf_token %}
        <div class="form-group row">
            <div class="col-sm-10 input-group" id="email_input_in_hero">
                <div class="input-group-addon" id="coming_soon_email_icon_in_hero"><i class="fa fa-envelope fa fa-2x" aria-hidden="true" id="email_icon_in_hero"></i></div>
                <input class="form-control" type="email" name="email" placeholder="If you want to get notified when we go live, please enter your email...." maxlength="255" required id="id_email"/>
            </div>
            <div class="col-sm-2" id="notify_email_button_in_hero">
                <button type="submit" class="btn btn-block btn-primary" id="submit_notify_email_in_hero"><i class="fa fa-bell nav-icon" aria-hidden="true"></i>Notify Me</button>
            </div>
        </div>
    </form>
</div>

<script src="{% static "landing/js/coming_soon.js" %}"></script>
</code>```

It seems to work, although I get an extra post request:

```<code>[07/Dec/2017 00:39:45] "POST /notify-email/add/ HTTP/1.1" 200 21
[07/Dec/2017 00:39:45] "POST / HTTP/1.1" 200 23016
</code>```

答:
Change your

```<code><button type="button" class="btn btn-block btn-primary" onclick="addNotifyEmailInHero()" id="submit_notify_email_in_hero"><i class="fa fa-bell nav-icon" aria-hidden="true"></i>Notify Me</button>
</code>```

to

```<code>            <button type="submit" class="btn btn-block btn-primary"  id="submit_notify_email_in_hero"><i class="fa fa-bell nav-icon" aria-hidden="true"></i>Notify Me</button>
</code>```

and change the opening form tag to

```<code><form action="{% url "notify:notify_email_add" %}" onsubmit="addNotifyEmailInHero()" method="post" id="notify_email_form_in_hero">
</code>```

It should work then

Body:
I am using Django to create a form where users will have to enter their email to get notified in the future. I have added a js function to handle submiting the form, because I want to display a modal.

While clicking to submit the form behaves as expected, when I press enter it does not.

This is the view that handles the form:

def add_notify_email(request):
    if request.method == "POST":
        form = NotifyEmailForm(request.POST)
        if form.is_valid():
            form.save(commit=True)
            return JsonResponse({"status": "success"})
        else:
            return JsonResponse({"status": "error"})
    else:
        form = NotifyEmailForm()
    return render(request, "landing/home.html", {"form": form})

The html code for the form is below:

<form action="{% url "notify:notify_email_add" %}" method="post" id="notify_email_form_in_hero">
    {% csrf_token %}

            <input class="form-control" type="email" name="email" onkeypress="if(event.keyCode === 13){addNotifyEmailInHero()}" placeholder="If you want to get notified when we go live, please enter your email...." maxlength="255" required id="id_email"/>

            <button type="button" class="btn btn-block btn-primary" onclick="addNotifyEmailInHero()" id="submit_notify_email_in_hero">Notify Me</button>

</form>

When the button submit_notify_email_in_hero is clicked, the script coming_soon.js is executed:

function addNotifyEmailInHero(e){
    var notifyEmailForm = $("#notify_email_form_in_hero");
    var thanksModal = $("#thanks");

    $.ajax({
    type: 'POST',
    url: '/notify-email/add/',
    data: notifyEmailForm.serialize(),
    success: function(res){
               alert(res.status);
               if(res.status === "success") {
                    thanksModal.modal('show');
                        }

                else {$("#id_email").val("");
                      $("#id_email").attr("placeholder", "Please Enter A Valid Email Address");
                        }
    }
})}

$("#id_email").keyup(function (e) {
    if (e.which === 13) {
       addNotifyEmailInHero();
}});

The form works perfecly by clicking the button, the issues come when you press enter to submit it.

If you press enter, from what I understand the function addNotifyEmailInHero is executed but instead of getting the json response and handle it, it just displays it: {"status": "success"}

Update:

I followed geebro's answer, leaving everything the except the suggested changes. This is by html code:

    <form onsubmit="addNotifyEmailInHero()" method="post" id="notify_email_form_in_hero">
        {% csrf_token %}

                <input class="form-control" type="email" name="email" placeholder="If you want to get notified when we go live, please enter your email...." maxlength="255" required id="id_email"/>

                <button type="submit" class="btn btn-block btn-primary" id="submit_notify_email_in_hero">Notify Me</button>

    </form>

It seems to work, although I get an extra post request:

[07/Dec/2017 00:39:45] "POST /notify-email/add/ HTTP/1.1" 200 21
[07/Dec/2017 00:39:45] "POST / HTTP/1.1" 200 23016

Body:
Change your

<button type="button" class="btn btn-block btn-primary" onclick="addNotifyEmailInHero()" id="submit_notify_email_in_hero"><i class="fa fa-bell nav-icon" aria-hidden="true"></i>Notify Me</button>

to

            <button type="submit" class="btn btn-block btn-primary"  id="submit_notify_email_in_hero"><i class="fa fa-bell nav-icon" aria-hidden="true"></i>Notify Me</button>

and change the opening form tag to

<form action="{% url "notify:notify_email_add" %}" onsubmit="addNotifyEmailInHero()" method="post" id="notify_email_form_in_hero">

It should work then


问:
Remove a property in an object immutably
I am using Redux. In my reducer I'm trying to remove a property from an object like this:

```<code>const state = {
    a: '1',
    b: '2',
    c: {
       x: '42',
       y: '43'
    },
}
</code>```

And I want to have something like this without having to mutate the original state:

```<code>const newState = {
    a: '1',
    b: '2',
    c: {
       x: '42',
    },
}
</code>```

I tried:

```<code>let newState = Object.assign({}, state);
delete newState.c.y
</code>```

but for some reasons, it deletes the property from both states.

Could help me to do that?

答:
As hinted in some of the answers already, it's because you are trying to modify a nested state ie. one level deeper. A canonical solution would be to add a reducer on the x state level:

```<code>const state = {
    a: '1',
    b: '2',
    c: {
       x: '42',
       y: '43'
    },
}
</code>```

Deeper level reducer

```<code>let newDeepState = Object.assign({}, state.c);
delete newDeepState.y;
</code>```

Original level reducer

```<code>let newState = Object.assign({}, state, {c: newDeepState});
</code>```

Body:
I am using Redux. In my reducer I'm trying to remove a property from an object like this:

const state = {
    a: '1',
    b: '2',
    c: {
       x: '42',
       y: '43'
    },
}

And I want to have something like this without having to mutate the original state:

const newState = {
    a: '1',
    b: '2',
    c: {
       x: '42',
    },
}

I tried:

let newState = Object.assign({}, state);
delete newState.c.y

but for some reasons, it deletes the property from both states.

Could help me to do that?

Body:
As hinted in some of the answers already, it's because you are trying to modify a nested state ie. one level deeper. A canonical solution would be to add a reducer on the x state level:

const state = {
    a: '1',
    b: '2',
    c: {
       x: '42',
       y: '43'
    },
}

Deeper level reducer

let newDeepState = Object.assign({}, state.c);
delete newDeepState.y;

Original level reducer

let newState = Object.assign({}, state, {c: newDeepState});


问:
Request to localhost from pod via its own service does not work
I have a service named foo with a selector to foo pod:

```<code>apiVersion: v1
kind: Service
metadata:
  labels:
    name: foo
  name: foo
  namespace: bar
spec:
  clusterIP: 172.20.166.230
  ports:
  - port: 8080
    protocol: TCP
    targetPort: 8080
  selector:
    name: foo
  sessionAffinity: None
  type: ClusterIP
</code>```

I have a deployment/pod named foo with a label foo:

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "3"
  generation: 3
  labels:
    name: foo
  name: foo
  namespace: bar
spec:
  selector:
    matchLabels:
      name: foo
  template:
    metadata:
      labels:
        name: foo
    spec:
      containers:
        image: my/image:tag
        imagePullPolicy: Always
        name: foo
        ports:
        - containerPort: 8080
          protocol: TCP
      dnsPolicy: ClusterFirst
</code>```

I make a request from foo pod to foo host, host resolved but requests just don't pass through:

```<code>$ curl -vvv foo:8080
* Rebuilt URL to: foo:8080/
*   Trying 172.20.166.230...
* TCP_NODELAY set
</code>```

Is this supposed to work like that in Kubernetes?

I don't have any problems requesting foo from other pods from the same namespace.

The reason why I don't simply use localhost:8080 (which works fine) is that I have the same config file with hosts used by different pods, so I don't want to write a specific logic per pod.

Kubernetes 1.6.4, single-node cluster, iptables mode.

答: It looks like this is a default behavior when using iptables as a proxy mode.</p>

Body:
I have a service named foo with a selector to foo pod:

apiVersion: v1
kind: Service
metadata:
  labels:
    name: foo
  name: foo
  namespace: bar
spec:
  clusterIP: 172.20.166.230
  ports:
  - port: 8080
    protocol: TCP
    targetPort: 8080
  selector:
    name: foo
  sessionAffinity: None
  type: ClusterIP

I have a deployment/pod named foo with a label foo:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "3"
  generation: 3
  labels:
    name: foo
  name: foo
  namespace: bar
spec:
  selector:
    matchLabels:
      name: foo
  template:
    metadata:
      labels:
        name: foo
    spec:
      containers:
        image: my/image:tag
        imagePullPolicy: Always
        name: foo
        ports:
        - containerPort: 8080
          protocol: TCP
      dnsPolicy: ClusterFirst

I make a request from foo pod to foo host, host resolved but requests just don't pass through:

$ curl -vvv foo:8080
* Rebuilt URL to: foo:8080/
*   Trying 172.20.166.230...
* TCP_NODELAY set

Is this supposed to work like that in Kubernetes?

I don't have any problems requesting foo from other pods from the same namespace.

The reason why I don't simply use localhost:8080 (which works fine) is that I have the same config file with hosts used by different pods, so I don't want to write a specific logic per pod.

Kubernetes 1.6.4, single-node cluster, iptables mode.


问:
append elements to vector in R returns only latest value
I would like to read through a for loop some data in a dataframe and create a ratio using them. The ratio is well calculated as the singular output is fine. However, I wish to create a vector out of the ratios. The issue is that the output of the vector is always the latest ratio. Could anybody help on that, please? Thanks.</p>

```<code>for(i in seq(from = 0, to = nrow(newdata2018), by = 2)){
  ratio1vector <- NULL

  ratio1 <- newdata2018$A_01[i]/newdata2018$A[i]*100
  ratio1vector <- c(ratio1vector, ratio1)

  print(ratio1vector)
}
</code>```

答: To solve the issue is sufficient to create the vector externally from the loop.</p>

Body:
I would like to read through a for loop some data in a dataframe and create a ratio using them. The ratio is well calculated as the singular output is fine. However, I wish to create a vector out of the ratios. The issue is that the output of the vector is always the latest ratio. Could anybody help on that, please? Thanks.

for(i in seq(from = 0, to = nrow(newdata2018), by = 2)){
  ratio1vector <- NULL

  ratio1 <- newdata2018$A_01[i]/newdata2018$A[i]*100
  ratio1vector <- c(ratio1vector, ratio1)

  print(ratio1vector)
}


问:
Amcharts time series data, first label showing date
I want to display only time series. but by default first label showing date. I want it to show "00:00"

https://i.stack.imgur.com/PdWuZ.png

答:
You can set markPeriodChange to false in your categoryAxis to prevent the axis from bolding and using a different date format for the first date:

```<code>AmCharts.makeChart("chartdiv", {
  // ...
  categoryAxis: {
    // ...
    markPeriodChange: false,
    // ...
  }
});
</code>```

Body:
You can set markPeriodChange to false in your categoryAxis to prevent the axis from bolding and using a different date format for the first date:

AmCharts.makeChart("chartdiv", {
  // ...
  categoryAxis: {
    // ...
    markPeriodChange: false,
    // ...
  }
});


问:
Two images comprising the background for a div?
I need to create the following in CSS and have it work on IE7+ (and Firefox if possible):

Everything is done except the background!

The quotation is different each time, so the background needs to automatically adjust in height.

It also needs to auto adjust to the width of the container it's placed within. By this, I mean the gradient cannot stretch. The background needs to be the fade-in left gradient, then the background colour, then the fade-out right gradient.

Here's my current code - now on JSFiddle:

HTML

```<code><div id="ehs-quotecontainer">
    <div id="ehs-bgleft">
    </div>
    <div id="ehs-bgright">
    </div>
    <div class="ehs-marks" id="ehs-marktop">
        “
    </div>
    <span class="ehs-quotetext">Once you believe anything, you stop thinking about it.</span>
    <div class="ehs-marks" id="ehs-markbottom">
        ”
    </div>
</div>
</code>```

CSS

```<code>#ehs-quotecontainer  {
    padding-top:8px;
    padding-bottom:8px;
    background-color:#F7F8FA;
    text-align:center;
}
#ehs-bgleft {
    background:transparent url(../images/ehsbgleft.jpg) repeat-y scroll right top;
}
#ehs-bgright {
    background:transparent url(../images/ehsbgright.jpg) repeat-y scroll right top;
}
.ehs-marks {
    height:20px;
    color:#8B8C90;
    font-size:5.0em;
}
#ehs-marktop {
    float:left;
    margin-top:-18px;
}
#ehs-markbottom {
    float:right;
    margin-top:-5px;
}
.ehs-quotetext {
    padding-left:4px;
    padding-right:4px;
    color:#000;
    font-size:1.1em;
    font-style:italic;
}
</code>```

Any ideas on how to make the background work correctly?

答:
i hate to say this but since you will be using a very small image would you not rather use  the background and insert your text having your background .

so here you will :

you keep the background with the quotation marks as it is

Insert your text in a  with the background that you have . And finally you can just give the text some padding . and you are ready to go .

Body:
I need to create the following in CSS and have it work on IE7+ (and Firefox if possible):

Everything is done except the background!

The quotation is different each time, so the background needs to automatically adjust in height.

It also needs to auto adjust to the width of the container it's placed within. By this, I mean the gradient cannot stretch. The background needs to be the fade-in left gradient, then the background colour, then the fade-out right gradient.

Here's my current code - now on JSFiddle:

HTML

        “

    Once you believe anything, you stop thinking about it.

        ”

CSS

#ehs-quotecontainer  {
    padding-top:8px;
    padding-bottom:8px;
    background-color:#F7F8FA;
    text-align:center;
}
#ehs-bgleft {
    background:transparent url(../images/ehsbgleft.jpg) repeat-y scroll right top;
}
#ehs-bgright {
    background:transparent url(../images/ehsbgright.jpg) repeat-y scroll right top;
}
.ehs-marks {
    height:20px;
    color:#8B8C90;
    font-size:5.0em;
}
#ehs-marktop {
    float:left;
    margin-top:-18px;
}
#ehs-markbottom {
    float:right;
    margin-top:-5px;
}
.ehs-quotetext {
    padding-left:4px;
    padding-right:4px;
    color:#000;
    font-size:1.1em;
    font-style:italic;
}

Any ideas on how to make the background work correctly?


问:
Disable a complete bar in highcharts when clicking on its label
I have a graph:

Location 1 is getting pretty big, which making it hard to read Location 2 data. How can I make a function to click on Location X to hide its bar?

For example, I click on Location 1 and its bar gets hidden and the label gets a gray out color, while the remaining locations data get re-ordered for a better view. When clicking on the gray out Location again it is shown again.

It should work like the label statuses but then per location.

Look at this basic example on JSFiddle. I've managed to make the labels clickable to do something.

This is the code I've added to the bottom of the javascript:

```<code>chart.xAxis[0].labelGroup.element.childNodes.forEach(function(label)
{
    label.style.cursor = "pointer";
  label.onclick = function(){
    alert('You clicked on '+this.textContent);
  }
});
</code>```

But how can I build on this to hide the entire relative bar and change the color of the label, and when click again, show the bar again?

EDIT

I'm sorry that I've made this discovery so late.

The graph is not created directly with JavaScript and the highchart library. It is created with a PHP Symfony Bundle so this is the action that creates the chart:

```<code>public function chartAction()
{
    $em = $this->getDoctrine()->getManager();

    $data = $em->getRepository(Order::class)
        ->getOrdersByStatusAndLocation();

    $statuses = [];
    $locations = [];
    foreach ($data as $row) {
        if (!in_array($row['name'], $locations)) {
            $locations[] = $row['name'];
        }

        $statuses[$row['status']][$row['name']] = [
            'y' => $row['number_of_orders'],
            'url' => $this->generateUrl(
                'order_list',
                ['filter' => [
                    'location' => ['type' => null, 'value' => $row['id']],
                    'status' => ['type' => null, 'value' => $row['status']],
                ]]
            )
        ];
    }

    $result = [];
    foreach ($statuses as $status => $value) {
        $row = [
            'name' => $status,
            'data' => array_fill(0, count($locations), 0)
        ];

        foreach ($value as $location => $numOfOrders) {
            $row['data'][array_search($location, $locations)] = $numOfOrders;
        }

        $result[] = $row;
    }

    $plotOptions = [
        'stacking' => 'normal',
        'cursor' => 'pointer',
        'point' => [
            'events' => [
                'click' => new Expr("function () {
                    location.href = this.url;
                }")
            ]
        ]
    ];

    $chart = new Highchart();
    $chart->chart->renderTo('locationOrderChart');  // The #id of the div where to render the chart
    $chart->chart->type('bar');
    $chart->plotOptions->series($plotOptions);
    $chart->title->text('Orders per location');
    $chart->xAxis->title(['text'  => 'location']);
    $chart->xAxis->categories($locations);
    $chart->yAxis->title(['text'  => 'Orders']);
    $chart->yAxis->allowDecimals(false);
    $chart->series($result);

    return $this->render('AppBundle:Dashboard:chart_location_order_status.html.twig', [
        'chart' => $chart,
    ]);
}
</code>```

Is there a way to implement the answer below into the code above to get the results like Patata's fiddle in the comment of the answer?

I'll really appreciate it if I can get this to work. Thanks in advance.

答:
I tried a solution, not so decent but it'll do your job:

var origCategories = ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
var user1 = [5, 3, 4, 7, 2];
var user2 = [2, 2, 3, 2, 1];
var user3 = [3, 4, 4, 2, 5];
var filteredCategories = [...origCategories];
var filteredUser1 = [...user1],
  filteredUser2 = [...user2],
  filteredUser3 = [...user3];

var data = {
  chart: {
    type: 'bar'
  },
  title: {
    text: 'Stacked bar chart'
  },
  xAxis: {
    categories: filteredCategories,
  },
  yAxis: {
    min: 0,
    title: {
      text: 'Total fruit consumption'
    }
  },
  legend: {
    reversed: true
  },
  plotOptions: {
    series: {
      stacking: 'normal'
    }
  },
  series: [{
    name: 'John',
    data: filteredUser1
  }, {
    name: 'Jane',
    data: filteredUser2
  }, {
    name: 'Joe',
    data: filteredUser3
  }]
}
generateChart = () => {
    chart.xAxis[0].labelGroup.element.childNodes.forEach(function(label) {
        label.style.cursor = "pointer";
        label.onclick = function() {
          let index = origCategories.indexOf(this.textContent);
          filteredUser1[index] = 0;
          filteredUser2[index] = 0;
          filteredUser3[index] = 0;
          chart.destroy();
          chart = Highcharts.chart('container', data);
          generateChart();
        }
      });
}
var chart = Highcharts.chart('container', data);
generateChart();

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container" style="min-width: 310px; max-width: 800px; height: 400px; margin: 0 auto"></div></code>```

You can also check the updated fiddle

Body:
I have a graph:

Location 1 is getting pretty big, which making it hard to read Location 2 data. How can I make a function to click on Location X to hide its bar?

For example, I click on Location 1 and its bar gets hidden and the label gets a gray out color, while the remaining locations data get re-ordered for a better view. When clicking on the gray out Location again it is shown again.

It should work like the label statuses but then per location.

Look at this basic example on JSFiddle. I've managed to make the labels clickable to do something.

This is the code I've added to the bottom of the javascript:

chart.xAxis[0].labelGroup.element.childNodes.forEach(function(label)
{
    label.style.cursor = "pointer";
  label.onclick = function(){
    alert('You clicked on '+this.textContent);
  }
});

But how can I build on this to hide the entire relative bar and change the color of the label, and when click again, show the bar again?

EDIT

I'm sorry that I've made this discovery so late.

The graph is not created directly with JavaScript and the highchart library. It is created with a PHP Symfony Bundle so this is the action that creates the chart:

public function chartAction()
{
    $em = $this->getDoctrine()->getManager();

    $data = $em->getRepository(Order::class)
        ->getOrdersByStatusAndLocation();

    $statuses = [];
    $locations = [];
    foreach ($data as $row) {
        if (!in_array($row['name'], $locations)) {
            $locations[] = $row['name'];
        }

        $statuses[$row['status']][$row['name']] = [
            'y' => $row['number_of_orders'],
            'url' => $this->generateUrl(
                'order_list',
                ['filter' => [
                    'location' => ['type' => null, 'value' => $row['id']],
                    'status' => ['type' => null, 'value' => $row['status']],
                ]]
            )
        ];
    }

    $result = [];
    foreach ($statuses as $status => $value) {
        $row = [
            'name' => $status,
            'data' => array_fill(0, count($locations), 0)
        ];

        foreach ($value as $location => $numOfOrders) {
            $row['data'][array_search($location, $locations)] = $numOfOrders;
        }

        $result[] = $row;
    }

    $plotOptions = [
        'stacking' => 'normal',
        'cursor' => 'pointer',
        'point' => [
            'events' => [
                'click' => new Expr("function () {
                    location.href = this.url;
                }")
            ]
        ]
    ];

    $chart = new Highchart();
    $chart->chart->renderTo('locationOrderChart');  // The #id of the div where to render the chart
    $chart->chart->type('bar');
    $chart->plotOptions->series($plotOptions);
    $chart->title->text('Orders per location');
    $chart->xAxis->title(['text'  => 'location']);
    $chart->xAxis->categories($locations);
    $chart->yAxis->title(['text'  => 'Orders']);
    $chart->yAxis->allowDecimals(false);
    $chart->series($result);

    return $this->render('AppBundle:Dashboard:chart_location_order_status.html.twig', [
        'chart' => $chart,
    ]);
}

Is there a way to implement the answer below into the code above to get the results like Patata's fiddle in the comment of the answer?

I'll really appreciate it if I can get this to work. Thanks in advance.

Body:
I tried a solution, not so decent but it'll do your job:

var origCategories = ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
var user1 = [5, 3, 4, 7, 2];
var user2 = [2, 2, 3, 2, 1];
var user3 = [3, 4, 4, 2, 5];
var filteredCategories = [...origCategories];
var filteredUser1 = [...user1],
  filteredUser2 = [...user2],
  filteredUser3 = [...user3];

var data = {
  chart: {
    type: 'bar'
  },
  title: {
    text: 'Stacked bar chart'
  },
  xAxis: {
    categories: filteredCategories,
  },
  yAxis: {
    min: 0,
    title: {
      text: 'Total fruit consumption'
    }
  },
  legend: {
    reversed: true
  },
  plotOptions: {
    series: {
      stacking: 'normal'
    }
  },
  series: [{
    name: 'John',
    data: filteredUser1
  }, {
    name: 'Jane',
    data: filteredUser2
  }, {
    name: 'Joe',
    data: filteredUser3
  }]
}
generateChart = () => {
    chart.xAxis[0].labelGroup.element.childNodes.forEach(function(label) {
        label.style.cursor = "pointer";
        label.onclick = function() {
          let index = origCategories.indexOf(this.textContent);
          filteredUser1[index] = 0;
          filteredUser2[index] = 0;
          filteredUser3[index] = 0;
          chart.destroy();
          chart = Highcharts.chart('container', data);
          generateChart();
        }
      });
}
var chart = Highcharts.chart('container', data);
generateChart();

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container" style="min-width: 310px; max-width: 800px; height: 400px; margin: 0 auto"></div>

You can also check the updated fiddle


问:
Place app widget on homescreen out of an activity
I know that it's not possible to place an app widget programatically on the homescreen - the user has to do it by himself. But is there a way, to let the user create an app widget without having to go to the "widgets-tab" and choosing it from the list of all available widgets?

My idea is to have a Button in my Activity, which provides some kind of shortcut to that list . This way the user still would create it by himself, but he wouldn't have to leave the app. Is there an Intent I could use in combination with startActivityForResult()?

答:
In Android O, its possible to pin app widget programmatically. Just watch at example here

Also check out Google official documentation


问:
LOESS model in R
I am trying to do a LOESS model for predicting Y based on the independent variable X

data sample is,

```<code>x <- c(10, 20, 25, 32, 40)
y <- c(1200, 1400, 1460, 1620, 1800)
</code>```

steps i use is as following,

```<code>lw1 <- loess(y ~ x,data=data)
plot(y ~ x, data=data,pch=19,cex=0.1)
j <- order(data$x)
lines(data$x[j],lw1$fitted[j])
</code>```

In above data sample , we have only 1 independent variable x.

Now what if we have 2 independent variable?? How to get a model for the following sample data,

```<code>x1 <- c(10,20,25,32,40)
x2 <- c(1.2,1.4,1.5,2.1,2.8)
y <- c(1200,1400,1460,1620,1800)
</code>```

Please help me with an R sample, how can we deal with X1 and X2 in a LOESS model???

Title: LOESS model in R

Body:
I am trying to do a LOESS model for predicting Y based on the independent variable X

data sample is,

x <- c(10, 20, 25, 32, 40)
y <- c(1200, 1400, 1460, 1620, 1800)

steps i use is as following,

lw1 <- loess(y ~ x,data=data)
plot(y ~ x, data=data,pch=19,cex=0.1)
j <- order(data$x)
lines(data$x[j],lw1$fitted[j])

In above data sample , we have only 1 independent variable x.

Now what if we have 2 independent variable?? How to get a model for the following sample data,

x1 <- c(10,20,25,32,40)
x2 <- c(1.2,1.4,1.5,2.1,2.8)
y <- c(1200,1400,1460,1620,1800)

Please help me with an R sample, how can we deal with X1 and X2 in a LOESS model???

Body:
Here is an example with loess(y ~ x1 + x2) and predict:

fit <- loess(y ~ x1 + x2);

pred <- data.frame(ypred = predict(fit, data.frame(x1 = x1, x2 = x2)));
pred$x1 <- x1;
pred$x2 <- x2;
pred$y <- y;

pred;
#      ypred x1  x2    y
#1 1199.8667 10 1.2 1200
#2 1016.4015 20 1.4 1400
#3  728.8215 25 1.5 1460
#4 1620.0000 32 2.1 1620
#5 1799.6245 40 2.8 1800

Sample data

x1 <- c(10,20,25,32,40)
x2 <- c(1.2,1.4,1.5,2.1,2.8)
y <- c(1200,1400,1460,1620,1800);


问:
For Dummies: Parsing XMLs which don't include "=" with LINQ in C#
I only ever find questions on stackoverflow in the vein of <AB> CD = EF </AB>, but hardly without. How would I parse this file in C# with LINQ?:

```<code><root>
    <aa ID=1000>
        <bb>*Value1*</bb>
        <cc>*Value2*</cc>
        <dd>*Value3*</dd>
        <ee>*Value4*</ee>
    </aa>
    <zz ID=2000>
        <bb>*Value5*</bb>
        <cc>*Value6*</cc>
        <dd>*Value7*</dd>
        <ee>*Value8*</ee>
    </zz>
    <aa ID=3000>
        <bb>*Value9*</bb>
        <cc>*Value10*</cc>
        <dd>*Value11*</dd>
        <ee>*Value12*</ee>
    </aa>
    <bb>*Value13*</bb>
    <cc>*Value14*</cc>
    <dd>*Value15*</dd>
    <ee>*Value16*</ee>
</root>
</code>```

I only want to read bb's and dd's, if the are within a aa. So my result (preferably but not necessarily a List) would be:

```<code>*Value1*
*Value3*
*Value9*
*Value11*
</code>```

Edit: Added root-level. To the comments: The zz-Tag is purposefully placed, as are the bb-Tags (etc.) on the same level.

答:
Apart from the fact that that is not valid XML it would be something in the line of (pseudocode)

```<code>XDocument.Parse(yourxml).GetChildren().Where(child => child.Name == "aa").GetChildren().Where(child2 => child2.Name == "bb" || child2.Name == "dd").Select(x => x.Value)
</code>```

This should do the work. It's pseudocode but I don't remember exactly the XDocument method names

Body:
I only ever find questions on stackoverflow in the vein of <AB> CD = EF </AB>, but hardly without. How would I parse this file in C# with LINQ?:

<root>
    <aa ID=1000>
        <bb>*Value1*</bb>
        <cc>*Value2*</cc>

*Value3*

        <ee>*Value4*</ee>
    </aa>
    <zz ID=2000>
        <bb>*Value5*</bb>
        <cc>*Value6*</cc>

*Value7*

        <ee>*Value8*</ee>
    </zz>
    <aa ID=3000>
        <bb>*Value9*</bb>
        <cc>*Value10*</cc>

*Value11*

        <ee>*Value12*</ee>
    </aa>
    <bb>*Value13*</bb>
    <cc>*Value14*</cc>

*Value15*

    <ee>*Value16*</ee>
</root>

I only want to read bb's and dd's, if the are within a aa. So my result (preferably but not necessarily a List) would be:

*Value1*
*Value3*
*Value9*
*Value11*

Edit: Added root-level. To the comments: The zz-Tag is purposefully placed, as are the bb-Tags (etc.) on the same level.

Body:
Apart from the fact that that is not valid XML it would be something in the line of (pseudocode)

XDocument.Parse(yourxml).GetChildren().Where(child => child.Name == "aa").GetChildren().Where(child2 => child2.Name == "bb" || child2.Name == "dd").Select(x => x.Value)

This should do the work. It's pseudocode but I don't remember exactly the XDocument method names


问:
Site matching query does not exist
The site was working very well until I clicked "log out" on my app. After that, the website would give me this error:
DoesNotExist at /login/
Site matching query does not exist.

I searched everywhere and the only solution I get relates to setting up the site framework, SITE_ID, etc. I think those items on my computer are fine, but I can't find a walkthrough/guide to help me check on them.

What's the problem and how can it be fixed?

```<code> DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '/home/dotcloud/nhs.db',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}
</code>```

答:
I fixed it without using python manage.py shell

At first I tried using the commands above using manage.py shell:

```<code>from django.contrib.sites.models import Site
new_site = Site.objects.create(domain='foo.com', name='foo.com')
print(new_site.id)
</code>```

But it gave out an INTEGRITY ERROR

The short answer is add SITE_ID = 1 to your settings.py
If you want to know what your site id is, then go into the actual database, I downloaded sqliteman to see what my table had. So whatever site id you have in the table is what gets assigned to SITE_ID

This is because there is a function get_current that goes looking for SITE_ID and it doesn't find it in your settings.py

```<code>tables
-django_site
--Columns
---id
</code>```

it should have id as 1, name as example.com, domain as example.com

Title: Site matching query does not exist

Body:
The site was working very well until I clicked "log out" on my app. After that, the website would give me this error:
DoesNotExist at /login/
Site matching query does not exist.

I searched everywhere and the only solution I get relates to setting up the site framework, SITE_ID, etc. I think those items on my computer are fine, but I can't find a walkthrough/guide to help me check on them.

What's the problem and how can it be fixed?

 DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '/home/dotcloud/nhs.db',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

Body:
I fixed it without using python manage.py shell

At first I tried using the commands above using manage.py shell:

from django.contrib.sites.models import Site
new_site = Site.objects.create(domain='foo.com', name='foo.com')
print(new_site.id)

But it gave out an INTEGRITY ERROR

The short answer is add SITE_ID = 1 to your settings.py
If you want to know what your site id is, then go into the actual database, I downloaded sqliteman to see what my table had. So whatever site id you have in the table is what gets assigned to SITE_ID

This is because there is a function get_current that goes looking for SITE_ID and it doesn't find it in your settings.py

tables
-django_site
--Columns
---id

it should have id as 1, name as example.com, domain as example.com