答:
Okay, first, there are some syntax errors in your TextGame.js file that causes the entire file to not load properly. Remove this part first in your code which is causing the syntax error:

```<code>document.getElementById('submit').addEventListener(onclick, choices);

function choices {
var choice = ['north', 'west', 'south', 'east', 'North', 'South', 'East', 'West', 'Hint', 'hint',
             'Help', 'help'];

var northExists = choice.indexOf('north', 'North') > -1;
if (northExists){
    document.getElementById(myFunction01);
}

var southExists = choice.indexOf('south', 'South') > -1;
else if (southExists){
    document.getElementById(myFunction04);
}

var westExists = choice.indexOf('West', 'west') > -1;
else if (westExists){
    document.getElementById(myFunction02);
}

var eastExists = choice.indexOf('East', 'east') > -1;
else if (eastExists){
    document.getElementById(myFunction03);
}

var helpExists = choice.indexOf('Help', 'help') > -1;
else if (helpExists){
    document.getElementById("help").innerHTML = "You must move around to find the cat somewhere in the world.";
}

var hintExists = choice.indexOf('Hint', 'hint') > -1;
else if (hintExists){
    document.getElementById("hint").innerHTML = "The cat is somewhere on the map.";
}

var none = choice.indexOf('north', 'west', 'south', 'east', 'North', 'South', 'East', 'West', 'Hint', 'hint','Help', 'help') < -1;
else if (none){
    document.getElementById("none").innerHTML = "Command invalid! Type in a valid command!";
}
}
</code>```

Next, You have to add an onclick event to the button, and then call the appropriate function depending on what the user entered in the text box.

First, add the onclick event which tells JavaScript which function to call when the button is clicked:

```<code><input id="submit" type="button" onclick="processInput" value="submit command">
</code>```

Then, in the processInput() function, get the value entered into the textbox, and then call the appropriate function to perform.

```<code>function processInput() {
    var command = document.getElementById("choice").value;
    if (command == "north") {
        // call the appropriate function
        myFunction01();
    }
    else if (command == "south") {
        // call the appropriate function
        myFunction04();
    }
    else if (command == "west") {
        // call the appropriate function
        myFunction02();
    }
    else if (command == "east") {
        // call the appropriate function
        myFunction03();
    }
}
</code>```

Here is the entire updated TextGame.js:

```<code>var north=0;
var south=0;
var west=0;
var east=0;
var position = "Central Room";
var worldsize=10;

function processInput() {
    var command = document.getElementById("choice").value;
    if (command == "north") {
        // call the appropriate function
        myFunction01();
    }
    else if (command == "south") {
        // call the appropriate function
        myFunction04();
    }
    else if (command == "west") {
        // call the appropriate function
        myFunction02();
    }
    else if (command == "east") {
        // call the appropriate function
        myFunction03();
    }
}

function myFunction01() {
if (north > worldsize){
return;
}
if (south < 1) {
        north = north + 1;
}else {
        south = south - 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "<br>" + "Location: " + position;
}

function myFunction02() {
if (west > worldsize){
return;
}
if (east < 1) {
        west = west + 1;
}else{
        east = east - 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "<br>" + "Location: " + position;
}

function myFunction03() {

if (east > worldsize){
return;
}
if (west < 1) {
        east = east + 1;
}else{
        west = west - 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "<br>" + "Location: " + position;
}

function myFunction04() {
if (south > worldsize){
return;
}
if (north > 0) {
        north = north - 1;
}else{
south = south + 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "<br>" + "Location: " + position;
}

function myposition() {
var image = document.getElementById('myImage');
if (north == 7 && east == 4){
position = "Cat Freak Out!";
image.src = "https://s-media-cache-ak0.pinimg.com/736x/32/ba/19/32ba192e9eb99068a91fd2e8a1e21189.jpg";
}

else{
position = "lost";
image.src = "http://www.noonco.com/rc/java_art/picture_field.jpg";
}
}
</code>```

Title: How to convert buttons to a text box and button (Javascript)

Body:
Okay, first, there are some syntax errors in your TextGame.js file that causes the entire file to not load properly. Remove this part first in your code which is causing the syntax error:

document.getElementById('submit').addEventListener(onclick, choices);

function choices {
var choice = ['north', 'west', 'south', 'east', 'North', 'South', 'East', 'West', 'Hint', 'hint',
             'Help', 'help'];

var northExists = choice.indexOf('north', 'North') > -1;
if (northExists){
    document.getElementById(myFunction01);
}

var southExists = choice.indexOf('south', 'South') > -1;
else if (southExists){
    document.getElementById(myFunction04);
}

var westExists = choice.indexOf('West', 'west') > -1;
else if (westExists){
    document.getElementById(myFunction02);
}

var eastExists = choice.indexOf('East', 'east') > -1;
else if (eastExists){
    document.getElementById(myFunction03);
}

var helpExists = choice.indexOf('Help', 'help') > -1;
else if (helpExists){
    document.getElementById("help").innerHTML = "You must move around to find the cat somewhere in the world.";
}

var hintExists = choice.indexOf('Hint', 'hint') > -1;
else if (hintExists){
    document.getElementById("hint").innerHTML = "The cat is somewhere on the map.";
}

var none = choice.indexOf('north', 'west', 'south', 'east', 'North', 'South', 'East', 'West', 'Hint', 'hint','Help', 'help') < -1;
else if (none){
    document.getElementById("none").innerHTML = "Command invalid! Type in a valid command!";
}
}

Next, You have to add an onclick event to the button, and then call the appropriate function depending on what the user entered in the text box.

First, add the onclick event which tells JavaScript which function to call when the button is clicked:

<input id="submit" type="button" onclick="processInput" value="submit command">

Then, in the processInput() function, get the value entered into the textbox, and then call the appropriate function to perform.

function processInput() {
    var command = document.getElementById("choice").value;
    if (command == "north") {
        // call the appropriate function
        myFunction01();
    }
    else if (command == "south") {
        // call the appropriate function
        myFunction04();
    }
    else if (command == "west") {
        // call the appropriate function
        myFunction02();
    }
    else if (command == "east") {
        // call the appropriate function
        myFunction03();
    }
}

Here is the entire updated TextGame.js:

var north=0;
var south=0;
var west=0;
var east=0;
var position = "Central Room";
var worldsize=10;

function processInput() {
    var command = document.getElementById("choice").value;
    if (command == "north") {
        // call the appropriate function
        myFunction01();
    }
    else if (command == "south") {
        // call the appropriate function
        myFunction04();
    }
    else if (command == "west") {
        // call the appropriate function
        myFunction02();
    }
    else if (command == "east") {
        // call the appropriate function
        myFunction03();
    }
}

