问:
How can i place 3 button horizontally and vertically aligned
I want these 3 buttons to be vertically and horizontally aligned but when I try to align them, the last button is falling down and I don't know why. This is the original code without alignment, some one can help me?

@import 'https://fonts.googleapis.com/css?family=Comfortaa:300,400,700&subset=cyrillic,cyrillic-ext,latin-ext';

body {
  background: url(https://wallpaperscraft.com/image/black_background_pattern_light_texture_55291_1920x1080.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
button {
  color:#454545;
  width: 200px;
  background:transparent;
  border-width:2px;
  border-style: solid;
  border-color: #454545;
  position:relative;
  margin:1em;
  display:inline-block;
  padding:0.5em 1em;
  transition:all 0.3s ease-in-out;
  text-align:center;
  font-family:comfortaa;
  font-weight:bold
}

button:before, button:after{
  content:'';
  display:block;
  position:absolute;
  border-color:#454545;
  box-sizing:border-box;
  border-style:solid;
  width:1em;height:1em;
  transition:all 0.3s ease-in-out
}

button:before {
  top:-6px;left:-6px;
  border-width:2px 0 0 2px;
  z-index:5;
}

button:after {
  bottom:-6px;
  right:-6px;
  border-width:0 2px 2px 0;
}

button:hover:before, button:hover:after {
  width:calc(100% + 12px);
  height:calc(100% + 12px);
  border-color:#fff
}

button:hover {
  color:#353535;
  background-color:#fff;
  border-color:#fff
}

.pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}

.rosso button {
  color:#ff0c0c;
  border-color:#ff0c0c
}

.rosso button:before, .rosso button:after  {
  border-color:#ff0c0c
}

.rosso button:hover:before, .rosso button:hover:after {
  border-color:#ff0c0c;
}

.rosso button:hover {
  color:#fff;
  background-color:#ff0c0c;
  border-color:#ff0c0c;
}

.rosso .pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}

.bianco button {
  color:#e8e8e8;
  border-color:#e8e8e8
}

.bianco button:before, .bianco button:after  {
  border-color:#e8e8e8
}

.bianco button:hover:before, .bianco button:hover:after {
  border-color:#e8e8e8;
}

.bianco button:hover {
  color:#000;
  background-color:#e8e8e8;
  border-color:#e8e8e8;
}

.bianco .pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}

.verde button {
  color:#e8e8e8;
  border-color:#e8e8e8
}

.verde button:before, .bianco button:after  {
  border-color:#e8e8e8
}

.verde button:hover:before, .bianco button:hover:after {
  border-color:#e8e8e8;
}

.verde button:hover {
  color:#000;
  background-color:#e8e8e8;
  border-color:#e8e8e8;
}

.verde .pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <body>
 <div class="pannello rosso">
    <button>TS3</button>
 </div>

 <div class="pannello bianco">
    <button>FORUM</button>
 </div>

 <div class="pannello verde">
    <button>BUYCRAFT</button>
 </div>

 </body></code>```

Thanks!

PS: If you can post the fiddle

答:
Use flex on the parent with justify-content: center; align-items: center; min-height: 100vh; to make the element at least the browser height, horizontally and vertically aligned. Then remove margin: auto from .pannello

@import 'https://fonts.googleapis.com/css?family=Comfortaa:300,400,700&subset=cyrillic,cyrillic-ext,latin-ext';

body {
  background: url(https://wallpaperscraft.com/image/black_background_pattern_light_texture_55291_1920x1080.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
button {
  color:#454545;
  width: 200px;
  background:transparent;
  border-width:2px;
  border-style: solid;
  border-color: #454545;
  position:relative;
  margin:1em;
  display:inline-block;
  padding:0.5em 1em;
  transition:all 0.3s ease-in-out;
  text-align:center;
  font-family:comfortaa;
  font-weight:bold
}

button:before, button:after{
  content:'';
  display:block;
  position:absolute;
  border-color:#454545;
  box-sizing:border-box;
  border-style:solid;
  width:1em;height:1em;
  transition:all 0.3s ease-in-out
}

button:before {
  top:-6px;left:-6px;
  border-width:2px 0 0 2px;
  z-index:5;
}

button:after {
  bottom:-6px;
  right:-6px;
  border-width:0 2px 2px 0;
}

button:hover:before, button:hover:after {
  width:calc(100% + 12px);
  height:calc(100% + 12px);
  border-color:#fff
}

button:hover {
  color:#353535;
  background-color:#fff;
  border-color:#fff
}

.pannello {
  max-width:960px;
  text-align:center;
  position:relative;
}

.rosso button {
  color:#ff0c0c;
  border-color:#ff0c0c
}

.rosso button:before, .rosso button:after  {
  border-color:#ff0c0c
}

.rosso button:hover:before, .rosso button:hover:after {
  border-color:#ff0c0c;
}

.rosso button:hover {
  color:#fff;
  background-color:#ff0c0c;
  border-color:#ff0c0c;
}

.rosso .pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}

.bianco button {
  color:#e8e8e8;
  border-color:#e8e8e8
}

.bianco button:before, .bianco button:after  {
  border-color:#e8e8e8
}

.bianco button:hover:before, .bianco button:hover:after {
  border-color:#e8e8e8;
}

.bianco button:hover {
  color:#000;
  background-color:#e8e8e8;
  border-color:#e8e8e8;
}

.bianco .pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}

.verde button {
  color:#e8e8e8;
  border-color:#e8e8e8
}

.verde button:before, .bianco button:after  {
  border-color:#e8e8e8
}

.verde button:hover:before, .bianco button:hover:after {
  border-color:#e8e8e8;
}

.verde button:hover {
  color:#000;
  background-color:#e8e8e8;
  border-color:#e8e8e8;
}

.verde .pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <body>
 <div class="pannello rosso">
    <button>TS3</button>
 </div>

 <div class="pannello bianco">
    <button>FORUM</button>
 </div>

 <div class="pannello verde">
    <button>BUYCRAFT</button>
 </div>

 </body></code>```

Body:
I want these 3 buttons to be vertically and horizontally aligned but when I try to align them, the last button is falling down and I don't know why. This is the original code without alignment, some one can help me?

@import 'https://fonts.googleapis.com/css?family=Comfortaa:300,400,700&subset=cyrillic,cyrillic-ext,latin-ext';

body {
  background: url(https://wallpaperscraft.com/image/black_background_pattern_light_texture_55291_1920x1080.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
button {
  color:#454545;
  width: 200px;
  background:transparent;
  border-width:2px;
  border-style: solid;
  border-color: #454545;
  position:relative;
  margin:1em;
  display:inline-block;
  padding:0.5em 1em;
  transition:all 0.3s ease-in-out;
  text-align:center;
  font-family:comfortaa;
  font-weight:bold
}

button:before, button:after{
  content:'';
  display:block;
  position:absolute;
  border-color:#454545;
  box-sizing:border-box;
  border-style:solid;
  width:1em;height:1em;
  transition:all 0.3s ease-in-out
}

button:before {
  top:-6px;left:-6px;
  border-width:2px 0 0 2px;
  z-index:5;
}

button:after {
  bottom:-6px;
  right:-6px;
  border-width:0 2px 2px 0;
}

button:hover:before, button:hover:after {
  width:calc(100% + 12px);
  height:calc(100% + 12px);
  border-color:#fff
}

button:hover {
  color:#353535;
  background-color:#fff;
  border-color:#fff
}

.pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}

.rosso button {
  color:#ff0c0c;
  border-color:#ff0c0c
}

.rosso button:before, .rosso button:after  {
  border-color:#ff0c0c
}

.rosso button:hover:before, .rosso button:hover:after {
  border-color:#ff0c0c;
}

.rosso button:hover {
  color:#fff;
  background-color:#ff0c0c;
  border-color:#ff0c0c;
}

.rosso .pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}

.bianco button {
  color:#e8e8e8;
  border-color:#e8e8e8
}

.bianco button:before, .bianco button:after  {
  border-color:#e8e8e8
}

.bianco button:hover:before, .bianco button:hover:after {
  border-color:#e8e8e8;
}

.bianco button:hover {
  color:#000;
  background-color:#e8e8e8;
  border-color:#e8e8e8;
}

.bianco .pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}

.verde button {
  color:#e8e8e8;
  border-color:#e8e8e8
}

.verde button:before, .bianco button:after  {
  border-color:#e8e8e8
}

.verde button:hover:before, .bianco button:hover:after {
  border-color:#e8e8e8;
}

.verde button:hover {
  color:#000;
  background-color:#e8e8e8;
  border-color:#e8e8e8;
}

.verde .pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}

    <button>TS3</button>

    <button>FORUM</button>

    <button>BUYCRAFT</button>

Thanks!

PS: If you can post the fiddle

Body:
Use flex on the parent with justify-content: center; align-items: center; min-height: 100vh; to make the element at least the browser height, horizontally and vertically aligned. Then remove margin: auto from .pannello

@import 'https://fonts.googleapis.com/css?family=Comfortaa:300,400,700&subset=cyrillic,cyrillic-ext,latin-ext';

body {
  background: url(https://wallpaperscraft.com/image/black_background_pattern_light_texture_55291_1920x1080.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
button {
  color:#454545;
  width: 200px;
  background:transparent;
  border-width:2px;
  border-style: solid;
  border-color: #454545;
  position:relative;
  margin:1em;
  display:inline-block;
  padding:0.5em 1em;
  transition:all 0.3s ease-in-out;
  text-align:center;
  font-family:comfortaa;
  font-weight:bold
}

button:before, button:after{
  content:'';
  display:block;
  position:absolute;
  border-color:#454545;
  box-sizing:border-box;
  border-style:solid;
  width:1em;height:1em;
  transition:all 0.3s ease-in-out
}

button:before {
  top:-6px;left:-6px;
  border-width:2px 0 0 2px;
  z-index:5;
}

button:after {
  bottom:-6px;
  right:-6px;
  border-width:0 2px 2px 0;
}

button:hover:before, button:hover:after {
  width:calc(100% + 12px);
  height:calc(100% + 12px);
  border-color:#fff
}

button:hover {
  color:#353535;
  background-color:#fff;
  border-color:#fff
}

.pannello {
  max-width:960px;
  text-align:center;
  position:relative;
}

.rosso button {
  color:#ff0c0c;
  border-color:#ff0c0c
}

.rosso button:before, .rosso button:after  {
  border-color:#ff0c0c
}

.rosso button:hover:before, .rosso button:hover:after {
  border-color:#ff0c0c;
}

.rosso button:hover {
  color:#fff;
  background-color:#ff0c0c;
  border-color:#ff0c0c;
}

.rosso .pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}

.bianco button {
  color:#e8e8e8;
  border-color:#e8e8e8
}

.bianco button:before, .bianco button:after  {
  border-color:#e8e8e8
}

.bianco button:hover:before, .bianco button:hover:after {
  border-color:#e8e8e8;
}

.bianco button:hover {
  color:#000;
  background-color:#e8e8e8;
  border-color:#e8e8e8;
}

.bianco .pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}

