问:
Push Notification in PHP using PEM file
I've been working through Ray Wenderlich's tutorials on push notifications using a PHP Script.

Reference: http://www.raywenderlich.com/32960/apple-push-notification-services-in-ios-6-tutorial-part-1

http://www.raywenderlich.com/32963/apple-push-notification-services-in-ios-6-tutorial-part-2

I have done a ton of research but I have ran into an issue on part 2 where you run the push.php file using the ck.pem file.

/Applications/XAMPP/bin/php push.php development

My only difference is that I'm using XAMPP and not MAMP.

I have confirmed that all the extensions are installed.

I am able to test out my certificate in the terminal by doing this:

openssl s_client -connect gateway.sandbox.push.apple.com:2195 -cert PushChatCert.pem -key PushChatKey.pem

It asks me to enter my passphrase and I do. Everything works successfully in the terminal.

However, when I run the push.php file, I get these errors:

PHP Warning:  stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
PHP Warning:  stream_socket_client(): Failed to enable crypto in

PHP Warning:  stream_socket_client(): unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Unknown error) in on line 140

Line 140 in the php file is:

$this->fp = stream_socket_client('ssl://' . $this->server, $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);

I found these:

iOS push notification does not work when using crontab scheduler

https://devforums.apple.com/message/1054840#1054840

Push notification in PHP

I have literally retried everything. I know my passphrase is correct. I've re-created my certificates, pem files, and keys. Nothing works. Same error every time I do this.

I'm beyond confused.

Does anyone have any suggestions or know what's going on?

Thank you!

UPDATE 1:

I have also tried setting the full path to the ck.pem file that does not fix the error either.

答:
Update to macOS sierra 10.12.5

please add

```<code>stream_context_set_option($ctx, 'ssl', 'verify_peer', false);
</code>```

The problem is in new PHP Version in macOS Sierra

Title: Push Notification in PHP using PEM file

Body:
Update to macOS sierra 10.12.5

please add

stream_context_set_option($ctx, 'ssl', 'verify_peer', false);

The problem is in new PHP Version in macOS Sierra


来源: stackexchange

问:
Compute the mean of a data blob during testing phase
I am using hdf5 layer that has data and label. </p>

```<code>layer {
  name: "data"
  type: "HDF5Data"
  top: "data"
  top: "label"
  include {
    phase: TEST
  }
  hdf5_data_param {
    source: "./list.txt"
    batch_size: 8
    shuffle: true
  }
}
</code>```

<p>During the testing phase, it will load 8 images from the testing set and feed the network. I would like to print the mean value of each image during the testing phase. Is it possible to use it in CAFFE? Which layer should I used? </p>

答:
I think you are looking for <code>"Reduction"</code> layer </p>

```<code>layer {
  type: "Reduction"
  name: "img_mean"
  bottom: "data"
  top: "img_mean"
  reduction_param {
    operation: MEAN
    axis: 0  # to reduce the entire batch, or axis: 1 for per-image mean
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using hdf5 layer that has data and label.

layer {
  name: "data"
  type: "HDF5Data"
  top: "data"
  top: "label"
  include {
    phase: TEST
  }
  hdf5_data_param {
    source: "./list.txt"
    batch_size: 8
    shuffle: true
  }
}

During the testing phase, it will load 8 images from the testing set and feed the network. I would like to print the mean value of each image during the testing phase. Is it possible to use it in CAFFE? Which layer should I used?

Body:
I think you are looking for "Reduction" layer

layer {
  type: "Reduction"
  name: "img_mean"
  bottom: "data"
  top: "img_mean"
  reduction_param {
    operation: MEAN
    axis: 0  # to reduce the entire batch, or axis: 1 for per-image mean
  }
}


问:
Write list of objects to text file
I've got a class Dish like this:

```<code>public class Dish
{
    public Dish(int cost, string name)
    {
        Cost = cost;
        Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }
}
</code>```

In the main form the user can enter the previous data.
Then I create a list of "Dish":

```<code>public static List<Piatto> List = new List<Piatto>();
</code>```

I created it in a static class, so I can access it from anywhere.
As soon as an item get added to the list, I want to save it in a text file (.txt) so I tried to use this:

```<code>public static void SaveToTxt()
    {
        using (TextWriter tw = new StreamWriter(Path))
        {
            foreach (var item in Data.List)
            {
                tw.WriteLine(item.ToString());
            }
        }
    }
</code>```

The issue is that when I open the text file where I saved my list, I get "WindowsFormsApplication1.Dish".

How can I save to a text file showing Cost and Name?

P.s. I would like to save the list in a text file because it's easier for me to delete a line, something that I don't know how to do in binary.

Thanks in advance.

EDIT:

Overriding the ToString() method worked fine. Thank you all for the answers!

答:
Change your code to something like this</p>

```<code>public static void SaveToTxt()
{
    using (TextWriter tw = new StreamWriter(Path))
    {
        foreach (var item in Data.List)
        {
            tw.WriteLine(string.Format("{0} {1}", item.Name, item.Cost));
        }
    }
}
</code>```

Title: Write list of objects to text file

Body:
I've got a class Dish like this:

public class Dish
{
    public Dish(int cost, string name)
    {
        Cost = cost;
        Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }
}

In the main form the user can enter the previous data.
Then I create a list of "Dish":

public static List<Piatto> List = new List<Piatto>();

I created it in a static class, so I can access it from anywhere.
As soon as an item get added to the list, I want to save it in a text file (.txt) so I tried to use this:

public static void SaveToTxt()
    {
        using (TextWriter tw = new StreamWriter(Path))
        {
            foreach (var item in Data.List)
            {
                tw.WriteLine(item.ToString());
            }
        }
    }

The issue is that when I open the text file where I saved my list, I get "WindowsFormsApplication1.Dish".

How can I save to a text file showing Cost and Name?

P.s. I would like to save the list in a text file because it's easier for me to delete a line, something that I don't know how to do in binary.

Thanks in advance.

EDIT:

Overriding the ToString() method worked fine. Thank you all for the answers!

Body:
Change your code to something like this

public static void SaveToTxt()
{
    using (TextWriter tw = new StreamWriter(Path))
    {
        foreach (var item in Data.List)
        {
            tw.WriteLine(string.Format("{0} {1}", item.Name, item.Cost));
        }
    }
}


答:
You need to override ToString method of your class like this:

```<code>public override string ToString()
{
    return string.Format("Name: {0}, Cost: {1}",Name,Cost);
}
</code>```

Title: Write list of objects to text file

Body:
You need to override ToString method of your class like this:

public override string ToString()
{
    return string.Format("Name: {0}, Cost: {1}",Name,Cost);
}


问:
How to create a date range with php?
I tried to make time with PHP. start date of 2017-01-29 to 2017-12-29. But that happened I could not print in February because the month maximum of only 28 days. How to order printed anyway but with the February date up to 28.

my script:

```<code>date_default_timezone_set('UTC');

// Start date
$date = '2017-01-29';
// End date
$end_date = '2017-12-29';

while (strtotime($date) <= strtotime($end_date)) {
    echo "$date\n";
    echo "<br>";
    $date = date ("Y-m-d", strtotime("+1 month", strtotime($date)));
}
</code>```

Output:

答:
Try this code:</p>

```<code>    <?php
         $from = new DateTime;
         $to = new DateTime('+1 year');

        for($date=clone $from; $date<$to; $date->modify('+1 day')){
              echo $date->format('Y-m-d');
         }
    ?>
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to create a date range with php?

Body:
I tried to make time with PHP. start date of 2017-01-29 to 2017-12-29. But that happened I could not print in February because the month maximum of only 28 days. How to order printed anyway but with the February date up to 28.

my script:

date_default_timezone_set('UTC');

// Start date
$date = '2017-01-29';
// End date
$end_date = '2017-12-29';

while (strtotime($date) <= strtotime($end_date)) {
    echo "$date\n";
    echo "
";
    $date = date ("Y-m-d", strtotime("+1 month", strtotime($date)));
}

Output:

Body:
Try this code:

    <?php
         $from = new DateTime;
         $to = new DateTime('+1 year');

        for($date=clone $from; $date<$to; $date->modify('+1 day')){
              echo $date->format('Y-m-d');
         }
    ?>


答:
your item is an object that contains several properties and you have to access them:

```<code>public static void SaveToTxt()
{
    using (TextWriter tw = new StreamWriter(Path))
    {
        foreach (var item in Data.List)
        {
            tw.WriteLine(string.Format("Item: {0} - Cost: {1}", item.Name, item.Cost.ToString()));
        }
    }
}
</code>```

Title: Write list of objects to text file

Body:
your item is an object that contains several properties and you have to access them:

public static void SaveToTxt()
{
    using (TextWriter tw = new StreamWriter(Path))
    {
        foreach (var item in Data.List)
        {
            tw.WriteLine(string.Format("Item: {0} - Cost: {1}", item.Name, item.Cost.ToString()));
        }
    }
}


问:
how to append item to an array value with Sequelize + PostgreSQL
I have a posgresql database, table has a column which is an array: Sequelize.ARRAY(Sequelize.BIGINT).

What is the right way to append a new item to the array?

I am new to posgresql, sequelize and nodejs. May be it is a trivial question.
From reading around I think I know how to use Promise.all to read all rows, append, and update back.
The question, isn't there any useful shortcut.

PostreSQL documentation mentions a function array_append(anyarray, anyelement).

Sequelize documentation offers a function fn, which Creates an object representing a database function, but only seems to be working in where and order parts

Any way to combine those for an append-like update?

答:
Array Datatype has many methods like append, concat etc. which you can see here. I will give an example with array_append function.

Room is a sequelize model and job_ids is a column in this model with datatype as Array of integer. sequelize is an instant of Sequelize class.

```<code>Room.update(
 {'job_ids': sequelize.fn('array_append', sequelize.col('job_ids'), new_jobId)},
 {'where': {'id': roomId}}
);
</code>```

Assuming default value of this column is an empty array else it may throw an error.

Body:
Array Datatype has many methods like append, concat etc. which you can see here. I will give an example with array_append function.

Room is a sequelize model and job_ids is a column in this model with datatype as Array of integer. sequelize is an instant of Sequelize class.

Room.update(
 {'job_ids': sequelize.fn('array_append', sequelize.col('job_ids'), new_jobId)},
 {'where': {'id': roomId}}
);

Assuming default value of this column is an empty array else it may throw an error.


问:
Decoding VP9 with Alpha Channel in Android, is it possible?
Currently FFmpeg support VP9 compression to yuva420p.

Using grafika as code base I am implemented playing VP9 yuva420p encoded video in Android (using SurfaceTexture and MediaCodec), but I can't get Alpha channel from the video.

