问:
How to access EntityManager into a RabbitMQBundle custom producer class?
I am using RabbitMQBundle in a Symfony 2.8 project, and I would like to use a custom producer class which persists an entity (Message) in database before publishing the RabbitMQ message.

I defined the custom producer class in config.yml:

```<code>old_sound_rabbit_mq:
  ...
  producers:
    myproducer:
      class: AppBundle\Services\GenericProducer
      connection: default
      exchange_options: {name: 'my_exchange', type: direct}
</code>```

And the custom Producer class:

```<code><?php

namespace AppBundle\Services;

use AppBundle\Entity\Message;
use OldSound\RabbitMqBundle\RabbitMq\Producer;

/**
 * Customised Producer, that publishes AMQP Messages
 * but also:
 * - writes an entry in the Message table
 */
class GenericProducer extends Producer
{
    /**
     * Entity Manager
     */
    protected $em;

    public function setEntityManager($entityManager)
    {
        $this->em = $entityManager;

        return $this;
    }

    /**
     * Publishes the message and merges additional properties with basic properties
     * And also:
     * - writes an entry in the Message table
     *
     * @param string $action
     * @param array $parameters
     * @param string $routingKey
     * @param array $additionalProperties
     * @param array|null $headers
     */
    public function publish($action, $parameters = array() , $routingKey = '', $additionalProperties = array(), array $headers = null)
    {
        $message = new Message();
        $message->setAction($action)
            ->setParameters($parameters);
        $this->em->persist($message);
        $this->em->flush();

        $msgBody = array(
            'action' => $action,
            'parameters' => $parameters
        );
        parent::publish($msgBody, $routingKey, $additionalProperties, $headers);
    }
}
</code>```

How can I make a call to GenericProducer->setEntityManager, as the producer is not defined in services.yml, like other services ?

Is there another way to achieve this ?

Thanks for your time.

答:
Following @lordrhodos suggestion, I decorated the producer service generated by RabbitMQBundle. Here is the complete code:

config.yml (nothing special to do):

```<code>old_sound_rabbit_mq:
  ...
  producers:
    myproducer:
      connection: default
      exchange_options: {name: 'my_exchange', type: direct}
</code>```

services.yml (here you define a decorating service):

```<code>app.decorating_myproducer_producer:
      class: AppBundle\Services\GenericProducer
      decorates: old_sound_rabbit_mq.myproducer_producer
      arguments: ['@
app.decorating_myproducer_producer.inner', '@doctrine.orm.entity_manager']
      public: false
</code>```

decorator class:

```<code><?php

namespace AppBundle\Services;

use AppBundle\Entity\Message;
use OldSound\RabbitMqBundle\RabbitMq\Producer;

/**
 * Customised Producer, that publishes AMQP Messages
 * but also:
 * - writes an entry in the Message table
 */
class GenericProducer extends Producer
{
    /**
     * @var Producer
     */
    protected $producer;

    /**
     * @var EntityManager
     */
    protected $em;

    /**
     * GenericProducer constructor.
     * @param Producer $producer
     * @param EntityManager $entityManager
     */
    public function __construct(Producer $producer, EntityManager $entityManager)
    {
        $this->producer = $producer;
        $this->em = $entityManager;
    }

    /**
     * Publishes the message and merges additional properties with basic properties
     * And also:
     * - writes an entry in the Message table
     *
     * @param string $action
     * @param array $parameters
     * @param string $routingKey
     * @param array $additionalProperties
     * @param array|null $headers
     */
    public function publish($action, $parameters = array() , $routingKey = '', $additionalProperties = array(), array $headers = null)
    {
        $message = new Message();
        $message->setAction($action)
            ->setParameters($parameters);
        $this->em->persist($message);
        $this->em->flush();

        $msgBody = array(
            'action' => $action,
            'parameters' => $parameters
        );
        $this->producer->publish(serialize($msgBody), $routingKey, $additionalProperties, $headers);

    }
}
</code>```

Finally, call the original producer from a controller:

```<code>$this->get('old_sound_rabbit_mq.myproducer_producer')->publish('wait', ['time' => 30]);
</code>```

Body:
I am using RabbitMQBundle in a Symfony 2.8 project, and I would like to use a custom producer class which persists an entity (Message) in database before publishing the RabbitMQ message.

I defined the custom producer class in config.yml:

old_sound_rabbit_mq:
  ...
  producers:
    myproducer:
      class: AppBundle\Services\GenericProducer
      connection: default
      exchange_options: {name: 'my_exchange', type: direct}

And the custom Producer class:

<?php

namespace AppBundle\Services;

use AppBundle\Entity\Message;
use OldSound\RabbitMqBundle\RabbitMq\Producer;

/**
 * Customised Producer, that publishes AMQP Messages
 * but also:
 * - writes an entry in the Message table
 */
class GenericProducer extends Producer
{
    /**
     * Entity Manager
     */
    protected $em;

    public function setEntityManager($entityManager)
    {
        $this->em = $entityManager;

        return $this;
    }

    /**
     * Publishes the message and merges additional properties with basic properties
     * And also:
     * - writes an entry in the Message table
     *
     * @param string $action
     * @param array $parameters
     * @param string $routingKey
     * @param array $additionalProperties
     * @param array|null $headers
     */
    public function publish($action, $parameters = array() , $routingKey = '', $additionalProperties = array(), array $headers = null)
    {
        $message = new Message();
        $message->setAction($action)
            ->setParameters($parameters);
        $this->em->persist($message);
        $this->em->flush();

        $msgBody = array(
            'action' => $action,
            'parameters' => $parameters
        );
        parent::publish($msgBody, $routingKey, $additionalProperties, $headers);
    }
}

How can I make a call to GenericProducer->setEntityManager, as the producer is not defined in services.yml, like other services ?

Is there another way to achieve this ?

Thanks for your time.

Body:
Following @lordrhodos suggestion, I decorated the producer service generated by RabbitMQBundle. Here is the complete code:

config.yml (nothing special to do):

old_sound_rabbit_mq:
  ...
  producers:
    myproducer:
      connection: default
      exchange_options: {name: 'my_exchange', type: direct}

services.yml (here you define a decorating service):