.verde button {
  color:#e8e8e8;
  border-color:#e8e8e8
}

.verde button:before, .bianco button:after  {
  border-color:#e8e8e8
}

.verde button:hover:before, .bianco button:hover:after {
  border-color:#e8e8e8;
}

.verde button:hover {
  color:#000;
  background-color:#e8e8e8;
  border-color:#e8e8e8;
}

.verde .pannello {
  max-width:960px;
  text-align:center;
  position:relative;
  margin:auto;
}

 <body>
 <div class="pannello rosso">
    <button>TS3</button>
 </div>

 <div class="pannello bianco">
    <button>FORUM</button>
 </div>

 <div class="pannello verde">
    <button>BUYCRAFT</button>
 </div>

 </body>


来源: stackexchange

问:
Sending a POST request with PHPUnit
I have a symfony website, and Im trying to do some unit testing. I have this kind of test where I try to submit something:

```<code><?php

namespace Acme\AcmeBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class HomeControllerTest extends WebTestCase {

    public function testrandomeThings() {

        $client = static::createClient();
        $crawler = $client->request(
            'POST',
            '/',
            array(
                "shopNumber"        => 0099,
                "cardNumber"        => 231,
                "cardPIN"           => "adasd"),
            array(),
            array());
        }
</code>```

but I dont think that the data Im sending is being received in the controler:

```<code>class HomeController extends Controller
{
    public function indexAction()
    {

        var_dump($_POST);
        die;
        return $this->render('AcmeBundle:Home:index.html.twig');
    }

}
</code>```

the var_dump is actually returning me an empty array.

What am I missing to send information through my POST request?

答:
I think you're trying to do this:

```<code>$client = static::createClient();
    $client->request($method, $url, [], [], [], json_encode($content));
    $this->assertEquals(
        200,
        $client->getResponse()
            ->getStatusCode()
    );
</code>```

You're putting your data (content) in as the params array but you want to put it in as the raw body content which is a JSON encoded string.

ContentLicense: CC BY-SA 3.0

Title: Sending a POST request with PHPUnit

Body:
I have a symfony website, and Im trying to do some unit testing. I have this kind of test where I try to submit something:

<?php

namespace Acme\AcmeBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class HomeControllerTest extends WebTestCase {