I checked that video encoded with VideoAlphaMode; ID: 0x53c0 size: 4, so I am sure that video contains alpha channel.

So the question is: does Android 4.4+ decoder supports VP9 with Alpha channel?

答:
Try It   </p>

```<code> ffmpeg -i input.mov -c:v libvpx -pix_fmt yuva420p out.webm
</code>```

Body:
Try It

 ffmpeg -i input.mov -c:v libvpx -pix_fmt yuva420p out.webm


问:
PHP - Do (and echo) operation only when remainder from is 0 - Going into infinite loop
Let me start by the end and the actual question:

I'm trying to write a PHP script that from two random numbers $x and $y will only we outputted and resolved when modulo == 0 (it should always echo a valid function)

What do I mean:

The script echos:

4 / 2 => GOOD!

The script echos:

4 / 3 => BAD!

NOTHING => BAD!

I'll try to guide you through my reasoning but be warned:

I'm a newbie so: I learn something, up the ante, and try to apply it conveniently.

First I generate the random numbers, easy:

```<code>$x = mt_rand(1,10);
$y = mt_rand(1,10);
</code>```

Now I say, I have two possibilities after division, remainder 0 or not 0, so an if() statement looks like a good idea, so I do:

if($x % $y == 0){

echo $x . "/" . $y;

}else{

echo "The remainder is not 0";

}

This works as expected except of course, I always want to generate this remainder is not 0 divisions.

So my approach was the following, why not use user generated functions (never used the before but could come in handy) so, if I know this works just fine:

```<code><?php

function hello(){
      echo "Hello!";
}

hello();
?>
</code>```

Why not up the ante as I said before and use it, so I mix the up:

```<code><?php
$x = mt_rand(1,10);
$y = mt_rand(1,10);

function foo(){

if($x % $y == 0){

echo $x . "/" . $y;

}else{

foo();

}

}

?>
</code>```

It doesn't work, I get a blank screen.

What was I expecting from this script:

Create a function with an if() statement on it

If the remainder is 0, great, echo.

else, start all over, again and again, till you get a division with no remainder.

This does't work.

So I basically ask, what I am doing wrong? What is wrong with the line of though behind this?

Can this work with a subtle change?

To experienced coders, I know you could all make a script that does this (but has nothing to do with mine) using MS PAINT as an IDE, BUT:

I have no interest in the code itself since this is ONLY for learning purposes.

This is not the first time it has happened to me, I keep hitting the wall with infinite loops VERY often, so the slighter the change (and the bigger the explanation) the better, and will be very much appreciated.

Thanks in advance!

Now that finish I've just realized the problem might not even be a infinite loop, even if it's not the question still stands, what do you think think of my approach? (of course I will also edit and remove the infinite loop from the question)

答:
Alright, let's start with the basics.

The reason why your application isn't displaying anything is because you haven't told it to. You've defined a function which will display something, but you've never actually called it.

Basically, you need to do this:

```<code>function foo() {
  // foo logic
}

foo();
</code>```

Notice how the call to foo is made outside of the function itself, in the mainline logic of the application.

Next, you need to move your calls to mt_rand() to be inside your foo() function, so that new random numbers will be generated on every call.

Finally, you don't need to make calls to foo() from within foo(). Doing this is allowed, and is something called "recursion", but it's really not needed here. What you should do is set your function up so that it returns a boolean (i.e. true/false) value when the function finishes, letting you know that it worked. You can then setup a while loop to repeatedly execute the function until it completes properly.

Here is an example:

```<code>function foo() {
  //define the random values
  $x = mt_rand(1,10);
  $y = mt_rand(1,10);

  //if they match, echo the statement and return true so the loop ends
  //otherwise, return false so the loop repeats
  if (($x % $y) == 0) {
    echo $x . "/" . $y;
    return true;
  } else {
    return false;
  }
}

//we're now *outside* of the function, and in mainline logic

//setup a variable to hold the return value of the function
//initialize it to false so that the first loop executes
$foundEquation = false;

//execute the function in a loop until we find
//the right equation
while(!$foundEquation) {
  $foundEquation = foo();
}
</code>```

Does that answer your question? Let me know if you have any trouble understanding what's happening here. I'm happy to clarify anything about this code.

ContentLicense: CC BY-SA 2.5

Body:
Let me start by the end and the actual question:

I'm trying to write a PHP script that from two random numbers $x and $y will only we outputted and resolved when modulo == 0 (it should always echo a valid function)

What do I mean:

The script echos:

4 / 2 => GOOD!

The script echos:

4 / 3 => BAD!

NOTHING => BAD!

I'll try to guide you through my reasoning but be warned:

I'm a newbie so: I learn something, up the ante, and try to apply it conveniently.

First I generate the random numbers, easy:

$x = mt_rand(1,10);
$y = mt_rand(1,10);

Now I say, I have two possibilities after division, remainder 0 or not 0, so an if() statement looks like a good idea, so I do:

if($x % $y == 0){

echo $x . "/" . $y;

}else{

echo "The remainder is not 0";

}

This works as expected except of course, I always want to generate this remainder is not 0 divisions.

So my approach was the following, why not use user generated functions (never used the before but could come in handy) so, if I know this works just fine:

<?php

function hello(){
      echo "Hello!";
}

hello();
?>

Why not up the ante as I said before and use it, so I mix the up:

<?php
$x = mt_rand(1,10);
$y = mt_rand(1,10);

function foo(){

if($x % $y == 0){

echo $x . "/" . $y;

}else{

foo();

}

}

?>

It doesn't work, I get a blank screen.

What was I expecting from this script:

Create a function with an if() statement on it

If the remainder is 0, great, echo.

else, start all over, again and again, till you get a division with no remainder.

This does't work.

So I basically ask, what I am doing wrong? What is wrong with the line of though behind this?

Can this work with a subtle change?

To experienced coders, I know you could all make a script that does this (but has nothing to do with mine) using MS PAINT as an IDE, BUT:

I have no interest in the code itself since this is ONLY for learning purposes.

This is not the first time it has happened to me, I keep hitting the wall with infinite loops VERY often, so the slighter the change (and the bigger the explanation) the better, and will be very much appreciated.

Thanks in advance!

Now that finish I've just realized the problem might not even be a infinite loop, even if it's not the question still stands, what do you think think of my approach? (of course I will also edit and remove the infinite loop from the question)

Body:
Alright, let's start with the basics.

The reason why your application isn't displaying anything is because you haven't told it to. You've defined a function which will display something, but you've never actually called it.

Basically, you need to do this:

function foo() {
  // foo logic
}

foo();

Notice how the call to foo is made outside of the function itself, in the mainline logic of the application.

Next, you need to move your calls to mt_rand() to be inside your foo() function, so that new random numbers will be generated on every call.

Finally, you don't need to make calls to foo() from within foo(). Doing this is allowed, and is something called "recursion", but it's really not needed here. What you should do is set your function up so that it returns a boolean (i.e. true/false) value when the function finishes, letting you know that it worked. You can then setup a while loop to repeatedly execute the function until it completes properly.

Here is an example:

function foo() {
  //define the random values
  $x = mt_rand(1,10);
  $y = mt_rand(1,10);

  //if they match, echo the statement and return true so the loop ends
  //otherwise, return false so the loop repeats
  if (($x % $y) == 0) {
    echo $x . "/" . $y;
    return true;
  } else {
    return false;
  }
}

//we're now *outside* of the function, and in mainline logic

//setup a variable to hold the return value of the function
//initialize it to false so that the first loop executes
$foundEquation = false;

//execute the function in a loop until we find
//the right equation
while(!$foundEquation) {
  $foundEquation = foo();
}

Does that answer your question? Let me know if you have any trouble understanding what's happening here. I'm happy to clarify anything about this code.


答:
I think you have to override ToString method in your Dish class:</p>

```<code>public class Dish
{
    public Dish(int cost, string name)
    {
        Cost = cost;
        Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }

    public override string ToString()
    {
        return $"{Name}: {Cost.ToString("c")}";
    }
}
</code>```

Title: Write list of objects to text file

Body:
I think you have to override ToString method in your Dish class:

public class Dish
{
    public Dish(int cost, string name)
    {
        Cost = cost;
        Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }

    public override string ToString()
    {
        return $"{Name}: {Cost.ToString("c")}";
    }
}


问:
How to create rss feed from my category joomla 3.2.3?
Does Joomla 3.2 have an RSS feed creator in core as 2.5 had? I would like to create an RSS feed with articles from one of my joomla's category.</p>

答:
You can specify the display format at the end of the category url in this way:

```<code>www.mypage.com/index.php?option=com_content&view=category&id=<YOUR_CATEGORY_ID>&format=feed&type=rss
</code>```

When you add &format=feed&type=rss string at the end of the URL you transform the classic page in an RSS feed. You can change type=rss with type=atom if you want.

Body:
You can specify the display format at the end of the category url in this way:

www.mypage.com/index.php?option=com_content&view=category&id=<YOUR_CATEGORY_ID>&format=feed&type=rss

When you add &format=feed&type=rss string at the end of the URL you transform the classic page in an RSS feed. You can change type=rss with type=atom if you want.


问:
A last part in query is not working
I have some code, but $query_last is not working, previous  identica part $query  -without problems.

I Don't understand what the problem is.

```<code><?php
    if ($_SERVER["REQUEST_METHOD"]=="POST"){
        require 'connect_k.php';
        createMessage();
    }

    function createMessage(){
        global $connect;
        $email = $_POST["email"];
        $price_main = $_POST["price_main"];
        $date = $_POST["date"];
        $order_number = $_POST["order_number"];
        $query="INSERT INTO final(email,name,size,quantity,price)SELECT email,name,size,quantity,price FROM items_cart WHERE email like ('$email');";
        $query_del="DELETE FROM items_cart WHERE email like ('$email');";
        $query_upd="UPDATE final SET price_main='$price_main',order_number='$order_number',date='$date' WHERE email like ('$email');";
----problem is here----
        $query_last="INSERT INTO order(email,name,size,quantity,price,price_main,order_number,date)SELECT email,name,size,quantity,price,price_main,order_number,date FROM final WHERE email like ('$email');";
        mysqli_query ($connect,$query)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_del)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_upd)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_last)or die (mysqli_error($connect));
        mysqli_close($connect);
    }
?>
</code>```

答:
Maybe the problem is that you are not escaping the query before passing it to the database, you should try using addslashes function for your inputs.