app.decorating_myproducer_producer:
      class: AppBundle\Services\GenericProducer
      decorates: old_sound_rabbit_mq.myproducer_producer
      arguments: ['@
app.decorating_myproducer_producer.inner', '@doctrine.orm.entity_manager']
      public: false

decorator class:

<?php

namespace AppBundle\Services;

use AppBundle\Entity\Message;
use OldSound\RabbitMqBundle\RabbitMq\Producer;

/**
 * Customised Producer, that publishes AMQP Messages
 * but also:
 * - writes an entry in the Message table
 */
class GenericProducer extends Producer
{
    /**
     * @var Producer
     */
    protected $producer;

    /**
     * @var EntityManager
     */
    protected $em;

    /**
     * GenericProducer constructor.
     * @param Producer $producer
     * @param EntityManager $entityManager
     */
    public function __construct(Producer $producer, EntityManager $entityManager)
    {
        $this->producer = $producer;
        $this->em = $entityManager;
    }

    /**
     * Publishes the message and merges additional properties with basic properties
     * And also:
     * - writes an entry in the Message table
     *
     * @param string $action
     * @param array $parameters
     * @param string $routingKey
     * @param array $additionalProperties
     * @param array|null $headers
     */
    public function publish($action, $parameters = array() , $routingKey = '', $additionalProperties = array(), array $headers = null)
    {
        $message = new Message();
        $message->setAction($action)
            ->setParameters($parameters);
        $this->em->persist($message);
        $this->em->flush();

        $msgBody = array(
            'action' => $action,
            'parameters' => $parameters
        );
        $this->producer->publish(serialize($msgBody), $routingKey, $additionalProperties, $headers);

    }
}

Finally, call the original producer from a controller:

$this->get('old_sound_rabbit_mq.myproducer_producer')->publish('wait', ['time' => 30]);


来源: stackexchange

问:
Php and SQL issued with foreach
I have this following warning :

Warning: Invalid argument supplied for foreach()

Because my function return false , but i don't understand why it returns false

There is the function :

```<code>function getPlayerId($pseudo){

    $bdd=getBDD();

    $thisPlayerId= $bdd->query('SELECT users.id FROM users WHERE users.pseudo='.$pseudo);

    return $thisPlayerId;

}
</code>```

and there is the call :

```<code>$thisPlayerID = getPlayerId("test");

//var_dump(isset($thisPlayerID));

foreach ($thisPlayerID as $r3){
    echo $r['id'].'<br>';
}
</code>```

答:
If you try to solve it with an additional empty check for the $thisPlayerID variable you won't get that error:

```<code>//var_dump(isset($thisPlayerID));
if(!empty($thisPlayerID))
{
    foreach ($thisPlayerID as $r3){
        echo $r3['id'].'<br>';
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Php and SQL issued with foreach

Body:
I have this following warning :

Warning: Invalid argument supplied for foreach()

Because my function return false , but i don't understand why it returns false

There is the function :

function getPlayerId($pseudo){

    $bdd=getBDD();

    $thisPlayerId= $bdd->query('SELECT users.id FROM users WHERE users.pseudo='.$pseudo);

    return $thisPlayerId;

}

and there is the call :

$thisPlayerID = getPlayerId("test");

//var_dump(isset($thisPlayerID));

foreach ($thisPlayerID as $r3){
    echo $r['id'].'
';
}

Body:
If you try to solve it with an additional empty check for the $thisPlayerID variable you won't get that error:

//var_dump(isset($thisPlayerID));
if(!empty($thisPlayerID))
{
    foreach ($thisPlayerID as $r3){
        echo $r3['id'].'<br>';
    }
}


问:
Store 2D Array in .png format with colours
I wrote this Python Program to create and save a matrix (2D Array) to a .png file. The program compiles and runs without any error. Even the IMAGE.png file is created but the png file won't open. When I try to open it in MSPaint, it says:

Cannot open image. Not a valid bitmap file or its format is not currently supported.

My objective is to create a RBG png image based on the numbers stored in the 2D Array.

Source Code:

```<code>    import numpy;
    import png;

    imagearray = numpy.zeros(shape=(512,512));

    /* Code to insert one '1', '2', '3' in certain locations
       of the numpy 2D Array. Rest of the location by default stores zero '0'.*/

    f = open("IMAGE.png", 'wb');
    f.write(imagearray);
    f.close();
</code>```

I don't understand where I went wrong as there is no error message. Please Help.

PS- I just want to save the matrix as an image file, so if you have a better and easy way of doing it in Python2.7, do suggest.

答:
Plot your image with matplotlib and save it.

```<code>import matplotlib.pyplot as plt
import numpy as np
a = np.random.uniform(size=(25, 25, 3))  # random 3D array
plt.imshow(a)
plt.savefig("img.png")
</code>```

imshow() has various parameters of interest, amongst which interpolation (examples here) and cmap (colormap)

To remove the axes and whitespaces, as per this question:

```<code>plt.axis('off')
plt.savefig("img.png", bbox_inches='tight')
</code>```

Body:
I wrote this Python Program to create and save a matrix (2D Array) to a .png file. The program compiles and runs without any error. Even the IMAGE.png file is created but the png file won't open. When I try to open it in MSPaint, it says:

Cannot open image. Not a valid bitmap file or its format is not currently supported.

My objective is to create a RBG png image based on the numbers stored in the 2D Array.

Source Code:

    import numpy;
    import png;

    imagearray = numpy.zeros(shape=(512,512));

    /* Code to insert one '1', '2', '3' in certain locations
       of the numpy 2D Array. Rest of the location by default stores zero '0'.*/

    f = open("IMAGE.png", 'wb');
    f.write(imagearray);
    f.close();

I don't understand where I went wrong as there is no error message. Please Help.

PS- I just want to save the matrix as an image file, so if you have a better and easy way of doing it in Python2.7, do suggest.

Body:
Plot your image with matplotlib and save it.

import matplotlib.pyplot as plt
import numpy as np
a = np.random.uniform(size=(25, 25, 3))  # random 3D array
plt.imshow(a)
plt.savefig("img.png")

imshow() has various parameters of interest, amongst which interpolation (examples here) and cmap (colormap)

To remove the axes and whitespaces, as per this question:

plt.axis('off')
plt.savefig("img.png", bbox_inches='tight')


问:
Magento 1.9 throws 500 error when user try to register
I have Magento version 1.9.3.2. When a user wants to register, it generates an Internal Server Error (HTTP error code 500). The user does not receive email, but he is registered.

If I reload the page, it shows the message "Thank you for registering" and account page is open.

I checked logs of Magento and Apache - nothing there.

Anybody have idea how to fix this?

Update.
I switched on display_errors in index.php file. I got message:

[05-Jul-2017 09:09:01 UTC] PHP Fatal error:  Call to a member function getPayment() on null in /home/some/public_html/some/app/code/community/Fooman/EmailAttachments/Model/Core/Email/Template/Mailer.php on line 34

This line 34 is this:
$paymentMethod = $this->getTemplateParams()['order']->getPayment()->getData("method");

So seems there is a block "Fooman" which tries to use instance of the class when it is not initialised.

Anybody know something about this extension Fooman?

Update.
Seems the problem is solved by this code. For registration I check if user has instance of class, if he don't have it I use standard template.

```<code>//here check if have instance of class
            if (isset($this->getTemplateParams()['order']))
            {
                //here 34 string where error occure
                $paymentMethod = $this->getTemplateParams()['order']->getPayment()->getData("method");

                if ($this->getTemplateId() == '1') {
                    switch($paymentMethod) {
                        case 'banktransfer':
                            $templateId = 9;
                            break;

                        case 'paypal_express':
                            $templateId = 8;

                        default:
                            $templateId = $this->getTemplateId();
                            break;
                    }
                } else {

                    $templateId = $this->getTemplateId();
                }
            }
            else {
                $templateId = $this->getTemplateId();
            }
</code>```

答:
some time when file not found Emogrifier.php below path

magento Root/lib/Pelago/Emogrifier.php

Check this file exist or not if it is not there then download from fresh magento and put it to there.

clear cache and try.

Body:
I have Magento version 1.9.3.2. When a user wants to register, it generates an Internal Server Error (HTTP error code 500). The user does not receive email, but he is registered.

If I reload the page, it shows the message "Thank you for registering" and account page is open.

I checked logs of Magento and Apache - nothing there.

Anybody have idea how to fix this?

Update.
I switched on display_errors in index.php file. I got message:

[05-Jul-2017 09:09:01 UTC] PHP Fatal error:  Call to a member function getPayment() on null in /home/some/public_html/some/app/code/community/Fooman/EmailAttachments/Model/Core/Email/Template/Mailer.php on line 34

This line 34 is this:
$paymentMethod = $this->getTemplateParams()['order']->getPayment()->getData("method");

So seems there is a block "Fooman" which tries to use instance of the class when it is not initialised.

Anybody know something about this extension Fooman?

Update.
Seems the problem is solved by this code. For registration I check if user has instance of class, if he don't have it I use standard template.

//here check if have instance of class
            if (isset($this->getTemplateParams()['order']))
            {
                //here 34 string where error occure
                $paymentMethod = $this->getTemplateParams()['order']->getPayment()->getData("method");

                if ($this->getTemplateId() == '1') {
                    switch($paymentMethod) {
                        case 'banktransfer':
                            $templateId = 9;
                            break;

                        case 'paypal_express':
                            $templateId = 8;

                        default:
                            $templateId = $this->getTemplateId();
                            break;
                    }
                } else {

                    $templateId = $this->getTemplateId();
                }
            }
            else {
                $templateId = $this->getTemplateId();
            }


问:
Does Scala run on the JamVM
Does Scala 2.8 run on the JamVM? </p>

答: I see no reason why it wouldn't, but the best way to check this is to try it out.</p>

ContentLicense: CC BY-SA 2.5

Title: Does Scala run on the JamVM

Body: Does Scala 2.8 run on the JamVM?


问:
How to sum up a value without remove duplicated row in pandas?
I have one dataframe:

```<code>   a     b     c     d    f
0  ai    Y     5     3    w
1  ai    Y     5     3    r
2  ai    Y     5     2    t
3  ai    Y     5     3    o
</code>```

i wish my output is:

```<code>   a     b     c     d    f     e
0  ai    Y     5     3    w     5
1  ai    Y     5     3    r     5
2  ai    Y     5     2    t     5
3  ai    Y     5     3    o     5
</code>```

the column e is sum of the unique value in column d(mean the unique value is 2 and 3), anyone can share me the idea of the code?

this is my code:

```<code> df.groupby(['a','b','c'])['d'].transform('max')
</code>```

答:
You can take the unique values from the Series then sum it.</p>

```<code>df['e'] = df.d.unique().sum()
</code>```

Body:
I have one dataframe:

   a     b     c     d    f
0  ai    Y     5     3    w
1  ai    Y     5     3    r
2  ai    Y     5     2    t
3  ai    Y     5     3    o

i wish my output is:

   a     b     c     d    f     e
0  ai    Y     5     3    w     5
1  ai    Y     5     3    r     5
2  ai    Y     5     2    t     5
3  ai    Y     5     3    o     5

the column e is sum of the unique value in column d(mean the unique value is 2 and 3), anyone can share me the idea of the code?

this is my code:

 df.groupby(['a','b','c'])['d'].transform('max')

Body:
You can take the unique values from the Series then sum it.

df['e'] = df.d.unique().sum()


问:
How do I add corner radius and icons to buttons?
How do I make a similar view like the one below

So technically both will be a button, and Currently I'm using 2 buttons and I use stack view to group it together

The questions are

How do I add corner radius to stack view

How do I add icons and the line between them

答:
1. Stack view appearance

You can't apply cornerRadius directly to UIStackView. You should embed it inside other UIView which could be configured as you want to.

The UIStackView is a nonrendering subclass of
UIView
; that is, it does not provide any user interface of its own. Instead, it just manages the position and size of its arranged views. As a result, some properties (like
backgroundColor
) have no effect on the stack view. Similarly, you cannot override
layerClass
,
draw(:)
, or draw(:in:).

https://developer.apple.com/documentation/uikit/uistackview

2. Icons and a line

Layout on your screenshot could be reproduces in few ways:

TableView: use cell.imageView and cell separator;

Manually built layout (makes more sense if you have only a few options to choose from)

In the second case you will have a Vertical StackView containing two views. Each view will have the imageView and titleLabel, first view will have pre-defined height constraint while the second view height will have equal constraint with the first one. To make a separator, create a 1pt height view inside the first view constraint to the bottom.

At this point I still don't understand why you want to use StackView. If you want your options list to be variable in count, use TableView. If some options should be hidden in certain cases, both StackView and TableView will fit, but if it is a Static menu I'd prefer replacing StackView with UIView.


问:
Double inverted commas from mysql command causing trouble in java string
I am using the following command to fetch report from my MySQL database. It works fine in the MySQL console but when i try using it in my Java code as a string, it starts throwing errors.

```<code>mysql -u root -ppass -e "SELECT * from CEM_LEGACY_INV" DBNAME | sed 's/\t/","/g;s/^/"/;s/$/"/' > /home/shahed/Desktop/filename.csv
</code>```

Instead of the query mentioned here, I want to use a string variable which has the query defined in it.

答:
You need to escap double quotes(") and back slash(\) - In java, You can escap this character using back slash(\).

You can try something like below -

```<code>String command = "mysql -u root -ppass -e \"SELECT * from CEM_LEGACY_INV\" DBNAME | sed 's/\\t/\",\"/g;s/^/\"/;s/$/\"/' ";
</code>```

Body:
I am using the following command to fetch report from my MySQL database. It works fine in the MySQL console but when i try using it in my Java code as a string, it starts throwing errors.

mysql -u root -ppass -e "SELECT * from CEM_LEGACY_INV" DBNAME | sed 's/\t/","/g;s/^/"/;s/$/"/' > /home/shahed/Desktop/filename.csv

Instead of the query mentioned here, I want to use a string variable which has the query defined in it.

Body:
You need to escap double quotes(") and back slash(\) - In java, You can escap this character using back slash(\).

You can try something like below -

String command = "mysql -u root -ppass -e \"SELECT * from CEM_LEGACY_INV\" DBNAME | sed 's/\\t/\",\"/g;s/^/\"/;s/$/\"/' ";


问:
How to pass multiple parameters through form action?
. .
    in my jsp page im using onclick event for a button. the event name is saveRecord(<%=rs.getInt(id)%>);". Here i'm passing the parameter of id.</p>

```<code>The method is
function saveRecord(id){
    var f=document.form;
    f.method="post";
    f.action='../MesDelivery?id='+id;
    f.submit();
}
Here i want to pass some more multiple parameters like name,address,etc
How to do? pls help me frndz...
</code>```

答:
Change your function as below</p>

```<code>function saveRecord(id,name,address){
    var f=document.form;
    f.method="post";
    f.action='../MesDelivery?id='+id+'&name='+name+'&address='+address;
    f.submit();
}
</code>```

Body:
. .
    in my jsp page im using onclick event for a button. the event name is saveRecord(<%=rs.getInt(id)%>);". Here i'm passing the parameter of id.

The method is
function saveRecord(id){
    var f=document.form;
    f.method="post";
    f.action='../MesDelivery?id='+id;
    f.submit();
}
Here i want to pass some more multiple parameters like name,address,etc
How to do? pls help me frndz...

Body:
Change your function as below

function saveRecord(id,name,address){
    var f=document.form;
    f.method="post";
    f.action='../MesDelivery?id='+id+'&name='+name+'&address='+address;
    f.submit();
}


问:
Include CSS and JS in PHP based on condition
Is there a way to search the PHP content body while it is being parsed by PHP for certain keywords, so I can include CSS and JS files based on the presence of those keywords before the page is being served?

If PHP would have a variable like $_CONTENT_BODY where it outputs the parsed page into, then I could search for keywords like in this example:

if(stripos($_CONTENT_BODY, 'usetinymce') !== false)) echo '';

答:
You can get the page itself and parse it. </p>

```<code><?php
if (!isset($_GET['doNotCallMeAgain']) || $_GET['doNotCallMeAgain'] !== 1) {
    $urltothisfile = 'urltothefilehimself'+'?doNotCallMeAgain=1';
    $result = file_get_contents ($urltothisfile); //in $result you will get your page as html and you can search in it
} ?>
</code>```

Body:
You can get the page itself and parse it.

<?php
if (!isset($_GET['doNotCallMeAgain']) || $_GET['doNotCallMeAgain'] !== 1) {
    $urltothisfile = 'urltothefilehimself'+'?doNotCallMeAgain=1';
    $result = file_get_contents ($urltothisfile); //in $result you will get your page as html and you can search in it
} ?>


问:
MySQL loop over each value in a column
I have a table with 2 columns:
id, tag

I want to get a result table with id and count_of_tag but with special counting requirement like this (count distinct tags for each id with id=1 always included):

For each i in id:

```<code>select id, count(distinct tag) from table where id in (1,i);
</code>```

How can I do this? I only have experience in select statements and new to stored procedure/functions.

----Sample Data-----

```<code>id |tag
1  |  A
1  |  B
1  |  C
2  |  A
2  |  D
3  |  C
3  |  D
3  |  E
</code>```

----Desired result----

```<code>id |count
1  |    3
2  |    4
3  |    5
</code>```

答:
Come up with a solution myself:</p>

```<code>select
   id, count(distinct tag)
from
   (select * from table
     union
     select * from
     (select distinct id from table where id<>1) as t1
     CROSS JOIN
     (select distinct tag from table where id=1) as t2) as final
group by id;
</code>```

ContentLicense: CC BY-SA 4.0

Title: MySQL loop over each value in a column

Body:
I have a table with 2 columns:
id, tag

I want to get a result table with id and count_of_tag but with special counting requirement like this (count distinct tags for each id with id=1 always included):

For each i in id:

select id, count(distinct tag) from table where id in (1,i);

How can I do this? I only have experience in select statements and new to stored procedure/functions.

----Sample Data-----

id |tag
1  |  A
1  |  B
1  |  C
2  |  A
2  |  D
3  |  C
3  |  D
3  |  E

----Desired result----

id |count
1  |    3
2  |    4
3  |    5

Body:
Come up with a solution myself:

select
   id, count(distinct tag)
from
   (select * from table
     union
     select * from
     (select distinct id from table where id<>1) as t1
     CROSS JOIN
     (select distinct tag from table where id=1) as t2) as final
group by id;


问:
Plot the data in real time in Matlab
I have a few files which I am planning to plot in Matlab. I have loaded the files and I wanted to plot it in real time. As in I want to see it as it is being plotted. </p>

```<code>%clear
[filename, pathname] = uigetfile('*.raw;*.prc', 'Pick raw or processed data file');
N=str2double(filename(5:6));
Fs = 145.3*10^3;
T = 1/Fs; % Sampling period
if isequal(filename(end-2:end),'raw')
    % load raw data file
    fid = fopen([pathname filename],'r','l');
    A=fread(fid,inf,'*uint16')'; %s=ftell(fid);
    B=bitand(A, hex2dec('0FFF')); C=bitshift(A,-12);
    channels=sort(C(1:N));
    rawdata(int16(numel(A)/N)+2,N)=uint16(0); % Need to add +2 due to data loss
    for ii=1:N
        %rawdata(:,ii)=B(C==channels(ii)); can't use due to data loss
        temp=B(C==channels(ii));
        rawdata(1:numel(temp),ii)=temp;
    end
    plot(3.3/4095*single(rawdata))
    legend(int2str(channels'))
else
    %load processed file
    fid = fopen([pathname filename],'r','b');
    A= fread(fid,inf,'*single')';
    prcdata=reshape(A,N,[])';

    %Find time
    N = size(prcdata(:,1),1);
    t=T*(0:N-1)';

for u = 1:N;
        x=0:(T*(0:u-1)');
        plot(x,prcdata(:,4));
   drawnow;
   end
end
</code>```

答:
try animinatedline

objects optimize line animations by accumulating data from a streaming data source. After you create the initial animated line using the animatedline function, you can add new points to the line without having to redefine the existing points. Modify the appearance of the animated line by setting its properties.

Title: Plot the data in real time in Matlab

Body:
I have a few files which I am planning to plot in Matlab. I have loaded the files and I wanted to plot it in real time. As in I want to see it as it is being plotted.

%clear
[filename, pathname] = uigetfile('*.raw;*.prc', 'Pick raw or processed data file');
N=str2double(filename(5:6));
Fs = 145.3*10^3;
T = 1/Fs; % Sampling period
if isequal(filename(end-2:end),'raw')
    % load raw data file
    fid = fopen([pathname filename],'r','l');
    A=fread(fid,inf,'*uint16')'; %s=ftell(fid);
    B=bitand(A, hex2dec('0FFF')); C=bitshift(A,-12);
    channels=sort(C(1:N));
    rawdata(int16(numel(A)/N)+2,N)=uint16(0); % Need to add +2 due to data loss
    for ii=1:N
        %rawdata(:,ii)=B(C==channels(ii)); can't use due to data loss
        temp=B(C==channels(ii));
        rawdata(1:numel(temp),ii)=temp;
    end
    plot(3.3/4095*single(rawdata))
    legend(int2str(channels'))
else
    %load processed file
    fid = fopen([pathname filename],'r','b');
    A= fread(fid,inf,'*single')';
    prcdata=reshape(A,N,[])';

    %Find time
    N = size(prcdata(:,1),1);
    t=T*(0:N-1)';

for u = 1:N;
        x=0:(T*(0:u-1)');
        plot(x,prcdata(:,4));
   drawnow;
   end
end


问:
Handling action correctly using Redux-saga
I'm new to Reactjs, so if anything wrong, just let me know.

I have one thing to ask about asynchronous, redux-saga.

Basically, I have one simple action: when I selected an item => delete it, if it's success, call api that get all items, again

Like this: ( this is happened inside my saga)

```<code>export function* delete (action)
   yield call(service.deleteanitem)
   ....
   yield call(service.getall)
   yield put {type: 'getall'}
</code>```

My idea is, I want it's sequential, I mean, when I delete item, a 'getall' action have to 'wait' whenever the previous action done, then its turn.

Any suggestion ?

答:
a 'getall' action have to 'wait' whenever the previous action done,
  then its turn.

Just use full-weight fork saga process and build your own custom execution flow with asynchronous operations.

Example which covers any case with cross await dependencies:

```<code>function* sagaProc() {
  let controlPromise, controlResolve;
  while(true) {
    // ...
    controlPromise = new Promise(resolve => (controlResolve = resolve))
    socket.on('message', msg => controlResolve(msg))
    yield put({ type: 'SOME_REQUEST' })
    yield call(() => fetch('SOME_URL'))
    const message = yield call(() => controlPromise)
    yield put({ type: 'SOME_RESPONSE', ...message })
    // ...
  }
}

function* mainSaga() {
  // ...
  yield fork(sagaProc)
  // ...
}
</code>```

Body:
I'm new to Reactjs, so if anything wrong, just let me know.

I have one thing to ask about asynchronous, redux-saga.

Basically, I have one simple action: when I selected an item => delete it, if it's success, call api that get all items, again

Like this: ( this is happened inside my saga)

export function* delete (action)
   yield call(service.deleteanitem)
   ....
   yield call(service.getall)
   yield put {type: 'getall'}

My idea is, I want it's sequential, I mean, when I delete item, a 'getall' action have to 'wait' whenever the previous action done, then its turn.

Any suggestion ?

Body:
a 'getall' action have to 'wait' whenever the previous action done,
  then its turn.

Just use full-weight fork saga process and build your own custom execution flow with asynchronous operations.

Example which covers any case with cross await dependencies:

function* sagaProc() {
  let controlPromise, controlResolve;
  while(true) {
    // ...
    controlPromise = new Promise(resolve => (controlResolve = resolve))
    socket.on('message', msg => controlResolve(msg))
    yield put({ type: 'SOME_REQUEST' })
    yield call(() => fetch('SOME_URL'))
    const message = yield call(() => controlPromise)
    yield put({ type: 'SOME_RESPONSE', ...message })
    // ...
  }
}

function* mainSaga() {
  // ...
  yield fork(sagaProc)
  // ...
}


问:
Is there are way to change value inside of AlertDialog.Builder?(Android)
I'm new to android.
Can I change the value inside of AlertDialog.Builder?</p>

```<code>int changeThisDataToOne = 0;

    new AlertDialog.Builder(view.getContext())
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Are you sure?")
            .setMessage("Do you want to delete this note?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            changeThisDataToOne = 1;
                           //error : Variable 'changeThisDataToOne' is accessed
                           //from within inner class, needs to be declared final
                        }
                    }
            )
            .setNegativeButton("No", null)
            .show();
}
</code>```

答: You can't access local variable(changeThisDataToOne) into inner class ,you should make it final or initialize it as global variable.

Body:
I'm new to android.
Can I change the value inside of AlertDialog.Builder?

int changeThisDataToOne = 0;

    new AlertDialog.Builder(view.getContext())
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Are you sure?")
            .setMessage("Do you want to delete this note?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            changeThisDataToOne = 1;
                           //error : Variable 'changeThisDataToOne' is accessed
                           //from within inner class, needs to be declared final
                        }
                    }
            )
            .setNegativeButton("No", null)
            .show();
}


答:
You can assemble a Variable which you can search and output at the End.</p>

```<code>$_CONTENT_BODY  = 'here ';
$_CONTENT_BODY .= 'is some ';
$_CONTENT_BODY .= 'content.';

if(stripos($_CONTENT_BODY, 'some')){
 // do whatever you like
}
</code>```

Title: Include CSS and JS in PHP based on condition

Body:
Is there a way to search the PHP content body while it is being parsed by PHP for certain keywords, so I can include CSS and JS files based on the presence of those keywords before the page is being served?

If PHP would have a variable like $_CONTENT_BODY where it outputs the parsed page into, then I could search for keywords like in this example:

if(stripos($_CONTENT_BODY, 'usetinymce') !== false)) echo '';

Body:
You can assemble a Variable which you can search and output at the End.

$_CONTENT_BODY  = 'here ';
$_CONTENT_BODY .= 'is some ';
$_CONTENT_BODY .= 'content.';

if(stripos($_CONTENT_BODY, 'some')){
 // do whatever you like
}


问:
Python using regex to extract parts of a string in pandas column
I've got a pandas df column called 'Raw' for which the format is inconsistent. The strings it contains look like that:

```<code>'(1T XXX, Europe)'
'(2T YYYY, Latin America)'
'(3T ZZ/ZZZZ, Europe)'
'(4T XXX XXX, Africa)'
</code>```

The only thing consistent in the strings in 'Raw' is that they start with a digit, includes a comma in the middle followed by a whitespace, and they contain parentheses as well.

Now, I'd like to create two extra columns (Model and Region) in my dataframe:

'Model' would contain the beginning of the string, i.e. everything between the first parenthesis and the comma

'Region' would contain the end of the string, i.e. everything between the whitespace after the comma and the final parenthesis

How do I do that using regex?

答:
```<code>Model=re.findall(r"(?<=\().+(?=\,)",s)
Region=re.findall(r"(?<=\, ).+(?=\))",s)
</code>```

The first regex checks for opening bracket "(" in front of the model and closing ",". The second regex checks for any string between "," and ")".

Body:
I've got a pandas df column called 'Raw' for which the format is inconsistent. The strings it contains look like that:

'(1T XXX, Europe)'
'(2T YYYY, Latin America)'
'(3T ZZ/ZZZZ, Europe)'
'(4T XXX XXX, Africa)'

The only thing consistent in the strings in 'Raw' is that they start with a digit, includes a comma in the middle followed by a whitespace, and they contain parentheses as well.

Now, I'd like to create two extra columns (Model and Region) in my dataframe:

'Model' would contain the beginning of the string, i.e. everything between the first parenthesis and the comma

'Region' would contain the end of the string, i.e. everything between the whitespace after the comma and the final parenthesis

How do I do that using regex?

Body:
Model=re.findall(r"(?<=\().+(?=\,)",s)
Region=re.findall(r"(?<=\, ).+(?=\))",s)

The first regex checks for opening bracket "(" in front of the model and closing ",". The second regex checks for any string between "," and ")".


问:
WPF close secondary window before main window
I have 2 windows in a WPF application, and If I close the Main one, I want to close the other too.

I achieved this by setting in my App.xaml:

```<code>ShutdownMode="OnMainWindowClose"
</code>```

The 2 windows have a Window_Closing event in which I de-initialise some components. Now what I want to achieve is: if I close the MainWindow, the Window_Closing event of the second window must execute before the closing event of the Main one, because the de-init of the second one has to be executed before the first. Any idea on how can I achive this?

答:
Could you simply call the Close() function of the second window from the main window Window_Closing event?</p>

```<code>void MainWindow_Closing(object sender, CancelEventArgs e)
{
    secondaryWindow.Close();

    ...
}
</code>```

Body:
I have 2 windows in a WPF application, and If I close the Main one, I want to close the other too.

I achieved this by setting in my App.xaml:

ShutdownMode="OnMainWindowClose"

The 2 windows have a Window_Closing event in which I de-initialise some components. Now what I want to achieve is: if I close the MainWindow, the Window_Closing event of the second window must execute before the closing event of the Main one, because the de-init of the second one has to be executed before the first. Any idea on how can I achive this?

Body:
Could you simply call the Close() function of the second window from the main window Window_Closing event?

void MainWindow_Closing(object sender, CancelEventArgs e)
{
    secondaryWindow.Close();

    ...
}


问:
Need help identifying type of UTF Encoding
I'm having a hard time trying to figure out the type of unicode that i need to convert to pass data for post request. Mostly would be chinese characters.

Example String:

的事故事务院治党派驻地是不是

Expected Unicode: %u7684%u4E8B%u6545%u4E8B%u52A1%u9662%u6CBB%u515A%u6D3E%u9A7B%u5730%u662F%u4E0D%u662F

Tried to encode to UTF16-BE:
%76%84%4E%8B%65%45%4E%8B%52%A1%5C%40%5C%40%95%7F%67%1F%8D%27%7B%49%5F%85%62%08%59%1A

Encoded text in UTF-16: %FF%FE%84%76%8B%4E%45%65%8B%4E%A1%52%62%96%BB%6C%5A%51%3E%6D%7B%9A%30%57%2F%66%0D%4E%2F%66

Encoded text in UTF-8: %E7%9A%84%E4%BA%8B%E6%95%85%E4%BA%8B%E5%8A%A1%E9%99%A2%E6%B2%BB%E5%85%9A%E6%B4%BE%E9%A9%BB%E5%9C%B0%E6%98%AF%E4%B8%8D%E6%98%AF

As you can see, UTF16-BE is the closest, but it only takes 2 bytes and there should be an additional %u in front of every character as shown in the expected unicode.

I've been using URLEncoder method to get the encoded text, with the standard charset encodings but it doesn't seem to return the expected unicode.

Code:

```<code>String text = "的事故事务院治党派驻地是不是";
URLEncoder.encode(text, "UTF-16BE");
</code>```

答:
I think that you are thinking too far. The encoding of a text doesn't need to "resemble" in any way the string of Unicode code points of this text. These are two different things.

To send the string 的事故事务院治党派驻地是不是 in a POST request, just write the entire POST request and encode it with UTF-8, and the resulting bytes are what is sent as the body of the POST request to the server.

As pointed out by @Andreas, UTF-8 is the default encoding of HTML5, so it's not even necessary to set the accept-charset attribute, because the server will automatically use UTF-8 to decode the body of your request, if accept-charset is not set.

Body:
I'm having a hard time trying to figure out the type of unicode that i need to convert to pass data for post request. Mostly would be chinese characters.

Example String:

的事故事务院治党派驻地是不是

Expected Unicode: %u7684%u4E8B%u6545%u4E8B%u52A1%u9662%u6CBB%u515A%u6D3E%u9A7B%u5730%u662F%u4E0D%u662F

Tried to encode to UTF16-BE:
%76%84%4E%8B%65%45%4E%8B%52%A1%5C%40%5C%40%95%7F%67%1F%8D%27%7B%49%5F%85%62%08%59%1A

Encoded text in UTF-16: %FF%FE%84%76%8B%4E%45%65%8B%4E%A1%52%62%96%BB%6C%5A%51%3E%6D%7B%9A%30%57%2F%66%0D%4E%2F%66

Encoded text in UTF-8: %E7%9A%84%E4%BA%8B%E6%95%85%E4%BA%8B%E5%8A%A1%E9%99%A2%E6%B2%BB%E5%85%9A%E6%B4%BE%E9%A9%BB%E5%9C%B0%E6%98%AF%E4%B8%8D%E6%98%AF

As you can see, UTF16-BE is the closest, but it only takes 2 bytes and there should be an additional %u in front of every character as shown in the expected unicode.

I've been using URLEncoder method to get the encoded text, with the standard charset encodings but it doesn't seem to return the expected unicode.

Code:

String text = "的事故事务院治党派驻地是不是";
URLEncoder.encode(text, "UTF-16BE");


问:
android comparing dates I couldn't compare two dates...I referred many tutorials
I am using the datepicker dialog and am trying to compare the  current date  with the date specified in the dialog.
if the date is before the current date I wish to display invalid date.

Both current date and date entered are in same format. but I am getting error. when printing in console both current date and entered date are coming the the same format

```<code>if(date1.before(currDate))
{
     Toast.makeText(getApplicationContext(), "Enter the valid Date", Toast.LENGTH_LONG).show();
}
</code>```

result:

current date 5/7/2017

picked date 5-7-2017

答:
you can directly deactivate past dates in datepicker by

```<code>datePicker.setMinDate(System.currentTimeMillis() - 1000);
</code>```

You can compare time only by converting it in milliseconds

```<code>  Date setDateTime = input.parse(todayTime);
  calendar1.setTime(setDateTime);
  selectedTime=calendar1.getTimeInMillis();

  msTime = System.currentTimeMillis();//current time
//and compare msTime and setsetDateTime
  if (selectedTime>msTime){
//your logic
}
</code>```

or you can direct compare date by formating date format in digits only like
for 5-7-2017 is 572017 and compare it to selected date in same format

Body:
I am using the datepicker dialog and am trying to compare the  current date  with the date specified in the dialog.
if the date is before the current date I wish to display invalid date.

Both current date and date entered are in same format. but I am getting error. when printing in console both current date and entered date are coming the the same format

if(date1.before(currDate))
{
     Toast.makeText(getApplicationContext(), "Enter the valid Date", Toast.LENGTH_LONG).show();
}

result:

current date 5/7/2017

picked date 5-7-2017

Body:
you can directly deactivate past dates in datepicker by

datePicker.setMinDate(System.currentTimeMillis() - 1000);

You can compare time only by converting it in milliseconds

  Date setDateTime = input.parse(todayTime);
  calendar1.setTime(setDateTime);
  selectedTime=calendar1.getTimeInMillis();

  msTime = System.currentTimeMillis();//current time
//and compare msTime and setsetDateTime
  if (selectedTime>msTime){
//your logic
}

or you can direct compare date by formating date format in digits only like
for 5-7-2017 is 572017 and compare it to selected date in same format


问:
Open Redis port for remote connections
I can ping pong Redis on the server:

```<code># redis-cli ping
PONG
</code>```

But remotely, I got problems:

```<code>$ src/redis-cli -h REMOTE.IP ping
Could not connect to Redis at REMOTE.IP:6379: Connection refused
</code>```

In config, I got the standard port:

```<code># Accept connections on the specified port, default is 6379.
# If port 0 is specified Redis will not listen on a TCP socket.
port 6379
</code>```

So maybe I should open port 6379 on the remote Ubuntu machine? How do I do it?

答:
1- Comment out bind 127.0.0.1

2- set requirepass yourpassword

then check if the firewall blocked your port

iptables -L -n

service iptables stop

Title: Open Redis port for remote connections

Body:
I can ping pong Redis on the server:

# redis-cli ping
PONG

But remotely, I got problems:

$ src/redis-cli -h REMOTE.IP ping
Could not connect to Redis at REMOTE.IP:6379: Connection refused

In config, I got the standard port:

# Accept connections on the specified port, default is 6379.
# If port 0 is specified Redis will not listen on a TCP socket.
port 6379

So maybe I should open port 6379 on the remote Ubuntu machine? How do I do it?


问:
How to parse Json object in ReactJS
I want to parse through a JSON list in reactJS.
Here is the model that I am using

```<code>public class ModelEmployee
{
    public List<Employeelist> Employees { get; set; }
    public int count { get; set; }
    public int Pagenumber { get; set; }
}
public class Employeelist
{
    public int EmployeeID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Phone { get; set; }
    public int RoleId { get; set; }
    public string RoleName { get; set; }
    public List<string> Roles { get; set; }
}
</code>```

And my controller is

```<code> public ActionResult Index(int pageNum = 1)
    {
        ModelEmployee model = new ModelEmployee();
            model = new ModelEmployee();
            model.Employees = FetchAllDevices(pageNum, 10);
            model.count = (int)Math.Ceiling((float)_empService.TotalCount() / _pageSize);
            model.Pagenumber = pageNum;
            return Json(model,JsonRequestBehavior.AllowGet);
    }
</code>```

This is what i have tried in ReactJS code to extract each values

```<code> componentWillMount: function(){

    var xhr = new XMLHttpRequest();
    xhr.open('get', this.props.url, true);
    xhr.onload = function () {
        var response = JSON.parse(xhr.responseText);
        this.setState({ result: response });

    }.bind(this);
    xhr.send();
},
render: function(){
    var rows = [];
    this.state.result.Employees.forEach(function (item) {
        rows.push(<EmployeeRow  key={item.EmployeeID} item={item }/>);
});
</code>```

Its not working. But when I change the setState with this,

```<code>this.setState({ result: response.Employees });
</code>```

it will work fine and can go through the Employees list. But cant access the pagenumber and count variables. Can you please help me to sort out this?
Thanks in advance.

答:
Why don't you also store the count and pagenumber in the state?

```<code>this.setState({
  employees: response.Employees,
  count: response.count,
  pageNumber: response.PageNumber
});
</code>```

Then you can access pageNumber and count from this.state.pageNumber and this.state.count respectively.

Title: How to parse Json object in ReactJS

Body:
I want to parse through a JSON list in reactJS.
Here is the model that I am using

public class ModelEmployee
{
    public List<Employeelist> Employees { get; set; }
    public int count { get; set; }
    public int Pagenumber { get; set; }
}
public class Employeelist
{
    public int EmployeeID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Phone { get; set; }
    public int RoleId { get; set; }
    public string RoleName { get; set; }
    public List<string> Roles { get; set; }
}

And my controller is

 public ActionResult Index(int pageNum = 1)
    {
        ModelEmployee model = new ModelEmployee();
            model = new ModelEmployee();
            model.Employees = FetchAllDevices(pageNum, 10);
            model.count = (int)Math.Ceiling((float)_empService.TotalCount() / _pageSize);
            model.Pagenumber = pageNum;
            return Json(model,JsonRequestBehavior.AllowGet);
    }

This is what i have tried in ReactJS code to extract each values

 componentWillMount: function(){

    var xhr = new XMLHttpRequest();
    xhr.open('get', this.props.url, true);
    xhr.onload = function () {
        var response = JSON.parse(xhr.responseText);
        this.setState({ result: response });

    }.bind(this);
    xhr.send();
},
render: function(){
    var rows = [];
    this.state.result.Employees.forEach(function (item) {
        rows.push(<EmployeeRow  key={item.EmployeeID} item={item }/>);
});

Its not working. But when I change the setState with this,

this.setState({ result: response.Employees });

it will work fine and can go through the Employees list. But cant access the pagenumber and count variables. Can you please help me to sort out this?
Thanks in advance.

Body:
Why don't you also store the count and pagenumber in the state?

this.setState({
  employees: response.Employees,
  count: response.count,
  pageNumber: response.PageNumber
});

Then you can access pageNumber and count from this.state.pageNumber and this.state.count respectively.


问:
Return type with generic with bounds
I have the following code

```<code>import scala.concurrent.Future

class RequestType
class Read extends RequestType
class Write extends RequestType

object Main {
  def main(args: Array[String]): Unit = {
  }

  def dbrequest[T <: RequestType](t: T): Future[T] = {
    val dBRequest = new DBRequest
    t match {
      case r: Read => dBRequest.read(r)
      case w: Write => dBRequest.write(w)
   }
  }
}

class DBRequest {
  def read(r: Read): Future[Read] = {
    Future(r)
  }

  def write(w: Write): Future[Write] = {
   Future(w)
  }
}
</code>```

read and write method return a Future of type RequestType. If T is bounded and Future is covariant, then why is the compiler failing to conform type of Future[Read] or Future[Write] to Future[T]

答:
If T is bounded and Future is covariant, then why is the compiler failing to conform type of Future[Read] or Future[Write] to Future[T]

Your code would make sense if T was guaranteed to be Read or Write.
But it could Read with SomeTrait. Or a singleton type (so even making RequestType, Read and Write sealed wouldn't help). Etc. See my answer to Returning subclass of parameterized type in Scala for a solution (just replace Output in that question with Future).

Title: Return type with generic with bounds

Body:
I have the following code

import scala.concurrent.Future

class RequestType
class Read extends RequestType
class Write extends RequestType

object Main {
  def main(args: Array[String]): Unit = {
  }

  def dbrequest[T <: RequestType](t: T): Future[T] = {
    val dBRequest = new DBRequest
    t match {
      case r: Read => dBRequest.read(r)
      case w: Write => dBRequest.write(w)
   }
  }
}

class DBRequest {
  def read(r: Read): Future[Read] = {
    Future(r)
  }

  def write(w: Write): Future[Write] = {
   Future(w)
  }
}

read and write method return a Future of type RequestType. If T is bounded and Future is covariant, then why is the compiler failing to conform type of Future[Read] or Future[Write] to Future[T]


问:
How to make a JSON parse object prototype less in Javascript?
I had a JavaScript object that is prototype-less.

```<code>var foo = Object.create(null);
</code>```

Then I read a JSON file (in Node.js) and used JSON.parse() to assign it to foo. Like this:

```<code>fs.readFile('talks.json', 'utf8', function(err, text) {
  if (err) {
    throw error;
  }
  foo = JSON.parse(text);
});
</code>```

But when I checked the prototype of foo it is not null anymore as it was originally intended to be.

Is there a way to make foo prototype-less again?

答:
I'm not a 100% sure about that but I think the issue here is that the javascript vm has to assign a prototype. If you check the prototype with .prototype, the value is undefined. If you check with .__proto__ it's a blank object.

This makes sense since the prototype shouldn't be nothing even if it's not defined. Programmers shouldn't use .__proto__. If you have to check the prototype, use .prototype.

var foo = Object.create(null);
console.log(foo); //{}
console.log(foo.__proto__); //undefined
console.log(foo.prototype); //undefined

var foo = JSON.parse("{\"a\":\"bla\"}");
console.log(foo); //like in the JSON string
console.log(foo.__proto__); //{}
console.log(foo.prototype); //undefined```

Body:
I had a JavaScript object that is prototype-less.

var foo = Object.create(null);

Then I read a JSON file (in Node.js) and used JSON.parse() to assign it to foo. Like this:

fs.readFile('talks.json', 'utf8', function(err, text) {
  if (err) {
    throw error;
  }
  foo = JSON.parse(text);
});

But when I checked the prototype of foo it is not null anymore as it was originally intended to be.

Is there a way to make foo prototype-less again?


问:
This Arthmetic Operation in MYSQL
I have 3 tables with almost same structure as seen below with some datas,

table name = myshop structure (id_no, time, teams, home, draw, away)

table name = myshop2 structure (id_no, time, teams, home, draw, away)

table name = myshop3 structure (id_no, teams, home, draw, away)

```<code> `TABLE NAME: MYSHOP
  ID_NO TIME    TEAMS                          HOME DRAW    AWAY
  209   00:00   FK PARTIZAN vs CSKA MOSCOW  3.3 3.75    1.85
  210   00:00   RAPID VIENNA vs CELTIC          2.6 3.3 2.3
  211   00:00   SPARTAK MOSCOW vs FK VOZDOVAC   1.3 5.2 6.75
  212   00:00   LUDOGORETS vs DINAMO MOSCOW 2.2 3.35    2.6
  213   00:00   FC THUN vs FC ZURICH            1.9 3.8 2.6
  214   01:00   FC NURNBERG vs BOHEMIANS 1905   1.45    3.9 4.6
  215   01:00   LILLESTROM vs STROMSGODSET  1.0 3.5 3.35
  216   01:00   HALMSTAD vs IF ELFSBORG         2.4 3.5 2.0
  217   05:00   FLANDRIA vs CHACARITA JUNIORS   3.78    2.67    2.54
  218   05:00   CA RIVER PLATE vs DANUBIO   3.25    3.15    2.7
  219   05:00   JUVENTUD vs CERRO           3.55    3.15    2.3

  TABLE NAME: MYSHOP 2
  ID_NO TIME    TEAMS                          HOME DRAW    AWAY
  9     00:00   FK PARTIZAN vs CSKA MOSCOW      2.3 3.75    1.85
  10    00:00   RAPID VIENNA vs CELTIC          1.6 3.3      2.3
  11    00:00   SPARTAK MOSCOW vs FK VOZDOVAC   2.3 5.2      6.75
  12    00:00   LUDOGORETS vs DINAMO MOSCOW     1.2 3.35     2.6
  13    00:00   FC THUN vs FC ZURICH            2.9 3.8      2.6
  14    01:00   FC NURNBERG vs BOHEMIANS 1905   2.453.9      4.6
  15    01:00   LILLESTROM vs STROMSGODSET      1.0 3.5      3.35
  16    01:00   HALMSTAD vs IF ELFSBORG         2.4 3.5      2.0
  17    05:00   FLANDRIA vs CHACARITA JUNIORS   1.782.67     2.54
  18    05:00   CA RIVER PLATE vs DANUBIO   1.25    3.15    2.7
  19    05:00   JUVENTUD vs CERRO           1.55    3.15    2.3

  TABLE NAME: MYSHOP 3
  ID_NO TEAMS                          HOME DRAW    AWAY
  33    FK PARTIZAN vs CSKA MOSCOW     2.3  2.75    2.85
  10    RAPID VIENNA vs CELTIC          1.6 2.3 2.3
  11    SPARTAK MOSCOW vs FK VOZDOVAC   2.3 3.2 6.75
  21    LUDOGORETS vs DINAMO MOSCOW     1.2 2.35    2.6
  31    FC THUN vs FC ZURICH            2.9 2.8 2.6
  42    FC NURNBERG vs BOHEMIANS 1905   2.45    2.9 4.6
  53    LILLESTROM vs STROMSGODSET       3.0    2.5 3.35
  64    HALMSTAD vs IF ELFSBORG         2.4 2.5 2.0
  75    FLANDRIA vs CHACARITA JUNIORS   1.78    1.67    2.54
  86    CA RIVER PLATE vs DANUBIO       1.25    1.15    2.7
  97    JUVENTUD vs CERRO               1.55    1.15    2.3
</code>```

`

Is it possible to perform a single arthmetic op

Datas that exist in those table have same teams values but different values on HOME, DRAW & AWAY so what i want is a sql syntax that will perform this specification.

It should take value of home in myshop table divide by 1, value of draw in myshop2 table divide by 1, value of away in myshop3 table divide by 1 then sum all the values and get one value for each team, and the output should be total with the corresponding team like simple example below.

FK PARTIZAN vs CSKA MOSCOW 105

IDEALLY SYNTAX IT SHOULD LOOK LIKE

SELECT from MYSHOP(home/1)+MYSHOP2(draw/1)+MYSHOP3(away/1) where TEAMS(MYSHOP=MYSHOP2=MYSHOP3)

Need your thoughts guys on this.

答:
I'm afraid your syntax wish and syntax reality are not matched.

I don't really know what you are trying to achieve but relying strings such as SPARTAK MOSCOW vs FK VOZDOVAC to join is not likely to work well. For example should these "join":

SPARTAK MOSCOW vs FK VOZDOVAC

FK VOZDOVAC vs SPARTAK MOSCOW

Consider this as a way to combine those 3 tables:

```<code>      SELECT
            1 tbl_src, id_no, teams, home, draw, away
      FROM myshop
      UNION ALL
      SELECT
            2 tbl_src, id_no, teams, home, draw, away
      FROM myshop2
      UNION ALL
      SELECT
            3 tbl_src, id_no, teams, home, draw, away
      FROM myshop3
</code>```

The try this:

```<code>SELECT
      teams
    , SUM(home)
    , SUM(draw)
    , SUM(away)
FROM (
      SELECT
            1 tbl_src, id_no, teams, home, draw, away
      FROM myshop
      UNION ALL
      SELECT
            2 tbl_src, id_no, teams, home, draw, away
      FROM myshop2
      UNION ALL
      SELECT
            3 tbl_src, id_no, teams, home, draw, away
      FROM myshop3
) AS d
GROUP BY
      teams
</code>```

Title: This Arthmetic Operation in MYSQL

Body:
I have 3 tables with almost same structure as seen below with some datas,

table name = myshop structure (id_no, time, teams, home, draw, away)

table name = myshop2 structure (id_no, time, teams, home, draw, away)

table name = myshop3 structure (id_no, teams, home, draw, away)

 `TABLE NAME: MYSHOP
  ID_NO TIME    TEAMS                          HOME DRAW    AWAY
  209   00:00   FK PARTIZAN vs CSKA MOSCOW  3.3 3.75    1.85
  210   00:00   RAPID VIENNA vs CELTIC          2.6 3.3 2.3
  211   00:00   SPARTAK MOSCOW vs FK VOZDOVAC   1.3 5.2 6.75
  212   00:00   LUDOGORETS vs DINAMO MOSCOW 2.2 3.35    2.6
  213   00:00   FC THUN vs FC ZURICH            1.9 3.8 2.6
  214   01:00   FC NURNBERG vs BOHEMIANS 1905   1.45    3.9 4.6
  215   01:00   LILLESTROM vs STROMSGODSET  1.0 3.5 3.35
  216   01:00   HALMSTAD vs IF ELFSBORG         2.4 3.5 2.0
  217   05:00   FLANDRIA vs CHACARITA JUNIORS   3.78    2.67    2.54
  218   05:00   CA RIVER PLATE vs DANUBIO   3.25    3.15    2.7
  219   05:00   JUVENTUD vs CERRO           3.55    3.15    2.3

  TABLE NAME: MYSHOP 2
  ID_NO TIME    TEAMS                          HOME DRAW    AWAY
  9     00:00   FK PARTIZAN vs CSKA MOSCOW      2.3 3.75    1.85
  10    00:00   RAPID VIENNA vs CELTIC          1.6 3.3      2.3
  11    00:00   SPARTAK MOSCOW vs FK VOZDOVAC   2.3 5.2      6.75
  12    00:00   LUDOGORETS vs DINAMO MOSCOW     1.2 3.35     2.6
  13    00:00   FC THUN vs FC ZURICH            2.9 3.8      2.6
  14    01:00   FC NURNBERG vs BOHEMIANS 1905   2.453.9      4.6
  15    01:00   LILLESTROM vs STROMSGODSET      1.0 3.5      3.35
  16    01:00   HALMSTAD vs IF ELFSBORG         2.4 3.5      2.0
  17    05:00   FLANDRIA vs CHACARITA JUNIORS   1.782.67     2.54
  18    05:00   CA RIVER PLATE vs DANUBIO   1.25    3.15    2.7
  19    05:00   JUVENTUD vs CERRO           1.55    3.15    2.3

  TABLE NAME: MYSHOP 3
  ID_NO TEAMS                          HOME DRAW    AWAY
  33    FK PARTIZAN vs CSKA MOSCOW     2.3  2.75    2.85
  10    RAPID VIENNA vs CELTIC          1.6 2.3 2.3
  11    SPARTAK MOSCOW vs FK VOZDOVAC   2.3 3.2 6.75
  21    LUDOGORETS vs DINAMO MOSCOW     1.2 2.35    2.6
  31    FC THUN vs FC ZURICH            2.9 2.8 2.6
  42    FC NURNBERG vs BOHEMIANS 1905   2.45    2.9 4.6
  53    LILLESTROM vs STROMSGODSET       3.0    2.5 3.35
  64    HALMSTAD vs IF ELFSBORG         2.4 2.5 2.0
  75    FLANDRIA vs CHACARITA JUNIORS   1.78    1.67    2.54
  86    CA RIVER PLATE vs DANUBIO       1.25    1.15    2.7
  97    JUVENTUD vs CERRO               1.55    1.15    2.3

`

Is it possible to perform a single arthmetic op

Datas that exist in those table have same teams values but different values on HOME, DRAW & AWAY so what i want is a sql syntax that will perform this specification.

It should take value of home in myshop table divide by 1, value of draw in myshop2 table divide by 1, value of away in myshop3 table divide by 1 then sum all the values and get one value for each team, and the output should be total with the corresponding team like simple example below.

FK PARTIZAN vs CSKA MOSCOW 105

IDEALLY SYNTAX IT SHOULD LOOK LIKE

SELECT from MYSHOP(home/1)+MYSHOP2(draw/1)+MYSHOP3(away/1) where TEAMS(MYSHOP=MYSHOP2=MYSHOP3)

Need your thoughts guys on this.

Body:
I'm afraid your syntax wish and syntax reality are not matched.

I don't really know what you are trying to achieve but relying strings such as SPARTAK MOSCOW vs FK VOZDOVAC to join is not likely to work well. For example should these "join":

SPARTAK MOSCOW vs FK VOZDOVAC

FK VOZDOVAC vs SPARTAK MOSCOW

Consider this as a way to combine those 3 tables:

      SELECT
            1 tbl_src, id_no, teams, home, draw, away
      FROM myshop
      UNION ALL
      SELECT
            2 tbl_src, id_no, teams, home, draw, away
      FROM myshop2
      UNION ALL
      SELECT
            3 tbl_src, id_no, teams, home, draw, away
      FROM myshop3

The try this:

SELECT
      teams
    , SUM(home)
    , SUM(draw)
    , SUM(away)
FROM (
      SELECT
            1 tbl_src, id_no, teams, home, draw, away
      FROM myshop
      UNION ALL
      SELECT
            2 tbl_src, id_no, teams, home, draw, away
      FROM myshop2
      UNION ALL
      SELECT
            3 tbl_src, id_no, teams, home, draw, away
      FROM myshop3
) AS d
GROUP BY
      teams


答: You could use ob_start(); and $text = ob_get_contents();.  Just make sure that you process these properly, check out http://php.net/manual/en/book.outcontrol.php.


问:
Understanding move semantics with objects returned by a function
I came across the following program from learncpp.com as an example for understanding the move semantics. I tried to run this program and see how the program flow is working as explained in the tutorial.

But, I fail to understand it in the function call.

```<code>Auto_ptr4<Resource> generateResource()
{
    Auto_ptr4<Resource> res(new Resource);
    return res; // this return value will invoke the move constructor
}
</code>```

Where it has been said that will use move constructor, but it is not doing that at all when I set a break point and debug.

Can anyone help me to understand why move constructor is not invoked here ? Does compiler eliding here ? If so, how to modify this so it will invoke move constructor. Please explain what is happening here.

Also, it would be great if you can share with some examples of where move constructor is called and how to use move constructors in place of copy constructor.

```<code>#include <iostream>

template<class T>
class Auto_ptr4
{
    T* m_ptr;
public:
    Auto_ptr4(T* ptr = nullptr)
    :m_ptr(ptr)
    {
    }

    ~Auto_ptr4()
    {
        delete m_ptr;
    }

    // Copy constructor
    // Do deep copy of a.m_ptr to m_ptr
    Auto_ptr4(const Auto_ptr4& a)
    {
        m_ptr = new T;
        *m_ptr = *a.m_ptr;
    }

    // Move constructor
    // Transfer ownership of a.m_mptr to m_ptr
    Auto_ptr4(Auto_ptr4&& a)
    : m_ptr(a.m_ptr)
    {
        a.m_ptr = nullptr;
    }

    // Copy assignment
    // Do deep copy of a.m_ptr to m_ptr
    Auto_ptr4& operator=(const Auto_ptr4& a)
    {
        // Self-assignment detection
        if (&a == this)
            return *this;

        // Release any resource we're holding
        delete m_ptr;

        // Copy the resource
        m_ptr = new T;
        *m_ptr = *a.m_ptr;

        return *this;
    }

    // Move assignment
    // Transfer ownership of a.m_ptr to m_ptr
    Auto_ptr4& operator=(Auto_ptr4&& a)
    {
        // Self-assignment detection
        if (&a == this)
            return *this;

        // Release any resource we're holding
        delete m_ptr;

        // Transfer ownership of a.m_ptr to m_ptr
        m_ptr = a.m_ptr;
        a.m_ptr = nullptr;

        return *this;
    }

    T& operator*() const { return *m_ptr; }
    T* operator->() const { return m_ptr; }
    bool isNull() const { return m_ptr == nullptr; }
};

class Resource
{
public:
    Resource() { std::cout << "Resource acquired\n"; }
    ~Resource() { std::cout << "Resource destroyed\n"; }
};

Auto_ptr4<Resource> generateResource()
{
    Auto_ptr4<Resource> res(new Resource);
    return res; // this return value will invoke the move constructor
}

int main()
{
    Auto_ptr4<Resource> mainres;
    mainres = generateResource(); // this assignment will invoke the move assignment

    return 0;
}
</code>```

Thanks

答:
```<code>Auto_ptr4<Resource> generateResource()
{
    Auto_ptr4<Resource> res(new Resource);
    return res; // this return value will invoke the move constructor
}
</code>```

Your code is written in a way that very much allows for copy elision. The C++ standard has an entire section devoted to just this use case.

[class.copy.elision/1.1]

in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function parameter or a variable introduced by the exception-declaration of a handler ([except.handle])) with the same type (ignoring cv-qualification) as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function call's return object

If you want to prevent elision, you need to return an expression that cannot be elided legally. Fortunately it's rather easy in this case to also force a move constructor to be called:

```<code>Auto_ptr4<Resource> generateResource()
{
    Auto_ptr4<Resource> res(new Resource);
    return std::move(res); // this return value will invoke the move constructor
}
</code>```

Since now the expression is not an automatic variable name, nor is Auto_ptr4<Resource>&& the same exactly as Auto_ptr4<Resource>. The c'tor isn't elided.

This is fine for learning purposes, but don't do it in real code. Copy elision is a very good thing that makes for more efficient code. Let the compiler do it for you when it can.

Body:
I came across the following program from learncpp.com as an example for understanding the move semantics. I tried to run this program and see how the program flow is working as explained in the tutorial.

But, I fail to understand it in the function call.

Auto_ptr4<Resource> generateResource()
{
    Auto_ptr4<Resource> res(new Resource);
    return res; // this return value will invoke the move constructor
}

Where it has been said that will use move constructor, but it is not doing that at all when I set a break point and debug.

Can anyone help me to understand why move constructor is not invoked here ? Does compiler eliding here ? If so, how to modify this so it will invoke move constructor. Please explain what is happening here.

Also, it would be great if you can share with some examples of where move constructor is called and how to use move constructors in place of copy constructor.

#include <iostream>

template<class T>
class Auto_ptr4
{
    T* m_ptr;
public:
    Auto_ptr4(T* ptr = nullptr)
    :m_ptr(ptr)
    {
    }

    ~Auto_ptr4()
    {
        delete m_ptr;
    }

    // Copy constructor
    // Do deep copy of a.m_ptr to m_ptr
    Auto_ptr4(const Auto_ptr4& a)
    {
        m_ptr = new T;
        *m_ptr = *a.m_ptr;
    }

    // Move constructor
    // Transfer ownership of a.m_mptr to m_ptr
    Auto_ptr4(Auto_ptr4&& a)
    : m_ptr(a.m_ptr)
    {
        a.m_ptr = nullptr;
    }

    // Copy assignment
    // Do deep copy of a.m_ptr to m_ptr
    Auto_ptr4& operator=(const Auto_ptr4& a)
    {
        // Self-assignment detection
        if (&a == this)
            return *this;

        // Release any resource we're holding
        delete m_ptr;

        // Copy the resource
        m_ptr = new T;
        *m_ptr = *a.m_ptr;

        return *this;
    }

    // Move assignment
    // Transfer ownership of a.m_ptr to m_ptr
    Auto_ptr4& operator=(Auto_ptr4&& a)
    {
        // Self-assignment detection
        if (&a == this)
            return *this;

        // Release any resource we're holding
        delete m_ptr;

        // Transfer ownership of a.m_ptr to m_ptr
        m_ptr = a.m_ptr;
        a.m_ptr = nullptr;

        return *this;
    }

    T& operator*() const { return *m_ptr; }
    T* operator->() const { return m_ptr; }
    bool isNull() const { return m_ptr == nullptr; }
};

class Resource
{
public:
    Resource() { std::cout << "Resource acquired\n"; }
    ~Resource() { std::cout << "Resource destroyed\n"; }
};

Auto_ptr4<Resource> generateResource()
{
    Auto_ptr4<Resource> res(new Resource);
    return res; // this return value will invoke the move constructor
}

int main()
{
    Auto_ptr4<Resource> mainres;
    mainres = generateResource(); // this assignment will invoke the move assignment

    return 0;
}

Thanks

Body:
Auto_ptr4<Resource> generateResource()
{
    Auto_ptr4<Resource> res(new Resource);
    return res; // this return value will invoke the move constructor
}

Your code is written in a way that very much allows for copy elision. The C++ standard has an entire section devoted to just this use case.

[class.copy.elision/1.1]

in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function parameter or a variable introduced by the exception-declaration of a handler ([except.handle])) with the same type (ignoring cv-qualification) as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function call's return object