    public function testrandomeThings() {

        $client = static::createClient();
        $crawler = $client->request(
            'POST',
            '/',
            array(
                "shopNumber"        => 0099,
                "cardNumber"        => 231,
                "cardPIN"           => "adasd"),
            array(),
            array());
        }

but I dont think that the data Im sending is being received in the controler:

class HomeController extends Controller
{
    public function indexAction()
    {

        var_dump($_POST);
        die;
        return $this->render('AcmeBundle:Home:index.html.twig');
    }

}

the var_dump is actually returning me an empty array.

What am I missing to send information through my POST request?

Body:
I think you're trying to do this:

$client = static::createClient();
    $client->request($method, $url, [], [], [], json_encode($content));
    $this->assertEquals(
        200,
        $client->getResponse()
            ->getStatusCode()
    );

You're putting your data (content) in as the params array but you want to put it in as the raw body content which is a JSON encoded string.


问:
App : Cake change to own
i have not that much of idea regarding cakephp v2.8.0.I install cakephp through command through  terminal and when i type "cake" i get below statement

> Welcome to CakePHP v2.8.0 Console

App : Cake

Path: /usr/share/php/Cake/

Current Paths:

-app: Cake
 -working: /usr/share/php/Cake
 -root: /usr/share/php
 -core: /usr/share/php

Changing Paths:

Your working path should be the same as your application path. To change your path use the '-app' param.
Example: -app relative/path/to/myapp or -app /absolute/path/to/myapp

Available Shells:

I want to change " App : Cake " to "App : my_app".
  Please help

答: check this to complete your installation: CakePHP Shells, Tasks & Console Tools</p>

Title: App : Cake change to own


问:
Dynamically Updating A Tab Bar Item In the More ViewController Table
OK. I haven't actually seen how to do this anywhere. It may be a question of "You can't get there from here." or "Holy #@$! That is such a disgusting hack it should be taken behind the woodshed and shot!".

I have a tabbed Swift 3 iOS app that will dynamically update the Tab Bar images of selected pages as the page state changes.

I do that sort of like this:

```<code>if let navController = self.navigationController as? MyNavController {
    navController.tabBarItem.image = navController.tabBarImage
    navController.tabBarItem.selectedImage = navController.tabBarImage
}
</code>```

The tabBarImage is actually a calculated property. This snippet is called within a UI callback that updates when the state changes.

This works great.

When in the MoreViewController, though, not so great. Those images remain stubbornly static, no matter what I do.

I have done some exploration of the MoreViewController. I can get at the tableView and the cells, but that smells like the kind of hack that will get my app taken behind the woodshed by the Blue Meanies at App Review.

Is there a proper way to do this?

答: You can use Notification and pass the images within a Dictionary as a Notification object. Then you can get different tabBarImage with different key value at once.</p>

Body:
OK. I haven't actually seen how to do this anywhere. It may be a question of "You can't get there from here." or "Holy #@$! That is such a disgusting hack it should be taken behind the woodshed and shot!".

I have a tabbed Swift 3 iOS app that will dynamically update the Tab Bar images of selected pages as the page state changes.

I do that sort of like this:

if let navController = self.navigationController as? MyNavController {
    navController.tabBarItem.image = navController.tabBarImage
    navController.tabBarItem.selectedImage = navController.tabBarImage
}

The tabBarImage is actually a calculated property. This snippet is called within a UI callback that updates when the state changes.

This works great.

When in the MoreViewController, though, not so great. Those images remain stubbornly static, no matter what I do.

I have done some exploration of the MoreViewController. I can get at the tableView and the cells, but that smells like the kind of hack that will get my app taken behind the woodshed by the Blue Meanies at App Review.

Is there a proper way to do this?


问:
Laravel 5.4 - Sending mail in a loop
I would like to send mail to several person using Laravel 5.4

```<code>foreach($company->getAllAdministrators() as $admin){
    Mail::to($admin->email)->send($email);
}
</code>```

Problem

The first email would be to : admin1@mail.com

The second email would be to : admin1@mail.com admin2@mail.com

Question

What is the right way to send the email to all recipients without adding them in the to. I do not want a admin to be able to see other recipients.

答:
Assuming your getAllAdministrators() method is returning Users you can use the bcc method on the Mail class. The bcc method accepts an email address, a user instance, or a collection of users. For example:

```<code>Mail::to('admins@mydomain.com')
    ->bcc($company->getAllAdministrators())
    ->send($email);
</code>```

Where admins@mydomain.com is simply a generic email address of your choice (it's also a good way to confirm delivery on your end).

Title: Laravel 5.4 - Sending mail in a loop

Body:
I would like to send mail to several person using Laravel 5.4

foreach($company->getAllAdministrators() as $admin){
    Mail::to($admin->email)->send($email);
}

Problem

The first email would be to : admin1@mail.com

The second email would be to : admin1@mail.com admin2@mail.com

Question

What is the right way to send the email to all recipients without adding them in the to. I do not want a admin to be able to see other recipients.

Body:
Assuming your getAllAdministrators() method is returning Users you can use the bcc method on the Mail class. The bcc method accepts an email address, a user instance, or a collection of users. For example:

Mail::to('admins@mydomain.com')
    ->bcc($company->getAllAdministrators())
    ->send($email);

Where admins@mydomain.com is simply a generic email address of your choice (it's also a good way to confirm delivery on your end).


问:
Where does finite-state machine code belong in µC?
I asked this question on EE forum. You guys on StackOverflow know more about coding than we do on EE so maybe you can give more detail information about this :)

When I learned about micrcontrollers, teachers taught me to always end the code with  while(1); with no code inside that loop.

This was to be sure that the software get "stuck" to keep interruption working. When I asked them if it was possible to put some code in this infinite loop, they told me it was a bad idea. Knowing that, I now try my best to keep this loop empty.

I now need to implement a finite state machine in a microcontroller. At first view, it seems that that code belong in this loop. That makes coding easier.

Is that a good idea? What are the pros and cons?

This is what I plan to do :

```<code>void main(void)
{
    // init phase

 while(1)
 {
    switch(current_State)
    {
    case 1:
        if(...)
        {
            current_State = 2;
        }
        else(...)
        {
            current_State = 3;
        }
        else
            current_State = 4;
        break;

    case 2:
        if(...)
        {
            current_State = 3;
        }
        else(...)
        {
            current_State = 1;
        }
        else
            current_State = 5;
        break;
   }
}
</code>```

Instead of:

```<code> void main(void)
    {
        // init phase

     while(1);
    }
</code>```

And manage the FSM with interrupt

答:
When doing embedded programming, one commonly used idiom is to use a "super loop" - an infinite loop that begins after initialization is complete that dispatches the separate components of your program as they need to run. Under this paradigm, you could run the finite state machine within the super loop as you're suggesting, and continue to run the hardware management functions from the interrupt context as it sounds like you're already doing. One of the disadvantages to doing this is that your processor will always be in a high power draw state - since you're always running that loop, the processor can never go to sleep. This would actually also be a problem in any of the code you had written however - even an empty infinite while loop will keep the processor running. The solution to this is usually to end your while loop with a series of instructions to put the processor into a low power state (completely architecture dependent) that will wake it when an interrupt comes through to be processed. If there are things happening in the FSM that are not driven by any interrupts, a normally used approach to keep the processor waking up at periodic intervals is to initialize a timer to interrupt on a regular basis to cause your main loop to continue execution.

One other thing to note, if you were previously executing all of your code from the interrupt context - interrupt service routines (ISRs) really should be as short as possible, because they literally "interrupt" the main execution of the program, which may cause unintended side effects if they take too long. A normal way to handle this is to have handlers in your super loop that are just signalled to by the ISR, so that the bulk of whatever processing that needs to be done is done in the main context when there is time, rather than interrupting a potentially time critical section of your main context.

Body:
I asked this question on EE forum. You guys on StackOverflow know more about coding than we do on EE so maybe you can give more detail information about this :)

When I learned about micrcontrollers, teachers taught me to always end the code with  while(1); with no code inside that loop.

This was to be sure that the software get "stuck" to keep interruption working. When I asked them if it was possible to put some code in this infinite loop, they told me it was a bad idea. Knowing that, I now try my best to keep this loop empty.

I now need to implement a finite state machine in a microcontroller. At first view, it seems that that code belong in this loop. That makes coding easier.

Is that a good idea? What are the pros and cons?

This is what I plan to do :

void main(void)
{
    // init phase

 while(1)
 {
    switch(current_State)
    {
    case 1:
        if(...)
        {
            current_State = 2;
        }
        else(...)
        {
            current_State = 3;
        }
        else
            current_State = 4;
        break;

    case 2:
        if(...)
        {
            current_State = 3;
        }
        else(...)
        {
            current_State = 1;
        }
        else
            current_State = 5;
        break;
   }
}

Instead of:

 void main(void)
    {
        // init phase

     while(1);
    }

And manage the FSM with interrupt


问:
cmake generate Xcode project from existing sources
This is what I have, when I started generation:

```<code>iMac:IXCSoftswitch alex$ /usr/bin/cmake -G Xcode .
-- CMAKE_SOURCE_DIR = /Users/alex/Desktop/ixc-v/IXCSoftswitch,   CMAKE_BINARY_DIR = /Users/alex/Desktop/ixc-v/IXCSoftswitch
CMake Error at CMakeLists.txt:25 (MESSAGE):
  Binary and source directory cannot be the same

-- Configuring incomplete, errors occurred!
</code>```

How can I fix it? I'm new to CMake, samples appreciated.

答:
From the root of your project directory.

```<code>cmake -G Xcode -H. -B_build
</code>```

This is similar to the answer above. However, you are manually managing the out of source build. -B sets your target build directory (I happen to prefer _build). I tried looking up -H to double check, but couldn't find it. If memory serves, it specifies where your CMakeLists.txt lives.

I keep this command in a .sh/.bat file (depending). This way, I can keep my scripts that build my project in the root where a new person can easily find them.

ContentLicense: CC BY-SA 4.0

Body:
This is what I have, when I started generation:

iMac:IXCSoftswitch alex$ /usr/bin/cmake -G Xcode .
-- CMAKE_SOURCE_DIR = /Users/alex/Desktop/ixc-v/IXCSoftswitch,   CMAKE_BINARY_DIR = /Users/alex/Desktop/ixc-v/IXCSoftswitch
CMake Error at CMakeLists.txt:25 (MESSAGE):
  Binary and source directory cannot be the same

-- Configuring incomplete, errors occurred!

How can I fix it? I'm new to CMake, samples appreciated.

Body:
From the root of your project directory.

cmake -G Xcode -H. -B_build

This is similar to the answer above. However, you are manually managing the out of source build. -B sets your target build directory (I happen to prefer _build). I tried looking up -H to double check, but couldn't find it. If memory serves, it specifies where your CMakeLists.txt lives.

I keep this command in a .sh/.bat file (depending). This way, I can keep my scripts that build my project in the root where a new person can easily find them.


问:
Align the table on the center of the page
I just want to put the table in the middle of the page. Any help would be great.</p>

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Randy's first html web page !</title>
<style type="text/css">
body
{background-image:url('Koala.gif');}
h1
{
text-align:center;
}
h2
{
text-align:center;
}
p
{
text-align:center;
font-size:200%;
color:#00fff0;
}
div
{
background-color:#efffff;
}
</style>
</head>
<h1> Hello Professor</h1>
<h2> By: Randy White</h2>
<P> I haven't done anything like this before.</P>
<P>Seems to be ok</P>
<P><img src="Hydrangeas.jpg" width="150" height="100" alt="Hydrangeas.jpg"></P>
<table border="1">
<tr>
<th>Month</th>
<th>Day</th>
<th>Year</th>
</tr>
<tr>
<td>December</td>
<td>1</td>
<td>2010</td>
</tr>
</table>
<a href="http://www.google.com">Visit Google!</a>
</body>
</html>
</code>```

答:
old style is align="center":</p>

```<code><table width="400" border="0" cellspacing="0" cellpadding="0" align="center">
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I just want to put the table in the middle of the page. Any help would be great.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">

<title>Randy's first html web page !</title>

 Hello Professor

 By: Randy White

 I haven't done anything like this before.

Seems to be ok

Month
Day
Year

December
1
2010

Visit Google!

Body:
old style is align="center":

<table width="400" border="0" cellspacing="0" cellpadding="0" align="center">


问:
Why do these Japanese characters have different top values?
I'm trying to figure out why the div with "コンシェルジュ" has a different top than the divs that contain "警備" and "洗濯".  You'll have to actually run the code snippet to see what I mean but on the first row the first row has a top 3 pixels above the second and third div on that row... I'm at a loss for why.  Is this a language thing?  How do I make them have the same top, in a natural sense?  I don't want to use Javascript to force the tops to be the same, because I'm using the top values already to determine what row a content div is in, so that could become circular.

There is an English version of this where only difference is the content's verbiage and in English (and Mandarin and Korean) and I do not have this problem.  It seems to be something unique to Japanese lettering, is there something I have to account for with Japanese?

.DemoQuest {
    text-align: center;
    font-family: Verlag, Arial;
    color: white;
    background: black;
}

.DemoQuest .Span {
    margin-right: 1%;
    margin-left: 2.5%;
    text-align: center;
}

.ResponseSet {
    margin-left: 2%;
    margin-right: 2%;
}

.DemoResp {
    display: inline-block;
    padding-top: .5%;
    padding-bottom: .5%;
    width: 32%;
}

.ResponseText {
    display: none;
}

input {
    display: none;
}

.DemoResp .Wrapper {
    text-align: center;
    vertical-align: top;
    background-color: #C4C4C4;
    border-radius: 3px;
    color: black;
    padding: 8px 8px;
    padding-top: 8px;
    transition-duration: 0.4s;
    font-size: 16px;
    vertical-align: middle;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    -o-user-select: none;
    user-select: none;
    cursor: pointer;
}

.DemoQuest .DemoResp .Selector .Wrapper {
    display: grid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="d2929b66837440708d3db2ed658ca0c6" class="DemoQuest">
  <div class="Span">以下、ホテル内でご利用いただいたサービスをお選び下さい</div>
  <div class="ResponseSet Below">
   <div id="96e3902628074785a3065df70c644566" class="DemoResp">
    <span class="Selector"><input type="checkbox" id="cb_96e3902628074785a3065df70c644566" name="cb_96e3902628074785a3065df70c644566" value="1"><div id="123" class="Wrapper"><div class="ResponseContent">コンシェルジュ</div></div></span>
    <span class="ResponseText">コンシェルジュ</span>
   </div>
   <div id="8d69877355cd4f05a4db3539c2f67fd6" class="DemoResp">
    <span class="Selector"><input type="checkbox" id="cb_8d69877355cd4f05a4db3539c2f67fd6" name="cb_8d69877355cd4f05a4db3539c2f67fd6" value="1"><div id="123" class="Wrapper"  for="cb_8d69877355cd4f05a4db3539c2f67fd6"><div class="ResponseContent">警備</div></div></span>
    <span class="ResponseText">警備</span>
   </div>
   <div id="de5a147b403f43568d44169142ae4a98" class="DemoResp">
    <span class="Selector"><input type="checkbox" id="cb_de5a147b403f43568d44169142ae4a98" name="cb_de5a147b403f43568d44169142ae4a98" value="1"><div id="123" class="Wrapper"  for="cb_de5a147b403f43568d44169142ae4a98"><div class="ResponseContent">洗濯</div></div></span>
    <span class="ResponseText">洗濯</span>
   </div>
   <div id="346cb8895aa34c4ebf879814f197e866" class="DemoResp">
    <span class="Selector"><input type="checkbox" id="cb_346cb8895aa34c4ebf879814f197e866" name="cb_346cb8895aa34c4ebf879814f197e866" value="1" ><div id="123" class="Wrapper"  for="cb_346cb8895aa34c4ebf879814f197e866"><div class="ResponseContent" style="height: 52px; top: 13px;">お土産屋</div></div></span>
    <span class="ResponseText">お土産屋</span>
   </div>
   <div id="6750438a3faf49a8afbbca7c23289a42" class="DemoResp">
    <span class="Selector"><input type="checkbox" id="cb_6750438a3faf49a8afbbca7c23289a42" name="cb_6750438a3faf49a8afbbca7c23289a42" value="1" ><div id="123" class="Wrapper"><div class="ResponseContent">バンニャンツリースパ</div></div></span>
    <span class="ResponseText">バンニャンツリースパ</span>
   </div>
   <div id="fd64fa6d551848d18943f7210633045b" class="DemoResp">
    <span class="Selector"><input type="checkbox" id="cb_fd64fa6d551848d18943f7210633045b" name="cb_fd64fa6d551848d18943f7210633045b" value="1"><div id="123" class="Wrapper"  for="cb_fd64fa6d551848d18943f7210633045b"><div class="ResponseContent">フィットネスセンター</div></div></span>
    <span class="ResponseText">フィットネスセンター</span>
   </div>
  </div>
 </div></code>```

答:
.DemoQuest {
    text-align: center;
    font-family: Verlag, Arial;
    color: white;
    background: black;
}

.DemoQuest .Span {
    margin-right: 1%;
    margin-left: 2.5%;
    text-align: center;
}

.ResponseSet {
    margin-left: 2%;
    margin-right: 2%;
}

.DemoResp {
    display: inline-block;
    padding-top: .5%;
    padding-bottom: .5%;
    width: 32%;
}

.ResponseText {
    display: none;
}

input {
    display: none;
}

.DemoResp .Wrapper {
    text-align: center;
    vertical-align: top;
    background-color: #C4C4C4;
    border-radius: 3px;
    color: black;
    height: 30px; /* <-- this is what i have add*/
    padding: 8px 8px;
    padding-top: 8px;
    transition-duration: 0.4s;
    font-size: 15px;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    -o-user-select: none;
    user-select: none;
    cursor: pointer;
}

.DemoQuest .DemoResp .Selector .Wrapper {
    display: grid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="d2929b66837440708d3db2ed658ca0c6" class="DemoQuest">
  <div class="Span">以下、ホテル内でご利用いただいたサービスをお選び下さい</div>
  <div class="ResponseSet Below">
   <div id="96e3902628074785a3065df70c644566" class="DemoResp">
    <span class="Selector"><input type="checkbox" id="cb_96e3902628074785a3065df70c644566" name="cb_96e3902628074785a3065df70c644566" value="1"><div id="123" class="Wrapper"><div class="ResponseContent">コンシェルジュ</div></div></span>
    <span class="ResponseText">コンシェルジュ</span>
   </div>
   <div id="8d69877355cd4f05a4db3539c2f67fd6" class="DemoResp">
    <span class="Selector"><input type="checkbox" id="cb_8d69877355cd4f05a4db3539c2f67fd6" name="cb_8d69877355cd4f05a4db3539c2f67fd6" value="1"><div id="123" class="Wrapper"  for="cb_8d69877355cd4f05a4db3539c2f67fd6"><div class="ResponseContent">警備</div></div></span>
    <span class="ResponseText">警備</span>
   </div>
   <div id="de5a147b403f43568d44169142ae4a98" class="DemoResp">
    <span class="Selector"><input type="checkbox" id="cb_de5a147b403f43568d44169142ae4a98" name="cb_de5a147b403f43568d44169142ae4a98" value="1"><div id="123" class="Wrapper"  for="cb_de5a147b403f43568d44169142ae4a98"><div class="ResponseContent">洗濯</div></div></span>
    <span class="ResponseText">洗濯</span>
   </div>
   <div id="346cb8895aa34c4ebf879814f197e866" class="DemoResp">
    <span class="Selector"><input type="checkbox" id="cb_346cb8895aa34c4ebf879814f197e866" name="cb_346cb8895aa34c4ebf879814f197e866" value="1" ><div id="123" class="Wrapper"  for="cb_346cb8895aa34c4ebf879814f197e866"><div class="ResponseContent" style="height: 52px; top: 13px;">お土産屋</div></div></span>
    <span class="ResponseText">お土産屋</span>
   </div>
   <div id="6750438a3faf49a8afbbca7c23289a42" class="DemoResp">
    <span class="Selector"><input type="checkbox" id="cb_6750438a3faf49a8afbbca7c23289a42" name="cb_6750438a3faf49a8afbbca7c23289a42" value="1" ><div id="123" class="Wrapper"><div class="ResponseContent">バンニャンツリースパ</div></div></span>
    <span class="ResponseText">バンニャンツリースパ</span>
   </div>
   <div id="fd64fa6d551848d18943f7210633045b" class="DemoResp">
    <span class="Selector"><input type="checkbox" id="cb_fd64fa6d551848d18943f7210633045b" name="cb_fd64fa6d551848d18943f7210633045b" value="1"><div id="123" class="Wrapper"  for="cb_fd64fa6d551848d18943f7210633045b"><div class="ResponseContent">フィットネスセンター</div></div></span>
    <span class="ResponseText">フィットネスセンター</span>
   </div>
  </div>
 </div></code>```

Body:
I'm trying to figure out why the div with "コンシェルジュ" has a different top than the divs that contain "警備" and "洗濯".  You'll have to actually run the code snippet to see what I mean but on the first row the first row has a top 3 pixels above the second and third div on that row... I'm at a loss for why.  Is this a language thing?  How do I make them have the same top, in a natural sense?  I don't want to use Javascript to force the tops to be the same, because I'm using the top values already to determine what row a content div is in, so that could become circular.

There is an English version of this where only difference is the content's verbiage and in English (and Mandarin and Korean) and I do not have this problem.  It seems to be something unique to Japanese lettering, is there something I have to account for with Japanese?

.DemoQuest {
    text-align: center;
    font-family: Verlag, Arial;
    color: white;
    background: black;
}

.DemoQuest .Span {
    margin-right: 1%;
    margin-left: 2.5%;
    text-align: center;
}

.ResponseSet {
    margin-left: 2%;
    margin-right: 2%;
}

.DemoResp {
    display: inline-block;
    padding-top: .5%;
    padding-bottom: .5%;
    width: 32%;
}

.ResponseText {
    display: none;
}

input {
    display: none;
}

.DemoResp .Wrapper {
    text-align: center;
    vertical-align: top;
    background-color: #C4C4C4;
    border-radius: 3px;
    color: black;
    padding: 8px 8px;
    padding-top: 8px;
    transition-duration: 0.4s;
    font-size: 16px;
    vertical-align: middle;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    -o-user-select: none;
    user-select: none;
    cursor: pointer;
}

.DemoQuest .DemoResp .Selector .Wrapper {
    display: grid;
}

以下、ホテル内でご利用いただいたサービスをお選び下さい

    <input type="checkbox" id="cb_96e3902628074785a3065df70c644566" name="cb_96e3902628074785a3065df70c644566" value="1">

コンシェルジュ

    コンシェルジュ

    <input type="checkbox" id="cb_8d69877355cd4f05a4db3539c2f67fd6" name="cb_8d69877355cd4f05a4db3539c2f67fd6" value="1">

警備

    警備

    <input type="checkbox" id="cb_de5a147b403f43568d44169142ae4a98" name="cb_de5a147b403f43568d44169142ae4a98" value="1">

洗濯

    洗濯

    <input type="checkbox" id="cb_346cb8895aa34c4ebf879814f197e866" name="cb_346cb8895aa34c4ebf879814f197e866" value="1" >

お土産屋

    お土産屋

    <input type="checkbox" id="cb_6750438a3faf49a8afbbca7c23289a42" name="cb_6750438a3faf49a8afbbca7c23289a42" value="1" >

バンニャンツリースパ

    バンニャンツリースパ

    <input type="checkbox" id="cb_fd64fa6d551848d18943f7210633045b" name="cb_fd64fa6d551848d18943f7210633045b" value="1">

フィットネスセンター

    フィットネスセンター

Body:
.DemoQuest {
    text-align: center;
    font-family: Verlag, Arial;
    color: white;
    background: black;
}

.DemoQuest .Span {
    margin-right: 1%;
    margin-left: 2.5%;
    text-align: center;
}

.ResponseSet {
    margin-left: 2%;
    margin-right: 2%;
}

.DemoResp {
    display: inline-block;
    padding-top: .5%;
    padding-bottom: .5%;
    width: 32%;
}

.ResponseText {
    display: none;
}

input {
    display: none;
}

.DemoResp .Wrapper {
    text-align: center;
    vertical-align: top;
    background-color: #C4C4C4;
    border-radius: 3px;
    color: black;
    height: 30px; /* <-- this is what i have add*/
    padding: 8px 8px;
    padding-top: 8px;
    transition-duration: 0.4s;
    font-size: 15px;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    -o-user-select: none;
    user-select: none;
    cursor: pointer;
}

.DemoQuest .DemoResp .Selector .Wrapper {
    display: grid;
}

<div id="d2929b66837440708d3db2ed658ca0c6" class="DemoQuest">
  <div class="Span">以下、ホテル内でご利用いただいたサービスをお選び下さい</div>
  <div class="ResponseSet Below">
   <div id="96e3902628074785a3065df70c644566" class="DemoResp">
    <span class="Selector"><input type="checkbox" id="cb_96e3902628074785a3065df70c644566" name="cb_96e3902628074785a3065df70c644566" value="1"><div id="123" class="Wrapper"><div class="ResponseContent">コンシェルジュ</div></div></span>
    <span class="ResponseText">コンシェルジュ</span>
   </div>
   <div id="8d69877355cd4f05a4db3539c2f67fd6" class="DemoResp">
    <span class="Selector"><input type="checkbox" id="cb_8d69877355cd4f05a4db3539c2f67fd6" name="cb_8d69877355cd4f05a4db3539c2f67fd6" value="1"><div id="123" class="Wrapper"  for="cb_8d69877355cd4f05a4db3539c2f67fd6"><div class="ResponseContent">警備</div></div></span>
    <span class="ResponseText">警備</span>
   </div>
   <div id="de5a147b403f43568d44169142ae4a98" class="DemoResp">
    <span class="Selector"><input type="checkbox" id="cb_de5a147b403f43568d44169142ae4a98" name="cb_de5a147b403f43568d44169142ae4a98" value="1"><div id="123" class="Wrapper"  for="cb_de5a147b403f43568d44169142ae4a98"><div class="ResponseContent">洗濯</div></div></span>
    <span class="ResponseText">洗濯</span>
   </div>
   <div id="346cb8895aa34c4ebf879814f197e866" class="DemoResp">
    <span class="Selector"><input type="checkbox" id="cb_346cb8895aa34c4ebf879814f197e866" name="cb_346cb8895aa34c4ebf879814f197e866" value="1" ><div id="123" class="Wrapper"  for="cb_346cb8895aa34c4ebf879814f197e866"><div class="ResponseContent" style="height: 52px; top: 13px;">お土産屋</div></div></span>
    <span class="ResponseText">お土産屋</span>
   </div>
   <div id="6750438a3faf49a8afbbca7c23289a42" class="DemoResp">
    <span class="Selector"><input type="checkbox" id="cb_6750438a3faf49a8afbbca7c23289a42" name="cb_6750438a3faf49a8afbbca7c23289a42" value="1" ><div id="123" class="Wrapper"><div class="ResponseContent">バンニャンツリースパ</div></div></span>
    <span class="ResponseText">バンニャンツリースパ</span>
   </div>
   <div id="fd64fa6d551848d18943f7210633045b" class="DemoResp">
    <span class="Selector"><input type="checkbox" id="cb_fd64fa6d551848d18943f7210633045b" name="cb_fd64fa6d551848d18943f7210633045b" value="1"><div id="123" class="Wrapper"  for="cb_fd64fa6d551848d18943f7210633045b"><div class="ResponseContent">フィットネスセンター</div></div></span>
    <span class="ResponseText">フィットネスセンター</span>
   </div>
  </div>
 </div>


问:
Host WiFi connection not working when VM is on
I have a Kali VM on VMWare and when I have it on the VM's internet connection works, but my host machine's doesn't

The VM is using a bridged network adapter and my host machine is a Mid-2012 MacBook Pro running Windows.

答: Ok so what I did was simple all I did was change the adapter to NAT.</p>


问:
Why does the root motion animation make the prefab move in the opposite direction?
So basically I want to make a prefab (a cat) climb a wall, I wanna do it with basic root motion animation. Since I am new with unity and is my first time doing this I decided that I need to do a little bit of testing without any complicated animations, that being said, I made a simple animation, just moving the cat prefab, in the animation clip, the cat is moving on the +z axis.

HOWEVER, when I check the "root motion" check box and I click "Generate root motion curves" , instead of moving on the +z axis the cat is now moving on the -z axis, even if the cat is animated to move on the +z axis. Why is this happening and how can I fix it?

答: I found the problem, I only used the position of the object in the unity animation, using the position PLUS the rotation will fix the problem.</p>


问:
which is faster in spark, collect() or toLocalIterator()
I have a spark application in which I need to get the data from executors to driver and I am using collect(). However, I also came across toLocalIterator(). As far as I have read about toLocalIterator() on Internet, it returns an iterator rather than sending whole RDD instantly, so it has better memory performance, but what about speed? How is the performance between collect() and toLocalIterator() when it comes to execution/computation time?

答:
As for the toLocalIterator, it is used to collect the data from the RDD scattered around your cluster into one only node, the one from which the program is running, and do something with all the data in the same node. It is similar to the collect method, but instead of returning a List it will return an Iterator.

So, after applying a function to an RDD using foreach you can call toLocalIterator to get an iterator to all the contents of the RDD and process it. However, bear in mind that if your RDD is very big, you may have memory issues. If you want to transform it to an RDD again after doing the operations you need, use the SparkContext to parallelize it.


答:
As me understand, you have to add vertical-align: top to your .DemoResp css to fix this problem.

```<code>.DemoResp {
    display: inline-block;
    padding-top: .5%;
    padding-bottom: .5%;
    width: 32%;
    vertical-align: top;
}
</code>```

Title: Why do these Japanese characters have different top values?

Body:
As me understand, you have to add vertical-align: top to your .DemoResp css to fix this problem.

.DemoResp {
    display: inline-block;
    padding-top: .5%;
    padding-bottom: .5%;
    width: 32%;
    vertical-align: top;
}


问:
read data file with mixed numbers and texts in r
I have data files that contain the following:
the first 10 columns are numbers, the last column is text. They are separated by space. The problem is that the text in the last column may also contain space. So when I used read.table() I got the following error:

```<code>Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec,  :
line 21 did not have 11 elements
</code>```

what's the easiest way of reading the first 10 columns into a data matrix, and the last column into a string vector? Should I use readLines() first then process it?

答:
The following solved my problem:

```<code>nc <- max(count.fields(fname), sep = " ")
data <- read.table(fname, fill = T, col.names = paste0("V", seq_len(nc)), sep = " ", header = F)
</code>```

Then the first 10 columns will be the numeric results I want and the remaining nc-10 columns can be combined into one string vector.
The most helpful post is:
How can you read a CSV file in R with different number of columns

Body:
I have data files that contain the following:
the first 10 columns are numbers, the last column is text. They are separated by space. The problem is that the text in the last column may also contain space. So when I used read.table() I got the following error:

Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec,  :
line 21 did not have 11 elements

what's the easiest way of reading the first 10 columns into a data matrix, and the last column into a string vector? Should I use readLines() first then process it?

Body:
The following solved my problem:

nc <- max(count.fields(fname), sep = " ")
data <- read.table(fname, fill = T, col.names = paste0("V", seq_len(nc)), sep = " ", header = F)

Then the first 10 columns will be the numeric results I want and the remaining nc-10 columns can be combined into one string vector.
The most helpful post is:
How can you read a CSV file in R with different number of columns


问:
How to Pass Parameters to a client executable in a link
If I have a link in my page of the form:

```<code><A HREF="/executable.exe?param=1">Run</A>
</code>```

Are the parameters after the "?" passed to the executable after the browser has downloaded the executable, and the user has chosen to run the executable?

I have examined argv, and the environment, but doesn't seem to be there.

Is there any other place where the browser might be passing the parameters to the executable?

答:
The parameters are just part of the url request.

What is done server side with it is completely up to you.

But if you expect the client to execute the file with those params, it will not work.

The file won't be executed at all but only downloaded, and that probably with a warning (in modern systems)

Once the file is Downloaded and the client executes it, it is just up the the client how he executes it. Nothing to do with your params any more

There is however a hack in early versions of internet explorer 5 or even 6 but I won't talk about that here because it has no relevancy any more and is only an harmful expoit.

Body:
If I have a link in my page of the form:

Run

Are the parameters after the "?" passed to the executable after the browser has downloaded the executable, and the user has chosen to run the executable?

I have examined argv, and the environment, but doesn't seem to be there.

Is there any other place where the browser might be passing the parameters to the executable?


问:
swift 3 facebook integration
trying to get Facebook connect working from a swift project.

Have been trying to follow along the following youtube video: https://www.youtube.com/watch?v=I6rTmfLp9aY

which unfortunately for me is in German.

so this is what I have so far:

I have my Facebook app with IOS enabled enabled and I planted my bundleID there.

Downloaded latest iOS framework and added to project

to the AppDelegate file I added:

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    FBSDKApplicationDelegate.sharedInstance()
    return true
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    FBSDKAppEvents.activateApp()
}
</code>```

and this is the ViewController file

```<code>import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import FBSDKShareKit

class ViewController: UIViewController, FBSDKAppInviteDialogDelegate, FBSDKLoginButtonDelegate{

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

              if (FBSDKAccessToken.current() != nil)
        {
            let content = FBSDKAppInviteContent()
            content.appLinkURL = NSURL(string: "{Facebook link to app}") as URL!
            FBSDKAppInviteDialog.show(from: self, with: content, delegate: self)
        }
        else
        {
            let loginView : FBSDKLoginButton = FBSDKLoginButton()
            self.view.addSubview(loginView)
            loginView.center = CGPoint(x: self.view.frame.midX, y: self.view.frame.midY + 100)
            loginView.readPermissions = ["public_profile", "email"]
        }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func appInviteDialog (_ appInviteDialog: FBSDKAppInviteDialog!, didCompleteWithResults results: [AnyHashable : Any]!)
{

}

func appInviteDialog (_ appInviteDialog: FBSDKAppInviteDialog!, didFailWithError  error: Error!) {
    print("Error took place in appInviteDialog \(error)")
}

func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {

    if ((error) != nil)
    {
        //process error
    }
    else if result.isCancelled {
        //handle cancelation
    }
    else {

        let content = FBSDKAppInviteContent()
        content.appLinkURL = NSURL(string: "{Facebook link to app}") as URL!
        FBSDKAppInviteDialog.show(from: self, with: content, delegate: self)

        if result.grantedPermissions.contains("email")
        {
            //do work
        }
    }
}

func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {

}

}
</code>```

No errors and no alerts. When i run simulator I get an empty screen. Must be doing something right cause I get the following msg:

SystemGroup/systemgroup.com.apple.configurationprofiles
2017-06-04 00:42:02.351876+0300 facebook_login[4569:144075] [MC] Reading from private effective user settings.

also, if I just paste in viewDidLoad the following lines from the code:

```<code>            let loginView : FBSDKLoginButton = FBSDKLoginButton()
            self.view.addSubview(loginView)
            loginView.center = CGPoint(x: self.view.frame.midX, y: self.view.frame.midY + 100)
            loginView.readPermissions = ["public_profile", "email"]
</code>```

I get a beautiful Facebook button in simulator that of course crashes when i press it.

any help to  work will be greatly appreciated

答:
Facebook has a Swift SDK you might find easier to use than the Objective-C one (which they just call iOS). Try looking around the documentation here:

https://developers.facebook.com/docs/swift

Also, follow the steps described in the (other) iOS SDK to get started:

https://developers.facebook.com/docs/ios/getting-started/

This is the minimal app delegate I could get to work (notice the Swift SDK is missing the FB prefixes that exist in the iOS SDK):

```<code>import UIKit
import FacebookCore

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
        SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
        return true
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        return SDKApplicationDelegate.shared.application(app, open: url, options: options)
    }

}
</code>```

And be sure to add all the required keys in your Info.plist or else you won't get authentication to work at all.

Title: swift 3 facebook integration

Body:
trying to get Facebook connect working from a swift project.

Have been trying to follow along the following youtube video: https://www.youtube.com/watch?v=I6rTmfLp9aY

which unfortunately for me is in German.

so this is what I have so far:

I have my Facebook app with IOS enabled enabled and I planted my bundleID there.

Downloaded latest iOS framework and added to project

to the AppDelegate file I added:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    FBSDKApplicationDelegate.sharedInstance()
    return true
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    FBSDKAppEvents.activateApp()
}

and this is the ViewController file

import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import FBSDKShareKit

class ViewController: UIViewController, FBSDKAppInviteDialogDelegate, FBSDKLoginButtonDelegate{

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

              if (FBSDKAccessToken.current() != nil)
        {
            let content = FBSDKAppInviteContent()
            content.appLinkURL = NSURL(string: "{Facebook link to app}") as URL!
            FBSDKAppInviteDialog.show(from: self, with: content, delegate: self)
        }
        else
        {
            let loginView : FBSDKLoginButton = FBSDKLoginButton()
            self.view.addSubview(loginView)
            loginView.center = CGPoint(x: self.view.frame.midX, y: self.view.frame.midY + 100)
            loginView.readPermissions = ["public_profile", "email"]
        }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func appInviteDialog (_ appInviteDialog: FBSDKAppInviteDialog!, didCompleteWithResults results: [AnyHashable : Any]!)
{

}

func appInviteDialog (_ appInviteDialog: FBSDKAppInviteDialog!, didFailWithError  error: Error!) {
    print("Error took place in appInviteDialog \(error)")
}

func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {

    if ((error) != nil)
    {
        //process error
    }
    else if result.isCancelled {
        //handle cancelation
    }
    else {

        let content = FBSDKAppInviteContent()
        content.appLinkURL = NSURL(string: "{Facebook link to app}") as URL!
        FBSDKAppInviteDialog.show(from: self, with: content, delegate: self)

        if result.grantedPermissions.contains("email")
        {
            //do work
        }
    }
}

func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {

}

}

No errors and no alerts. When i run simulator I get an empty screen. Must be doing something right cause I get the following msg:

SystemGroup/systemgroup.com.apple.configurationprofiles
2017-06-04 00:42:02.351876+0300 facebook_login[4569:144075] [MC] Reading from private effective user settings.

also, if I just paste in viewDidLoad the following lines from the code:

            let loginView : FBSDKLoginButton = FBSDKLoginButton()
            self.view.addSubview(loginView)
            loginView.center = CGPoint(x: self.view.frame.midX, y: self.view.frame.midY + 100)
            loginView.readPermissions = ["public_profile", "email"]

I get a beautiful Facebook button in simulator that of course crashes when i press it.

any help to  work will be greatly appreciated

Body:
Facebook has a Swift SDK you might find easier to use than the Objective-C one (which they just call iOS). Try looking around the documentation here:

https://developers.facebook.com/docs/swift

Also, follow the steps described in the (other) iOS SDK to get started:

https://developers.facebook.com/docs/ios/getting-started/

This is the minimal app delegate I could get to work (notice the Swift SDK is missing the FB prefixes that exist in the iOS SDK):

import UIKit
import FacebookCore

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
        SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
        return true
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        return SDKApplicationDelegate.shared.application(app, open: url, options: options)
    }

}

And be sure to add all the required keys in your Info.plist or else you won't get authentication to work at all.


问:
Sending an image via POST in a Swift Playground
I try to send an image to the MS Cognitive Services Visions API in a Swift Playground.

The message I get as response is:

Response ["requestId": …, "code": InternalServerError, "message": Internal server error.]

Here is the code I use

```<code>let image = #imageLiteral(resourceName: "paper.jpg")
let imageData = UIImageJPEGRepresentation(image, 1)!