```<code>    function createMessage(){
        global $connect;
        $email = addslashes($_POST["email"]);
        $price_main = addslashes($_POST["price_main"]);
        $date = addslashes($_POST["date"]);
        $order_number = addslashes($_POST["order_number"]);
        $query="INSERT INTO final(email,name,size,quantity,price)SELECT email,name,size,quantity,price FROM items_cart WHERE email like ('$email');";
        $query_del="DELETE FROM items_cart WHERE email like ('$email');";
        $query_upd="UPDATE final SET price_main='$price_main',order_number='$order_number',date='$date' WHERE email like ('$email');";
----problem is here----
        $query_last="INSERT INTO order(email,name,size,quantity,price,price_main,order_number,date)SELECT email,name,size,quantity,price,price_main,order_number,date FROM final WHERE email like ('$email');";
        mysqli_query ($connect,$query)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_del)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_upd)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_last)or die (mysqli_error($connect));
        mysqli_close($connect);
    }
</code>```

Title: A last part in query is not working

Body:
I have some code, but $query_last is not working, previous  identica part $query  -without problems.

I Don't understand what the problem is.

<?php
    if ($_SERVER["REQUEST_METHOD"]=="POST"){
        require 'connect_k.php';
        createMessage();
    }

    function createMessage(){
        global $connect;
        $email = $_POST["email"];
        $price_main = $_POST["price_main"];
        $date = $_POST["date"];
        $order_number = $_POST["order_number"];
        $query="INSERT INTO final(email,name,size,quantity,price)SELECT email,name,size,quantity,price FROM items_cart WHERE email like ('$email');";
        $query_del="DELETE FROM items_cart WHERE email like ('$email');";
        $query_upd="UPDATE final SET price_main='$price_main',order_number='$order_number',date='$date' WHERE email like ('$email');";
----problem is here----
        $query_last="INSERT INTO order(email,name,size,quantity,price,price_main,order_number,date)SELECT email,name,size,quantity,price,price_main,order_number,date FROM final WHERE email like ('$email');";
        mysqli_query ($connect,$query)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_del)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_upd)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_last)or die (mysqli_error($connect));
        mysqli_close($connect);
    }
?>

Body:
Maybe the problem is that you are not escaping the query before passing it to the database, you should try using addslashes function for your inputs.

    function createMessage(){
        global $connect;
        $email = addslashes($_POST["email"]);
        $price_main = addslashes($_POST["price_main"]);
        $date = addslashes($_POST["date"]);
        $order_number = addslashes($_POST["order_number"]);
        $query="INSERT INTO final(email,name,size,quantity,price)SELECT email,name,size,quantity,price FROM items_cart WHERE email like ('$email');";
        $query_del="DELETE FROM items_cart WHERE email like ('$email');";
        $query_upd="UPDATE final SET price_main='$price_main',order_number='$order_number',date='$date' WHERE email like ('$email');";
----problem is here----
        $query_last="INSERT INTO order(email,name,size,quantity,price,price_main,order_number,date)SELECT email,name,size,quantity,price,price_main,order_number,date FROM final WHERE email like ('$email');";
        mysqli_query ($connect,$query)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_del)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_upd)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_last)or die (mysqli_error($connect));
        mysqli_close($connect);
    }


答:
Its simple, You are almost there, I think you forgot to override the .ToString() method inside your class. By overriding the .ToString() method you can return the string representation of its object. You can format them as well. So you have to add this overrided .ToString() method to make it work. Consider the following code

```<code>public class Dish
{
    public Dish(int cost, string name)
    {
        Cost = cost;
        Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }
    public override string ToString()
    {
       return String.Format("Item Name :{0} \n Item Cost : {1}", this.Name,this.Cost);
    }
}
</code>```

Title: Write list of objects to text file

Body:
Its simple, You are almost there, I think you forgot to override the .ToString() method inside your class. By overriding the .ToString() method you can return the string representation of its object. You can format them as well. So you have to add this overrided .ToString() method to make it work. Consider the following code

public class Dish
{
    public Dish(int cost, string name)
    {
        Cost = cost;
        Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }
    public override string ToString()
    {
       return String.Format("Item Name :{0} \n Item Cost : {1}", this.Name,this.Cost);
    }
}


问:
Play video from emulator sd card on VideoView - Android (Xamarin)
I am trying to display a mp4 video from my emulator on a VideoView and eventually display the thumbnail of the video using thumbnailUtils but I get "Can't play this video". I am assuming I am getting the path wrong since I can play the video from the Assets folder with:

```<code>Android.Net.Uri vid = Android.Net.Uri.Parse("android.resource://" + PackageName + "/" + Resource.Drawable.SampleVideo1)
</code>```

Using the device monitor I can see that my video is on /data/media/0/SampleVideo1.mp4 even though when I dragged and dropped the video on Genymotion it said that the file was copied on sdcard/Download. From other threads I saw people giving the path like this:

```<code>static string path = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
string file = System.IO.Path.Combine(path.ToString(), "SampleVideo1.mp4");
</code>```

and I also tried with this way:

```<code>var vidPath = "/data/media/0/SampleVideo1.mp4";
videoview.SetVideoPath(vidPath);
</code>```

What am I doing wrong and which is the correct way to set a path since I know that my video is on /data/media/0/ ?

答:
What am I doing wrong and which is the correct way to set a path since I know that my video is on /data/media/0/ ?

It is possible that your file path is wrong, from your code I thought your file is saved in external storage(sd card), then the file path should be for example like this:

/storage/0/Movies/your file

But your file path is /data/media/0/, it's internal storage Environment.DataDirectory, and your app doesn't have permissions for reading and writing the file under the system media, I suggest to change your file path either to the external storage Environment.ExternalStorageDirectory or to the local data of your app for example to FilesDir.

Based on the title of your question, you file should be placed for example here:

And code for example like this:

```<code>var filename = "one.mp4";
var path = System.IO.Path.Combine(Environment.ExternalStorageDirectory.AbsoluteFile.ToString(), filename);
videoView.SetVideoPath(path);
videoView.Start();
</code>```

Body:
I am trying to display a mp4 video from my emulator on a VideoView and eventually display the thumbnail of the video using thumbnailUtils but I get "Can't play this video". I am assuming I am getting the path wrong since I can play the video from the Assets folder with:

Android.Net.Uri vid = Android.Net.Uri.Parse("android.resource://" + PackageName + "/" + Resource.Drawable.SampleVideo1)

Using the device monitor I can see that my video is on /data/media/0/SampleVideo1.mp4 even though when I dragged and dropped the video on Genymotion it said that the file was copied on sdcard/Download. From other threads I saw people giving the path like this:

static string path = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
string file = System.IO.Path.Combine(path.ToString(), "SampleVideo1.mp4");

and I also tried with this way:

var vidPath = "/data/media/0/SampleVideo1.mp4";
videoview.SetVideoPath(vidPath);

What am I doing wrong and which is the correct way to set a path since I know that my video is on /data/media/0/ ?

Body:
What am I doing wrong and which is the correct way to set a path since I know that my video is on /data/media/0/ ?

It is possible that your file path is wrong, from your code I thought your file is saved in external storage(sd card), then the file path should be for example like this:

/storage/0/Movies/your file

But your file path is /data/media/0/, it's internal storage Environment.DataDirectory, and your app doesn't have permissions for reading and writing the file under the system media, I suggest to change your file path either to the external storage Environment.ExternalStorageDirectory or to the local data of your app for example to FilesDir.

Based on the title of your question, you file should be placed for example here:

And code for example like this:

var filename = "one.mp4";
var path = System.IO.Path.Combine(Environment.ExternalStorageDirectory.AbsoluteFile.ToString(), filename);
videoView.SetVideoPath(path);
videoView.Start();


问:
Learning J/K/APL
I know all 3 are related, and I've seen quite a few answers for problems in Project Euler written in J, and a few written K. What I'm wondering is, which would you suggest learning, and where would you suggest going about getting the materials to learn it?</p>

答:
APL

Created by Kenneth Iverson as the original array programming language. Uses a non-ASCII character set as there are no reserved words. The British APL Association keeps an up-to-date list of interpreters (both free and commercial) as well as information on the APL-inspired languages covered below.

A+

Created by Arthur Whitney as a follow-up to APL. The source code is available under GPL and there is an included XEmacs extension. Download from the website.

J

Created by Kenneth Iverson and Roger Hui, this only requires ASCII characters. The source used to cost money, though recently was released under GPL. Download from the website.

K

Another Arthur Whitney language, this also uses ASCII characters. The company behind it has since decommissioned the language, but there is the open-source Kona.

Q

Built on top of K to include SQL-like query/join capabilities (tables are a built-in container), this language is built on handling lots of data. A non-commercial licensed version can be downloaded from the website.

As for what's actively used, Q is fairly popular in finance, whereas J has some support from academia and hobbyists. Those two are your best bet for array programming these days.

Title: Learning J/K/APL


问:
Why These javascript expressions works unexpectedly
There are some javascript syntaxes and I didnt understand why they works.

1.

```<code>({} === {}) // returns false
</code>```

2.

```<code>function foo() {
       return
       {
          foo: 'bar'
       }
    }

    function bar() {
       return {
          foo: 'bar'
       }
    }

(typeof foo() === typeof bar()) //return false again
</code>```

3.

```<code>([1,2,3] == [1,2,3]); //very interesting false again
</code>```

答: In all of these cases, a reference check is performed on the objects on the left and right hand side of the comparison operator. This returns false because although they look the same, they are actually different instances.</p>

Body:
There are some javascript syntaxes and I didnt understand why they works.

1.

({} === {}) // returns false

2.

function foo() {
       return
       {
          foo: 'bar'
       }
    }

    function bar() {
       return {
          foo: 'bar'
       }
    }

(typeof foo() === typeof bar()) //return false again

3.

([1,2,3] == [1,2,3]); //very interesting false again


问:
sql statement to fetch data from the database of exactly 5 days past
I was working on something and I needed to query a record from the database that is exactly 5 days from now, but it did not work as expected.

I have tried something but it's just fetching record of from 5 days till now. All I wanted is the record of exactly 5 days past (or ago). Here is my code, please tell me want I am not doing right.

```<code>SELECT * FROM ts_user
WHERE user_registerdate >= DATE_SUB(CURDATE(), INTERVAL 5 day) AND user_registerdate <= CURDATE()
ORDER BY user_registerdate DESC;
</code>```

答:
This gets exactly 5 days ago,</p>

```<code>SELECT *, DATE_FORMAT(user_registerdate, '%m/%d/%Y')
FROM ts_user
WHERE DATE(user_registerdate) = CURDATE() - INTERVAL 5 DAY;
</code>```

Body:
I was working on something and I needed to query a record from the database that is exactly 5 days from now, but it did not work as expected.

I have tried something but it's just fetching record of from 5 days till now. All I wanted is the record of exactly 5 days past (or ago). Here is my code, please tell me want I am not doing right.