If you want to prevent elision, you need to return an expression that cannot be elided legally. Fortunately it's rather easy in this case to also force a move constructor to be called:

Auto_ptr4<Resource> generateResource()
{
    Auto_ptr4<Resource> res(new Resource);
    return std::move(res); // this return value will invoke the move constructor
}

Since now the expression is not an automatic variable name, nor is Auto_ptr4<Resource>&& the same exactly as Auto_ptr4<Resource>. The c'tor isn't elided.

This is fine for learning purposes, but don't do it in real code. Copy elision is a very good thing that makes for more efficient code. Let the compiler do it for you when it can.


问:
UnknownHostException in Nifi GetHttp processor running inside VirtualBox (Hortonworks Sandbox)
I am trying to get data from the following URL:
http://webservices.nextbus.com/service/publicXMLFeed?command=vehicleLocations&a=sf-muni&r=M&t=0

I have configured Nifi (that is running on Oracle VirtualBox) GetHttp proccesor URL property to the aforementioned URL, however I am getting following exception:

```<code>Caused by: java.net.UnknownHostException: webservices.nextbus.com
  at java.net.InetAddress.getAllByName0(InetAddress.java:1280) ~[na:1.8.0_111]
  at java.net.InetAddress.getAllByName(InetAddress.java:1192) ~[na:1.8.0_111]
  at java.net.InetAddress.getAllByName(InetAddress.java:1126) ~[na:1.8.0_111]
</code>```