let endpoint = ("https://westeurope.api.cognitive.microsoft.com/vision/v1.0/analyze?visualFeatures=Description,Categories,Tags&subscription-key=\(subscriptionKey)")

let requestURL = URL(string: endpoint)!
let session = URLSession(configuration: URLSessionConfiguration.default)
var request:URLRequest = URLRequest(url: requestURL)
request.httpMethod = "POST"

// Image
let boundary = UUID().uuidString
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var body = NSMutableData()
body.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"file\"; filename=\"image.jpg\"\\r\n".data(using: .utf8)!)
body.append("Content-Type: application/octet-stream\r\n\r\n".data(using: .utf8)!)
body.append(imageData)
body.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
request.httpBody = body as Data

let task = session.dataTask(with: request) { (data, response, error) in
    guard let data = data, error == nil else { return }
    do {
        let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
        print("Response \(json)")
    } catch let error as Error {
        print("Error \(error)")
    }
}

task.resume()
</code>```

I suspect I am not sending the image correctly. Any ideas?

答:
It's probably best to not bother with a multi-part MIME, especially when you consider that the other Cognitive Service properties (namely Face and Emotion) don't support it.</p>

```<code>let subscriptionKey = "YOUR-KEY"
let image = #imageLiteral(resourceName:"monkey.jpg")
let imageData  = UIImageJPEGRepresentation(image, 1.0)!