function myFunction01() {
if (north > worldsize){
return;
}
if (south < 1) {
        north = north + 1;
}else {
        south = south - 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "<br>" + "Location: " + position;
}

function myFunction02() {
if (west > worldsize){
return;
}
if (east < 1) {
        west = west + 1;
}else{
        east = east - 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "<br>" + "Location: " + position;
}

function myFunction03() {

if (east > worldsize){
return;
}
if (west < 1) {
        east = east + 1;
}else{
        west = west - 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "<br>" + "Location: " + position;
}

function myFunction04() {
if (south > worldsize){
return;
}
if (north > 0) {
        north = north - 1;
}else{
south = south + 1;
}
myposition();
        document.getElementById("demo").innerHTML =
        "North: " + north +"   South: " + south+"   East: " + east + "   West: " + west + "<br>" + "Location: " + position;
}

function myposition() {
var image = document.getElementById('myImage');
if (north == 7 && east == 4){
position = "Cat Freak Out!";
image.src = "https://s-media-cache-ak0.pinimg.com/736x/32/ba/19/32ba192e9eb99068a91fd2e8a1e21189.jpg";
}

else{
position = "lost";
image.src = "http://www.noonco.com/rc/java_art/picture_field.jpg";
}
}


来源: stackexchange

问:
bootstrap 3 show label and btn inline
The code below shows label and button in vertical, I want to show inline. It's necessary and important the first div.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Productos

    <button class="btn btn-success" type="button">Sleccione

                            </button>

HTML

CSS

Java

```

答:
Change col-md-2 To col-md-4.If you dont change col-md-2,when resize browser, Elements will be vertically again.

And

Add This Code to Css:

```<code>.dropdown {
   display: inline-block;
}
h3 {
   display: inline-block;
}
</code>```

Full Code :

.dropdown {
   display: inline-block;
}
h3{
   display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class=" col-sm-9 col-sm-offset-3 col-md-4 col-md-offset-2 main">
  <h3><span class = "label label-success">Productos</span></h3>
    <div class="dropdown">
      <button class="btn btn-success" type="button">Sleccione
        <span class="caret"></span>
      </button>
      <ul class="dropdown-menu">
        <li>HTML</li>
        <li>CSS</li>
        <li>Java</li>
        </ul>
    </div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Title: bootstrap 3 show label and btn inline

Body:
Change col-md-2 To col-md-4.If you dont change col-md-2,when resize browser, Elements will be vertically again.

And

Add This Code to Css:

.dropdown {
   display: inline-block;
}
h3 {
   display: inline-block;
}

Full Code :

.dropdown {
   display: inline-block;
}
h3{
   display: inline-block;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class=" col-sm-9 col-sm-offset-3 col-md-4 col-md-offset-2 main">
  <h3><span class = "label label-success">Productos</span></h3>
    <div class="dropdown">
      <button class="btn btn-success" type="button">Sleccione
        <span class="caret"></span>
      </button>
      <ul class="dropdown-menu">
        <li><a href="#">HTML</a></li>
        <li><a href="#">CSS</a></li>
        <li><a href="#">Java</a></li>
        </ul>
    </div>
</div>


问:
Unauthorized Exception when trying to register Xamarin App with Azure Notification Hub
We are trying to use Azure Notification Hub to deliver push notifications via GCM / Firebase to a Xamarin Forms application.

This is the code we use to create the MobileServiceClient object in the PCL:

```<code>public App()
{
    mobileServiceClient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient("https://namespace.servicebus.windows.net/NotificationHubName", new ModernHttpClient.NativeMessageHandler());
}
</code>```

As far as I understood the documentation, it shouldn't matter that we are not using a custom HTTP handler as we don't need to supply any additional headers or anything like that. We just want the notifications, we don't require Azure to provide authentication at this point (we use Azure Active Directory B2C for that). I might be wrong though, as missing authentication headers could obviously cause an Unauthorized exception.

This is the code we use to try to register our application with Azure Notification Hub:

```<code>public async void Register(Microsoft.WindowsAzure.MobileServices.Push push, IEnumerable<string> tags)
{
    try
    {
        const string templateBodyGCM = "{\"data\":{\"message\":\"$(messageParam)\"}}";

        JObject templates = new JObject();
        templates["genericMessage"] = new JObject
        {
            {"body", templateBodyGCM}
        };

        await push.RegisterAsync(RegistrationID, templates);
        Log.Info("Push Installation Id", push.InstallationId.ToString());
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex.Message);
        Debugger.Break();
    }
}
</code>```

Unfortunately, an exception is thrown in await push.RegisterAsync(RegistrationID, templates):

```<code>{Microsoft.WindowsAzure.MobileServices.MobileServiceInvalidOperationException: The request could not be completed.  (Unauthorized)
</code>```

We successfully receive a Registration ID from GCM and get the exception when trying to register our application with Azure to receive the push notifications.

Unfortunately, most examples concerning the Notification Hub use older code that doesn't require the second parameter in the MobileServiceClient constructor. The code is based on this repository: https://github.com/xamarin/xamarin-forms-samples/tree/master/WebServices/TodoAzurePush

Thanks in advance for any help!

Edit: Date/Time synchronization is turned on on the testing device. This appearently caused similar issued for other developers, but doesn't seem to be the issue here.

答:
mobileServiceClient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient("https://namespace.servicebus.windows.net/NotificationHubName", new ModernHttpClient.NativeMessageHandler());

According to your description and error, I found you have pass the wrong url parameter to the MobileServiceClient object.

The Microsoft.WindowsAzure.MobileServices.MobileServiceClient's url is your mobile app's url not the notification hub url.

Like below:

```<code>mobileServiceClient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient("http://yourmobileappname.azurewebsites.net", new ModernHttpClient.NativeMessageHandler());
</code>```

After you have set the connection to the notification hub in the mobile service portal, the azure mobile SDK will automatic could get the push object according to the right MobileServiceClient.

I suggest you could also check you have already connected to the notification hub in your mobile app as below:

Body:
We are trying to use Azure Notification Hub to deliver push notifications via GCM / Firebase to a Xamarin Forms application.

This is the code we use to create the MobileServiceClient object in the PCL:

public App()
{
    mobileServiceClient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient("https://namespace.servicebus.windows.net/NotificationHubName", new ModernHttpClient.NativeMessageHandler());
}

As far as I understood the documentation, it shouldn't matter that we are not using a custom HTTP handler as we don't need to supply any additional headers or anything like that. We just want the notifications, we don't require Azure to provide authentication at this point (we use Azure Active Directory B2C for that). I might be wrong though, as missing authentication headers could obviously cause an Unauthorized exception.

This is the code we use to try to register our application with Azure Notification Hub:

public async void Register(Microsoft.WindowsAzure.MobileServices.Push push, IEnumerable<string> tags)
{
    try
    {
        const string templateBodyGCM = "{\"data\":{\"message\":\"$(messageParam)\"}}";

        JObject templates = new JObject();
        templates["genericMessage"] = new JObject
        {
            {"body", templateBodyGCM}
        };

        await push.RegisterAsync(RegistrationID, templates);
        Log.Info("Push Installation Id", push.InstallationId.ToString());
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex.Message);
        Debugger.Break();
    }
}

Unfortunately, an exception is thrown in await push.RegisterAsync(RegistrationID, templates):

{Microsoft.WindowsAzure.MobileServices.MobileServiceInvalidOperationException: The request could not be completed.  (Unauthorized)

We successfully receive a Registration ID from GCM and get the exception when trying to register our application with Azure to receive the push notifications.

Unfortunately, most examples concerning the Notification Hub use older code that doesn't require the second parameter in the MobileServiceClient constructor. The code is based on this repository: https://github.com/xamarin/xamarin-forms-samples/tree/master/WebServices/TodoAzurePush

Thanks in advance for any help!

Edit: Date/Time synchronization is turned on on the testing device. This appearently caused similar issued for other developers, but doesn't seem to be the issue here.

Body:
mobileServiceClient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient("https://namespace.servicebus.windows.net/NotificationHubName", new ModernHttpClient.NativeMessageHandler());

According to your description and error, I found you have pass the wrong url parameter to the MobileServiceClient object.

The Microsoft.WindowsAzure.MobileServices.MobileServiceClient's url is your mobile app's url not the notification hub url.

Like below:

mobileServiceClient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient("http://yourmobileappname.azurewebsites.net", new ModernHttpClient.NativeMessageHandler());

After you have set the connection to the notification hub in the mobile service portal, the azure mobile SDK will automatic could get the push object according to the right MobileServiceClient.

I suggest you could also check you have already connected to the notification hub in your mobile app as below:


问:
Which .NET Memcached client do you use, EnyimMemcached vs. BeITMemcached?
Seems like both EnyimMemcached (https://github.com/enyim/EnyimMemcached) and BeITMemcached (http://code.google.com/p/beitmemcached/) are popular .NET Memcached libraries. Both are reasonably active projects under development and have over a thousand downloads. Trying to figure out which one to use but found competing remarks!  I did read another related post but still want to ask more people on this before making a decision.

EnyimMemcached claims on its project homepage (https://github.com/enyim/EnyimMemcached), that

based on our non-disclosed specially handcrafted in-house performance test we're the fastest C# client ever, using negative amount of system resources, be it memory or CPU time

and

we follow memcached's protocol specification as strictly as no one else: even the memcached guys ask us if they don't understand something

While BeITMemcached claims on its project wiki page (http://code.google.com/p/beitmemcached/wiki/Features) that

We have performed extensive functional testing and performance testing of the BeIT Memcached client and we are satisifed that it is working as it should. When we compared the performance against two other clients, the java port and the Enyim memcached client, our client consumed the least resources and had the best performance. It is also following the memcached protocol specifications more strictly, has the most memcached features, and is still much smaller in actual code size.

So for those who have experience on these or anything similar, which client did you choose to use and possibly why you chose the one you chose?

Thank you,

Ray.

答:
Eniym client's Store() sometimes does not work correctly. It happens when key does not present in cache, for most cases after memcached service restart. This construction:

```<code>        T val = _client.Get<T>(key);
        if (val == null)
        {
            // ... filling val variable ...
            var result = _client.Store(StoreMode.Add, key, val);
            // ... result can be false, sometimes ...
        }
</code>```

works 50/50. T entity is [Serializable].

Body:
Eniym client's Store() sometimes does not work correctly. It happens when key does not present in cache, for most cases after memcached service restart. This construction:

        T val = _client.Get<T>(key);
        if (val == null)
        {
            // ... filling val variable ...
            var result = _client.Store(StoreMode.Add, key, val);
            // ... result can be false, sometimes ...
        }

works 50/50. T entity is [Serializable].

ContentLicense: CC BY-SA 2.5


问:
Hiding flash message after some seconds in codeigniter php
Hi i have tried with some script hiding the flash message once it is shown but it is not working.Displaying the flash message until i refresh the page.

Controller:

```<code>if ($this->email->send())
        {
           $this->session->set_flashdata('msg','<div class="alert alert-success text-center" id="successMessage">Thank you for contacting us we will get back to you soon!</div>');
            redirect('contact');
        }
        else
        {
            $this->session->set_flashdata('msg','<div class="alert alert-danger text-center">There is error in sending mail! Please try again later</div>');
            redirect('contact');
        }
</code>```

View:

```<code><script>
$(function() {
// setTimeout() function will be fired after page is loaded
// it will wait for 5 sec. and then will fire
// $("#successMessage").hide() function
setTimeout(function() {
    $(".alert-success").hide('blind', {}, 500)
}, 5000);
});
</script>
<div class="container">

<div class="row contactpageback">

        <div class="col-lg-6 contactuspagedetails">
            <form name="contact"  id="contactform" enctype="multipart/form-data" method="post" action="<?php echo base_url();?>contact">
            <?php echo  $this->session->flashdata('msg');?>
            <?php if(isset($msg)){?>
             <?php echo $msg;?>
               <?php } ?>
</code>```

答:
Controller:

```<code>$this->load->library('session');
 if ($this->email->send())
        {
           $this->flash->success('Thank you for contacting us we will get back to you soon!</div>');
            redirect('contact');
        }
        else
        {
            $this->flash->success('There is error in sending mail! Please try again later');
            redirect('contact');
        }
</code>```

View:

```<code><div id="mydivs">
        <?php    echo $this->flash->display('success', TRUE);?>
    </div>
    <script>
        setTimeout(function() {
            $('#mydivs').hide('fast');
        }, 10000);
    </script>
</code>```

Body:
Hi i have tried with some script hiding the flash message once it is shown but it is not working.Displaying the flash message until i refresh the page.

Controller:

if ($this->email->send())
        {
           $this->session->set_flashdata('msg','
Thank you for contacting us we will get back to you soon!
');
            redirect('contact');
        }
        else
        {
            $this->session->set_flashdata('msg','
There is error in sending mail! Please try again later
');
            redirect('contact');
        }

View:

            <form name="contact"  id="contactform" enctype="multipart/form-data" method="post" action="<?php echo base_url();?>contact">
            <?php echo  $this->session->flashdata('msg');?>
            <?php if(isset($msg)){?>
             <?php echo $msg;?>
               <?php } ?>

Body:
Controller:

$this->load->library('session');
 if ($this->email->send())
        {
           $this->flash->success('Thank you for contacting us we will get back to you soon!</div>');
            redirect('contact');
        }
        else
        {
            $this->flash->success('There is error in sending mail! Please try again later');
            redirect('contact');
        }

View:

<div id="mydivs">
        <?php    echo $this->flash->display('success', TRUE);?>
    </div>
    <script>
        setTimeout(function() {
            $('#mydivs').hide('fast');
        }, 10000);
    </script>


问:
Merging two multi-dimensional arrays using key and adding values
I want to merge two array's using key(product_id) and adding that values(usage).
Array 1

```
Array
(
    [0] => Array
        (
            [name] => Reschedule A Service
            [usage] => 1
            [product_id] => 8
        )

    [1] => Array
        (
            [name] => Adding An Image
            [usage] => 1
            [product_id] => 5
        )

    [2] => Array
        (
            [name] => Each Calendar Event
            [usage] => 1
            [product_id] => 14
        )

)
```

Array 2

```
Array
(
    [0] => Array
        (
            [name] => Adding An Image
            [usage] => 1
            [product_id] => 5
        )

    [1] => Array
        (
            [name] => Schedule A Service
            [usage] => 3
            [product_id] => 11
        )

    [2] => Array
        (
            [name] => Each Calendar Event
            [usage] => 2
            [product_id] => 14
        )

    [3] => Array
        (
            [name] => Sales Performance Dashboard
            [usage] => 2
            [product_id] => 30
        )

    [4] => Array
        (
            [name] => Quote
            [usage] => 1
            [product_id] => 32
        )

)
```

I need an out put like this merging and adding usage values.

```
Array
(
    [0] => Array
        (
            [name] => Adding An Image
            [usage] => 2
            [product_id] => 5
        )

    [1] => Array
        (
            [name] => Schedule A Service
            [usage] => 3
            [product_id] => 11
        )

    [2] => Array
        (
            [name] => Each Calendar Event
            [usage] => 3
            [product_id] => 14
        )

    [3] => Array
        (
            [name] => Sales Performance Dashboard
            [usage] => 2
            [product_id] => 30
        )

    [4] => Array
        (
            [name] => Quote
            [usage] => 1
            [product_id] => 32
        )

    [5] => Array
        (
            [name] => Reschedule A Service
            [usage] => 1
            [product_id] => 8
        )

)
```

This is my code for creating arrays

```

    foreach($query->rows as $product){

     $top_products[]=array(
        'name'=>$product['name'],
        'usage'=>$product['pusage'],
        'product_id'=>$product['product_id']
     );

    }

```

```

    foreach($query_2->rows as $product){

         $top_point_products[]=array(
           'name'=>$product['name'],
           'usage'=>$product['p_usage'],
           'product_id'=>$product['product_id']
         );

    }

```

答:
```
$first =array(

    array(
        "name" => "Reschedule A Service",
        "usage" => 1,
        "product_id" => 8
    ),
    array(
        "name" => "Adding An Image",
        "usage" => 1,
        "product_id" => 5
    ),
    array(
        "name" => "Each Calendar Event",
        "usage" => 1,
        "product_id" => 14
    )
    );
$second =array(

    array(
        "name" => "Adding An Image",
        "usage" => 1,
        "product_id" => 5
    ),
    array(
        "name" => "Schedule A Service",
        "usage" => 3,
        "product_id" => 11
    ),
    array(
        "name" => "Each Calendar Event",
        "usage" => 2,
        "product_id" => 14
    ),
    array(
        "name" => "Sales Performance Dashboard",
        "usage" => 2,
        "product_id" => 30
    ),
    array(
        "name" => "Quote",
        "usage" => 1,
        "product_id" => 32
    )
);

$result = array_unique(array_merge($first,$second), SORT_REGULAR);
```

Use array_unique & array_merge

Body:
I want to merge two array's using key(product_id) and adding that values(usage).
Array 1

Array
(
    [0] => Array
        (
            [name] => Reschedule A Service
            [usage] => 1
            [product_id] => 8
        )

    [1] => Array
        (
            [name] => Adding An Image
            [usage] => 1
            [product_id] => 5
        )

    [2] => Array
        (
            [name] => Each Calendar Event
            [usage] => 1
            [product_id] => 14
        )

)

Array 2

Array
(
    [0] => Array
        (
            [name] => Adding An Image
            [usage] => 1
            [product_id] => 5
        )

    [1] => Array
        (
            [name] => Schedule A Service
            [usage] => 3
            [product_id] => 11
        )

    [2] => Array
        (
            [name] => Each Calendar Event
            [usage] => 2
            [product_id] => 14
        )

    [3] => Array
        (
            [name] => Sales Performance Dashboard
            [usage] => 2
            [product_id] => 30
        )

    [4] => Array
        (
            [name] => Quote
            [usage] => 1
            [product_id] => 32
        )

)

I need an out put like this merging and adding usage values.

Array
(
    [0] => Array
        (
            [name] => Adding An Image
            [usage] => 2
            [product_id] => 5
        )

    [1] => Array
        (
            [name] => Schedule A Service
            [usage] => 3
            [product_id] => 11
        )

    [2] => Array
        (
            [name] => Each Calendar Event
            [usage] => 3
            [product_id] => 14
        )

    [3] => Array
        (
            [name] => Sales Performance Dashboard
            [usage] => 2
            [product_id] => 30
        )

    [4] => Array
        (
            [name] => Quote
            [usage] => 1
            [product_id] => 32
        )

    [5] => Array
        (
            [name] => Reschedule A Service
            [usage] => 1
            [product_id] => 8
        )

)

This is my code for creating arrays

    foreach($query->rows as $product){

     $top_products[]=array(
        'name'=>$product['name'],
        'usage'=>$product['pusage'],
        'product_id'=>$product['product_id']
     );

    }

    foreach($query_2->rows as $product){

         $top_point_products[]=array(
           'name'=>$product['name'],
           'usage'=>$product['p_usage'],
           'product_id'=>$product['product_id']
         );

    }

Body:
$first =array(

    array(
        "name" => "Reschedule A Service",
        "usage" => 1,
        "product_id" => 8
    ),
    array(
        "name" => "Adding An Image",
        "usage" => 1,
        "product_id" => 5
    ),
    array(
        "name" => "Each Calendar Event",
        "usage" => 1,
        "product_id" => 14
    )
    );
$second =array(

    array(
        "name" => "Adding An Image",
        "usage" => 1,
        "product_id" => 5
    ),
    array(
        "name" => "Schedule A Service",
        "usage" => 3,
        "product_id" => 11
    ),
    array(
        "name" => "Each Calendar Event",
        "usage" => 2,
        "product_id" => 14
    ),
    array(
        "name" => "Sales Performance Dashboard",
        "usage" => 2,
        "product_id" => 30
    ),
    array(
        "name" => "Quote",
        "usage" => 1,
        "product_id" => 32
    )
);

$result = array_unique(array_merge($first,$second), SORT_REGULAR);

Use array_unique & array_merge


问:
C# How to combine 2 list in different row count then implement in Form of DataGridView Controller?
I have 2 list list1, list2,

```<code>class classList
{
    public string p1{ get; set; }
    public string p2 { get; set; }
    public string p3 { get; set; }
    public string p4 { get; set; }
}

List<classList> list1= new List<classList>();
List<classList> list2= new List<classList>();

        p1  p2  p3  p4
list1 =  1   2   3   4
         5   6   7   8

        p1   p2   p3   p4
list2 = 10   12   13   14
        15   16   17   18
        19   20   21   22
</code>```

now I would like joint 2 list to datagridview just like this

How can I do that?
Thanks!

答:
You should create a type that can hold a combined data item for a full row. For example:

```<code>class CombinedItem
{
    public string p1 { get; set; }
    public string p2 { get; set; }
    public string p3 { get; set; }
    public string p4 { get; set; }

    public string q1 { get; set; }
    public string q2 { get; set; }
    public string q3 { get; set; }
    public string q4 { get; set; }
}
</code>```

Then merge your source lists. I use Enumerable.Repeat and Concat to bring the lists to same size and then Zip and the null-conditional operator to create the result:

```<code>List<classList> list1 = new List<classList>();
List<classList> list2 = new List<classList>();

IEnumerable<classList> enumerable1 = list1;
IEnumerable<classList> enumerable2 = list2;
if (list1.Count < list2.Count)
{
    enumerable1 = enumerable1.Concat(Enumerable.Repeat(default(classList), list2.Count - list1.Count));
}
else if (list2.Count < list1.Count)
{
    enumerable2 = enumerable2.Concat(Enumerable.Repeat(default(classList), list1.Count - list2.Count));
}
var resultItems = enumerable1.Zip(enumerable2, (e1, e2) => new CombinedItem
    {
        p1 = e1?.p1,
        p2 = e1?.p2,
        p3 = e1?.p3,
        p4 = e1?.p4,
        q1 = e2?.p1,
        q2 = e2?.p2,
        q3 = e2?.p3,
        q4 = e2?.p4,
    }).ToList();
</code>```

Edit:

You can try DisplayNameAttribute in order to make the q1, q2, q3, q4 columns appear as p1, p2, p3, p4 like:

```<code>[DisplayName("p1")]
public string q1 { get; set; }
</code>```

But you have to test if your DataGridView is actually using this attribute and whether duplicate display names are accepted.

Body:
I have 2 list list1, list2,

class classList
{
    public string p1{ get; set; }
    public string p2 { get; set; }
    public string p3 { get; set; }
    public string p4 { get; set; }
}

List<classList> list1= new List<classList>();
List<classList> list2= new List<classList>();

        p1  p2  p3  p4
list1 =  1   2   3   4
         5   6   7   8

        p1   p2   p3   p4
list2 = 10   12   13   14
        15   16   17   18
        19   20   21   22

now I would like joint 2 list to datagridview just like this

How can I do that?
Thanks!

Body:
You should create a type that can hold a combined data item for a full row. For example:

class CombinedItem
{
    public string p1 { get; set; }
    public string p2 { get; set; }
    public string p3 { get; set; }
    public string p4 { get; set; }

    public string q1 { get; set; }
    public string q2 { get; set; }
    public string q3 { get; set; }
    public string q4 { get; set; }
}

Then merge your source lists. I use Enumerable.Repeat and Concat to bring the lists to same size and then Zip and the null-conditional operator to create the result:

List<classList> list1 = new List<classList>();
List<classList> list2 = new List<classList>();

IEnumerable<classList> enumerable1 = list1;
IEnumerable<classList> enumerable2 = list2;
if (list1.Count < list2.Count)
{
    enumerable1 = enumerable1.Concat(Enumerable.Repeat(default(classList), list2.Count - list1.Count));
}
else if (list2.Count < list1.Count)
{
    enumerable2 = enumerable2.Concat(Enumerable.Repeat(default(classList), list1.Count - list2.Count));
}
var resultItems = enumerable1.Zip(enumerable2, (e1, e2) => new CombinedItem
    {
        p1 = e1?.p1,
        p2 = e1?.p2,
        p3 = e1?.p3,
        p4 = e1?.p4,
        q1 = e2?.p1,
        q2 = e2?.p2,
        q3 = e2?.p3,
        q4 = e2?.p4,
    }).ToList();

Edit:

You can try DisplayNameAttribute in order to make the q1, q2, q3, q4 columns appear as p1, p2, p3, p4 like:

[DisplayName("p1")]
public string q1 { get; set; }

But you have to test if your DataGridView is actually using this attribute and whether duplicate display names are accepted.


问:
No plot displayed with plotly in shiny
when I'm pasting the code from https://plot.ly/r/shinyapp-plotly-events/ into my console no plotly graph is diplayed, I can't get any plot in shiny displayed with plotly.

My sessionInfo:

```<code>R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

locale:
[1] LC_COLLATE=German_Germany.1252  LC_CTYPE=German_Germany.1252    LC_MONETARY=German_Germany.1252 LC_NUMERIC=C                    LC_TIME=German_Germany.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] plotly_4.7.0       ggplot2_2.2.1.9000 feather_0.3.1      RODBC_1.3-15       dplyr_0.5.0        shiny_1.0.3
</code>```

Am I using the wrong package versions? I reinstalled everything from cran but i never see a plotly graph with shiny.
I can produce the plotly graph's inside RStudio in the Viewer. Do I have to use any of the devtools versions of plotly/ggplot/shiny or all devtool versions? I tried plotly_4.7.0.9000 but still no output is shown.

I found a post plotly graph doesn't show up that renderPlotly({return(plot_ly(x))}) is broken, but even with renderPlotly(data) I can't produce any frames in shiny.

Example Code from the plotly gallery, the error should be in my setup I suppose, as a mater of form the code:

```<code>library(plotly)
library(shiny)

ui <- fluidPage(
  radioButtons("plotType", "Plot Type:", choices = c("ggplotly", "plotly")),
  plotlyOutput("plot"),
  verbatimTextOutput("hover"),
  verbatimTextOutput("click"),
  verbatimTextOutput("brush"),
  verbatimTextOutput("zoom")
)

server <- function(input, output, session) {

  output$plot <- renderPlotly({
    # use the key aesthetic/argument to help uniquely identify selected observations
    key <- row.names(mtcars)
    if (identical(input$plotType, "ggplotly")) {
      p <- ggplot(mtcars, aes(x = mpg, y = wt, colour = factor(vs), key = key)) +
        geom_point()
      ggplotly(p) %>% layout(dragmode = "select")
    } else {
      plot_ly(mtcars, x = ~mpg, y = ~wt, key = ~key) %>%
        layout(dragmode = "select")
    }
  })

  output$hover <- renderPrint({
    d <- event_data("plotly_hover")
    if (is.null(d)) "Hover events appear here (unhover to clear)" else d
  })

  output$click <- renderPrint({
    d <- event_data("plotly_click")
    if (is.null(d)) "Click events appear here (double-click to clear)" else d
  })

  output$brush <- renderPrint({
    d <- event_data("plotly_selected")
    if (is.null(d)) "Click and drag events (i.e., select/lasso) appear here (double-click to clear)" else d
  })

  output$zoom <- renderPrint({
    d <- event_data("plotly_relayout")
    if (is.null(d)) "Relayout (i.e., zoom) events appear here" else d
  })

}

shinyApp(ui, server)
</code>```

Any suggestions are very welcome, thanks!

答:
Issue was hotfixed by https://github.com/ropensci/plotly/issues/1042 in the devtools version of plotly.</p>

```<code>devtools::install_github('ropensci/plotly')
</code>```

Title: No plot displayed with plotly in shiny

Body:
when I'm pasting the code from https://plot.ly/r/shinyapp-plotly-events/ into my console no plotly graph is diplayed, I can't get any plot in shiny displayed with plotly.

My sessionInfo:

R version 3.4.0 (2017-04-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

locale:
[1] LC_COLLATE=German_Germany.1252  LC_CTYPE=German_Germany.1252    LC_MONETARY=German_Germany.1252 LC_NUMERIC=C                    LC_TIME=German_Germany.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] plotly_4.7.0       ggplot2_2.2.1.9000 feather_0.3.1      RODBC_1.3-15       dplyr_0.5.0        shiny_1.0.3

Am I using the wrong package versions? I reinstalled everything from cran but i never see a plotly graph with shiny.
I can produce the plotly graph's inside RStudio in the Viewer. Do I have to use any of the devtools versions of plotly/ggplot/shiny or all devtool versions? I tried plotly_4.7.0.9000 but still no output is shown.

I found a post plotly graph doesn't show up that renderPlotly({return(plot_ly(x))}) is broken, but even with renderPlotly(data) I can't produce any frames in shiny.

Example Code from the plotly gallery, the error should be in my setup I suppose, as a mater of form the code:

library(plotly)
library(shiny)

ui <- fluidPage(
  radioButtons("plotType", "Plot Type:", choices = c("ggplotly", "plotly")),
  plotlyOutput("plot"),
  verbatimTextOutput("hover"),
  verbatimTextOutput("click"),
  verbatimTextOutput("brush"),
  verbatimTextOutput("zoom")
)

server <- function(input, output, session) {

  output$plot <- renderPlotly({
    # use the key aesthetic/argument to help uniquely identify selected observations
    key <- row.names(mtcars)
    if (identical(input$plotType, "ggplotly")) {
      p <- ggplot(mtcars, aes(x = mpg, y = wt, colour = factor(vs), key = key)) +
        geom_point()
      ggplotly(p) %>% layout(dragmode = "select")
    } else {
      plot_ly(mtcars, x = ~mpg, y = ~wt, key = ~key) %>%
        layout(dragmode = "select")
    }
  })

  output$hover <- renderPrint({
    d <- event_data("plotly_hover")
    if (is.null(d)) "Hover events appear here (unhover to clear)" else d
  })

  output$click <- renderPrint({
    d <- event_data("plotly_click")
    if (is.null(d)) "Click events appear here (double-click to clear)" else d
  })

  output$brush <- renderPrint({
    d <- event_data("plotly_selected")
    if (is.null(d)) "Click and drag events (i.e., select/lasso) appear here (double-click to clear)" else d
  })

  output$zoom <- renderPrint({
    d <- event_data("plotly_relayout")
    if (is.null(d)) "Relayout (i.e., zoom) events appear here" else d
  })

}

shinyApp(ui, server)

Any suggestions are very welcome, thanks!

Body:
Issue was hotfixed by https://github.com/ropensci/plotly/issues/1042 in the devtools version of plotly.

devtools::install_github('ropensci/plotly')


问:
Bing Ads API Reporting Data with R - get ReportRequestId
I want to directly load data from the Bing Ads Api into the statistic tool R.
I use the httr package within R, which uses Curl to enable a connection between R and the API.
According to the API manual I try to SubmitGenerateReport, but I do not receive a ReportRequestId.

Here is the R Code:

```<code>#loads the httr package

library(httr)

#creates the statement, body of http soap object

`body <- '<s:Body>
             <SubmitGenerateReportRequestxmlns="https://bingads.microsoft.com/Reporting/v9">

<ReportRequest i:nil="false" i:type="KeywordPerformanceReportRequest">

<Format i:nil="false">Csv</Format>

<Language i:nil="false">English</Language>

<ReportName i:nil="false">Test</ReportName>
       <ReturnOnlyCompleteData>false</ReturnOnlyCompleteData>

<Aggregation>Daily</Aggregation>

<Columns>\

<KeywordPerformanceReportColumn>AccountName</KeywordPerformanceReportColumn>\
    <KeywordPerformanceReportColumn>CampaignName</KeywordPerformanceReportColumn>\
    <KeywordPerformanceReportColumn>Keyword</KeywordPerformanceReportColumn>\
    <KeywordPerformanceReportColumn>TimePeriod</KeywordPerformanceReportColumn>\
    <KeywordPerformanceReportColumn>Impressions</KeywordPerformanceReportColumn>\
    <KeywordPerformanceReportColumn>Conversions</KeywordPerformanceReportColumn>\

</Columns>\

<Scope>\

    <AccountIds>MyAccountId</AccountIds>\

    </Scope>\

<Time>\

<PredefinedTime>LastSevenDays</PredefinedTime>\

</Time>\

</ReportRequest>

    </SubmitGenerateReportRequest>

</s:Body>'`

# post the api request
response <- POST("https://bingads.microsoft.com/Reporting/v9",
     c(verbose(),add_headers("Action" = "SubmitGenerateReport",
                              "Content-Type" = "text/xml; charset=utf-8",
                              "CustomerAccountId"  =  "MyCustomerAccountId",
                              "CustomerId"  =  "MyCustomerId",
                              "DeveloperToken"  =  "MyDevToken",
                              "Password"  =  "MyPassword",
                              "UserName"  =  "MyUserName")),
     body = body)
</code>```

The Api returns following:

```<code>* Adding handle: conn: 0x7fd10d167200
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x7fd10d167200) send_pipe: 1, recv_pipe: 0
* About to connect() to bingads.microsoft.com port 443 (#0)
*   Trying ***.**.***.***...
* Connected to bingads.microsoft.com (***.**.***.***) port 443 (#0)
* TLS 1.0 connection using TLS_RSA_WITH_RC4_128_SHA
* Server certificate: bingads.microsoft.com
* Server certificate: VeriSign Class 3 Extended Validation SSL SGC CA
* Server certificate: VeriSign Class 3 Public Primary Certification Authority - G5
> POST /Reporting/v9 HTTP/1.1
Host: bingads.microsoft.com
Accept: */*
Accept-Encoding: gzip
user-agent: curl/7.30.0 Rcurl/1.95.4.1 httr/0.3
Action: SubmitGenerateReport
Content-Type: text/xml; charset=utf-8
CustomerAccountId: *******
CustomerId: ******
DeveloperToken: **************
Password: *********
UserName: ***********
Content-Length: 1056
Expect: 100-continue

< HTTP/1.1 302 Found
< Location: https://bingads.microsoft.com//default.aspx?reason=1&msg=sessionexpired&rurl=https%3a%2f%2fbingads.microsoft.com%2fReporting%2fv9
* Server Microsoft-IIS/8.0 is not blacklisted
< Server: Microsoft-IIS/8.0
< X-MiniProfiler-Ids: []
< X-Powered-By: ASP.NET
< p3p: CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Methods: GET, POST, OPTIONS
< Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
< Date: Tue, 29 Apr 2014 09:45:54 GMT
< Content-Length: 254
<
* Closing connection 0
* Issue another request to this URL: 'https://bingads.microsoft.com//default.aspx?reason=1&msg=sessionexpired&rurl=https%3a%2f%2fbingads.microsoft.com%2fReporting%2fv9'
* About to connect() to bingads.microsoft.com port 443 (#1)
*   Trying ***.**.***.***...
* Adding handle: conn: 0x7fd10a685800
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 1 (0x7fd10a685800) send_pipe: 1, recv_pipe: 0
* Connected to bingads.microsoft.com (***.**.***.***) port 443 (#1)
* TLS 1.0 connection using TLS_RSA_WITH_RC4_128_SHA
* Server certificate: bingads.microsoft.com
* Server certificate: VeriSign Class 3 Extended Validation SSL SGC CA
* Server certificate: VeriSign Class 3 Public Primary Certification Authority - G5
> POST //default.aspx?reason=1&msg=sessionexpired&rurl=https%3a%2f%2fbingads.microsoft.com%2fReporting%2fv9 HTTP/1.1
Host: bingads.microsoft.com
Accept: */*
Accept-Encoding: gzip
user-agent: curl/7.30.0 Rcurl/1.95.4.1 httr/0.3
Action: SubmitGenerateReport
Content-Type: text/xml; charset=utf-8
CustomerAccountId: ********
CustomerId: *********
DeveloperToken: ***************
Password: **********
UserName: ***********
Content-Length: 1056
Expect: 100-continue

< HTTP/1.1 302 Redirect
< Cache-Control: private, no-store
< Content-Type: text/html; charset=UTF-8
< Location: https://secure.bingads.microsoft.com/?reason=1&msg=sessionexpired&rurl=https%3a%2f%2fbingads.microsoft.com%2fReporting%2fv9
* Server Microsoft-IIS/8.0 is not blacklisted
< Server: Microsoft-IIS/8.0
< X-Powered-By: ASP.NET
< p3p: CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"
< Date: Tue, 29 Apr 2014 09:45:55 GMT
< Content-Length: 254
<
* Closing connection 1
* Issue another request to this URL: 'https://secure.bingads.microsoft.com/?reason=1&msg=sessionexpired&rurl=https%3a%2f%2fbingads.microsoft.com%2fReporting%2fv9'
* Adding handle: conn: 0x7fd10e450e00
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 2 (0x7fd10e450e00) send_pipe: 1, recv_pipe: 0
* About to connect() to secure.bingads.microsoft.com port 443 (#2)
*   Trying **.**.***.***...
* Connected to secure.bingads.microsoft.com (**.**.***.***) port 443 (#2)
* TLS 1.0 connection using TLS_RSA_WITH_RC4_128_SHA
* Server certificate: bingads.microsoft.com
* Server certificate: VeriSign Class 3 Extended Validation SSL SGC CA
* Server certificate: VeriSign Class 3 Public Primary Certification Authority - G5
> POST /?reason=1&msg=sessionexpired&rurl=https%3a%2f%2fbingads.microsoft.com%2fReporting%2fv9 HTTP/1.1
Host: secure.bingads.microsoft.com
Accept: */*
Accept-Encoding: gzip
user-agent: curl/7.30.0 Rcurl/1.95.4.1 httr/0.3
Action: SubmitGenerateReport
Content-Type: text/xml; charset=utf-8
CustomerAccountId: *********
CustomerId: ********
DeveloperToken: ***************
Password: ********
UserName: ***********
Content-Length: 1056
Expect: 100-continue

< HTTP/1.1 100 Continue
* We are completely uploaded and fine
< HTTP/1.1 200 OK
< Cache-Control: no-cache, no-store
< Pragma: no-cache
< Content-Type: text/html; charset=utf-8
< Expires: -1
* Server Microsoft-IIS/8.0 is not blacklisted
< Server: Microsoft-IIS/8.0
* Added cookie JFX_SessionId="********************************" for domain bingads.microsoft.com, path /, expire 0
< Set-Cookie: JFX_SessionId=********************************; domain=bingads.microsoft.com; path=/; secure; HttpOnly
* Added cookie LCIDCookie="1033" for domain bingads.microsoft.com, path /, expire 1430290800
< Set-Cookie: LCIDCookie=1033; domain=bingads.microsoft.com; expires=Wed, 29-Apr-2015 07:00:00 GMT; path=/; secure
* Added cookie MarketIDCookie="1033" for domain bingads.microsoft.com, path /, expire 1430290800
< Set-Cookie: MarketIDCookie=1033; domain=bingads.microsoft.com; expires=Wed, 29-Apr-2015 07:00:00 GMT; path=/; secure
* Added cookie IetfLanguageTag="" for domain bingads.microsoft.com, path /, expire 1430290800
< Set-Cookie: IetfLanguageTag=; domain=bingads.microsoft.com; expires=Wed, 29-Apr-2015 07:00:00 GMT; path=/; secure
< X-AspNetMvc-Version: 3.0
< X-AspNet-Version: 4.0.30319
* Replaced cookie JFX_SessionId="********************************" for domain bingads.microsoft.com, path /, expire 0
< Set-Cookie: JFX_SessionId=********************************; domain=bingads.microsoft.com; path=/; secure; HttpOnly
* Replaced cookie LCIDCookie="1033" for domain bingads.microsoft.com, path /, expire 1430290800
< Set-Cookie: LCIDCookie=1033; domain=bingads.microsoft.com; expires=Wed, 29-Apr-2015 07:00:00 GMT; path=/; secure
* Replaced cookie MarketIDCookie="1033" for domain bingads.microsoft.com, path /, expire 1430290800
< Set-Cookie: MarketIDCookie=1033; domain=bingads.microsoft.com; expires=Wed, 29-Apr-2015 07:00:00 GMT; path=/; secure
* Replaced cookie IetfLanguageTag="" for domain bingads.microsoft.com, path /, expire 1430290800
< Set-Cookie: IetfLanguageTag=; domain=bingads.microsoft.com; expires=Wed, 29-Apr-2015 07:00:00 GMT; path=/; secure
* Added cookie __RequestVerificationToken_Lw__="********************************" for domain secure.bingads.microsoft.com, path /, expire 0
< Set-Cookie: __RequestVerificationToken_Lw__=********************************; path=/; secure; HttpOnly
< X-Powered-By: ASP.NET
< X-UA-Compatible: IE=Edge
< p3p: CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"
< Date: Tue, 29 Apr 2014 09:45:57 GMT
< Content-Length: 16393
<
* Connection #2 to host secure.bingads.microsoft.com left intact
</code>```

I am really looking forward to any help?

Kind regards,

Johannes

答:
The newest version of the httr lib has build-in oauth2 functions for services like twitter, linkedin, google and azure. The azure oauth2 lib is the one you want if you're trying to connect to the bing ads api v11 with oauth2. The script is here:

https://github.com/hadley/httr/blob/master/demo/oauth2-azure.r

Change this line:

```<code>azure_endpoint <- oauth_endpoints('azure')
</code>```

To this:

```<code>azure_endpoint <- oauth_endpoint(authorize = "https://login.live.com/oauth20_authorize.srf", access = "https://login.live.com/oauth20_token.srf")
</code>```

Now httr is able to connect to the bing api and retrieve the oauth2 token. You will need to modify the script further by entering your application ID, secret and so on.

Note: this does not actually solve the XML issue you've posted here I post this because the v9 and v10 versions of the API will be depreciated later this year and I noticed you're using httr with the v9 bing ads api.

Body:
I want to directly load data from the Bing Ads Api into the statistic tool R.
I use the httr package within R, which uses Curl to enable a connection between R and the API.
According to the API manual I try to SubmitGenerateReport, but I do not receive a ReportRequestId.

Here is the R Code:

#loads the httr package

library(httr)

#creates the statement, body of http soap object

`body <- '<s:Body>
             <SubmitGenerateReportRequestxmlns="https://bingads.microsoft.com/Reporting/v9">

<ReportRequest i:nil="false" i:type="KeywordPerformanceReportRequest">

<Format i:nil="false">Csv</Format>

<Language i:nil="false">English</Language>

<ReportName i:nil="false">Test</ReportName>
       <ReturnOnlyCompleteData>false</ReturnOnlyCompleteData>

<Aggregation>Daily</Aggregation>

<Columns>\

<KeywordPerformanceReportColumn>AccountName</KeywordPerformanceReportColumn>\
    <KeywordPerformanceReportColumn>CampaignName</KeywordPerformanceReportColumn>\
    <KeywordPerformanceReportColumn>Keyword</KeywordPerformanceReportColumn>\
    <KeywordPerformanceReportColumn>TimePeriod</KeywordPerformanceReportColumn>\
    <KeywordPerformanceReportColumn>Impressions</KeywordPerformanceReportColumn>\
    <KeywordPerformanceReportColumn>Conversions</KeywordPerformanceReportColumn>\

</Columns>\

<Scope>\

    <AccountIds>MyAccountId</AccountIds>\

    </Scope>\

<Time>\

<PredefinedTime>LastSevenDays</PredefinedTime>\

</Time>\

</ReportRequest>

    </SubmitGenerateReportRequest>

</s:Body>'`

# post the api request
response <- POST("https://bingads.microsoft.com/Reporting/v9",
     c(verbose(),add_headers("Action" = "SubmitGenerateReport",
                              "Content-Type" = "text/xml; charset=utf-8",
                              "CustomerAccountId"  =  "MyCustomerAccountId",
                              "CustomerId"  =  "MyCustomerId",
                              "DeveloperToken"  =  "MyDevToken",
                              "Password"  =  "MyPassword",
                              "UserName"  =  "MyUserName")),
     body = body)

The Api returns following:

* Adding handle: conn: 0x7fd10d167200
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x7fd10d167200) send_pipe: 1, recv_pipe: 0
* About to connect() to bingads.microsoft.com port 443 (#0)
*   Trying ***.**.***.***...
* Connected to bingads.microsoft.com (***.**.***.***) port 443 (#0)
* TLS 1.0 connection using TLS_RSA_WITH_RC4_128_SHA
* Server certificate: bingads.microsoft.com
* Server certificate: VeriSign Class 3 Extended Validation SSL SGC CA
* Server certificate: VeriSign Class 3 Public Primary Certification Authority - G5
> POST /Reporting/v9 HTTP/1.1
Host: bingads.microsoft.com
Accept: */*
Accept-Encoding: gzip
user-agent: curl/7.30.0 Rcurl/1.95.4.1 httr/0.3
Action: SubmitGenerateReport
Content-Type: text/xml; charset=utf-8
CustomerAccountId: *******
CustomerId: ******
DeveloperToken: **************
Password: *********
UserName: ***********
Content-Length: 1056
Expect: 100-continue

< HTTP/1.1 302 Found
< Location: https://bingads.microsoft.com//default.aspx?reason=1&msg=sessionexpired&rurl=https%3a%2f%2fbingads.microsoft.com%2fReporting%2fv9
* Server Microsoft-IIS/8.0 is not blacklisted
< Server: Microsoft-IIS/8.0
< X-MiniProfiler-Ids: []
< X-Powered-By: ASP.NET
< p3p: CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Methods: GET, POST, OPTIONS
< Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
< Date: Tue, 29 Apr 2014 09:45:54 GMT
< Content-Length: 254
<
* Closing connection 0
* Issue another request to this URL: 'https://bingads.microsoft.com//default.aspx?reason=1&msg=sessionexpired&rurl=https%3a%2f%2fbingads.microsoft.com%2fReporting%2fv9'
* About to connect() to bingads.microsoft.com port 443 (#1)
*   Trying ***.**.***.***...
* Adding handle: conn: 0x7fd10a685800
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 1 (0x7fd10a685800) send_pipe: 1, recv_pipe: 0
* Connected to bingads.microsoft.com (***.**.***.***) port 443 (#1)
* TLS 1.0 connection using TLS_RSA_WITH_RC4_128_SHA
* Server certificate: bingads.microsoft.com
* Server certificate: VeriSign Class 3 Extended Validation SSL SGC CA
* Server certificate: VeriSign Class 3 Public Primary Certification Authority - G5
> POST //default.aspx?reason=1&msg=sessionexpired&rurl=https%3a%2f%2fbingads.microsoft.com%2fReporting%2fv9 HTTP/1.1
Host: bingads.microsoft.com
Accept: */*
Accept-Encoding: gzip
user-agent: curl/7.30.0 Rcurl/1.95.4.1 httr/0.3
Action: SubmitGenerateReport
Content-Type: text/xml; charset=utf-8
CustomerAccountId: ********
CustomerId: *********
DeveloperToken: ***************
Password: **********
UserName: ***********
Content-Length: 1056
Expect: 100-continue

< HTTP/1.1 302 Redirect
< Cache-Control: private, no-store
< Content-Type: text/html; charset=UTF-8
< Location: https://secure.bingads.microsoft.com/?reason=1&msg=sessionexpired&rurl=https%3a%2f%2fbingads.microsoft.com%2fReporting%2fv9
* Server Microsoft-IIS/8.0 is not blacklisted
< Server: Microsoft-IIS/8.0
< X-Powered-By: ASP.NET
< p3p: CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"
< Date: Tue, 29 Apr 2014 09:45:55 GMT
< Content-Length: 254
<
* Closing connection 1
* Issue another request to this URL: 'https://secure.bingads.microsoft.com/?reason=1&msg=sessionexpired&rurl=https%3a%2f%2fbingads.microsoft.com%2fReporting%2fv9'
* Adding handle: conn: 0x7fd10e450e00
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 2 (0x7fd10e450e00) send_pipe: 1, recv_pipe: 0
* About to connect() to secure.bingads.microsoft.com port 443 (#2)
*   Trying **.**.***.***...
* Connected to secure.bingads.microsoft.com (**.**.***.***) port 443 (#2)
* TLS 1.0 connection using TLS_RSA_WITH_RC4_128_SHA
* Server certificate: bingads.microsoft.com
* Server certificate: VeriSign Class 3 Extended Validation SSL SGC CA
* Server certificate: VeriSign Class 3 Public Primary Certification Authority - G5
> POST /?reason=1&msg=sessionexpired&rurl=https%3a%2f%2fbingads.microsoft.com%2fReporting%2fv9 HTTP/1.1
Host: secure.bingads.microsoft.com
Accept: */*
Accept-Encoding: gzip
user-agent: curl/7.30.0 Rcurl/1.95.4.1 httr/0.3
Action: SubmitGenerateReport
Content-Type: text/xml; charset=utf-8
CustomerAccountId: *********
CustomerId: ********
DeveloperToken: ***************
Password: ********
UserName: ***********
Content-Length: 1056
Expect: 100-continue

< HTTP/1.1 100 Continue
* We are completely uploaded and fine
< HTTP/1.1 200 OK
< Cache-Control: no-cache, no-store
< Pragma: no-cache
< Content-Type: text/html; charset=utf-8
< Expires: -1
* Server Microsoft-IIS/8.0 is not blacklisted
< Server: Microsoft-IIS/8.0
* Added cookie JFX_SessionId="********************************" for domain bingads.microsoft.com, path /, expire 0
< Set-Cookie: JFX_SessionId=********************************; domain=bingads.microsoft.com; path=/; secure; HttpOnly
* Added cookie LCIDCookie="1033" for domain bingads.microsoft.com, path /, expire 1430290800
< Set-Cookie: LCIDCookie=1033; domain=bingads.microsoft.com; expires=Wed, 29-Apr-2015 07:00:00 GMT; path=/; secure
* Added cookie MarketIDCookie="1033" for domain bingads.microsoft.com, path /, expire 1430290800
< Set-Cookie: MarketIDCookie=1033; domain=bingads.microsoft.com; expires=Wed, 29-Apr-2015 07:00:00 GMT; path=/; secure
* Added cookie IetfLanguageTag="" for domain bingads.microsoft.com, path /, expire 1430290800
< Set-Cookie: IetfLanguageTag=; domain=bingads.microsoft.com; expires=Wed, 29-Apr-2015 07:00:00 GMT; path=/; secure
< X-AspNetMvc-Version: 3.0
< X-AspNet-Version: 4.0.30319
* Replaced cookie JFX_SessionId="********************************" for domain bingads.microsoft.com, path /, expire 0
< Set-Cookie: JFX_SessionId=********************************; domain=bingads.microsoft.com; path=/; secure; HttpOnly
* Replaced cookie LCIDCookie="1033" for domain bingads.microsoft.com, path /, expire 1430290800
< Set-Cookie: LCIDCookie=1033; domain=bingads.microsoft.com; expires=Wed, 29-Apr-2015 07:00:00 GMT; path=/; secure
* Replaced cookie MarketIDCookie="1033" for domain bingads.microsoft.com, path /, expire 1430290800
< Set-Cookie: MarketIDCookie=1033; domain=bingads.microsoft.com; expires=Wed, 29-Apr-2015 07:00:00 GMT; path=/; secure
* Replaced cookie IetfLanguageTag="" for domain bingads.microsoft.com, path /, expire 1430290800
< Set-Cookie: IetfLanguageTag=; domain=bingads.microsoft.com; expires=Wed, 29-Apr-2015 07:00:00 GMT; path=/; secure
* Added cookie __RequestVerificationToken_Lw__="********************************" for domain secure.bingads.microsoft.com, path /, expire 0
< Set-Cookie: __RequestVerificationToken_Lw__=********************************; path=/; secure; HttpOnly
< X-Powered-By: ASP.NET
< X-UA-Compatible: IE=Edge
< p3p: CP="ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI"
< Date: Tue, 29 Apr 2014 09:45:57 GMT
< Content-Length: 16393
<
* Connection #2 to host secure.bingads.microsoft.com left intact

I am really looking forward to any help?

Kind regards,

Johannes

Body:
The newest version of the httr lib has build-in oauth2 functions for services like twitter, linkedin, google and azure. The azure oauth2 lib is the one you want if you're trying to connect to the bing ads api v11 with oauth2. The script is here:

https://github.com/hadley/httr/blob/master/demo/oauth2-azure.r

Change this line:

azure_endpoint <- oauth_endpoints('azure')

To this:

azure_endpoint <- oauth_endpoint(authorize = "https://login.live.com/oauth20_authorize.srf", access = "https://login.live.com/oauth20_token.srf")

Now httr is able to connect to the bing api and retrieve the oauth2 token. You will need to modify the script further by entering your application ID, secret and so on.

Note: this does not actually solve the XML issue you've posted here I post this because the v9 and v10 versions of the API will be depreciated later this year and I noticed you're using httr with the v9 bing ads api.


问:
How to get PDF box size from CGPDFPage
I'm getting errors however I try to get the mediabox of a PDF Page in Swift.:

```<code>if let pdf = CGPDFDocument(pdfURL) {
    let numberOfPages = pdf.numberOfPages
    for index in 0...numberOfPages {
        let pdfPage = pdf.page(at: index)
        print(CGPDFPageGetBoxRect(pdfPage!, kCGPDFMediaBox))

}
</code>```

I've also tried:

```<code>print(pdfPage.getBoxRect(kCGPDFMediaBox))
</code>```

as well as using PDFDisplayBox.mediaBox, mediaBox and pretty much every other variant. It works fine in python.
I can also get the info fine using PDFPage (as opposed to CGPDFPage), but I need to use CGPDFPage for other things that PDFPage can't do.)

The second part is: from what I can tell, the mediaBox result does not factor in the rotation. So a landscape page might have a portrait mediabox with a rotation of 90. Is there any easy way to get the "actual" display dimensions, or do I have to do the transformation myself?

答:
PDF pages are numbered starting at 1, not at zero. And getBoxRect()
takes a enum CGPDFBox argument in Swift 3. So this should work:

```<code>for pageNo in 1...pdf.numberOfPages {
    if let pdfPage = pdf.page(at: pageNo) {
        let mediaBox = pdfPage.getBoxRect(.mediaBox)
        print(mediaBox)
    }
}
</code>```

The PDF bounding boxes do not take the page rotation into account.
The following might work to compute the rotated box (untested):

```<code>// Get rotation angle and convert from degrees to radians:
let angle = CGFloat(pdfPage.rotationAngle) * CGFloat.pi / 180
// Apply rotation transform to media box:
let rotatedBox = mediaBox.applying(CGAffineTransform(rotationAngle: angle))
</code>```

Title: How to get PDF box size from CGPDFPage

Body:
I'm getting errors however I try to get the mediabox of a PDF Page in Swift.:

if let pdf = CGPDFDocument(pdfURL) {
    let numberOfPages = pdf.numberOfPages
    for index in 0...numberOfPages {
        let pdfPage = pdf.page(at: index)
        print(CGPDFPageGetBoxRect(pdfPage!, kCGPDFMediaBox))

}

I've also tried:

print(pdfPage.getBoxRect(kCGPDFMediaBox))

as well as using PDFDisplayBox.mediaBox, mediaBox and pretty much every other variant. It works fine in python.
I can also get the info fine using PDFPage (as opposed to CGPDFPage), but I need to use CGPDFPage for other things that PDFPage can't do.)

The second part is: from what I can tell, the mediaBox result does not factor in the rotation. So a landscape page might have a portrait mediabox with a rotation of 90. Is there any easy way to get the "actual" display dimensions, or do I have to do the transformation myself?

Body:
PDF pages are numbered starting at 1, not at zero. And getBoxRect()
takes a enum CGPDFBox argument in Swift 3. So this should work:

for pageNo in 1...pdf.numberOfPages {
    if let pdfPage = pdf.page(at: pageNo) {
        let mediaBox = pdfPage.getBoxRect(.mediaBox)
        print(mediaBox)
    }
}

The PDF bounding boxes do not take the page rotation into account.
The following might work to compute the rotated box (untested):

// Get rotation angle and convert from degrees to radians:
let angle = CGFloat(pdfPage.rotationAngle) * CGFloat.pi / 180
// Apply rotation transform to media box:
let rotatedBox = mediaBox.applying(CGAffineTransform(rotationAngle: angle))


问:
Live video from raw tcp packets
we are trying to make a small python app that display a live video from sniffed packets using scapy and ffplay. This is part of our master degree research project. The goal is to make a proof of concept app that spies on video transimitted over tcp.

We have a working script that writes into a .dat file and then we read it using ffplay. It works ok but have a lot of latency and we think we could do better : directly stream it into ffplay without the need to write raw data in a file.

Here's our script :

```<code>from scapy.all import *
import os

export_dat = open("data.dat", "a")

def write_packet_raw(packet):
    export_dat.write(str(packet.getlayer(Raw)))

def realtime_packet():
    p = sniff(iface="wlan0", filter="tcp and (port 5555)", count=5000, prn=write_packet_raw)

realtime_packet()
export_dat.close()
</code>```

And then we launch : ffplay -window_title Videostream -framedrop -infbuf -f h264 -i data.dat

Any idea on how we can achieve that ? thanks.

答:
Write to stdout in binary mode instead of a file and pipe the output to ffplay.

```<code>import sys
sys.stdout.buffer.write(...)
sys.stdout.flush()
</code>```

Then run it like:

python3 sniff.py | ffplay -f h264 -i -

The - means stdin.

Title: Live video from raw tcp packets

Body:
we are trying to make a small python app that display a live video from sniffed packets using scapy and ffplay. This is part of our master degree research project. The goal is to make a proof of concept app that spies on video transimitted over tcp.

We have a working script that writes into a .dat file and then we read it using ffplay. It works ok but have a lot of latency and we think we could do better : directly stream it into ffplay without the need to write raw data in a file.

Here's our script :

from scapy.all import *
import os

export_dat = open("data.dat", "a")

def write_packet_raw(packet):
    export_dat.write(str(packet.getlayer(Raw)))

def realtime_packet():
    p = sniff(iface="wlan0", filter="tcp and (port 5555)", count=5000, prn=write_packet_raw)

realtime_packet()
export_dat.close()

And then we launch : ffplay -window_title Videostream -framedrop -infbuf -f h264 -i data.dat

Any idea on how we can achieve that ? thanks.

Body:
Write to stdout in binary mode instead of a file and pipe the output to ffplay.

import sys
sys.stdout.buffer.write(...)
sys.stdout.flush()

Then run it like:

python3 sniff.py | ffplay -f h264 -i -

The - means stdin.


问:
How to Save Excel File in a specific Folder
I am exporting excel file from database using following method.But i have one problem when i am exporting excel file than it is automatically downloading to download folder and i don't want this to be happen,I want my excel file to be downloaded in my project folder</p>

```<code>var formsection = from fs in db.FormSections
                  join form in Form on fs.FormId equals form.FormId
                  select fs;
XLWorkbook wb = new XLWorkbook();
string sheetName = "ARTICLE"; //Give name for export file.

var Fs = wb.Worksheets.Add("FORMSECTION");
Fs.Cell(2, 1).InsertTable(formsection.ToList());// assign list here.
HttpContext.Response.Clear();
HttpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Response.AddHeader("content-disposition", String.Format(@"attachment;filename={0}.xlsx", sheetName.Replace(" ", "_")));
var filePath = Path.Combine(Server.MapPath("~/Content"));
using (MemoryStream memoryStream = new MemoryStream())
{
    wb.SaveAs(memoryStream);
    memoryStream.WriteTo(HttpContext.Response.OutputStream);
    memoryStream.Close();
}
HttpContext.Response.End();
</code>```

答:
Here is an example that converts a datatable to a .csv file and save the file to the folder of your project for me its store the file in Domestic folder as the path given by me.</p>

```<code>private void test(DataTable dt1) {

    string csv = string.Empty;

    foreach (DataColumn column in dt1.Columns)
    {
        //Add the Header row for CSV file.
        csv += column.ColumnName + ',';
    }

    //Add new line.
    csv += "\r\n";

    foreach (DataRow row in dt1.Rows)
    {
        foreach (DataColumn column in dt1.Columns)
        {
            //Add the Data rows.
            csv += row[column.ColumnName].ToString().Replace(",", ";") +',';
        }

        //Add new line.
        csv += "\r\n";
    }

    string datetime = Convert.ToString(DateTime.Today.ToString("dd-MM-yyyy")).Trim();
    string filepath = "C:\\Users\\Prateek\\Desktop\\MMR New  27-07 -\\Domestic\\";
    string filename= @"BILLING_BOOK_NO" + "_4005" + "_"+datetime+".CSV";
    string combinepath = filepath + filename;
   System.IO.File.WriteAllText(combinepath,csv);
}`
</code>```

Body:
I am exporting excel file from database using following method.But i have one problem when i am exporting excel file than it is automatically downloading to download folder and i don't want this to be happen,I want my excel file to be downloaded in my project folder

var formsection = from fs in db.FormSections
                  join form in Form on fs.FormId equals form.FormId
                  select fs;
XLWorkbook wb = new XLWorkbook();
string sheetName = "ARTICLE"; //Give name for export file.

var Fs = wb.Worksheets.Add("FORMSECTION");
Fs.Cell(2, 1).InsertTable(formsection.ToList());// assign list here.
HttpContext.Response.Clear();
HttpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Response.AddHeader("content-disposition", String.Format(@"attachment;filename={0}.xlsx", sheetName.Replace(" ", "_")));
var filePath = Path.Combine(Server.MapPath("~/Content"));
using (MemoryStream memoryStream = new MemoryStream())
{
    wb.SaveAs(memoryStream);
    memoryStream.WriteTo(HttpContext.Response.OutputStream);
    memoryStream.Close();
}
HttpContext.Response.End();

Body:
Here is an example that converts a datatable to a .csv file and save the file to the folder of your project for me its store the file in Domestic folder as the path given by me.

private void test(DataTable dt1) {

    string csv = string.Empty;

    foreach (DataColumn column in dt1.Columns)
    {
        //Add the Header row for CSV file.
        csv += column.ColumnName + ',';
    }

    //Add new line.
    csv += "\r\n";

    foreach (DataRow row in dt1.Rows)
    {
        foreach (DataColumn column in dt1.Columns)
        {
            //Add the Data rows.
            csv += row[column.ColumnName].ToString().Replace(",", ";") +',';
        }

        //Add new line.
        csv += "\r\n";
    }

    string datetime = Convert.ToString(DateTime.Today.ToString("dd-MM-yyyy")).Trim();
    string filepath = "C:\\Users\\Prateek\\Desktop\\MMR New  27-07 -\\Domestic\\";
    string filename= @"BILLING_BOOK_NO" + "_4005" + "_"+datetime+".CSV";
    string combinepath = filepath + filename;
   System.IO.File.WriteAllText(combinepath,csv);
}`


问:
Why does Node not read the env var of the current shell?
As you can see below, I set an environment variable FOO, but when I execute console.log on the next line, it's undefined. If I set it on the same line where I execute console.log, it is present. Why is the behaviour as such?

```<code>$ FOO="123"
$ echo $FOO
123
$ node -e "console.log(process.env.FOO)"
undefined
$ FOO="123" node -e "console.log(process.env.FOO)"
123
</code>```

Node version: 6.6.0

答:
If you want to set the environment variable for the current terminal session, you need to use EXPORT

So, this code will work

```<code>export FOO=123
node -e "console.log(process.env.FOO)"
123
</code>```

EXPORT makes the assignment visible to subprocesses. Check this thread for more details

Body:
As you can see below, I set an environment variable FOO, but when I execute console.log on the next line, it's undefined. If I set it on the same line where I execute console.log, it is present. Why is the behaviour as such?

$ FOO="123"
$ echo $FOO
123
$ node -e "console.log(process.env.FOO)"
undefined
$ FOO="123" node -e "console.log(process.env.FOO)"
123

Node version: 6.6.0

Body:
If you want to set the environment variable for the current terminal session, you need to use EXPORT

So, this code will work

export FOO=123
node -e "console.log(process.env.FOO)"
123

EXPORT makes the assignment visible to subprocesses. Check this thread for more details


问:
MySql PDO - Referring two colowns and displaying the id as result
I have been checking for more than an hour but i cant get the result, my question is, by checking two columns it must display the other columns value as result using PDO.

```<code>$sql ="SELECT column3 FROM tablename WHERE column1 = :request AND column2= :recived";
$conn = $conn->prepare($sql);
$fetch = $conn->execute(array(':request'=> $value1,':recived'=>$value2));
$fetch = $fetch->fetchColumn();
</code>```

please help me with this. Thanks in advance

答:
Change it as such:

```<code>$sql ="SELECT column3 FROM tablename WHERE column1 = :request AND column2= :recived";
$conn = $conn->prepare($sql);
$conn->execute(array(':request'=> $value1,':recived'=>$value2));
$fetch = $conn ->fetchColumn();
</code>```

You should call fetchColumn() on the statement. Because execute() only returns a boolean as result.

Body:
I have been checking for more than an hour but i cant get the result, my question is, by checking two columns it must display the other columns value as result using PDO.

$sql ="SELECT column3 FROM tablename WHERE column1 = :request AND column2= :recived";
$conn = $conn->prepare($sql);
$fetch = $conn->execute(array(':request'=> $value1,':recived'=>$value2));
$fetch = $fetch->fetchColumn();

please help me with this. Thanks in advance

Body:
Change it as such:

$sql ="SELECT column3 FROM tablename WHERE column1 = :request AND column2= :recived";
$conn = $conn->prepare($sql);
$conn->execute(array(':request'=> $value1,':recived'=>$value2));
$fetch = $conn ->fetchColumn();

You should call fetchColumn() on the statement. Because execute() only returns a boolean as result.


答:
One approach would be to do it by hand. You need to specify the number of columns in advance:

```<code>dataGridView1.ColumnCount = 8;
</code>```

Then iterate with a loop through each list and assign the values:

```<code>void fillDataGrid()
{
    list1.Add(new classList { p1 = "1", p2 = "2", p3 = "3", p4 = "4" });
    list1.Add(new classList { p1 = "5", p2 = "6", p3 = "7", p4 = "8" });

    list2.Add(new classList { p1 = "9", p2 = "10", p3 = "11", p4 = "12" });
    list2.Add(new classList { p1 = "13", p2 = "14", p3 = "15", p4 = "16" });

    dataGridView1.ColumnCount = 8;

    for (int i = 0; i < list1.Count; i++)
    {
        this.dataGridView1.Rows.Add();
        this.dataGridView1.Rows[i].Cells[0].Value = list1[i].p1;
        this.dataGridView1.Rows[i].Cells[1].Value = list1[i].p2;
        this.dataGridView1.Rows[i].Cells[2].Value = list1[i].p3;
        this.dataGridView1.Rows[i].Cells[3].Value = list1[i].p4;
    }

    for (int i = 0; i < list2.Count; i++)
    {
        this.dataGridView1.Rows[i].Cells[4].Value = list2[i].p1;
        this.dataGridView1.Rows[i].Cells[5].Value = list2[i].p2;
        this.dataGridView1.Rows[i].Cells[6].Value = list2[i].p3;
        this.dataGridView1.Rows[i].Cells[7].Value = list2[i].p4;
    }
}
</code>```

The resulting DataGridView will look like this:

EDIT: if you want the headers you can specify them like this:

```<code>for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
    dataGridView1.Columns[i].HeaderText = "p" + ((i % 4)+1);
}
</code>```

or you can use System.Reflection to get the real names of your properties if you like:

```<code>int propCount = 0;
string [] propnames = typeof(classList).GetProperties().Select(x=>x.Name).ToArray();
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
    dataGridView1.Columns[i].HeaderText = propnames[propCount];
    propCount = i % propnames.Length;
}
</code>```

Title: C# How to combine 2 list in different row count then implement in Form of DataGridView Controller?

Body:
One approach would be to do it by hand. You need to specify the number of columns in advance:

dataGridView1.ColumnCount = 8;

Then iterate with a loop through each list and assign the values:

void fillDataGrid()
{
    list1.Add(new classList { p1 = "1", p2 = "2", p3 = "3", p4 = "4" });
    list1.Add(new classList { p1 = "5", p2 = "6", p3 = "7", p4 = "8" });

    list2.Add(new classList { p1 = "9", p2 = "10", p3 = "11", p4 = "12" });
    list2.Add(new classList { p1 = "13", p2 = "14", p3 = "15", p4 = "16" });

    dataGridView1.ColumnCount = 8;

    for (int i = 0; i < list1.Count; i++)
    {
        this.dataGridView1.Rows.Add();
        this.dataGridView1.Rows[i].Cells[0].Value = list1[i].p1;
        this.dataGridView1.Rows[i].Cells[1].Value = list1[i].p2;
        this.dataGridView1.Rows[i].Cells[2].Value = list1[i].p3;
        this.dataGridView1.Rows[i].Cells[3].Value = list1[i].p4;
    }

    for (int i = 0; i < list2.Count; i++)
    {
        this.dataGridView1.Rows[i].Cells[4].Value = list2[i].p1;
        this.dataGridView1.Rows[i].Cells[5].Value = list2[i].p2;
        this.dataGridView1.Rows[i].Cells[6].Value = list2[i].p3;
        this.dataGridView1.Rows[i].Cells[7].Value = list2[i].p4;
    }
}

The resulting DataGridView will look like this:

EDIT: if you want the headers you can specify them like this:

for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
    dataGridView1.Columns[i].HeaderText = "p" + ((i % 4)+1);
}

or you can use System.Reflection to get the real names of your properties if you like:

int propCount = 0;
string [] propnames = typeof(classList).GetProperties().Select(x=>x.Name).ToArray();
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
    dataGridView1.Columns[i].HeaderText = propnames[propCount];
    propCount = i % propnames.Length;
}


问:
Override Spring data JPA id annotation.
I'm using Spring-data-Jpa where I've an entity

```<code>@Entity(name="person")
public class Person implements Serializable {

@javax.persistence.Id
private long dbId;

@Id
private final String id;

// others attributes removed
}
</code>```

In above class I've two different ids id (marked with org.springframework.data.annotation.Id) and dbId(marked with javax.persistence.Id) , since my id field is always populated with a unique identifier (for Person class which I'm getting from somewhere else) so while using Spring JpaRepository it always tries to update the record and since it's not in db, nothing happens.

I've debug code and saw that it uses SimpleKeyValueRepository which gets the id field which is id, and thus it always gets a value and tries to update record, can I override this behavior to use dbId instead of id field? Is there any way to achieve same with some configuration or annotation, any help is greatly appreciated.

答:
Each entity must have exactly one @Id. On the other hand, you might want to declare a column as unique. It can be done by:

```<code>@Entity(name="person")
public class Person implements Serializable {

    @Id
    private Long id;

    @Column(unique = true)
    private final String uuid;

    // others attributes removed
}
</code>```

Also remember, that Spring Data JPA id should be reference Long instead of a primitive as you want to save objects with id = null.

String id should probably be String uuid and be initialized as String uuid = UUID.randomUUID().toString();

Similar situation would be an unique email requirement for user. On one hand it'll be a primary key, but on the other, you won't mark it as @Id.

If you need further clarification or your environment is more complicated, just ask in comments section below.

Title: Override Spring data JPA id annotation.

Body:
I'm using Spring-data-Jpa where I've an entity

@Entity(name="person")
public class Person implements Serializable {

@javax.persistence.Id
private long dbId;

@Id
private final String id;

// others attributes removed
}

In above class I've two different ids id (marked with org.springframework.data.annotation.Id) and dbId(marked with javax.persistence.Id) , since my id field is always populated with a unique identifier (for Person class which I'm getting from somewhere else) so while using Spring JpaRepository it always tries to update the record and since it's not in db, nothing happens.

I've debug code and saw that it uses SimpleKeyValueRepository which gets the id field which is id, and thus it always gets a value and tries to update record, can I override this behavior to use dbId instead of id field? Is there any way to achieve same with some configuration or annotation, any help is greatly appreciated.

Body:
Each entity must have exactly one @Id. On the other hand, you might want to declare a column as unique. It can be done by:

@Entity(name="person")
public class Person implements Serializable {

    @Id
    private Long id;

    @Column(unique = true)
    private final String uuid;

    // others attributes removed
}

Also remember, that Spring Data JPA id should be reference Long instead of a primitive as you want to save objects with id = null.

String id should probably be String uuid and be initialized as String uuid = UUID.randomUUID().toString();

Similar situation would be an unique email requirement for user. On one hand it'll be a primary key, but on the other, you won't mark it as @Id.

If you need further clarification or your environment is more complicated, just ask in comments section below.


问:
TypeScript Default Value for property
I have defined an Interface in TypeScript like below:

```<code>export interface User {
    id?: number;
    name?: string;
    logoUrl?: File;
    emailUserName?: string;
    emailPassword?: string;
}
</code>```

With User, I bind it to Angular html input. If I enter anything in the input, the User Object will contains the value, But, If I do not enter, the property like name will be undefine. How could I get empty value for name if I do not enter string for name.
Update

```<code><div *ngIf="hero">
<h2>{{hero.name}} details!</h2>
<div>
<label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="hero.name" placeholder="name" />
<input [(ngModel)]="hero.location" placeholder="location" />
</div>
<button (click)="goBack()">Back</button>
</div>
//model
    export class Hero {
    private _location:string="test";
    constructor(){
    console.log(this._location);
    this.location=this._location;
    }
    public id: number;
    public name: string;
    public location:string;
    }

goBack(): void {
console.log(this.hero);
// this.hero=new Hero();
// console.log(this.hero);
//this.location.back();
}
}
</code>```

goBack will output hero without location property if I do not enter any value for it in input.

答:
You can have a class for User instead of an interface, and in the getter do something like:

```<code>class User {
    private _name: string;
    ...

    get name() {
        return this._name || "";
    }
}
</code>```

or even assign an empty string to this._name in the constructor.

If you prefer to use an interface you can have a function that does that:

```<code>function normalizeUser(user: User) {
    return Object.assign({ name: "" }, user);
}
</code>```

Edit

Yes, here's how to set the default value in the ctor:

```<code>class User {
    private static DEFAULT_NAME = "";

    public name: string;
    ...

    constructor() {
        this.name = User.DEFAULT_NAME;
    }
}
</code>```

As for the get name() part, it's an accessor, so if you use it then:

```<code>let a = new User();
console.log(a.name);
</code>```

More on accessors.

Title: TypeScript Default Value for property

Body:
I have defined an Interface in TypeScript like below:

export interface User {
    id?: number;
    name?: string;
    logoUrl?: File;
    emailUserName?: string;
    emailPassword?: string;
}

With User, I bind it to Angular html input. If I enter anything in the input, the User Object will contains the value, But, If I do not enter, the property like name will be undefine. How could I get empty value for name if I do not enter string for name.
Update

{{hero.name}} details!

id: {{hero.id}}

name:
<input [(ngModel)]="hero.name" placeholder="name" />
<input [(ngModel)]="hero.location" placeholder="location" />

<button (click)="goBack()">Back</button>

//model
    export class Hero {
    private _location:string="test";
    constructor(){
    console.log(this._location);
    this.location=this._location;
    }
    public id: number;
    public name: string;
    public location:string;
    }

goBack(): void {
console.log(this.hero);
// this.hero=new Hero();
// console.log(this.hero);
//this.location.back();
}
}

goBack will output hero without location property if I do not enter any value for it in input.

Body:
You can have a class for User instead of an interface, and in the getter do something like:

class User {
    private _name: string;
    ...

    get name() {
        return this._name || "";
    }
}

or even assign an empty string to this._name in the constructor.

If you prefer to use an interface you can have a function that does that:

function normalizeUser(user: User) {
    return Object.assign({ name: "" }, user);
}

Edit

Yes, here's how to set the default value in the ctor:

class User {
    private static DEFAULT_NAME = "";

    public name: string;
    ...

    constructor() {
        this.name = User.DEFAULT_NAME;
    }
}

As for the get name() part, it's an accessor, so if you use it then:

let a = new User();
console.log(a.name);

More on accessors.


问:
Transforming a Hlist[F[A]] into F[B] where case class B has aligned types with A
Note: I am learning shapeless, so please ask for clarification if I miss any details.

Background:

I am building an encoding/decoding solution for fixed-length format while practising Shapeless. The idea is that each case class would have its own encoder/decoder defined as an HList aligned with its properties.

Even if two classes share the same properties, their encoding may be different. The description for each field would contain some(4) values. But this is not important in the problem.

Problem:

The full code is available here: https://github.com/atais/Fixed-Length/blob/03b395947a6b00e548ea1e76a9660e471f136565/src/main/scala/test/Main.scala

I declare a sample case class and its encoder:

```<code>case class Employee(name: String, number: Int, manager: Boolean)

object Employee {
  implicit val employeeEncoder =
    FLEncoder.fixed((s: String) => s) ::
    FLEncoder.fixed((s: String) => s) ::
    FLEncoder.fixed((s: Int) => s.toString) ::
    FLEncoder.fixed((s: Boolean) => s.toString) ::
      HNil
}
</code>```

so the type of my employeeEncoder is a beautiful:

```<code>::[FLEncoder[String], ::[FLEncoder[String], ::[FLEncoder[Int], ::[FLEncoder[Boolean], HNil]]]]
</code>```

Now, encoder implicitly is looking for an FLEncoder[Employee], which I hope could be the above implementation.

I have used this solution to combine TypeClasses for tuples:

Composing typeclasses for tuples in Scala

https://www.scala-exercises.org/shapeless/auto_typeclass_derivation

But I am getting:

```<code>Error:(69, 17) could not find implicit value for parameter enc: test.FLEncoder[test.Employee]
  println(encode(example))
</code>```

If I declare those encoders separately, they are working fine

```<code>implicit val a = fixed((s: String) => s)
implicit val b = fixed((s: Int) => s.toString)
implicit val c = fixed((s: Boolean) => s.toString)
</code>```

Question:

So basically, how to use Shapeless so it would know that this Hlist is an encoder type for an aligned case class?

A Similar problem is solved in scodec. If you check a demo here:
https://github.com/atais/Fixed-Length/blob/03b395947a6b00e548ea1e76a9660e471f136565/src/main/scala/test/Fixed.scala

you are able to do such transformation:

```<code>case class Person(name: String, age: Int)

val pc: Codec[shapeless.::[String, shapeless.::[Int, HNil]]] = (("name" | fixed(10, '_')) :: ("age" | fixed(6, '0').narrow[Int](strToInt, _.toString)))

val personCodec: Codec[Person] = pc.as[Person]
</code>```

But I do not know how could I use TransformSyntax.as in my case.

答:
What you need is to give a way to tell the compiler that your list of FLEncoder can be converted to a FLEncoder of list. Since we are on the type level, this can be done with a typeclass:

```<code>trait ListOfEncoder[L <: HList] {
  type Inside <: HList
  def merge(l: L): FLEncoder[Inside]
}

object ListOfEncoder {
  type Aux[L <: HList, I <: HList] = ListOfEncoder[L] { type Inside = I }

  implicit val hnil: Aux[HNil, HNil] = new ListOfEncoder[HNil] {
    type Inside = HNil
    def merge(l: HNil) = FLEncoder.fixed(_ => "")
  }

  implicit def hcons[H, T <: HList](implicit T: ListOfEncoder[T]): Aux[FLEncoder[H] :: T, H :: T.Inside] = new ListOfEncoder[FLEncoder[H] :: T] {
    type Inside = H :: T.Inside
    def merge(l: FLEncoder[H] :: T): FLEncoder[H :: T.Inside] =
      FLEncoder.fixed((ht: H :: T.Inside) => l.head.encode(ht.head) + T.merge(l.tail).encode(ht.tail))
  }
}
</code>```

Now, in your `FLEncoder object, add this implicit class:

```<code>implicit class EncoderAsGeneric[L <: HList, I <: HList](l: L)(implicit L: ListOfEncoder.Aux[L, I]) {
  def as[E](implicit gen: Generic.Aux[E, I]) =
    FLEncoder.fixed((e: E) => L.merge(l).encode(gen.to(e))
}
</code>```

This will allow you to define

```<code>implicit val employeeEncoder = (fixed((s: String) => s) ::
  fixed((s: String) => s) ::
  fixed((s: Int) => s.toString) ::
  fixed((s: Boolean) => s.toString) ::
    HNil).as[Employee]
</code>```

And now, all the implicits should be in scope for your Main as it is.

By the way, since you define your FLEncoder with HList, there is no need for ProductTypeClassCompanion anymore, since this is only for inference from base cases.

Body:
Note: I am learning shapeless, so please ask for clarification if I miss any details.

Background:

I am building an encoding/decoding solution for fixed-length format while practising Shapeless. The idea is that each case class would have its own encoder/decoder defined as an HList aligned with its properties.

Even if two classes share the same properties, their encoding may be different. The description for each field would contain some(4) values. But this is not important in the problem.

Problem:

The full code is available here: https://github.com/atais/Fixed-Length/blob/03b395947a6b00e548ea1e76a9660e471f136565/src/main/scala/test/Main.scala

I declare a sample case class and its encoder:

case class Employee(name: String, number: Int, manager: Boolean)

object Employee {
  implicit val employeeEncoder =
    FLEncoder.fixed((s: String) => s) ::
    FLEncoder.fixed((s: String) => s) ::
    FLEncoder.fixed((s: Int) => s.toString) ::
    FLEncoder.fixed((s: Boolean) => s.toString) ::
      HNil
}

so the type of my employeeEncoder is a beautiful:

::[FLEncoder[String], ::[FLEncoder[String], ::[FLEncoder[Int], ::[FLEncoder[Boolean], HNil]]]]

Now, encoder implicitly is looking for an FLEncoder[Employee], which I hope could be the above implementation.

I have used this solution to combine TypeClasses for tuples:

Composing typeclasses for tuples in Scala

https://www.scala-exercises.org/shapeless/auto_typeclass_derivation

But I am getting:

Error:(69, 17) could not find implicit value for parameter enc: test.FLEncoder[test.Employee]
  println(encode(example))

If I declare those encoders separately, they are working fine

implicit val a = fixed((s: String) => s)
implicit val b = fixed((s: Int) => s.toString)
implicit val c = fixed((s: Boolean) => s.toString)

Question:

So basically, how to use Shapeless so it would know that this Hlist is an encoder type for an aligned case class?

A Similar problem is solved in scodec. If you check a demo here:
https://github.com/atais/Fixed-Length/blob/03b395947a6b00e548ea1e76a9660e471f136565/src/main/scala/test/Fixed.scala

you are able to do such transformation:

case class Person(name: String, age: Int)

val pc: Codec[shapeless.::[String, shapeless.::[Int, HNil]]] = (("name" | fixed(10, '_')) :: ("age" | fixed(6, '0').narrow[Int](strToInt, _.toString)))

val personCodec: Codec[Person] = pc.as[Person]

But I do not know how could I use TransformSyntax.as in my case.

Body:
What you need is to give a way to tell the compiler that your list of FLEncoder can be converted to a FLEncoder of list. Since we are on the type level, this can be done with a typeclass:

trait ListOfEncoder[L <: HList] {
  type Inside <: HList
  def merge(l: L): FLEncoder[Inside]
}

object ListOfEncoder {
  type Aux[L <: HList, I <: HList] = ListOfEncoder[L] { type Inside = I }

  implicit val hnil: Aux[HNil, HNil] = new ListOfEncoder[HNil] {
    type Inside = HNil
    def merge(l: HNil) = FLEncoder.fixed(_ => "")
  }

  implicit def hcons[H, T <: HList](implicit T: ListOfEncoder[T]): Aux[FLEncoder[H] :: T, H :: T.Inside] = new ListOfEncoder[FLEncoder[H] :: T] {
    type Inside = H :: T.Inside
    def merge(l: FLEncoder[H] :: T): FLEncoder[H :: T.Inside] =
      FLEncoder.fixed((ht: H :: T.Inside) => l.head.encode(ht.head) + T.merge(l.tail).encode(ht.tail))
  }
}

Now, in your `FLEncoder object, add this implicit class:

implicit class EncoderAsGeneric[L <: HList, I <: HList](l: L)(implicit L: ListOfEncoder.Aux[L, I]) {
  def as[E](implicit gen: Generic.Aux[E, I]) =
    FLEncoder.fixed((e: E) => L.merge(l).encode(gen.to(e))
}

This will allow you to define

implicit val employeeEncoder = (fixed((s: String) => s) ::
  fixed((s: String) => s) ::
  fixed((s: Int) => s.toString) ::
  fixed((s: Boolean) => s.toString) ::
    HNil).as[Employee]

And now, all the implicits should be in scope for your Main as it is.

By the way, since you define your FLEncoder with HList, there is no need for ProductTypeClassCompanion anymore, since this is only for inference from base cases.


问:
The type or namespace name 'Mvc' does not exist
I have recently installed visual studio 2013. After downloaded a sample project from web, while i run it, it gives me the following errors-

```<code>The type or namespace name 'Mvc' does not exist in the namespace 'System.Web' (are you missing an assembly reference?)
</code>```

How to overcome this error?

答: My solution was to simply open up the nuget package manager console and run the command update-package -reinstall Microsoft.AspNet.Mvc

Body:
I have recently installed visual studio 2013. After downloaded a sample project from web, while i run it, it gives me the following errors-

The type or namespace name 'Mvc' does not exist in the namespace 'System.Web' (are you missing an assembly reference?)

How to overcome this error?