SELECT * FROM ts_user
WHERE user_registerdate >= DATE_SUB(CURDATE(), INTERVAL 5 day) AND user_registerdate <= CURDATE()
ORDER BY user_registerdate DESC;

Body:
This gets exactly 5 days ago,

SELECT *, DATE_FORMAT(user_registerdate, '%m/%d/%Y')
FROM ts_user
WHERE DATE(user_registerdate) = CURDATE() - INTERVAL 5 DAY;


问:
Laravel development: Implication when creating MySQL database manually
I'm in the process of building a Laravel application and I started with the database design. I implemented this directly on the commandline (mysql).

Now, I have this lingering concern as for what this could lead to in the coming development cycles.

I do know that I miss out on the version control as well as the rollback of database structure changes that php artisan provides.

Are there other Laravel/PHP specific aspects I should keep in mind?

Would you (Laravel developer), recommend that I recreate the entire database structure using php artisan make:migration?

I could really use your input based on this situation of Laravel/PHP development in many cycles without database migration control?

Please advice.

答:
Yes, In my opinion you should go for using migrations. Migrations provide a great interface to change database structure in version controlled manner.

For instance, If in future you have to move from mysql to some other database system. Following your current approach your would have to create all the db structures according to the new system.

While using migrations, you just have to update a config file for the db driver. And you are done.


问:
Find two fields with the same value within separate arrays
```<code>"first_name" : [

    ]
</code>```

I have database like above . I want find field first_name and last_name have type = primary . I tried this code but it get all data :

```<code> var fieledUsers = {
            'first_name': 1,
            'last_name': 1,

            };
            var matching = {
                'first_name.type' :'primary',
                'last_name.type' :'primary'
            }
            var conditionUsers = {"_id": users_id};
            db.collection('users').aggregate([{$project:fieledUsers},{$match:matching}],function (err, resUsers) {
</code>```

How can I do it . Thank in advance

答:
According to MongoDB documentation

```<code>The $elemMatch operator matches documents that contain an array
field with at least one element that matches all the specified query
criteria.
</code>```

As a solution according to above mentioned description please try executing following query in MongoDB shell.

```<code>db.collection.find({first_name:{$elemMatch:{type:'primary'}},
last_name:{$elemMatch:{type:'primary'}}})
</code>```

Body:
"first_name" : [

    ]