let endpoint = ("https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?visualFeatures=Description,Categories,Tags")

let requestURL = URL(string: endpoint)!
let session = URLSession(configuration: URLSessionConfiguration.default)
var request:URLRequest = URLRequest(url: requestURL)
request.httpMethod = "POST"
request.addValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
request.addValue(subscriptionKey, forHTTPHeaderField: "Ocp-Apim-Subscription-Key")
request.httpBody = imageData

var semaphore = DispatchSemaphore.init(value: 0);

let task = session.dataTask(with: request) { (data, response, error) in
    guard let data = data, error == nil else { return }
    do {
        let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
        print("Response \(json)")
    } catch let error as Error {
        print("Error \(error)")
    }
    semaphore.signal()
}

task.resume()
semaphore.wait()
</code>```

Body:
I try to send an image to the MS Cognitive Services Visions API in a Swift Playground.

The message I get as response is:

Response ["requestId": …, "code": InternalServerError, "message": Internal server error.]

Here is the code I use

let image = #imageLiteral(resourceName: "paper.jpg")
let imageData = UIImageJPEGRepresentation(image, 1)!

let endpoint = ("https://westeurope.api.cognitive.microsoft.com/vision/v1.0/analyze?visualFeatures=Description,Categories,Tags&subscription-key=\(subscriptionKey)")

let requestURL = URL(string: endpoint)!
let session = URLSession(configuration: URLSessionConfiguration.default)
var request:URLRequest = URLRequest(url: requestURL)
request.httpMethod = "POST"

// Image
let boundary = UUID().uuidString
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var body = NSMutableData()
body.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"file\"; filename=\"image.jpg\"\\r\n".data(using: .utf8)!)
body.append("Content-Type: application/octet-stream\r\n\r\n".data(using: .utf8)!)
body.append(imageData)
body.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
request.httpBody = body as Data

let task = session.dataTask(with: request) { (data, response, error) in
    guard let data = data, error == nil else { return }
    do {
        let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
        print("Response \(json)")
    } catch let error as Error {
        print("Error \(error)")
    }
}

task.resume()

I suspect I am not sending the image correctly. Any ideas?

Body:
It's probably best to not bother with a multi-part MIME, especially when you consider that the other Cognitive Service properties (namely Face and Emotion) don't support it.

let subscriptionKey = "YOUR-KEY"
let image = #imageLiteral(resourceName:"monkey.jpg")
let imageData  = UIImageJPEGRepresentation(image, 1.0)!

let endpoint = ("https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?visualFeatures=Description,Categories,Tags")

let requestURL = URL(string: endpoint)!
let session = URLSession(configuration: URLSessionConfiguration.default)
var request:URLRequest = URLRequest(url: requestURL)
request.httpMethod = "POST"
request.addValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
request.addValue(subscriptionKey, forHTTPHeaderField: "Ocp-Apim-Subscription-Key")
request.httpBody = imageData

var semaphore = DispatchSemaphore.init(value: 0);

let task = session.dataTask(with: request) { (data, response, error) in
    guard let data = data, error == nil else { return }
    do {
        let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
        print("Response \(json)")
    } catch let error as Error {
        print("Error \(error)")
    }
    semaphore.signal()
}

task.resume()
semaphore.wait()


问:
Make predictions using a tensorflow graph from a keras model
I have a model trained using Keras with Tensorflow as my backend, but now I need to turn my model into a tensorflow graph for a certain application. I attempted to do this and make predictions to insure that it is working correctly, but when comparing to the results gathered from model.predict() I get very different values. For instance:

```<code>from keras.models import load_model
import tensorflow as tf