I have used following command on both VM and Host machine.

```<code>nslookup webservices.nextbus.com
</code>```

which outputs following on both VM and Host:

```<code>Non-authoritative answer:
Name:    4yu7q.x.incapdns.net
Address: 192.230.77.86
Aliases:  webservices.nextbus.com
</code>```

I am using Google DNS (inside /etc/resolv.conf I have following)

```<code>nameserver 8.8.8.8
</code>```

Pinging webservices.nextbus.com is also successful

```<code>ping webservices.nextbus.com

Pinging 4yu7q.x.incapdns.net [192.230.77.86] with 32 bytes of data:
Reply from 192.230.77.86: bytes=32 time=15ms TTL=56
Reply from 192.230.77.86: bytes=32 time=14ms TTL=56
</code>```

What could be the cause for the UnknownHostException and how to fix it?

答: DNS changes weren't picked up from resolv.conf file. Restarting NiFi fixed the issue. </p>

Body:
I am trying to get data from the following URL:
http://webservices.nextbus.com/service/publicXMLFeed?command=vehicleLocations&a=sf-muni&r=M&t=0

I have configured Nifi (that is running on Oracle VirtualBox) GetHttp proccesor URL property to the aforementioned URL, however I am getting following exception:

Caused by: java.net.UnknownHostException: webservices.nextbus.com
  at java.net.InetAddress.getAllByName0(InetAddress.java:1280) ~[na:1.8.0_111]
  at java.net.InetAddress.getAllByName(InetAddress.java:1192) ~[na:1.8.0_111]
  at java.net.InetAddress.getAllByName(InetAddress.java:1126) ~[na:1.8.0_111]