I have database like above . I want find field first_name and last_name have type = primary . I tried this code but it get all data :

 var fieledUsers = {
            'first_name': 1,
            'last_name': 1,

            };
            var matching = {
                'first_name.type' :'primary',
                'last_name.type' :'primary'
            }
            var conditionUsers = {"_id": users_id};
            db.collection('users').aggregate([{$project:fieledUsers},{$match:matching}],function (err, resUsers) {

How can I do it . Thank in advance

Body:
According to MongoDB documentation

The $elemMatch operator matches documents that contain an array
field with at least one element that matches all the specified query
criteria.

As a solution according to above mentioned description please try executing following query in MongoDB shell.

db.collection.find({first_name:{$elemMatch:{type:'primary'}},
last_name:{$elemMatch:{type:'primary'}}})


问:
Database connector giving error: "Bulk mode operations require a Iterable/Iterator as payload. Got java.util.LinkedHashMap instead"
I'm using a datamapper to transform the payload to a collection prior to passing it to the database connector.  What am I missing here?

Here's the code:

```<code>    `<data-mapper:config name="CSV_To_Map"`

transformationGraphPath="csv_to_map.grf" doc:name="CSV_To_Map"/>
    <batch:job name="batchcustomerimport3.6.0Batch1">
        <batch:input>
            <file:inbound-endpoint path="C:\Users\hhernandez\testworkspace411\batchcustomerimport3.6.0Collection\src\test\resources\in" moveToPattern="#[message.inboundProperties.originalFileName]" moveToDirectory="C:\Users\hhernandez\testworkspace411\batchcustomerimport3.6.0Collection\src\test\resources\out" responseTimeout="10000" doc:name="File">
                <file:filename-regex-filter pattern="CustomerImportTest.csv" caseSensitive="true"/>
            </file:inbound-endpoint>
            <file:file-to-string-transformer doc:name="File to String"/>
            <data-mapper:transform config-ref="CSV_To_Map" doc:name="CSV To Map"/>
            <logger level="INFO" doc:name="Logger"/>
        </batch:input>
        <batch:process-records>
            <batch:step name="Batch_Step">
                <db:update config-ref="Generic_Database_Configuration" bulkMode="true" doc:name="Database">
                    <db:parameterized-query><![CDATA[UPDATE FBF05P
SET STORE#X = #[payload['STORENO']]
WHERE VIP#X = #[payload['CUSTID']]]]>
                </db:update>
            </batch:step>
        </batch:process-records>
        <batch:on-complete>
            <logger level="INFO" doc:name="Logger"/>
        </batch:on-complete>
    </batch:job>
</code>```

答:
Change your batch step to update records using batch commit.like

```<code><batch:step name="Batch_Step">
    <batch:commit doc:name="Batch Commit" size="500">
        <db:update config-ref="Generic_Database_Configuration" bulkMode="true" doc:name="Database">
            <db:parameterized-query>
                <![CDATA[
                    UPDATE FBF05P
                    SET STORE#X = #[payload['STORENO']]
                    WHERE VIP#X = #[payload['CUSTID']]
                ]]>
            </db:parameterized-query>
        </db:update>
    </batch:commit>
</batch:step>
</code>```

As your input is list but in batch step it would be single record which is Map. So with batch commit you can send bunch of records for update.

Hope this helps.

Body:
I'm using a datamapper to transform the payload to a collection prior to passing it to the database connector.  What am I missing here?

Here's the code:

    `<data-mapper:config name="CSV_To_Map"`

transformationGraphPath="csv_to_map.grf" doc:name="CSV_To_Map"/>
    <batch:job name="batchcustomerimport3.6.0Batch1">
        <batch:input>
            <file:inbound-endpoint path="C:\Users\hhernandez\testworkspace411\batchcustomerimport3.6.0Collection\src\test\resources\in" moveToPattern="#[message.inboundProperties.originalFileName]" moveToDirectory="C:\Users\hhernandez\testworkspace411\batchcustomerimport3.6.0Collection\src\test\resources\out" responseTimeout="10000" doc:name="File">
                <file:filename-regex-filter pattern="CustomerImportTest.csv" caseSensitive="true"/>
            </file:inbound-endpoint>
            <file:file-to-string-transformer doc:name="File to String"/>
            <data-mapper:transform config-ref="CSV_To_Map" doc:name="CSV To Map"/>
            <logger level="INFO" doc:name="Logger"/>
        </batch:input>
        <batch:process-records>
            <batch:step name="Batch_Step">
                <db:update config-ref="Generic_Database_Configuration" bulkMode="true" doc:name="Database">
                    <db:parameterized-query><![CDATA[UPDATE FBF05P
SET STORE#X = #[payload['STORENO']]
WHERE VIP#X = #[payload['CUSTID']]]]>
                </db:update>
            </batch:step>
        </batch:process-records>
        <batch:on-complete>
            <logger level="INFO" doc:name="Logger"/>
        </batch:on-complete>
    </batch:job>

Body:
Change your batch step to update records using batch commit.like

<batch:step name="Batch_Step">
    <batch:commit doc:name="Batch Commit" size="500">
        <db:update config-ref="Generic_Database_Configuration" bulkMode="true" doc:name="Database">
            <db:parameterized-query>
                <![CDATA[
                    UPDATE FBF05P
                    SET STORE#X = #[payload['STORENO']]
                    WHERE VIP#X = #[payload['CUSTID']]
                ]]>
            </db:parameterized-query>
        </db:update>
    </batch:commit>
</batch:step>

As your input is list but in batch step it would be single record which is Map. So with batch commit you can send bunch of records for update.

Hope this helps.


问:
How do I delete an element dragged and dropped
I'm trying to delete an element when it is dragged into a Bin (id="list4") but not when dragged into another list.  When dropped I update the database as well.  This is the code I'm using to delete elements dropped into list4.

```<code>for(var i = 0; i < $('#list4').length; i++){
    $( '#list4' )[i].remove();
}
</code>```

It deletes the
 holding the
 elements rather than just the
 elements. What am I doing wrong?

EDIT - Added full script

```<code>$(document).ready(function(){
    $("#list0, #list1, #list2, #list3, #list4").sortable({
        connectWith: ".connectList",
        update: function( event, ui ) {
            var list0 = $( "#list0" ).sortable( "toArray" );
            var list1 = $( "#list1" ).sortable( "toArray" );
            var list2 = $( "#list2" ).sortable( "toArray" );
            var list3 = $( "#list3" ).sortable( "toArray" );
            var list4 = $( "#list4" ).sortable( "toArray" );
            campaignBoardAJAX(window.JSON.stringify(list0), window.JSON.stringify(list1), window.JSON.stringify(list2), window.JSON.stringify(list3), window.JSON.stringify(list4));
            for(var i = 0; i < $('#list4').length; i++){
                $( '#list4' )[i].remove();
                }
        }
    }).disableSelection();
});
</code>```

答:
My solution:</p>

```<code>$(document).ready(function(){
    $("#list0, #list1, #list2, #list3, #list4").sortable({
        connectWith: ".connectList",
        update: function( event, ui ) {
            var list0 = $( "#list0" ).sortable( "toArray" );
            var list1 = $( "#list1" ).sortable( "toArray" );
            var list2 = $( "#list2" ).sortable( "toArray" );
            var list3 = $( "#list3" ).sortable( "toArray" );
            var list4 = $( "#list4" ).sortable( "toArray" );
            campaignBoardAJAX(window.JSON.stringify(list0), window.JSON.stringify(list1), window.JSON.stringify(list2), window.JSON.stringify(list3), window.JSON.stringify(list4));
            $("#list4").empty() ;
        }
    }).disableSelection();
});
</code>```

Body:
I'm trying to delete an element when it is dragged into a Bin (id="list4") but not when dragged into another list.  When dropped I update the database as well.  This is the code I'm using to delete elements dropped into list4.

for(var i = 0; i < $('#list4').length; i++){
    $( '#list4' )[i].remove();
}

It deletes the
 holding the
 elements rather than just the
 elements. What am I doing wrong?

EDIT - Added full script

$(document).ready(function(){
    $("#list0, #list1, #list2, #list3, #list4").sortable({
        connectWith: ".connectList",
        update: function( event, ui ) {
            var list0 = $( "#list0" ).sortable( "toArray" );
            var list1 = $( "#list1" ).sortable( "toArray" );
            var list2 = $( "#list2" ).sortable( "toArray" );
            var list3 = $( "#list3" ).sortable( "toArray" );
            var list4 = $( "#list4" ).sortable( "toArray" );
            campaignBoardAJAX(window.JSON.stringify(list0), window.JSON.stringify(list1), window.JSON.stringify(list2), window.JSON.stringify(list3), window.JSON.stringify(list4));
            for(var i = 0; i < $('#list4').length; i++){
                $( '#list4' )[i].remove();
                }
        }
    }).disableSelection();
});

Body:
My solution:

$(document).ready(function(){
    $("#list0, #list1, #list2, #list3, #list4").sortable({
        connectWith: ".connectList",
        update: function( event, ui ) {
            var list0 = $( "#list0" ).sortable( "toArray" );
            var list1 = $( "#list1" ).sortable( "toArray" );
            var list2 = $( "#list2" ).sortable( "toArray" );
            var list3 = $( "#list3" ).sortable( "toArray" );
            var list4 = $( "#list4" ).sortable( "toArray" );
            campaignBoardAJAX(window.JSON.stringify(list0), window.JSON.stringify(list1), window.JSON.stringify(list2), window.JSON.stringify(list3), window.JSON.stringify(list4));
            $("#list4").empty() ;
        }
    }).disableSelection();
});


问:
Guidance for making a program with only pure assembly on Mac OS X?
I have realized I have to study Assembly language to understand programming deeply during trying to implement coroutine.

So I decided to start study Assembly. I want to start this by making small programs with only pure assembly. What's required and where should I start from? Easy Tutorials? Any guidance would be appreciated. Thanks.

PS.
I'm using Mac OS X 10.6 on iMac Core i5 machine.

答:
MIPS is a nice and short instruction set.

Nothing fancy to get in your way.

MIPS Emulators

SPIM was a classic emulator used for years. Some useful info here.

Mars looks promising and runs in java.


问:
How to insert elements into the list at arbitrary positions?
I have this

```<code>>>> a = [1, 4, 7, 11, 17]
</code>```

Is there any way to add 4 characters '-' randomly between the other elements to achieve, for example

```<code>['-', 1, '-', 4, 7, '-', '-', 11, 17]
</code>```

Body:
I have this

>>> a = [1, 4, 7, 11, 17]

Is there any way to add 4 characters '-' randomly between the other elements to achieve, for example

['-', 1, '-', 4, 7, '-', '-', 11, 17]

Body:
Since performance is not an issue, the following is another solution to your issue (amended per @AChampion comment):

from __future__ import print_function

import random

_max = 4
in_list = [1, 4, 7, 11, 17]
out_list = list()

for d in in_list:
    if _max:
        if random.choice([True, False]):
            out_list.append(d)
        else:
            out_list.extend(["-", d])
            _max -= 1
    else:
        out_list.append(d)

# If not all 4 (-max) "-" have not been added, add the missing "-"s at random.
for m in range(_max):
    place = random.randrange(len(out_list)+1)
    out_list.insert(place, "-")

print(out_list)

Which gives:

$ for i in {1..15}; do python /tmp/tmp.py; done
[1, '-', 4, '-', '-', 7, 11, '-', 17]
['-', 1, 4, '-', '-', 7, 11, '-', 17]
['-', 1, 4, '-', 7, '-', 11, 17, '-']
[1, '-', 4, '-', '-', 7, '-', 11, 17]
[1, '-', 4, '-', '-', 7, 11, '-', 17]
['-', 1, 4, '-', 7, 11, '-', 17, '-']
['-', '-', 1, '-', 4, '-', 7, 11, 17]
[1, 4, '-', 7, '-', '-', '-', 11, 17]
['-', 1, 4, 7, '-', 11, '-', '-', 17]
[1, 4, '-', '-', '-', 7, '-', 11, 17]
['-', '-', 1, 4, 7, 11, '-', 17, '-']
['-', '-', 1, '-', 4, '-', 7, 11, 17]
['-', 1, '-', 4, '-', 7, 11, '-', 17]
[1, '-', 4, '-', 7, '-', 11, '-', 17]
[1, '-', '-', 4, '-', 7, 11, '-', 17]


问:
Append DOM element not working with jQuery selectable
Try to move selected item from one List to Another but append dom element not working:

//Assign action modules
    $('#Modal_Task #assigned_module').click(function () {
        var list = $("#Modal_Task .unassigned li.ui-selected");
        $('#Modal_Task .assigned').append(list);
        list.remove();
    });

//UnAssign action modules
    $('#Modal_Task #unassigned_module').click(function () {
        var list = $("#Modal_Task .assigned li.ui-selected");
        $('#Modal_Task .unassigned').append(list);
        list.remove();
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="modal fade in" id="Modal_Task" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false" style="display: block;"><div class="modal-backdrop fade in"></div>
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                    <h4 class="modal-title" id="myModalLabel">Link Tasks</h4>
                </div>
                <div class="modal-body">
                    <div class="row" id="actionee_modal">
                        <div id="info_message_task" class="alert hidden-element dv-message"></div>
                        <div class="col-md-4 side-box">
                            <label>Unassigned:</label>
                            <div class="selectable-wraper">
                                <ul class="unassigned selectable ui-selectable"><li data-id="3" class="ui-selectee"><strong class="ui-selectee">Title 3</strong></li><li data-id="2" class="ui-selectee"><strong class="ui-selectee">Title 2</strong></li></ul>
                            </div>
                        </div>
                        <div class="col-md-2 center-box">
                            <label>Action</label>
                            <button type="button" class="btn btn-success btn-xs" id="assigned_module"><i class="fa fa-arrow-circle-right"></i></button>
                            <button type="button" class="btn btn-danger btn-xs" id="unassigned_module"><i class="fa fa-arrow-circle-left"></i></button>
                        </div>
                        <div class="col-md-4 side-box">
                            <label>Assigned:</label>
                            <div class="selectable-wraper">
                                <ul class="assigned selectable ui-selectable"></ul>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="save_task">Save changes</button>
                </div>
            </div>
        </div>
    </div></code>```

答:
```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="modal fade in" id="Modal_Task" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false" style="display: block;"><div class="modal-backdrop fade in"></div>
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                    <h4 class="modal-title" id="myModalLabel">Link Tasks</h4>
                </div>
                <div class="modal-body">
                    <div class="row" id="actionee_modal">
                        <div id="info_message_task" class="alert hidden-element dv-message"></div>
                        <div class="col-md-4 side-box">
                            <label>Unassigned:</label>
                            <div class="selectable-wraper">
                                <ul class="unassigned selectable ui-selectable">
                                    <li data-id="3" class="ui-selected">
                                        <strong class="ui-selected">Title 3</strong>
                                    </li>
                                    <li data-id="2" class="ui-selected">
                                        <strong class="ui-selected">Title 2</strong>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="col-md-2 center-box">
                            <label>Action</label>
                            <button type="button" class="btn btn-success btn-xs" id="assigned_module"><i class="fa fa-arrow-circle-right"></i>right</button>
                            <button type="button" class="btn btn-danger btn-xs" id="unassigned_module"><i class="fa fa-arrow-circle-left"></i>left</button>
                        </div>
                        <div class="col-md-4 side-box">
                            <label>Assigned:</label>
                            <div class="selectable-wraper">
                                <ul class="assigned selectable ui-selectable"></ul>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="save_task">Save changes</button>
                </div>
            </div>
        </div>
    </div>

   <script>
   //Assign action modules
   $('#Modal_Task #assigned_module').click(function () {
        var list = $("#Modal_Task .unassigned li.ui-selected");
        $('#Modal_Task .assigned').append(list);
        list.remove();
    });

//UnAssign action modules
    $('#Modal_Task #unassigned_module').click(function () {
        var list = $("#Modal_Task .assigned li.ui-selected");
        $('#Modal_Task .unassigned').append(list);
        list.remove();
    });
</script>
</code>```

Body:
Try to move selected item from one List to Another but append dom element not working:

//Assign action modules
    $('#Modal_Task #assigned_module').click(function () {
        var list = $("#Modal_Task .unassigned li.ui-selected");
        $('#Modal_Task .assigned').append(list);
        list.remove();
    });

//UnAssign action modules
    $('#Modal_Task #unassigned_module').click(function () {
        var list = $("#Modal_Task .assigned li.ui-selected");
        $('#Modal_Task .unassigned').append(list);
        list.remove();
    });

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Link Tasks

                            Unassigned:

Title 3

Title 2

                            Action
                            <button type="button" class="btn btn-success btn-xs" id="assigned_module"></button>
                            <button type="button" class="btn btn-danger btn-xs" id="unassigned_module"></button>

                            Assigned:

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="save_task">Save changes</button>


问:
How can rustfmt be configured to not emit aligning spaces for the match unsafe block pattern?
My rustfmt config currently formats the following code to have aligning spaces as is shown bellow. I have replaced spaces with . and tabs with ---> in the following code.

```<code>fn main() {
--->match unsafe {
--->--->......0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1
--->--->.....} {
--->--->0 => println!("0"),
--->--->_ => println!("not 0 or 1"),
--->}
}
</code>```

My rustfmt config(rustfmt.toml file) that produced the above code example:

```<code>tab_spaces = 4
hard_tabs = true
array_layout = "Block"
reorder_imports = true
newline_style = "Unix"
spaces_within_angle_brackets = false
spaces_within_parens = false
spaces_within_square_brackets = false
fn_args_layout = "Block"
fn_call_style = "Block"
fn_return_indent = "WithArgs"
fn_brace_style = "SameLineWhere"
generics_indent= "Block"
item_brace_style = "PreferSameLine"
control_style = "Rfc"
match_style = "Rfc"
unsafe_style = "Rfc"
where_layout = "Horizontal"
where_pred_indent = "Block"
where_style = "Rfc"
</code>```

How can rustfmt be configured to not emit the aligning spaces(marked by: .) for the prior code, so rustfmt only indents with tabs like the following code?

```<code>fn main() {
--->match unsafe {
--->--->0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1
--->--->} {
--->--->0 => println!("0"),
--->--->_ => println!("not 0 or 1"),
--->}
}
</code>```

答: This is a bug. I created a PR to fix this, so after it gets merged rustfmt will not emit spaces with your configuration.</p>

Body:
My rustfmt config currently formats the following code to have aligning spaces as is shown bellow. I have replaced spaces with . and tabs with ---> in the following code.

fn main() {
--->match unsafe {
--->--->......0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1
--->--->.....} {
--->--->0 => println!("0"),
--->--->_ => println!("not 0 or 1"),
--->}
}

My rustfmt config(rustfmt.toml file) that produced the above code example:

tab_spaces = 4
hard_tabs = true
array_layout = "Block"
reorder_imports = true
newline_style = "Unix"
spaces_within_angle_brackets = false
spaces_within_parens = false
spaces_within_square_brackets = false
fn_args_layout = "Block"
fn_call_style = "Block"
fn_return_indent = "WithArgs"
fn_brace_style = "SameLineWhere"
generics_indent= "Block"
item_brace_style = "PreferSameLine"
control_style = "Rfc"
match_style = "Rfc"
unsafe_style = "Rfc"
where_layout = "Horizontal"
where_pred_indent = "Block"
where_style = "Rfc"

How can rustfmt be configured to not emit the aligning spaces(marked by: .) for the prior code, so rustfmt only indents with tabs like the following code?

fn main() {
--->match unsafe {
--->--->0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1
--->--->} {
--->--->0 => println!("0"),
--->--->_ => println!("not 0 or 1"),
--->}
}


问:
How to read CSV file having empty columns in java and few columns with only some data?
I have my Test.csv file like below,Now i want to read the csv file (Using JAVA) by skipping empty columns if any.
If total column is comming as empty then i want to skip that column

```<code>111, ,John,2000,   ,US
222, ,Alle,3000,   ,China
333, ,Kite,4000,LCD,IND
444, ,King,5000,LED,Aust

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
    public class Test {
        public static void main(String[] args)
        {
            Scanner s = null;
            try {
                s = new Scanner(new File("D:/sri/Test.txt"));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            while (s.hasNextLine()) {
                String line = s.nextLine();
            }
        }
    }
</code>```

Here Iam able to read empty columns also.Could you please suggest regarding this

答:
I suggest you to using SuperCSV with CsvBeanReader,you could custom a CellProcessor to ignore line when data is empty.
SuperCSV document

A simple solution is using CsvReader and read line by line, then check each data after parser. Once you get an empty string, then move to next line!
CSV Reader Document

Body:
I have my Test.csv file like below,Now i want to read the csv file (Using JAVA) by skipping empty columns if any.
If total column is comming as empty then i want to skip that column

111, ,John,2000,   ,US
222, ,Alle,3000,   ,China
333, ,Kite,4000,LCD,IND
444, ,King,5000,LED,Aust

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
    public class Test {
        public static void main(String[] args)
        {
            Scanner s = null;
            try {
                s = new Scanner(new File("D:/sri/Test.txt"));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            while (s.hasNextLine()) {
                String line = s.nextLine();
            }
        }
    }

Here Iam able to read empty columns also.Could you please suggest regarding this


问:
Apache Ignite on DCOS marathon not working
I installed Apache ignite in DCOS

```<code>{
   "volumes": null,
  "id": "/ignite",
   "cmd": "cd $MESOS_SANDBOX; java -Xmx2048m -jar ignite-mesos-2.0.0.jar",
  "args": null,
  "user": null,
  "env": {
    "IGNITE_MEMORY_PER_NODE": "3072",
    "IGNITE_NODE_COUNT": "3",
    "IGNITE_VERSION": "2.0.0",
    "MESOS_MASTER_URL": "zk://localhost:2181/mesos",
    "IGNITE_RUN_CPU_PER_NODE": "0.1"
  },
  "cpus": 1,
  "mem": 3072.0,
  "instances": 1,
  "uris": ["http://servername/ignite/ignite-mesos-2.0.0.jar"],
  "container": {
    "type": "DOCKER",
    "docker": {
      "image": "openjdk:8-alpine",
      "network": "HOST",
      "portMappings": [
        { "containerPort": 0, "hostPort": 0, "servicePort": 0, "protocol": "tcp" }
      ]
    }
  },
  "labels": {
    "DCOS_SERVICE_SCHEME": "http",
    "DCOS_SERVICE_NAME": "ignite",
    "DCOS_SERVICE_PORT_INDEX": "0"
  },
  "acceptedResourceRoles": ["*","slave_public"]
}
</code>```

i get the below error
Exception in thread "main" java.lang.UnsatisfiedLinkError: no mesos in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1867)

i tried keeping  "MESOS_NATIVE_JAVA_LIBRARY": "/usr/lib/libmesos.so", but still same error

答:
Try explicitly add that .so to java.library.path and keep env variable "MESOS_NATIVE_JAVA_LIBRARY" configured.

Also, start job-server with root privileges.

Body:
I installed Apache ignite in DCOS

{
   "volumes": null,
  "id": "/ignite",
   "cmd": "cd $MESOS_SANDBOX; java -Xmx2048m -jar ignite-mesos-2.0.0.jar",
  "args": null,
  "user": null,
  "env": {
    "IGNITE_MEMORY_PER_NODE": "3072",
    "IGNITE_NODE_COUNT": "3",
    "IGNITE_VERSION": "2.0.0",
    "MESOS_MASTER_URL": "zk://localhost:2181/mesos",
    "IGNITE_RUN_CPU_PER_NODE": "0.1"
  },
  "cpus": 1,
  "mem": 3072.0,
  "instances": 1,
  "uris": ["http://servername/ignite/ignite-mesos-2.0.0.jar"],
  "container": {
    "type": "DOCKER",
    "docker": {
      "image": "openjdk:8-alpine",
      "network": "HOST",
      "portMappings": [
        { "containerPort": 0, "hostPort": 0, "servicePort": 0, "protocol": "tcp" }
      ]
    }
  },
  "labels": {
    "DCOS_SERVICE_SCHEME": "http",
    "DCOS_SERVICE_NAME": "ignite",
    "DCOS_SERVICE_PORT_INDEX": "0"
  },
  "acceptedResourceRoles": ["*","slave_public"]
}

i get the below error
Exception in thread "main" java.lang.UnsatisfiedLinkError: no mesos in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1867)

i tried keeping  "MESOS_NATIVE_JAVA_LIBRARY": "/usr/lib/libmesos.so", but still same error


问:
Write list of objects to text file
I've got a class Dish like this:

```<code>public class Dish
{
    public Dish(int cost, string name)
    {
        Cost = cost;
        Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }
}
</code>```

In the main form the user can enter the previous data.
Then I create a list of "Dish":

```<code>public static List<Piatto> List = new List<Piatto>();
</code>```

I created it in a static class, so I can access it from anywhere.
As soon as an item get added to the list, I want to save it in a text file (.txt) so I tried to use this:

```<code>public static void SaveToTxt()
    {
        using (TextWriter tw = new StreamWriter(Path))
        {
            foreach (var item in Data.List)
            {
                tw.WriteLine(item.ToString());
            }
        }
    }
</code>```

The issue is that when I open the text file where I saved my list, I get "WindowsFormsApplication1.Dish".

How can I save to a text file showing Cost and Name?

P.s. I would like to save the list in a text file because it's easier for me to delete a line, something that I don't know how to do in binary.

Thanks in advance.

EDIT:

Overriding the ToString() method worked fine. Thank you all for the answers!

答:
Consider using XmlSerializer to write content of your object to an XML-file.

https://support.microsoft.com/en-us/help/815813/how-to-serialize-an-object-to-xml-by-using-visual-c

Title: Write list of objects to text file

Body:
I've got a class Dish like this:

public class Dish
{
    public Dish(int cost, string name)
    {
        Cost = cost;
        Name = name;
    }

    public int Cost { get; set; }
    public string Name { get; set; }
}

In the main form the user can enter the previous data.
Then I create a list of "Dish":

public static List<Piatto> List = new List<Piatto>();

I created it in a static class, so I can access it from anywhere.
As soon as an item get added to the list, I want to save it in a text file (.txt) so I tried to use this:

public static void SaveToTxt()
    {
        using (TextWriter tw = new StreamWriter(Path))
        {
            foreach (var item in Data.List)
            {
                tw.WriteLine(item.ToString());
            }
        }
    }

The issue is that when I open the text file where I saved my list, I get "WindowsFormsApplication1.Dish".

How can I save to a text file showing Cost and Name?

P.s. I would like to save the list in a text file because it's easier for me to delete a line, something that I don't know how to do in binary.

Thanks in advance.

EDIT:

Overriding the ToString() method worked fine. Thank you all for the answers!


问:
How to use radiobutton to count something eg if the first option shows list 1 if option 2 marked show list 2?
I have two RadioButtons in RadioGroup. What I want: if first RadioButton ischecked to display method one and second RadioButton ischecked to dispaly method two.
How to do it?

```<code>public void onRadioButtonClicked (View view) {
    boolean checked = ((RadioButton) view).isChecked();

    switch (view.getId()) {
        case R.id.radio_button_equal_payment_principal:
            if (checked) {
            "display method PaymentPrincipal"

            }
            break;
        case R.id.radio_button_equal_payment_total:
            if (checked) {
          "display method PaymentTotal"
            }
            break;
    }
    return ;
}
</code>```

答:
you can use setOnCheckedChangeListener try this :</p>

```<code>itemtypeGroup
        .setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
Log.d("chk", "id" + checkedId);

                if (checkedId == R.id.radio_button_equal_payment_principal) {
                    // "display method PaymentPrincipal"
                } else if (checkedId == R.id.radio_button_equal_payment_total) {
                    //  "display method PaymentTotal"
                }

            }

        });
</code>```

Body:
I have two RadioButtons in RadioGroup. What I want: if first RadioButton ischecked to display method one and second RadioButton ischecked to dispaly method two.
How to do it?

public void onRadioButtonClicked (View view) {
    boolean checked = ((RadioButton) view).isChecked();

    switch (view.getId()) {
        case R.id.radio_button_equal_payment_principal:
            if (checked) {
            "display method PaymentPrincipal"

            }
            break;
        case R.id.radio_button_equal_payment_total:
            if (checked) {
          "display method PaymentTotal"
            }
            break;
    }
    return ;
}

Body:
you can use setOnCheckedChangeListener try this :

itemtypeGroup
        .setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
Log.d("chk", "id" + checkedId);

                if (checkedId == R.id.radio_button_equal_payment_principal) {
                    // "display method PaymentPrincipal"
                } else if (checkedId == R.id.radio_button_equal_payment_total) {
                    //  "display method PaymentTotal"
                }

            }

        });


问:
Dashboard to Powerpoint in TABLEAU Public
I am using TABLEAU Public.. I am not using TABLEAU Desktop.

I created a Dashboard and stored in TABLEAU Public .

Now I want to have the dashboard which I created in terms of Power point presentation.

Is it possible in TABLEAU public  to convert dashboard in to Power point(.ppt)?

答:
There is option to download your worksheet in pdf,image but you dashboard will not integrative or dynamic.

I recommand you to put link and display in web.


问:
Spring Boot JPA not finding data source
I have a spring boot application with the following configuration:

Application

```<code>@SpringBootApplication(exclude = {ErrorMvcAutoConfiguration.class,
        DataSourceAutoConfiguration.class,JpaRepositoriesAutoConfiguration.class})
public class Application extends SpringBootServletInitializer {
</code>```

Main configuration class:

```<code>@Configuration
@ComponentScan("com.mycompany.it")
@Import(DatabaseConfiguration.class)
public class Configuration extends WebMvcConfigurationSupport {
</code>```

Database configuration:

```<code>@Configuration
@ComponentScan(basePackages = {"com.mycompany.it.xp2.integration.workday.dao","com.mycompany.it.xp2.integration.workday.application","com.company.it.xp2.integration.workday.model"})
@EnableAspectJAutoProxy
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = {"com.company.it.xp2.integration.workday.dao","com.company.it.xp2.integration.workday.model"})
public class DatabaseConfiguration {
</code>```

With DataSource bean declaration:

```<code>@Bean(destroyMethod = "close")
    @Primary
    public DataSource dataSource() throws PropertyVetoException {
        ComboPooledDataSource source = new ComboPooledDataSource();
        source.setDriverClass(driverClass);
        source.setJdbcUrl(jdbcUrl);
        source.setUser(jdbcUsername);
        source.setPassword(jdbcPassword);
        source.setInitialPoolSize(initialSize);
        source.setMaxPoolSize(maxActive);
        source.setMinPoolSize(minIdle);
        return source;
    }
</code>```

However when I start up the application I get the following error:

Caused by:
  org.springframework.beans.factory.UnsatisfiedDependencyException:
  Error creating bean with name
  'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration':
  Unsatisfied dependency expressed through constructor parameter 0;
  nested exception is
  org.springframework.beans.factory.NoSuchBeanDefinitionException: No
  qualifying bean of type 'javax.sql.DataSource' available: expected at
  least 1 bean which qualifies as autowire candidate. Dependency
  annotations: {}

Here are the related lines from gradle:

```<code>compile group: 'org.springframework.boot', name: 'spring-boot-starter-web'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-actuator'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-aop'
compile group: 'org.springframework', name: 'spring-orm'

compile group: "org.springframework.boot", name: "spring-boot-starter-jdbc"
compile "org.springframework.boot:spring-boot-starter-data-jpa"
</code>```

Spring boot version 1.5.3

答:
Check the error log

1 bean which qualifies as autowire candidate. Dependency annotations

It seems that there is an error when you configured the bean.

Title: Spring Boot JPA not finding data source

Body:
I have a spring boot application with the following configuration:

Application

@SpringBootApplication(exclude = {ErrorMvcAutoConfiguration.class,
        DataSourceAutoConfiguration.class,JpaRepositoriesAutoConfiguration.class})
public class Application extends SpringBootServletInitializer {

Main configuration class:

@Configuration
@ComponentScan("com.mycompany.it")
@Import(DatabaseConfiguration.class)
public class Configuration extends WebMvcConfigurationSupport {

Database configuration:

@Configuration
@ComponentScan(basePackages = {"com.mycompany.it.xp2.integration.workday.dao","com.mycompany.it.xp2.integration.workday.application","com.company.it.xp2.integration.workday.model"})
@EnableAspectJAutoProxy
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = {"com.company.it.xp2.integration.workday.dao","com.company.it.xp2.integration.workday.model"})
public class DatabaseConfiguration {

With DataSource bean declaration:

@Bean(destroyMethod = "close")
    @Primary
    public DataSource dataSource() throws PropertyVetoException {
        ComboPooledDataSource source = new ComboPooledDataSource();
        source.setDriverClass(driverClass);
        source.setJdbcUrl(jdbcUrl);
        source.setUser(jdbcUsername);
        source.setPassword(jdbcPassword);
        source.setInitialPoolSize(initialSize);
        source.setMaxPoolSize(maxActive);
        source.setMinPoolSize(minIdle);
        return source;
    }

However when I start up the application I get the following error:

Caused by:
  org.springframework.beans.factory.UnsatisfiedDependencyException:
  Error creating bean with name
  'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration':
  Unsatisfied dependency expressed through constructor parameter 0;
  nested exception is
  org.springframework.beans.factory.NoSuchBeanDefinitionException: No
  qualifying bean of type 'javax.sql.DataSource' available: expected at
  least 1 bean which qualifies as autowire candidate. Dependency
  annotations: {}

Here are the related lines from gradle:

compile group: 'org.springframework.boot', name: 'spring-boot-starter-web'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-actuator'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-aop'
compile group: 'org.springframework', name: 'spring-orm'

compile group: "org.springframework.boot", name: "spring-boot-starter-jdbc"
compile "org.springframework.boot:spring-boot-starter-data-jpa"

Spring boot version 1.5.3


问:
How do you do Design by Contract in Perl?
I'm investigating using DbC in our Perl projects, and I'm trying to find the best way to verify contracts in the source (e.g. checking pre/post conditions, invariants, etc.)

Class::Contract was written by Damian Conway and is now maintained by C. Garret Goebel, but it looks like it hasn't been touched in over 8 years.

It looks like what I want to use is Moose, as it seems as though it might offer functionality that could be used for DbC, but I was wondering if anyone had any resources (articles, etc.) on how to go about this, or if there are any helpful modules out there that I haven't been able to find.

Is anyone doing DbC with Perl?  Should I just "jump in" to Moose and see what I can get it to do for me?

答:
Moose gives you a lot of the tools (if not all the sugar) to do DbC.  Specifically, you can use the before, after and around method hooks (here's some examples) to perform whatever assertions you might want to make on arguments and return values.

As an alternative to "roll your own DbC" you could use a module like MooseX::Method::Signatures or MooseX::Method to take care of validating parameters passed to a subroutine.  These modules don't handle the "post" or "invariant" validations that DbC typically provides, however.

EDIT: Motivated by this question, I've hacked together MooseX::Contract and uploaded it to the CPAN.  I'd be curious to get feedback on the API as I've never really used DbC first-hand.

OwnerDisplayName: Adam Bellaire

LastEditorDisplayName: brian d foy

OwnerDisplayName: Brian Phillips

LastEditorDisplayName: Brian Phillips


问:
Angular JS - Changing state depending on item clicked
I want to display content beneath a table, from a JSON file, relative to to item the user clicked on in the table

Example:

JSON file

```<code>{
    "patentInfo": [
        {
            "name": "item1",
            "cost": "$33",
            "date": "13/06",
        },
        {
            "name": "item2",
            "cost": "$29",
            "date": "02/02",
        }
    ]
}
</code>```

View - table

click on item 1 > DISPLAY price:$33, date:13/06

click on item 2 > DISPLAY price:$29, date:02/02

I asked this question last week but didn't get a response as I don't think I made it too clear. I'm using ui-view to display content, and it is the state patents.list.item URL that needs to be relative, dependent on what the user clicked on. Any ideas on how to achieve this?

```<code>var app = angular.module('myApp', ['ngRoute', 'angularMoment', 'ui.router', "chart.js"]);

app.config(['$stateProvider', '$locationProvider', '$urlRouterProvider', function($stateProvider, $locationProvider, $urlRouterProvider ) {

    $urlRouterProvider
                  .when('', '/patents/list-patents')
                  .when('/', '/patents/list-patents')
                  .when('/patents', '/patents/list-patents')
                  .when('/transactions', '/transactions/current-transactions')
                  .otherwise('/patents/list-patents');

    $stateProvider
    .state("patents", {
        url: "/patents",
        templateUrl: "templates/patents/patent-nav.htm",
        controller: "patentCtrl"
    })
    .state("patents.list", {
        url: "/list-patents",
        templateUrl: "templates/patents/list/list-patents.htm",
        controller: "patentCtrl"
    })

    .state("patents.list.item", {
        url: "/patent-item",
        templateUrl: "templates/patents/list/patent-item.htm",
        controller: "patentCtrl"
    })
</code>```

Controller

```<code>app.controller('patentCtrl', ['$scope', '$http', 'patentTabFactory', 'loadPatents', '$stateParams', 'patentService', function($scope, $http, patentTabFactory, loadPatents, $stateParams, patentService) {

    patentService.items.then(function (patents) {

        $scope.items = patents.data;
        console.log($scope.patents);
        $scope.patents = patents.data[patentService.getPatentItem($scope.items, "aid", $stateParams.id)];

    });

    $scope.patent={id:null,applicationNumber:'',clientRef:'',costRenew:'',renewalDate:'',basketStatus:'', costEnd: '', nextStage:''};
    $scope.patents=[];
    $scope.submit = $scope.submit;
    $scope.remove = $scope.remove;

    $scope.fetchAllPatents = function(){
        loadPatents.fetchAllPatents()
            .then(
            function(d) {
                $scope.patents = d;
            },
            function(errResponse){
                console.error('Error while fetching Users');
            }
        );
    }

    $scope.fetchAllPatents();

    $scope.deletePatent = function(id){
        loadPatents.deletePatent(id)
            .then(
             $scope.fetchAllPatents,
            function(errResponse){
                console.error('Error while deleting Patent');
            }
        );
    }

    $scope.submit = function() {
        if($scope.patent.id===null){
            console.log('Saving New User', $scope.patent);
            loadPatents.createPatent($scope.patent);
        }
        console.log('User updated with id ', $scope.patent.id);

    }

    $scope.remove = function(id){
        console.log('id to be deleted', id);
        if($scope.patent.id === id) {//clean form if the patent to be deleted is shown there.
            reset();
        }
         $scope.deletePatent(id);
    }

    $scope.tabs = patentTabFactory.tabs;
    $scope.currentTab = patentTabFactory.currentTab;
     // $scope.isActiveTab = patentTabFactory.isActiveTab();
    $scope.onClickTab = function(currentTab) {
        patentTabFactory.onClickTab(currentTab);
        $scope.currentTab = patentTabFactory.currentTab;
    };

    $scope.isActiveTab = function(tabUrl) {
        return tabUrl == patentTabFactory.currentTab;
    }
}]);
</code>```

list-patents view

```<code><div class="row">
    <div class="col-md-12">
        <table class="table table-bordered table-striped text-md-center">
            <thead class="thead-inverse">
                <tr>
                    <td ng-click="patentAppOrder()" class="align-middle">Application No. </td>
                    <td class="align-middle">Client Ref</td>
                    <td class="align-middle">Cost to renew</td>
                    <td class="align-middle">Basket</td>
                    <td class="align-middle">Remove</td>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="x in patents">
                    <td><a ui-sref="patents.list.item">{{x.applicationNumber}}</a></td>
                    <td ng-bind="x.clientRef"></td>
                    <td ng-bind="x.costToRenew">$</td>
                    <td ng-bind="x.renewalDueDate"></td>
                    <td><button type="button" class="btn btn-danger" ng-click="remove(x.id)">Remove</button></td>
                </tr>
            </tbody>
        </table>
        <div ui-view></div>
    </div>
</div>
<div ui-view></div>
</code>```

patent item view

```<code><div id="tabs">
    <ul>
        <li ng-repeat="tab in tabs"
            ng-class="{active:isActiveTab(tab.url)}"
            ng-click="onClickTab(tab)">{{tab.title}}</li> <!--applies active to the returned tab url -->
    </ul>
    <div id="mainView">
        <div class="row">
            <div ng-include="currentTab"></div>
        </div>
    </div>
</div>
<script type="text/ng-template" id="patent-info.htm">
    <div class="col-md-6 text-xs-center">
        <h2>Application Number</h2>
        <table class="table table-striped">
            <tbody>
                <table>
                    <tr ng-repeat="(x, y) in patents">
                        <td ng-repeat="x.id in patents"></td>
                        <td>{{y.applicationNumber}}</td>
                  </tr>
                </table>
            </tbody>
        </table>
    </div>
    <div class="col-md-6 text-xs-center">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
        </p>
    </div>
</script>
<script type="text/ng-template" id="cost-analysis.htm">
    <div class="col-md-6 text-xs-center" ng-controller="LineCtrl">
        <h2>Cost Analysis</h2>
        <canvas class="chart chart-line" chart-data="data" chart-labels="labels"
chart-series="series" chart-click="onClick"></canvas>
    </div>
</script>
<script type="text/ng-template" id="renewal-history.htm">
    <div class="col-md-6 text-xs-center">
        <h2>Renewal History</h2>
        <p>In pellentesque faucibus vestibulum. Nulla at nulla justo, eget luctus tortor..</p>
    </div>
</script>
</code>```

答:
What you have to do first is to add a dynamic URL parameter to the route which is supposed to display information about a selected patent and give it another controller.

```<code>.state("patents.list.item", {
    url: "/patent-item/:name",
    templateUrl: "templates/patents/list/patent-item.htm",
    controller: "patentDetailsCtrl"
})
</code>```

Then when you are navigating to that patent, you have to include the name (assuming that is a unique identifier) in the link.

```<code><td><a ui-sref="patents.list.item({ name: x.name })">{{x.applicationNumber}}</a></td>
</code>```

After that in your patentDetailsCtrl, you can fetch information about the patent from the JSON file and display it.

Alternative Solutions

Another solution would be handle it in your patentCtrl without an additional (patents.list.item) route. But I would not recommend that approach.

You could also use components if you are using AngularJS v1.5+. To learn more about components, see the official documentation.

Body:
I want to display content beneath a table, from a JSON file, relative to to item the user clicked on in the table

Example:

JSON file

{
    "patentInfo": [
        {
            "name": "item1",
            "cost": "$33",
            "date": "13/06",
        },
        {
            "name": "item2",
            "cost": "$29",
            "date": "02/02",
        }
    ]
}

View - table

click on item 1 > DISPLAY price:$33, date:13/06

click on item 2 > DISPLAY price:$29, date:02/02

I asked this question last week but didn't get a response as I don't think I made it too clear. I'm using ui-view to display content, and it is the state patents.list.item URL that needs to be relative, dependent on what the user clicked on. Any ideas on how to achieve this?

var app = angular.module('myApp', ['ngRoute', 'angularMoment', 'ui.router', "chart.js"]);

app.config(['$stateProvider', '$locationProvider', '$urlRouterProvider', function($stateProvider, $locationProvider, $urlRouterProvider ) {

    $urlRouterProvider
                  .when('', '/patents/list-patents')
                  .when('/', '/patents/list-patents')
                  .when('/patents', '/patents/list-patents')
                  .when('/transactions', '/transactions/current-transactions')
                  .otherwise('/patents/list-patents');

    $stateProvider
    .state("patents", {
        url: "/patents",
        templateUrl: "templates/patents/patent-nav.htm",
        controller: "patentCtrl"
    })
    .state("patents.list", {
        url: "/list-patents",
        templateUrl: "templates/patents/list/list-patents.htm",
        controller: "patentCtrl"
    })

    .state("patents.list.item", {
        url: "/patent-item",
        templateUrl: "templates/patents/list/patent-item.htm",
        controller: "patentCtrl"
    })

Controller

app.controller('patentCtrl', ['$scope', '$http', 'patentTabFactory', 'loadPatents', '$stateParams', 'patentService', function($scope, $http, patentTabFactory, loadPatents, $stateParams, patentService) {

    patentService.items.then(function (patents) {

        $scope.items = patents.data;
        console.log($scope.patents);
        $scope.patents = patents.data[patentService.getPatentItem($scope.items, "aid", $stateParams.id)];

    });

    $scope.patent={id:null,applicationNumber:'',clientRef:'',costRenew:'',renewalDate:'',basketStatus:'', costEnd: '', nextStage:''};
    $scope.patents=[];
    $scope.submit = $scope.submit;
    $scope.remove = $scope.remove;

    $scope.fetchAllPatents = function(){
        loadPatents.fetchAllPatents()
            .then(
            function(d) {
                $scope.patents = d;
            },
            function(errResponse){
                console.error('Error while fetching Users');
            }
        );
    }

    $scope.fetchAllPatents();

    $scope.deletePatent = function(id){
        loadPatents.deletePatent(id)
            .then(
             $scope.fetchAllPatents,
            function(errResponse){
                console.error('Error while deleting Patent');
            }
        );
    }

    $scope.submit = function() {
        if($scope.patent.id===null){
            console.log('Saving New User', $scope.patent);
            loadPatents.createPatent($scope.patent);
        }
        console.log('User updated with id ', $scope.patent.id);

    }

    $scope.remove = function(id){
        console.log('id to be deleted', id);
        if($scope.patent.id === id) {//clean form if the patent to be deleted is shown there.
            reset();
        }
         $scope.deletePatent(id);
    }

    $scope.tabs = patentTabFactory.tabs;
    $scope.currentTab = patentTabFactory.currentTab;
     // $scope.isActiveTab = patentTabFactory.isActiveTab();
    $scope.onClickTab = function(currentTab) {
        patentTabFactory.onClickTab(currentTab);
        $scope.currentTab = patentTabFactory.currentTab;
    };

    $scope.isActiveTab = function(tabUrl) {
        return tabUrl == patentTabFactory.currentTab;
    }
}]);

list-patents view

                    Application No.
                    Client Ref
                    Cost to renew
                    Basket
                    Remove

                    {{x.applicationNumber}}

                    $

                    <button type="button" class="btn btn-danger" ng-click="remove(x.id)">Remove</button>

patent item view

{{tab.title}}

Body:
What you have to do first is to add a dynamic URL parameter to the route which is supposed to display information about a selected patent and give it another controller.

.state("patents.list.item", {
    url: "/patent-item/:name",
    templateUrl: "templates/patents/list/patent-item.htm",
    controller: "patentDetailsCtrl"
})

Then when you are navigating to that patent, you have to include the name (assuming that is a unique identifier) in the link.

<td><a ui-sref="patents.list.item({ name: x.name })">{{x.applicationNumber}}</a></td>

After that in your patentDetailsCtrl, you can fetch information about the patent from the JSON file and display it.

Alternative Solutions

Another solution would be handle it in your patentCtrl without an additional (patents.list.item) route. But I would not recommend that approach.

You could also use components if you are using AngularJS v1.5+. To learn more about components, see the official documentation.


问:
Load egg file in Panda3D in Jupyter Notebook
I'm trying to use Panda3D in a Jupyter Notebook, but I'm having problems loading a model (i.e. an .egg file).

This snippet of code runs at the command line but not in a Jupyter Notebook:

```<code>from direct.showbase.ShowBase import ShowBase
from panda3d.core import Filename

class MyApp(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)

    def load_a_model(self):
        panda_file = Filename.fromOsSpecific('models\\myModel')
        obj_model = self.loader.loadModel(panda_file)

anApp = MyApp()
anApp.load_a_model()
anApp.run()
</code>```

The error given by Jupyter Notebook is:

```<code>---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-1-c9c9444b3a7f> in <module>()
     11
     12 anApp = MyApp()
---> 13 anApp.load_a_model()
     14 anApp.run()

<ipython-input-1-c9c9444b3a7f> in load_a_model(self)
      8     def load_a_model(self):
      9         panda_file = Filename.fromOsSpecific('models\\myModel')
---> 10         obj_model = self.loader.loadModel(panda_file)
     11
     12 anApp = MyApp()

C:\Panda3D-1.9.3-x64\direct\showbase\Loader.pyc in loadModel(self, modelPath, loaderOptions, noCache, allowInstance, okMissing, callback, extraArgs, priority)
    168             if not okMissing and None in result:
    169                 message = 'Could not load model file(s): %s' % (modelList,)
--> 170                 raise IOError, message
    171
    172             if gotList:

IOError: Could not load model file(s): [Filename('models/myModel')]
</code>```

Any idea what the problem is?

答: Panda3D uses platform-independent paths, so you should use a forward slash instead of a backward slash.  So, specify models/myModel.

Body:
I'm trying to use Panda3D in a Jupyter Notebook, but I'm having problems loading a model (i.e. an .egg file).

This snippet of code runs at the command line but not in a Jupyter Notebook:

from direct.showbase.ShowBase import ShowBase
from panda3d.core import Filename

class MyApp(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)

    def load_a_model(self):
        panda_file = Filename.fromOsSpecific('models\\myModel')
        obj_model = self.loader.loadModel(panda_file)

anApp = MyApp()
anApp.load_a_model()
anApp.run()

The error given by Jupyter Notebook is:

---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-1-c9c9444b3a7f> in <module>()
     11
     12 anApp = MyApp()
---> 13 anApp.load_a_model()
     14 anApp.run()

<ipython-input-1-c9c9444b3a7f> in load_a_model(self)
      8     def load_a_model(self):
      9         panda_file = Filename.fromOsSpecific('models\\myModel')
---> 10         obj_model = self.loader.loadModel(panda_file)
     11
     12 anApp = MyApp()

C:\Panda3D-1.9.3-x64\direct\showbase\Loader.pyc in loadModel(self, modelPath, loaderOptions, noCache, allowInstance, okMissing, callback, extraArgs, priority)
    168             if not okMissing and None in result:
    169                 message = 'Could not load model file(s): %s' % (modelList,)
--> 170                 raise IOError, message
    171
    172             if gotList:

IOError: Could not load model file(s): [Filename('models/myModel')]

Any idea what the problem is?