model = load_model('model_file.h5')

x_placeholder = tf.placeholder(tf.float32, shape=(None,7214,1))
y = model(x_placeholder)

x = np.ones((1,7214,1))

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print("Predictions from:\ntf graph:      "+str(sess.run(y, feed_dict={x_placeholder:x})))
    print("keras predict: "+str(model.predict(x)))
</code>```

returns:

```<code>Predictions from:
tf graph:      [[-0.1015993   0.07432419  0.0592984 ]]
keras predict: [[ 0.39339241  0.57949686 -3.67846966]]
</code>```

The values from keras predict are correct, but the tf graph results are not.

If it helps to know the final intended application, I am creating a jacobian matrix with the tf.gradients() function, but currently it does not return the correct results when comparing to theano's jacobian function, which gives the correct jacobian. Here is my tensorflow jacobian code:

```<code>x = tf.placeholder(tf.float32, shape=(None,7214,1))
y = tf.reshape(model(x)[0],[-1])
y_list = tf.unstack(y)

jacobian_list = [tf.gradients(y_, x)[0] for y_ in y_list]
jacobian = tf.stack(jacobian_list)
</code>```

EDIT: Model code

```<code>import numpy as np

from keras.models import Sequential
from keras.layers import Dense, InputLayer, Flatten
from keras.layers.convolutional import Conv1D
from keras.layers.convolutional import MaxPooling1D
from keras.optimizers import Adam
from keras.callbacks import EarlyStopping, ReduceLROnPlateau

# activation function used following every layer except for the output layers
activation = 'relu'

# model weight initializer
initializer = 'he_normal'

# shape of input data that is fed into the input layer
input_shape = (None,7214,1)

# number of filters used in the convolutional layers
num_filters = [4,16]

# length of the filters in the convolutional layers
filter_length = 8

# length of the maxpooling window
pool_length = 4

# number of nodes in each of the hidden fully connected layers
num_hidden_nodes = [256,128]

# number of samples fed into model at once during training
batch_size = 64

# maximum number of interations for model training
max_epochs = 30

# initial learning rate for optimization algorithm
lr = 0.0007

# exponential decay rate for the 1st moment estimates for optimization algorithm
beta_1 = 0.9

# exponential decay rate for the 2nd moment estimates for optimization algorithm
beta_2 = 0.999

# a small constant for numerical stability for optimization algorithm
optimizer_epsilon = 1e-08

model = Sequential([

    InputLayer(batch_input_shape=input_shape),

    Conv1D(kernel_initializer=initializer, activation=activation, padding="same", filters=num_filters[0], kernel_size=filter_length),

    Conv1D(kernel_initializer=initializer, activation=activation, padding="same", filters=num_filters[1], kernel_size=filter_length),

    MaxPooling1D(pool_size=pool_length),

    Flatten(),

    Dense(units=num_hidden_nodes[0], kernel_initializer=initializer, activation=activation),

    Dense(units=num_hidden_nodes[1], kernel_initializer=initializer, activation=activation),

    Dense(units=3, activation="linear", input_dim=num_hidden_nodes[1]),
])

# compile model
loss_function = mean squared error
early_stopping_min_delta = 0.0001
early_stopping_patience = 4
reduce_lr_factor = 0.5
reuce_lr_epsilon = 0.0009
reduce_lr_patience = 2
reduce_lr_min = 0.00008

optimizer = Adam(lr=lr, beta_1=beta_1, beta_2=beta_2, epsilon=optimizer_epsilon, decay=0.0)

early_stopping = EarlyStopping(monitor='val_loss',     min_delta=early_stopping_min_delta,
                                   patience=early_stopping_patience, verbose=2, mode='min')

reduce_lr = ReduceLROnPlateau(monitor='loss', factor=0.5, epsilon=reuce_lr_epsilon,
                              patience=reduce_lr_patience,     min_lr=reduce_lr_min, mode='min', verbose=2)

model.compile(optimizer=optimizer, loss=loss_function)

model.fit(train_x, train_y, validation_data=(cv_x, cv_y),
      epochs=max_epochs, batch_size=batch_size, verbose=2,
      callbacks=[reduce_lr,early_stopping])

model.save('model_file.h5')
</code>```

答:
@frankyjuang linked me to here

https://github.com/amir-abdi/keras_to_tensorflow

and combining this with code from

https://github.com/metaflow-ai/blog/blob/master/tf-freeze/load.py

and

https://github.com/tensorflow/tensorflow/issues/675

I have found a solution to both predicting using a tf graph and creating the jacobian function:

```<code>import tensorflow as tf
import numpy as np

# Create function to convert saved keras model to tensorflow graph
def convert_to_pb(weight_file,input_fld='',output_fld=''):

    import os
    import os.path as osp
    from tensorflow.python.framework import graph_util
    from tensorflow.python.framework import graph_io
    from keras.models import load_model
    from keras import backend as K

    # weight_file is a .h5 keras model file
    output_node_names_of_input_network = ["pred0"]
    output_node_names_of_final_network = 'output_node'

    # change filename to a .pb tensorflow file
    output_graph_name = weight_file[:-2]+'pb'
    weight_file_path = osp.join(input_fld, weight_file)

    net_model = load_model(weight_file_path)

    num_output = len(output_node_names_of_input_network)
    pred = [None]*num_output
    pred_node_names = [None]*num_output

    for i in range(num_output):
        pred_node_names[i] = output_node_names_of_final_network+str(i)
        pred[i] = tf.identity(net_model.output[i], name=pred_node_names[i])

    sess = K.get_session()

    constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph.as_graph_def(), pred_node_names)
    graph_io.write_graph(constant_graph, output_fld, output_graph_name, as_text=False)
    print('saved the constant graph (ready for inference) at: ', osp.join(output_fld, output_graph_name))

    return output_fld+output_graph_name
</code>```

Call:

```<code>tf_model_path = convert_to_pb('model_file.h5','/model_dir/','/model_dir/')
</code>```

Create function to load the tf model as a graph:

```<code>def load_graph(frozen_graph_filename):
    # We load the protobuf file from the disk and parse it to retrieve the
    # unserialized graph_def
    with tf.gfile.GFile(frozen_graph_filename, "rb") as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())

    # Then, we can use again a convenient built-in function to import a graph_def into the
    # current default Graph
    with tf.Graph().as_default() as graph:
        tf.import_graph_def(
            graph_def,
            input_map=None,
            return_elements=None,
            name="prefix",
            op_dict=None,
            producer_op_list=None
        )

    input_name = graph.get_operations()[0].name+':0'
    output_name = graph.get_operations()[-1].name+':0'

    return graph, input_name, output_name