I have used following command on both VM and Host machine.

nslookup webservices.nextbus.com

which outputs following on both VM and Host:

Non-authoritative answer:
Name:    4yu7q.x.incapdns.net
Address: 192.230.77.86
Aliases:  webservices.nextbus.com

I am using Google DNS (inside /etc/resolv.conf I have following)

nameserver 8.8.8.8

Pinging webservices.nextbus.com is also successful

ping webservices.nextbus.com

Pinging 4yu7q.x.incapdns.net [192.230.77.86] with 32 bytes of data:
Reply from 192.230.77.86: bytes=32 time=15ms TTL=56
Reply from 192.230.77.86: bytes=32 time=14ms TTL=56

What could be the cause for the UnknownHostException and how to fix it?


问:
Jquery Cool Drag and Drop snap to position
Anyone know how you do that cool thing in JQuery where you can drag and drop divs and it snaps to position and saves location?</p>

答:
Have a look at DropThings.

This is an open source project available at Codeplex that could be a good source of information for your requirement


问:
Spring Batch :- Running Job in two stages
Here is the spring batch design for job recommending to my client:-

UI application will call Rest API on API server. Rest API creates a unique id , and send unique id, job params, job name as jms message to some batch server.  Rest API sends the unique token id to UI.

JMS message listener on batch server create a new spring batch job instance and set up unique id as job param and run the job.

UI keeps on polling the Status Rest API by passing the unique token.

Rest API finds from job param table for unique id, job execution id and provide the job status to UI.

Please advise, any suggestion so that we can create the job on API server, so that job instance and param created but does not execute any steps. We know the job execution id

On batch server with input job execution id, we can rerun/resume the job again.

答:
I think you could use a JobRequest-table to store the initial request with the initial unique token. You could pass this token to the JMS server along with the batch request. As soon as the JMS batch server creates/starts the request it should also update the JobRequest-table and insert the actual Batch-JobInstance-Id.

So clients can ask the status by using the unique token. Rest-API server can use that token to look up the job id and get information about the job progress


问:
I can not display the data from my json_encode ($.each)
Hello to every one and thank you for your time.
My problem is that i can not display the json_encode from my php database but in my chrome the data is appear.
The $.each is not dispaly all only one
enter image description here

now the code for the php :

comment.php

```<code>$data = $_REQUEST;
$photo_id =38;//$data['photo_id_comment'];
$con = mysqli_connect('localhost','root','','gallery');

$sql  = "SELECT * FROM comments";
$sql .= " WHERE photo_id = " . $database->escape_string($photo_id);
$sql .= " ORDER  BY photo_id ASC";

$result = mysqli_query( $con,$sql);

$arr = array();
$row_count = mysqli_num_rows($result);

while ($row = mysqli_fetch_array($result)) {
    array_push($arr , $row);
}

mysqli_close($con);
echo json_encode($arr);
</code>```