</code>```

Create a function to make model predictions using the tf graph

```<code>def predict(model_path, input_data):
    # load tf graph
    tf_model,tf_input,tf_output = load_graph(model_path)

    # Create tensors for model input and output
    x = tf_model.get_tensor_by_name(tf_input)
    y = tf_model.get_tensor_by_name(tf_output)

    # Number of model outputs
    num_outputs = y.shape.as_list()[0]
    predictions = np.zeros((input_data.shape[0],num_outputs))
    for i in range(input_data.shape[0]):
        with tf.Session(graph=tf_model) as sess:
            y_out = sess.run(y, feed_dict={x: input_data[i:i+1]})
            predictions[i] = y_out

    return predictions
</code>```

Make predictions:

```<code>tf_predictions = predict(tf_model_path,test_data)
</code>```

Jacobian function:

```<code>def compute_jacobian(model_path,input_data):

    tf_model,tf_input,tf_output = load_graph(model_path)

    x = tf_model.get_tensor_by_name(tf_input)
    y = tf_model.get_tensor_by_name(tf_output)
    y_list = tf.unstack(y)
    num_outputs = y.shape.as_list()[0]
    jacobian = np.zeros((num_outputs,input_data.shape[0],input_data.shape[1]))
    for i in range(input_data.shape[0]):
        with tf.Session(graph=tf_model) as sess:
            y_out = sess.run([tf.gradients(y_, x)[0] for y_ in y_list], feed_dict={x: input_data[i:i+1]})
            jac_temp = np.asarray(y_out)
        jacobian[:,i:i+1,:]=jac_temp[:,:,:,0]
    return jacobian
</code>```

Compute Jacobian Matrix:

```<code>jacobians = compute_jacobian(tf_model_path,test_data)
</code>```

Body:
I have a model trained using Keras with Tensorflow as my backend, but now I need to turn my model into a tensorflow graph for a certain application. I attempted to do this and make predictions to insure that it is working correctly, but when comparing to the results gathered from model.predict() I get very different values. For instance:

from keras.models import load_model
import tensorflow as tf

model = load_model('model_file.h5')

x_placeholder = tf.placeholder(tf.float32, shape=(None,7214,1))
y = model(x_placeholder)

x = np.ones((1,7214,1))

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print("Predictions from:\ntf graph:      "+str(sess.run(y, feed_dict={x_placeholder:x})))
    print("keras predict: "+str(model.predict(x)))

returns:

Predictions from:
tf graph:      [[-0.1015993   0.07432419  0.0592984 ]]
keras predict: [[ 0.39339241  0.57949686 -3.67846966]]

The values from keras predict are correct, but the tf graph results are not.

If it helps to know the final intended application, I am creating a jacobian matrix with the tf.gradients() function, but currently it does not return the correct results when comparing to theano's jacobian function, which gives the correct jacobian. Here is my tensorflow jacobian code:

x = tf.placeholder(tf.float32, shape=(None,7214,1))
y = tf.reshape(model(x)[0],[-1])
y_list = tf.unstack(y)

jacobian_list = [tf.gradients(y_, x)[0] for y_ in y_list]
jacobian = tf.stack(jacobian_list)

EDIT: Model code

import numpy as np

from keras.models import Sequential
from keras.layers import Dense, InputLayer, Flatten
from keras.layers.convolutional import Conv1D
from keras.layers.convolutional import MaxPooling1D
from keras.optimizers import Adam
from keras.callbacks import EarlyStopping, ReduceLROnPlateau

# activation function used following every layer except for the output layers
activation = 'relu'

# model weight initializer
initializer = 'he_normal'

# shape of input data that is fed into the input layer
input_shape = (None,7214,1)

# number of filters used in the convolutional layers
num_filters = [4,16]

# length of the filters in the convolutional layers
filter_length = 8

# length of the maxpooling window
pool_length = 4

# number of nodes in each of the hidden fully connected layers
num_hidden_nodes = [256,128]

# number of samples fed into model at once during training
batch_size = 64

# maximum number of interations for model training
max_epochs = 30

# initial learning rate for optimization algorithm
lr = 0.0007

# exponential decay rate for the 1st moment estimates for optimization algorithm
beta_1 = 0.9

# exponential decay rate for the 2nd moment estimates for optimization algorithm
beta_2 = 0.999

# a small constant for numerical stability for optimization algorithm
optimizer_epsilon = 1e-08

model = Sequential([

    InputLayer(batch_input_shape=input_shape),

    Conv1D(kernel_initializer=initializer, activation=activation, padding="same", filters=num_filters[0], kernel_size=filter_length),

    Conv1D(kernel_initializer=initializer, activation=activation, padding="same", filters=num_filters[1], kernel_size=filter_length),

    MaxPooling1D(pool_size=pool_length),

    Flatten(),

    Dense(units=num_hidden_nodes[0], kernel_initializer=initializer, activation=activation),

    Dense(units=num_hidden_nodes[1], kernel_initializer=initializer, activation=activation),

    Dense(units=3, activation="linear", input_dim=num_hidden_nodes[1]),
])

# compile model
loss_function = mean squared error
early_stopping_min_delta = 0.0001
early_stopping_patience = 4
reduce_lr_factor = 0.5
reuce_lr_epsilon = 0.0009
reduce_lr_patience = 2
reduce_lr_min = 0.00008

optimizer = Adam(lr=lr, beta_1=beta_1, beta_2=beta_2, epsilon=optimizer_epsilon, decay=0.0)

early_stopping = EarlyStopping(monitor='val_loss',     min_delta=early_stopping_min_delta,
                                   patience=early_stopping_patience, verbose=2, mode='min')

reduce_lr = ReduceLROnPlateau(monitor='loss', factor=0.5, epsilon=reuce_lr_epsilon,
                              patience=reduce_lr_patience,     min_lr=reduce_lr_min, mode='min', verbose=2)

model.compile(optimizer=optimizer, loss=loss_function)

model.fit(train_x, train_y, validation_data=(cv_x, cv_y),
      epochs=max_epochs, batch_size=batch_size, verbose=2,
      callbacks=[reduce_lr,early_stopping])

model.save('model_file.h5')

Body:
@frankyjuang linked me to here

https://github.com/amir-abdi/keras_to_tensorflow

and combining this with code from

https://github.com/metaflow-ai/blog/blob/master/tf-freeze/load.py

and

https://github.com/tensorflow/tensorflow/issues/675

I have found a solution to both predicting using a tf graph and creating the jacobian function:

import tensorflow as tf
import numpy as np

# Create function to convert saved keras model to tensorflow graph
def convert_to_pb(weight_file,input_fld='',output_fld=''):

    import os
    import os.path as osp
    from tensorflow.python.framework import graph_util
    from tensorflow.python.framework import graph_io
    from keras.models import load_model
    from keras import backend as K

    # weight_file is a .h5 keras model file
    output_node_names_of_input_network = ["pred0"]
    output_node_names_of_final_network = 'output_node'

    # change filename to a .pb tensorflow file
    output_graph_name = weight_file[:-2]+'pb'
    weight_file_path = osp.join(input_fld, weight_file)

    net_model = load_model(weight_file_path)

    num_output = len(output_node_names_of_input_network)
    pred = [None]*num_output
    pred_node_names = [None]*num_output

    for i in range(num_output):
        pred_node_names[i] = output_node_names_of_final_network+str(i)
        pred[i] = tf.identity(net_model.output[i], name=pred_node_names[i])

    sess = K.get_session()

    constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph.as_graph_def(), pred_node_names)
    graph_io.write_graph(constant_graph, output_fld, output_graph_name, as_text=False)
    print('saved the constant graph (ready for inference) at: ', osp.join(output_fld, output_graph_name))

    return output_fld+output_graph_name

Call:

tf_model_path = convert_to_pb('model_file.h5','/model_dir/','/model_dir/')

Create function to load the tf model as a graph:

def load_graph(frozen_graph_filename):
    # We load the protobuf file from the disk and parse it to retrieve the
    # unserialized graph_def
    with tf.gfile.GFile(frozen_graph_filename, "rb") as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())

    # Then, we can use again a convenient built-in function to import a graph_def into the
    # current default Graph
    with tf.Graph().as_default() as graph:
        tf.import_graph_def(
            graph_def,
            input_map=None,
            return_elements=None,
            name="prefix",
            op_dict=None,
            producer_op_list=None
        )

    input_name = graph.get_operations()[0].name+':0'
    output_name = graph.get_operations()[-1].name+':0'

    return graph, input_name, output_name

Create a function to make model predictions using the tf graph

def predict(model_path, input_data):
    # load tf graph
    tf_model,tf_input,tf_output = load_graph(model_path)

    # Create tensors for model input and output
    x = tf_model.get_tensor_by_name(tf_input)
    y = tf_model.get_tensor_by_name(tf_output)

    # Number of model outputs
    num_outputs = y.shape.as_list()[0]
    predictions = np.zeros((input_data.shape[0],num_outputs))
    for i in range(input_data.shape[0]):
        with tf.Session(graph=tf_model) as sess:
            y_out = sess.run(y, feed_dict={x: input_data[i:i+1]})
            predictions[i] = y_out

    return predictions

Make predictions:

tf_predictions = predict(tf_model_path,test_data)

Jacobian function:

def compute_jacobian(model_path,input_data):

    tf_model,tf_input,tf_output = load_graph(model_path)

    x = tf_model.get_tensor_by_name(tf_input)
    y = tf_model.get_tensor_by_name(tf_output)
    y_list = tf.unstack(y)
    num_outputs = y.shape.as_list()[0]
    jacobian = np.zeros((num_outputs,input_data.shape[0],input_data.shape[1]))
    for i in range(input_data.shape[0]):
        with tf.Session(graph=tf_model) as sess:
            y_out = sess.run([tf.gradients(y_, x)[0] for y_ in y_list], feed_dict={x: input_data[i:i+1]})
            jac_temp = np.asarray(y_out)
        jacobian[:,i:i+1,:]=jac_temp[:,:,:,0]
    return jacobian

Compute Jacobian Matrix:

jacobians = compute_jacobian(tf_model_path,test_data)


问:
Python - Random sample from a range whilst avoiding certain values
I have been reading up about the random.sample() function in the random module and have not seen anything that solves my problem.

I know that using random.sample(range(1,100),5) would give me 5 unique samples from the 'population'...

I would like to get a random number in range(0,999). I could use random.sample(range(0,999),1) but why then am I thinking about using random.sample() ?

I need the random number in that range to not match any number in a separate array (Say, [443,122,738])

Is there a relatively easy way I could go about doing this?

Also, I am pretty new to python and am definitely a beginner -- If you would like me to update the question with any information I may have missed then I will.

EDIT:
Accidentally said random.range() once. Whoops.

答:
One way you can accomplish that is by simply checking the number and then appending it to a list where you can then use the numbers.</p>

```<code>import random

non_match = [443, 122, 738]
match = []

while len(match) < 6: # Where 6 can be replaced with how many numbers you want minus 1
    x = random.sample(range(0,999),1)
    if x not in non_match:
        match.append(x)
</code>```

Body:
One way you can accomplish that is by simply checking the number and then appending it to a list where you can then use the numbers.

import random

non_match = [443, 122, 738]
match = []

while len(match) < 6: # Where 6 can be replaced with how many numbers you want minus 1
    x = random.sample(range(0,999),1)
    if x not in non_match:
        match.append(x)


问:
Expression Property with Generic Parameter
Here goes my first question in Stack Overflow. So, please bear with me and I hope I can point you right to my problem... (sorry if this is a repeat, but I searched a lot and I couldn't find an answer for the exact issue I'm having nor I could figure it out from other answers).

Let me show you the code first so you can get some context (spoiler: the issue I'm having is with keySelector).

I have this method in a class:

```<code>public class BaseTableDataStore<T> : BaseTableDataStore, ITableDataStore<T> where T : Models.EntityData
{
    ...
    public virtual async Task<IEnumerable<T>> GetItemsQueryAsync<Tkey>(Expression<Func<T, bool>> predicate, Expression<Func<T, Tkey>> keySelector)
    {
        ...
        return await Table.Where(predicate).OrderBy(keySelector).ToEnumerableAsync();
        ...

    }
    ...
}
</code>```

Then, I have this other class:

```<code>public class ConnectedObservableCollection<T> : ObservableRangeCollection<T> where T : EntityData
{
    ITableDataStore<T> table;
    public Expression<Func<T, bool>> Predicate { get; set; }
    public Expression<Func<T, long?>> KeySelector { get; set; }
    ...
    public async Task Refresh()
    {
        ...
        _items = await table.GetItemsQueryAsync(Predicate, KeySelector);
        ...
    }
    ...
}
</code>```

Finally, I have the following code in another class:

```<code>ConnectedObservableCollection<MeterEntry> meterEntries;
...
meterEntries.Predicate = (s => s.Type == 1);
meterEntries.KeySelector = (s => s.Value);

await MeterEntries.Refresh(wait);
...
</code>```

That will of course work fine when s.Value is long?. But I would like to make this property generic so I can use any type of parameter instead of just long?

```<code>public Expression<Func<T, long?>> KeySelector { get; set; }
</code>```

I hope it's clear enough...

Thanks!

答:
If you want to change this:

```<code>public Expression<Func<T, long?>> KeySelector { get; set; }
</code>```

to this (replace long with a second generic type)

```<code>public Expression<Func<T, T2>> KeySelector { get; set; }
</code>```

then that second generic type must be included in your class definition.

Change

```<code>public class ConnectedObservableCollection<T>
    : ObservableRangeCollection<T> where T : EntityData
</code>```

to

```<code>public class ConnectedObservableCollection<T, T2>
    : ObservableRangeCollection<T> where T : EntityData
</code>```

Body:
Here goes my first question in Stack Overflow. So, please bear with me and I hope I can point you right to my problem... (sorry if this is a repeat, but I searched a lot and I couldn't find an answer for the exact issue I'm having nor I could figure it out from other answers).

Let me show you the code first so you can get some context (spoiler: the issue I'm having is with keySelector).

I have this method in a class:

public class BaseTableDataStore<T> : BaseTableDataStore, ITableDataStore<T> where T : Models.EntityData
{
    ...
    public virtual async Task<IEnumerable<T>> GetItemsQueryAsync<Tkey>(Expression<Func<T, bool>> predicate, Expression<Func<T, Tkey>> keySelector)
    {
        ...
        return await Table.Where(predicate).OrderBy(keySelector).ToEnumerableAsync();
        ...

    }
    ...
}

Then, I have this other class:

public class ConnectedObservableCollection<T> : ObservableRangeCollection<T> where T : EntityData
{
    ITableDataStore<T> table;
    public Expression<Func<T, bool>> Predicate { get; set; }
    public Expression<Func<T, long?>> KeySelector { get; set; }
    ...
    public async Task Refresh()
    {
        ...
        _items = await table.GetItemsQueryAsync(Predicate, KeySelector);
        ...
    }
    ...
}

Finally, I have the following code in another class:

ConnectedObservableCollection<MeterEntry> meterEntries;
...
meterEntries.Predicate = (s => s.Type == 1);
meterEntries.KeySelector = (s => s.Value);

await MeterEntries.Refresh(wait);
...

That will of course work fine when s.Value is long?. But I would like to make this property generic so I can use any type of parameter instead of just long?

public Expression<Func<T, long?>> KeySelector { get; set; }

I hope it's clear enough...

Thanks!

Body:
If you want to change this:

public Expression<Func<T, long?>> KeySelector { get; set; }

to this (replace long with a second generic type)

public Expression<Func<T, T2>> KeySelector { get; set; }

then that second generic type must be included in your class definition.

Change

public class ConnectedObservableCollection<T>
    : ObservableRangeCollection<T> where T : EntityData

to

public class ConnectedObservableCollection<T, T2>
    : ObservableRangeCollection<T> where T : EntityData


问:
Remove duplicates from sql query for reservation select
I have the following tables:

rtable

reservation

Now rtable has the following columns:

id int primary key

seats int

position varchar(10)

And reservation has the following columns:

reservation_id int primary key

table_id int foreign key(references rtable.id)

reservation_date date

start_hour

Now I want to perform the following query:
use restaurant;

```<code>select id,position,seats from rtable,reservation
            where (seats >= 6 and position = 'Indoors')
            and (not exists(select * from reservation where table_id = id) or(
            (exists(select 1 from reservation where table_id = id) and
                (reservation_date != '2017-05-23' or reservation.start_hour != 16))))
</code>```

However this query returns duplicates for rtable.id.
Is there any way to remove these duplicates

Here is an example output:

答:
Try this:</p>

```<code>select distinct id,position,seats from rtable,reservation
            where (seats >= 6 and position = 'Indoors')
            and (not exists(select * from reservation where table_id = id) or(
            (exists(select 1 from reservation where table_id = id) and
                (reservation_date != '2017-05-23' or reservation.start_hour != 16))))
</code>```

Body:
I have the following tables:

rtable

reservation

Now rtable has the following columns:

id int primary key

seats int

position varchar(10)

And reservation has the following columns:

reservation_id int primary key

table_id int foreign key(references rtable.id)

reservation_date date

start_hour

Now I want to perform the following query:
use restaurant;

select id,position,seats from rtable,reservation
            where (seats >= 6 and position = 'Indoors')
            and (not exists(select * from reservation where table_id = id) or(
            (exists(select 1 from reservation where table_id = id) and
                (reservation_date != '2017-05-23' or reservation.start_hour != 16))))

However this query returns duplicates for rtable.id.
Is there any way to remove these duplicates

Here is an example output:

Body:
Try this:

select distinct id,position,seats from rtable,reservation
            where (seats >= 6 and position = 'Indoors')
            and (not exists(select * from reservation where table_id = id) or(
            (exists(select 1 from reservation where table_id = id) and
                (reservation_date != '2017-05-23' or reservation.start_hour != 16))))


问:
Can't get to any Vagrant sites on Ubuntu 17.04
I'm on a fresh install of Ubuntu Budgie 17.04, and have only installed updates, Virtual Box, and Vagrant.

I've tried to go through the set up on https://box.scotch.io as well as the set up for https://laravel.com/docs/5.4/homestead.

They both successfully run vagrant up with no errors being thrown. However if I try to go to http://192.168.33.10/ for the default Scotchbox page or try to go to the default homestead.app (it is in my hosts file) the page just loads forever and says connection timed out.

Any ideas on how to troubleshoot and fix this?

Edit: I can go to localhost:8000 and see my vagrant dummy index.html file... but still can't get there by using homestead.app or 192.168.10.10

Edit 2: Not sure if this is really a good solution, but at the top of my hosts file I had this line...

```<code>127.0.1.1 xander-pc
</code>```

And deleting this line has fixed all my vagrant issues. Is there any negative side effects that will happen from deleting this line?

答:
I had the same problem with all vagrant boxes and found the solution to be:

removing the second line in the /etc/hosts file
 like you suggested just uncomment or remove the line containing:

     127.0.1.1 [computer-name]

Installing net-tools:
It seems like ubuntu 17.04 is not installing the package net-tools anymore.

So installing them via

     sudo apt-get install net-tools

and it should work again.

Body:
I'm on a fresh install of Ubuntu Budgie 17.04, and have only installed updates, Virtual Box, and Vagrant.

I've tried to go through the set up on https://box.scotch.io as well as the set up for https://laravel.com/docs/5.4/homestead.

They both successfully run vagrant up with no errors being thrown. However if I try to go to http://192.168.33.10/ for the default Scotchbox page or try to go to the default homestead.app (it is in my hosts file) the page just loads forever and says connection timed out.

Any ideas on how to troubleshoot and fix this?

Edit: I can go to localhost:8000 and see my vagrant dummy index.html file... but still can't get there by using homestead.app or 192.168.10.10

Edit 2: Not sure if this is really a good solution, but at the top of my hosts file I had this line...

127.0.1.1 xander-pc

And deleting this line has fixed all my vagrant issues. Is there any negative side effects that will happen from deleting this line?


问:
Why pass memory value to register and back
There's this assembly excerpt :

```<code>movl  (%ecx,%edx,4), %eax
...
incl    %eax
movl    %eax, (%ecx,%edx,4)
</code>```

Which translates into c :

```<code>a[i] += 1;
</code>```

With:

```<code>a -> ecx and i -> edx
</code>```

My question is what's the point of using eax as a middleman ? Is it faster or is it impossible to increment the memory value directly ?

答:
Thanks for the answers, from what I've gathered both ways are valid and it's up to the compiler and the optimization level.

I'm writing this to mark the question answered.

Body:
There's this assembly excerpt :

movl  (%ecx,%edx,4), %eax
...
incl    %eax
movl    %eax, (%ecx,%edx,4)

Which translates into c :

a[i] += 1;

With:

a -> ecx and i -> edx

My question is what's the point of using eax as a middleman ? Is it faster or is it impossible to increment the memory value directly ?


问:
RFC822 to date format using asp
I try converting RFC822 date format (from rss) into a standard date/time format
using asp3.

Thanks

答:
Take a look at the source code of this Classic ASP RSS reader.

There are some funky functions involving the use of JScript, which look like they will work for you.

It looks like you need the VBScript functions parseDate and newDate, and the two JScript functions.

Title: RFC822 to date format using asp