And the ajax to retrieve data is: script.js

```<code>function refreshComment() {

requestData = $("#photo_id_comment").serialize();
$.ajax({
    url: "http://localhost/udemy/app_php/includes/comment.php",
    type: "get",
    data: requestData,
    dataType: "text",
    success : function (data) {
        jQuery.each(data, function(index, item) {
            //now you can access properties using dot notation
            $('#chat_box').val( $('#chat_box').val() + item.body + '\n');
            /* $('#author_comment').html(item.author);
            $('#chat_box').html(item.body);*/
        });
    },
    error: function (http, status, error) {
        alert('Some error occurred :'+error);
    }
});

    return false;
}

setInterval( refreshComment , 5000 );
</code>```

And the html where the data is not display is: photo.php.

```<code> <div class="media">
                <a class="pull-left" href="#">
                    <img class="media-object" src="http://placehold.it/64x64" alt="">

                </a>
                <div class="media-body">
                    <h4 id="author_comment"  class="media-heading"></h4>
                    <p id="chat_box"></p>
                    <p class="text-info">This is post at: </p>
                </div>
            </div>
</code>```

答:
change dataType:text to dataType:JSON

EDIT

use this instead of $.each

```<code>for(var i = 0;i < data.length ; i++)
{
/*access data as data[i].orfeas*/
}
</code>```

PHP

```<code>  $array = array();
  $i = 0;`

 foreach($res as $r){
   $array[$i] = $r;
  $i++;
 }

header('Content-Type:Application/json');
echo json_encode($array);
</code>```

EDIT2

USE Header to help jQuery to identify the response type and then jQuery will parse the JSON and you can access it by using a loop above mentioned

Body:
Hello to every one and thank you for your time.
My problem is that i can not display the json_encode from my php database but in my chrome the data is appear.
The $.each is not dispaly all only one
enter image description here

now the code for the php :

comment.php

$data = $_REQUEST;
$photo_id =38;//$data['photo_id_comment'];
$con = mysqli_connect('localhost','root','','gallery');

$sql  = "SELECT * FROM comments";
$sql .= " WHERE photo_id = " . $database->escape_string($photo_id);
$sql .= " ORDER  BY photo_id ASC";

$result = mysqli_query( $con,$sql);

$arr = array();
$row_count = mysqli_num_rows($result);

while ($row = mysqli_fetch_array($result)) {
    array_push($arr , $row);
}

mysqli_close($con);
echo json_encode($arr);

And the ajax to retrieve data is: script.js

function refreshComment() {

requestData = $("#photo_id_comment").serialize();
$.ajax({
    url: "http://localhost/udemy/app_php/includes/comment.php",
    type: "get",
    data: requestData,
    dataType: "text",
    success : function (data) {
        jQuery.each(data, function(index, item) {
            //now you can access properties using dot notation
            $('#chat_box').val( $('#chat_box').val() + item.body + '\n');
            /* $('#author_comment').html(item.author);
            $('#chat_box').html(item.body);*/
        });
    },
    error: function (http, status, error) {
        alert('Some error occurred :'+error);
    }
});

    return false;
}

setInterval( refreshComment , 5000 );

And the html where the data is not display is: photo.php.

This is post at:

Body:
change dataType:text to dataType:JSON

EDIT

use this instead of $.each

for(var i = 0;i < data.length ; i++)
{
/*access data as data[i].orfeas*/
}

PHP

  $array = array();
  $i = 0;`

 foreach($res as $r){
   $array[$i] = $r;
  $i++;
 }

header('Content-Type:Application/json');
echo json_encode($array);

EDIT2

USE Header to help jQuery to identify the response type and then jQuery will parse the JSON and you can access it by using a loop above mentioned


问:
Eclipse 3.5 Unable to install plugins
I really don't know what's going on with Eclipse 3.5 (3.5.0 or 3.5.1, same issues), but it's been now 2 days that I'm struggling with Eclipse to find a way to make the plugins installation work via the "Install New Software screen"!!! I have visited a lot of forums and blogs, tried many solutions but in vain: each time the current problem disappears and a new one appears.

I'm trying to make it work at my office, so behind proxy. The best advice I got so far is the one regarding the known issue with NTLM proxies: http://wiki.eclipse.org/ECF_Filetransfer_Support_for_NTLMv2_Proxies. I put in place the hint, but now I have a new error message: Eclipse cannot find the repositories at all... For instance here is what I get now with the Galileo update site itself:

```<code>org.eclipse.equinox.internal.provisional.p2.core.ProvisionException: No repository found at http://download.eclipse.org/releases/galileo.
    at org.eclipse.equinox.internal.p2.repository.helpers.AbstractRepositoryManager.fail(AbstractRepositoryManager.java:380)
    at org.eclipse.equinox.internal.p2.repository.helpers.AbstractRepositoryManager.loadRepository(AbstractRepositoryManager.java:606)
    at org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager.loadRepository(MetadataRepositoryManager.java:92)
    at org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager.loadRepository(MetadataRepositoryManager.java:88)
    at org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil.loadMetadataRepository(ProvisioningUtil.java:88)
    at org.eclipse.equinox.internal.provisional.p2.ui.QueryableMetadataRepositoryManager.doLoadRepository(QueryableMetadataRepositoryManager.java:55)
    at org.eclipse.equinox.internal.provisional.p2.ui.QueryableRepositoryManager.loadRepository(QueryableRepositoryManager.java:195)
    at org.eclipse.equinox.internal.provisional.p2.ui.QueryableRepositoryManager.loadAll(QueryableRepositoryManager.java:108)
    at org.eclipse.equinox.internal.p2.ui.sdk.PreloadingRepositoryHandler$2.run(PreloadingRepositoryHandler.java:71)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)
</code>```

Samething with http://download.eclipse.org/eclipse/updates/3.5, or http://download.eclipse.org/tools/mylyn/update/e3.4/ and whatever the site: no one works.

Please somebody help!

PS: Some more details below:

I have the same issue with third party software too... for instance: http://www.epic-ide.org/updates/testing/site.xml.... same error message.

If I go to Preferences > Install / Updates > Available Software Sites, click on whatever the site and on Test Connection I get a ProvisionException with this error message (when I click on details):

Unable to read repository at http://download.eclipse.org/technology/epp/packages/galileo/site.xml.
  Unable to read repository at http://download.eclipse.org/technology/epp/packages/galileo/site.xml.
  Server redirected too many  times (20)

the solution is:
add following lines to your eclipse.ini file (before -vmargs):
(verified on 3.5 ; 3.5.1; 3.6.2)

```<code>-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient
-Dhttp.proxyPort=8080
-Dhttp.proxyHost=myproxy
-Dhttp.proxyUser=mydomain\myusername
-Dhttp.proxyPassword=mypassword
-Dhttp.nonProxyHosts=localhost|127.0.0.1
</code>```

答:
In my eclipse Luna  faced the same issue because of this URL https://sourceforge.net/projects/restfulplugin/files/site/

So i just Disabled  the URL that was Shown in the Error From the Available Software Sites.

You may Check the URL or Try with the Updated URL reg to that Exception :)

Title: Eclipse 3.5 Unable to install plugins

Body:
I really don't know what's going on with Eclipse 3.5 (3.5.0 or 3.5.1, same issues), but it's been now 2 days that I'm struggling with Eclipse to find a way to make the plugins installation work via the "Install New Software screen"!!! I have visited a lot of forums and blogs, tried many solutions but in vain: each time the current problem disappears and a new one appears.

I'm trying to make it work at my office, so behind proxy. The best advice I got so far is the one regarding the known issue with NTLM proxies: http://wiki.eclipse.org/ECF_Filetransfer_Support_for_NTLMv2_Proxies. I put in place the hint, but now I have a new error message: Eclipse cannot find the repositories at all... For instance here is what I get now with the Galileo update site itself:

org.eclipse.equinox.internal.provisional.p2.core.ProvisionException: No repository found at http://download.eclipse.org/releases/galileo.
    at org.eclipse.equinox.internal.p2.repository.helpers.AbstractRepositoryManager.fail(AbstractRepositoryManager.java:380)
    at org.eclipse.equinox.internal.p2.repository.helpers.AbstractRepositoryManager.loadRepository(AbstractRepositoryManager.java:606)
    at org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager.loadRepository(MetadataRepositoryManager.java:92)
    at org.eclipse.equinox.internal.p2.metadata.repository.MetadataRepositoryManager.loadRepository(MetadataRepositoryManager.java:88)
    at org.eclipse.equinox.internal.provisional.p2.ui.operations.ProvisioningUtil.loadMetadataRepository(ProvisioningUtil.java:88)
    at org.eclipse.equinox.internal.provisional.p2.ui.QueryableMetadataRepositoryManager.doLoadRepository(QueryableMetadataRepositoryManager.java:55)
    at org.eclipse.equinox.internal.provisional.p2.ui.QueryableRepositoryManager.loadRepository(QueryableRepositoryManager.java:195)
    at org.eclipse.equinox.internal.provisional.p2.ui.QueryableRepositoryManager.loadAll(QueryableRepositoryManager.java:108)
    at org.eclipse.equinox.internal.p2.ui.sdk.PreloadingRepositoryHandler$2.run(PreloadingRepositoryHandler.java:71)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)

Samething with http://download.eclipse.org/eclipse/updates/3.5, or http://download.eclipse.org/tools/mylyn/update/e3.4/ and whatever the site: no one works.

Please somebody help!

PS: Some more details below:

I have the same issue with third party software too... for instance: http://www.epic-ide.org/updates/testing/site.xml.... same error message.

If I go to Preferences > Install / Updates > Available Software Sites, click on whatever the site and on Test Connection I get a ProvisionException with this error message (when I click on details):

Unable to read repository at http://download.eclipse.org/technology/epp/packages/galileo/site.xml.
  Unable to read repository at http://download.eclipse.org/technology/epp/packages/galileo/site.xml.
  Server redirected too many  times (20)

the solution is:
add following lines to your eclipse.ini file (before -vmargs):
(verified on 3.5 ; 3.5.1; 3.6.2)

-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient
-Dhttp.proxyPort=8080
-Dhttp.proxyHost=myproxy
-Dhttp.proxyUser=mydomain\myusername
-Dhttp.proxyPassword=mypassword
-Dhttp.nonProxyHosts=localhost|127.0.0.1


问:
Function that check if value exists in sql server
Hei,

I need a function in php that checks if a value entered by form is already in database (sql - server -- PDO), and return TRUE or FALSE.

I tried to do this, but I got stuck and didn't found a solution on internet.
could you give me a hint on how to threat the above condition ?

```<code>function check_code($code) {
GLOBAL $handler;
$code = check_input($code);
        try{
      $query2 = $handler -> prepare("SELECT code from stock where code = :code");
      $query2 -> execute(array(
                    ':code' => $code
                    ));
return  >???<
        }
        catch(PDOException $e){
            echo $e -> getMessage();
      }  }
</code>```

答:
I've never work with sql-server before but I had worked with PDO many times, basically this is how would check in pdo

```<code><?php
function check_code($code)
{
    GLOBAL $handler;

    $code = check_input($code);
    try {
        $query2 = $handler->prepare("SELECT code from stock where code = :code");
        $query2->execute(array(':code' => $code));
        $results = $query2->fetchColumn();
        if (count($results) > 0) {
            echo "exists";
        } else {

            echo "does not exist";
        }
    }
    catch (PDOException $e) {
        echo $e->getMessage();
    }
}
?>
</code>```

NB: Avoid using the Global var... Stop using `global` in PHP

Body:
Hei,

I need a function in php that checks if a value entered by form is already in database (sql - server -- PDO), and return TRUE or FALSE.

I tried to do this, but I got stuck and didn't found a solution on internet.
could you give me a hint on how to threat the above condition ?

function check_code($code) {
GLOBAL $handler;
$code = check_input($code);
        try{
      $query2 = $handler -> prepare("SELECT code from stock where code = :code");
      $query2 -> execute(array(
                    ':code' => $code
                    ));
return  >???<
        }
        catch(PDOException $e){
            echo $e -> getMessage();
      }  }

Body:
I've never work with sql-server before but I had worked with PDO many times, basically this is how would check in pdo

<?php
function check_code($code)
{
    GLOBAL $handler;

    $code = check_input($code);
    try {
        $query2 = $handler->prepare("SELECT code from stock where code = :code");
        $query2->execute(array(':code' => $code));
        $results = $query2->fetchColumn();
        if (count($results) > 0) {
            echo "exists";
        } else {

            echo "does not exist";
        }
    }
    catch (PDOException $e) {
        echo $e->getMessage();
    }
}
?>

NB: Avoid using the Global var... Stop using `global` in PHP


问:
Socket.io wont emit events
I started to learning socket.io.
I begin the tutorial with the socket.io website example
I installed all things correctly but I think socket cant emit the event in the index.html
any one can help

here is my code
index.js

```<code>    var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(Socket){
    Socket.on('chat message', function(msg){
    consloe.log('hi');
    io.emit('chat message', msg);
  });
});

http.listen(port, function(){
  console.log('listening on *:' + port);
});
</code>```

index.html

```<code><!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
      #messages { margin-bottom: 40px }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
  $(function () {
    var socket = io();
    $('form').submit(function(){
      socket.emit('chat message', $('#m').val());
      $('#m').val('');
      console.log('sample');
      return false;
    });
    socket.on('chat message', function(msg){
        console.log('sample');
      $('#messages').append($('<li>').text(msg));
    });
  });
</script>
  </body>
</html>
</code>```

答:
You have mistyped console.log to consloe.log in Socket.on('chat message') on server. That's why it is crashing, and not emitting.

Also, use latest version of socket.io on server and browser.

https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js

Title: Socket.io wont emit events

Body:
I started to learning socket.io.
I begin the tutorial with the socket.io website example
I installed all things correctly but I think socket cant emit the event in the index.html
any one can help

here is my code
index.js

    var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(Socket){
    Socket.on('chat message', function(msg){
    consloe.log('hi');
    io.emit('chat message', msg);
  });
});

http.listen(port, function(){
  console.log('listening on *:' + port);
});

index.html

<!doctype html>

    <title>Socket.IO chat</title>

    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>


问:
How Do I Fail webpack2 on a TS Compile Error?
I have a webpack2 configuration that is working well, except for the fact that I do not want the build to continue if there is a TS compile error. Here is an example of a legitimate error that I am getting:

```<code>ERROR in ./ClientSide/app/panels/panel-side-bar/my-organizer/my-organizer.component.ts
(127,33): error TS2346: Supplied parameters do not match any signature of call target.
</code>```

This is a correct error, but I want webpack to not just continue. Currently, no matter what TS compile errors occur during the webpack compile, webpack still builds the bundle. I'd like to have webpack throw the error it is already emitting (in red), and stop the bundle process when this happens.

I tried adding the configuration switch in my webpack.config:

```<code>bail: true,
</code>```

But that did not resolve the issue.

If I am supposed to identify something in the loader for TS, how would I tell it to push the error to webpack2?  I tried the following TS loader options but they didn't have the effect of propagating the error to webpack:

```<code>module: {
    rules: [
        {
            test: /\.tsx?$/,
            use: ['ts-loader?' + JSON.stringify({transpileOnly: false, noEmitOnError: true})],
            exclude: [/node_modules/, /test/]
        },
</code>```

However, this did not work either.

It seems that there should be someway built into webpack or its loaders to properly propagate errors up to fail the process. Anyone have a solution that can allow me to configure for such failures to be bubbled up and still allow me to view the TS errors that are being produced (that way I can not only know the build failed, but the specific TS error that caused it).

I did some research and found people claiming that using (webpack-fail-plugin) should fix this problem, however, that was apparently meant for just webpack 1. Supposedly, webpack2 fixes this issue, as the plugin clearly claims https://www.npmjs.com/package/webpack-fail-plugin . However, this is not true, as my post here is confirming. And, in fact, the ts-loader itself claims that you will need to use the plugin for webpack 2 (see https://github.com/TypeStrong/ts-loader#failing-the-build-on-typescript-compilation-error ). To try every last possible solution, I imported the plugin to my project and tried using it as per the usage docs ( https://github.com/TiddoLangerak/webpack-fail-plugin#usage ). But, alas, it fails not the build.

I'm losing my mind trying to understand a solution for webpack 2.  Any one out there come to a reasonable answer on this?

答:
Just add a Plugin in your webpack config like this:

```<code>plugins: [function() {
    this.plugin("done", function(stats) {
        //Since webpack dependent Stats.js
        //Just see the API of Stats.js
        //You can do anything with the stats output
        if (stats && stats.hasErrors()) {
            stats.toJson().errors.forEach((err) => {
                console.error(err);
            });
            process.exit(1);
        }
    }
}]
</code>```

Test in Webpack 2.6.1 with ts-loader 2.2.2.

Hope this help:)

Body:
I have a webpack2 configuration that is working well, except for the fact that I do not want the build to continue if there is a TS compile error. Here is an example of a legitimate error that I am getting:

ERROR in ./ClientSide/app/panels/panel-side-bar/my-organizer/my-organizer.component.ts
(127,33): error TS2346: Supplied parameters do not match any signature of call target.

This is a correct error, but I want webpack to not just continue. Currently, no matter what TS compile errors occur during the webpack compile, webpack still builds the bundle. I'd like to have webpack throw the error it is already emitting (in red), and stop the bundle process when this happens.

I tried adding the configuration switch in my webpack.config:

bail: true,

But that did not resolve the issue.

If I am supposed to identify something in the loader for TS, how would I tell it to push the error to webpack2?  I tried the following TS loader options but they didn't have the effect of propagating the error to webpack:

module: {
    rules: [
        {
            test: /\.tsx?$/,
            use: ['ts-loader?' + JSON.stringify({transpileOnly: false, noEmitOnError: true})],
            exclude: [/node_modules/, /test/]
        },

However, this did not work either.

It seems that there should be someway built into webpack or its loaders to properly propagate errors up to fail the process. Anyone have a solution that can allow me to configure for such failures to be bubbled up and still allow me to view the TS errors that are being produced (that way I can not only know the build failed, but the specific TS error that caused it).

I did some research and found people claiming that using (webpack-fail-plugin) should fix this problem, however, that was apparently meant for just webpack 1. Supposedly, webpack2 fixes this issue, as the plugin clearly claims https://www.npmjs.com/package/webpack-fail-plugin . However, this is not true, as my post here is confirming. And, in fact, the ts-loader itself claims that you will need to use the plugin for webpack 2 (see https://github.com/TypeStrong/ts-loader#failing-the-build-on-typescript-compilation-error ). To try every last possible solution, I imported the plugin to my project and tried using it as per the usage docs ( https://github.com/TiddoLangerak/webpack-fail-plugin#usage ). But, alas, it fails not the build.

I'm losing my mind trying to understand a solution for webpack 2.  Any one out there come to a reasonable answer on this?

Body:
Just add a Plugin in your webpack config like this:

plugins: [function() {
    this.plugin("done", function(stats) {
        //Since webpack dependent Stats.js
        //Just see the API of Stats.js
        //You can do anything with the stats output
        if (stats && stats.hasErrors()) {
            stats.toJson().errors.forEach((err) => {
                console.error(err);
            });
            process.exit(1);
        }
    }
}]

Test in Webpack 2.6.1 with ts-loader 2.2.2.

Hope this help:)