问:
How to bind nested objects on HttpPost in ASP.NET MVC
I have started to implement this solution bind attribute include and exclude property with complex type nested objects

but it does not work at all.

The same question is here Binding nested model with MVC3 on HttpPost

but no concrete answer.

Model

```<code>[Bind(Include = "FirstName,MiddleName,LastName,Position,TruckTypeID,Direction,Organization,Objective,TimeStart,TimeEnd")]
public partial class UserRequestRegisterModel
{
    [DisplayName("Имя")]
    [Required]
    public string FirstName { get; set; }

    [DisplayName("Фамилия")]
    [Required]
    public string MiddleName { get; set; }

    [DisplayName("Отчество")]
    [Required]
    public string LastName { get; set; }

    [DisplayName("Должность")]
    [Required]
    public string Position { get; set; }

    [DisplayName("Тип транспорта")]
    [Required]
    public System.Guid TruckTypeID { get; set; }

    [DisplayName("Направление")]
    [Required]
    public string Direction { get; set; }

    [DisplayName("Организация")]
    [Required]
    public string Organization { get; set; }

    [DisplayName("Цель")]
    [Required]
    public string Objective { get; set; }

    [DisplayName("Время убытия")]
    [Required]
    // [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy  HH:mm}", ApplyFormatInEditMode = true)]
    public System.DateTime TimeStart { get; set; }

    [DisplayName("Время прибытия")]
    [Required]
    // [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm}", ApplyFormatInEditMode = true)]
    public Nullable<System.DateTime> TimeEnd { get; set; }
}

[Bind(Include = "UserRequest")]
public partial class RequestUserModel
{
    public List<UserRequestViewItem> UserRequestViewItems { get; set; }
    public UserRequestRegisterModel UserRequest { get; set; }

    public RequestUserModel()
    {
        UserRequestViewItems = new List<UserRequestViewItem>();
        UserRequest = new UserRequestRegisterModel();
    }
}
</code>```

Controller

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind(Include = "FirstName,MiddleName,LastName,Position,TruckTypeID,Direction,Organization,Objective,TimeStart,TimeEnd")] RequestUserModel userRequest)
//public ActionResult Index(RequestUserModel userRequest)
{
    // !  userRequest.UserRequest is empty  !
    //...
}
</code>```

答:
After 30 minutes of freestyle experimenting I finally get it working.

So, guys, solution is following

Model

```<code> [Bind(Include = "FirstName,MiddleName,LastName,Position,TruckTypeID,Direction,Organization,Objective,TimeStart,TimeEnd")]
    public partial class UserRequestRegisterModel
    {
        [DisplayName("Имя")]
        [Required]
        public string FirstName { get; set; }

        [DisplayName("Фамилия")]
        [Required]
        public string MiddleName { get; set; }

        [DisplayName("Отчество")]
        [Required]
        public string LastName { get; set; }

        [DisplayName("Должность")]
        [Required]
        public string Position { get; set; }

        [DisplayName("Тип транспорта")]
        [Required]
        public System.Guid TruckTypeID { get; set; }

        [DisplayName("Направление")]
        [Required]
        public string Direction { get; set; }

        [DisplayName("Организация")]
        [Required]
        public string Organization { get; set; }

        [DisplayName("Цель")]
        [Required]
        public string Objective { get; set; }

        [DisplayName("Время убытия")]
        [Required]
        // [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy  HH:mm}", ApplyFormatInEditMode = true)]
        public System.DateTime TimeStart { get; set; }

        [DisplayName("Время прибытия")]
        [Required]
        // [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm}", ApplyFormatInEditMode = true)]
        public Nullable<System.DateTime> TimeEnd { get; set; }
    }

public partial class RequestUserModel
    {
        public List<UserRequestViewItem> UserRequestViewItems { get; set; }
        public UserRequestRegisterModel UserRequest { get; set; }

        public RequestUserModel()
        {
            UserRequestViewItems = new List<UserRequestViewItem>();
            UserRequest = new UserRequestRegisterModel();
        }
    }
</code>```

HTML

```<code>@model TransportRequests.Models.RequestUserModel
...

@using (Html.BeginForm("CreateUserRequest", null, FormMethod.Post, null))
{
   @Html.EditorFor(model => model.UserRequest.FirstName, new { htmlAttributes = new { @class = "form-control", @style = "width:200px" } })
}
</code>```

Controller

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateUserRequest([Bind(Include = "UserRequest")] RequestUserModel model)
{
     // and here all properties has inputed values... YEAH!!!  :)

     var firstName = model.UserRequest.FirstName;

     return RedirectToAction("Index");
}
</code>```

Body:
I have started to implement this solution bind attribute include and exclude property with complex type nested objects

but it does not work at all.

The same question is here Binding nested model with MVC3 on HttpPost

but no concrete answer.

Model

[Bind(Include = "FirstName,MiddleName,LastName,Position,TruckTypeID,Direction,Organization,Objective,TimeStart,TimeEnd")]
public partial class UserRequestRegisterModel
{
    [DisplayName("Имя")]
    [Required]
    public string FirstName { get; set; }

    [DisplayName("Фамилия")]
    [Required]
    public string MiddleName { get; set; }

    [DisplayName("Отчество")]
    [Required]
    public string LastName { get; set; }

    [DisplayName("Должность")]
    [Required]
    public string Position { get; set; }

    [DisplayName("Тип транспорта")]
    [Required]
    public System.Guid TruckTypeID { get; set; }

    [DisplayName("Направление")]
    [Required]
    public string Direction { get; set; }

    [DisplayName("Организация")]
    [Required]
    public string Organization { get; set; }

    [DisplayName("Цель")]
    [Required]
    public string Objective { get; set; }

    [DisplayName("Время убытия")]
    [Required]
    // [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy  HH:mm}", ApplyFormatInEditMode = true)]
    public System.DateTime TimeStart { get; set; }

    [DisplayName("Время прибытия")]
    [Required]
    // [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm}", ApplyFormatInEditMode = true)]
    public Nullable<System.DateTime> TimeEnd { get; set; }
}

[Bind(Include = "UserRequest")]
public partial class RequestUserModel
{
    public List<UserRequestViewItem> UserRequestViewItems { get; set; }
    public UserRequestRegisterModel UserRequest { get; set; }

    public RequestUserModel()
    {
        UserRequestViewItems = new List<UserRequestViewItem>();
        UserRequest = new UserRequestRegisterModel();
    }
}

Controller

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind(Include = "FirstName,MiddleName,LastName,Position,TruckTypeID,Direction,Organization,Objective,TimeStart,TimeEnd")] RequestUserModel userRequest)
//public ActionResult Index(RequestUserModel userRequest)
{
    // !  userRequest.UserRequest is empty  !
    //...
}

Body:
After 30 minutes of freestyle experimenting I finally get it working.

So, guys, solution is following

Model

 [Bind(Include = "FirstName,MiddleName,LastName,Position,TruckTypeID,Direction,Organization,Objective,TimeStart,TimeEnd")]
    public partial class UserRequestRegisterModel
    {
        [DisplayName("Имя")]
        [Required]
        public string FirstName { get; set; }

        [DisplayName("Фамилия")]
        [Required]
        public string MiddleName { get; set; }

        [DisplayName("Отчество")]
        [Required]
        public string LastName { get; set; }

        [DisplayName("Должность")]
        [Required]
        public string Position { get; set; }

        [DisplayName("Тип транспорта")]
        [Required]
        public System.Guid TruckTypeID { get; set; }

        [DisplayName("Направление")]
        [Required]
        public string Direction { get; set; }

        [DisplayName("Организация")]
        [Required]
        public string Organization { get; set; }

        [DisplayName("Цель")]
        [Required]
        public string Objective { get; set; }

        [DisplayName("Время убытия")]
        [Required]
        // [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy  HH:mm}", ApplyFormatInEditMode = true)]
        public System.DateTime TimeStart { get; set; }

        [DisplayName("Время прибытия")]
        [Required]
        // [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm}", ApplyFormatInEditMode = true)]
        public Nullable<System.DateTime> TimeEnd { get; set; }
    }

public partial class RequestUserModel
    {
        public List<UserRequestViewItem> UserRequestViewItems { get; set; }
        public UserRequestRegisterModel UserRequest { get; set; }

        public RequestUserModel()
        {
            UserRequestViewItems = new List<UserRequestViewItem>();
            UserRequest = new UserRequestRegisterModel();
        }
    }

HTML

@model TransportRequests.Models.RequestUserModel
...

@using (Html.BeginForm("CreateUserRequest", null, FormMethod.Post, null))
{
   @Html.EditorFor(model => model.UserRequest.FirstName, new { htmlAttributes = new { @class = "form-control", @style = "width:200px" } })
}

Controller

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateUserRequest([Bind(Include = "UserRequest")] RequestUserModel model)
{
     // and here all properties has inputed values... YEAH!!!  :)

     var firstName = model.UserRequest.FirstName;

     return RedirectToAction("Index");
}


来源: stackexchange

问:
TensorFlow: How to predict from a SavedModel?
I have exported a SavedModel and now I with to load it back in and make a prediction. It was trained with the following features and labels:

```<code>F1 : FLOAT32
F2 : FLOAT32
F3 : FLOAT32
L1 : FLOAT32
</code>```

So say I want to feed in the values 20.9, 1.8, 0.9 get a single FLOAT32 prediction. How do I accomplish this? I have managed to successfully load the model, but I am not sure how to access it to make the prediction call.

```<code>with tf.Session(graph=tf.Graph()) as sess:
    tf.saved_model.loader.load(
        sess,
        [tf.saved_model.tag_constants.SERVING],
        "/job/export/Servo/1503723455"
    )

    # How can I predict from here?
    # I want to do something like prediction = model.predict([20.9, 1.8, 0.9])
</code>```

This question is not a duplicate of the question posted here. This question focuses on a minimal example of performing inference on a SavedModel of any model class (not just limited to tf.estimator) and the syntax of specifying input and output node names.

答:
For anyone who needs a working example of saving a trained canned model and serving it without tensorflow serving ,I have documented here
https://github.com/tettusud/tensorflow-examples/tree/master/estimators

You can create a predictor from tf.tensorflow.contrib.predictor.from_saved_model( exported_model_path)

Prepare input

```<code>tf.train.Example(
    features= tf.train.Features(
        feature={
            'x': tf.train.Feature(
                 float_list=tf.train.FloatList(value=[6.4, 3.2, 4.5, 1.5])
            )
        }
    )
)
</code>```

Here x is the name of the input that was given in input_receiver_function at the time of exporting.
 for eg:

```<code>feature_spec = {'x': tf.FixedLenFeature([4],tf.float32)}

def serving_input_receiver_fn():
    serialized_tf_example = tf.placeholder(dtype=tf.string,
                                           shape=[None],
                                           name='input_tensors')
    receiver_tensors = {'inputs': serialized_tf_example}
    features = tf.parse_example(serialized_tf_example, feature_spec)
    return tf.estimator.export.ServingInputReceiver(features, receiver_tensors)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have exported a SavedModel and now I with to load it back in and make a prediction. It was trained with the following features and labels:

F1 : FLOAT32
F2 : FLOAT32
F3 : FLOAT32
L1 : FLOAT32

So say I want to feed in the values 20.9, 1.8, 0.9 get a single FLOAT32 prediction. How do I accomplish this? I have managed to successfully load the model, but I am not sure how to access it to make the prediction call.

with tf.Session(graph=tf.Graph()) as sess:
    tf.saved_model.loader.load(
        sess,
        [tf.saved_model.tag_constants.SERVING],
        "/job/export/Servo/1503723455"
    )

    # How can I predict from here?
    # I want to do something like prediction = model.predict([20.9, 1.8, 0.9])

This question is not a duplicate of the question posted here. This question focuses on a minimal example of performing inference on a SavedModel of any model class (not just limited to tf.estimator) and the syntax of specifying input and output node names.

Body:
For anyone who needs a working example of saving a trained canned model and serving it without tensorflow serving ,I have documented here
https://github.com/tettusud/tensorflow-examples/tree/master/estimators

You can create a predictor from tf.tensorflow.contrib.predictor.from_saved_model( exported_model_path)

Prepare input

tf.train.Example(
    features= tf.train.Features(
        feature={
            'x': tf.train.Feature(
                 float_list=tf.train.FloatList(value=[6.4, 3.2, 4.5, 1.5])
            )
        }
    )
)

Here x is the name of the input that was given in input_receiver_function at the time of exporting.
 for eg:

feature_spec = {'x': tf.FixedLenFeature([4],tf.float32)}

def serving_input_receiver_fn():
    serialized_tf_example = tf.placeholder(dtype=tf.string,
                                           shape=[None],
                                           name='input_tensors')
    receiver_tensors = {'inputs': serialized_tf_example}
    features = tf.parse_example(serialized_tf_example, feature_spec)
    return tf.estimator.export.ServingInputReceiver(features, receiver_tensors)


问:
mysql string compares - md5 faster?
Would an indexed compare of two string fields be faster if those fields were md5'd during the import, and the md5 field used in the compare instead of the source string field?</p>

答: Probably not. It may depend on the type of index used. You can specify USING HASH when creating the index. In this case, MySQL will use some kind of hashing (probably MD5 as well) to build the index with, but it will avoid the risk of collision. When two values have the same hash, the hash will just function as a range for both rows.

ContentLicense: CC BY-SA 2.5

Title: mysql string compares - md5 faster?


问:
How to conduct an Accent Sensitive search in MySql
I have a MySQL table with utf8 general ci collation. In the table, I can see two entries:

abad

abád

I am using a query that looks like this:

```<code>SELECT *  FROM `words` WHERE `word` = 'abád'
</code>```

The query result gives both words:

abad

abád

Is there a way to indicate that I only want MySQL to find the accented word? I want the query to only return

abád

I have also tried this query:

```<code>SELECT *  FROM `words` WHERE BINARY `word` = 'abád'
</code>```

It gives me no results. Thank you for the help.

答:
Accepted answer is good, but beware that you may have to use COLLATE utf8mb4_bin instead!

```<code>WHERE col_name = 'abád' collate utf8mb4_bin
</code>```

Above fixes errors like:

MySQL said: Documentation 1253 - COLLATION 'utf8_bin' is not valid for
  CHARACTER SET 'utf8mb4'

OwnerDisplayName: Chris

Body:
I have a MySQL table with utf8 general ci collation. In the table, I can see two entries:

abad

abád

I am using a query that looks like this:

SELECT *  FROM `words` WHERE `word` = 'abád'

The query result gives both words:

abad

abád

Is there a way to indicate that I only want MySQL to find the accented word? I want the query to only return

abád

I have also tried this query:

SELECT *  FROM `words` WHERE BINARY `word` = 'abád'

It gives me no results. Thank you for the help.

Body:
Accepted answer is good, but beware that you may have to use COLLATE utf8mb4_bin instead!

WHERE col_name = 'abád' collate utf8mb4_bin

Above fixes errors like:

MySQL said: Documentation 1253 - COLLATION 'utf8_bin' is not valid for
  CHARACTER SET 'utf8mb4'


问:
How to create custom marker in Ar.js?
I Was wondering how things work in Ar.js , But i was stuck with
creating custom Markers and custom shapes , is there any way to
customize things.

this is What i have got things to getting started.

```<code><script src="https://aframe.io/releases/0.6.0/aframe.min.js"></script>
<!-- include ar.js for A-Frame -->
<script src="https://jeromeetienne.github.io/AR.js/aframe/build/aframe-ar.js"></script>
<body style='margin : 0px; overflow: hidden;'>
  <a-scene embedded arjs>
    <!-- create your content here. just a box for now -->
    <a-box position='0 0.5 0' material='opacity: 0.5;'></a-box>
    <!-- define a camera which will move according to the marker position -->
    <a-marker-camera preset='hiro'></a-marker-camera>
  </a-scene>
</body>
</code>```

This is simple example for getting started

答:
You will need to create & specify a custom pattern file.
See Is it possible to use bespoke markers?

You should also remove the hiro preset.

Title: How to create custom marker in Ar.js?

Body:
I Was wondering how things work in Ar.js , But i was stuck with
creating custom Markers and custom shapes , is there any way to
customize things.

this is What i have got things to getting started.

This is simple example for getting started


问:
Codeigniter's controller data always shows on top of the html
I am trying to get the data of another function inside the controller, but there is a problem when I load it with the view. Anyway I placed the output of the controller inside the view and it still goes to the top of the HTML

this is the controller code

public function index()
    {
        $data['record'] = $this->samples();
        $this->load->view('home',$data);
    }//end index()

    public function samples(){
        echo "string";
    }
```

<p>this is the view</p>

```<!DOCTYPE html>

    <title></title>

<?php echo $record;?>

This is a sample

```

Now when I go to the browser it looks ok, but when you go to the source code you can see the data is on top of HTML. Why is that?

source code from view

答:
You should return it</p>

```<code>public function index()
{
   $data['record'] = $this->samples();
   $this->load->view('home',$data);
}

public function samples(){
    return "string";
}
</code>```

Body:
I am trying to get the data of another function inside the controller, but there is a problem when I load it with the view. Anyway I placed the output of the controller inside the view and it still goes to the top of the HTML

this is the controller code

public function index()
    {
        $data['record'] = $this->samples();
        $this->load->view('home',$data);
    }//end index()

    public function samples(){
        echo "string";
    }

this is the view

<!DOCTYPE html>

    <title></title>

<?php echo $record;?>

This is a sample

Now when I go to the browser it looks ok, but when you go to the source code you can see the data is on top of HTML. Why is that?

source code from view

Body:
You should return it

public function index()
{
   $data['record'] = $this->samples();
   $this->load->view('home',$data);
}

public function samples(){
    return "string";
}


问:
Avoiding nil Slider Values?
Anybody have suggestions on how to avoid getting errors due to sliders being nil when switching between view controllers?  My app has a main screen that controls audio playing and buttons to five other view controllers.  One that allows audio file selection, and four that have parameters to adjust distortion, filter, reverb, and delay parameters.  I am using unwind segues to get back to the main screen from these separate screens.  The issue is that the optionals are nil when I load the project since they are on a separate view controller.  I want to be able to access these parameters, adjust them in real time and go back to the menu with the parameters maintaining their new values.  Another aspect of this issue is that I will load my audio file in the "select audio file" controller that I have, but when I switch back to the main view controller, the loaded song reverts back to nil in the audio player after the unwind.  Any suggestions on how to organize the view controllers to allow this functionality would be very helpful!</p>

答:
If you have default values you want to use when these values are nil, you can use the nil coalescing operator "??"

```<code>someParameter = slider?.value ?? someParameter
</code>```

Would probably be okay I guess? I'd be very careful tying your sound to the view controller life cycle. Probably your slider should talk to a central audio data store (sometimes I'll call it the conductor or engine) and have that be the only thing that truly changes audio parameter values, and have it do so with care.

Title: Avoiding nil Slider Values?

Body:
If you have default values you want to use when these values are nil, you can use the nil coalescing operator "??"

someParameter = slider?.value ?? someParameter

Would probably be okay I guess? I'd be very careful tying your sound to the view controller life cycle. Probably your slider should talk to a central audio data store (sometimes I'll call it the conductor or engine) and have that be the only thing that truly changes audio parameter values, and have it do so with care.


问:
Unable to upload files in SilverStripe 4
I've created a simple extension to SiteConfig to add a logo uploadfield to the settings section. However, the server returns an error upon uploading a file.

SiteConfig.php

```<code>namespace mymodule\siteconfig;

use SilverStripe\ORM\DataExtension;
use SilverStripe\Forms\FieldList;
use SilverStripe\AssetAdmin\Forms\UploadField;

class SiteConfig extends DataExtension {

    private static $has_one = array(
        'Logo' => 'SilverStripe\\Assets\\File'
    );

    public function updateCMSFields(FieldList $fields) {

        $fields->addFieldToTab('Root.Main', $logo = UploadField::create('Logo', 'Logo upload'));

    }

}
</code>```

Server's error log does not show anything relevant to this error. Whats going on here?

UPDATE

I just tried to upload a file to the Files section in the CMS, got the exact same error.

答:
```<code>private static $has_one = [
    'LogoImage' => Image::class,
];

public function updateCMSFields(FieldList $fields) {

   $fields->addFieldToTab('Root.Main', UploadField::create('LogoImage', 'Logo'));

}
</code>```

Body:
I've created a simple extension to SiteConfig to add a logo uploadfield to the settings section. However, the server returns an error upon uploading a file.

SiteConfig.php

namespace mymodule\siteconfig;

use SilverStripe\ORM\DataExtension;
use SilverStripe\Forms\FieldList;
use SilverStripe\AssetAdmin\Forms\UploadField;

class SiteConfig extends DataExtension {

    private static $has_one = array(
        'Logo' => 'SilverStripe\\Assets\\File'
    );

    public function updateCMSFields(FieldList $fields) {

        $fields->addFieldToTab('Root.Main', $logo = UploadField::create('Logo', 'Logo upload'));

    }

}

Server's error log does not show anything relevant to this error. Whats going on here?

UPDATE

I just tried to upload a file to the Files section in the CMS, got the exact same error.


问:
how to get text outside in HTML JS
```<code><ul class="select2-selection__rendered">
  <li class="select2-selection__choice" title="List"><span class="select2-selection__choice__remove" role="presentation">×</span>**List**</li>
  <li class="select2-search select2-search--inline">
    <input class="select2-search__field" type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="textbox" aria-autocomplete="list" placeholder="" style="width: 0.75em;">
  </li>
</ul>
</code>```

Thats the code ..

I want to get text "List" which I bold .

```<code>alert( $("ul > li > .select2-selection__choice").text() );
</code>```

still can't get the text .
Thanks

答:
From HERE - this gives you just '**List**

alert($('.select2-selection__choice').contents().filter(function() {
  return this.nodeType == 3;
})[0].nodeValue);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="select2-selection__rendered">
  <li class="select2-selection__choice" title="List"><span class="select2-selection__choice__remove" role="presentation">×</span>**List**</li>
  <li class="select2-search select2-search--inline">
    <input class="select2-search__field" type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="textbox" aria-autocomplete="list" placeholder="" style="width: 0.75em;">
  </li>
</ul></code>```

Title: how to get text outside in HTML JS

Body:
×**List**

    <input class="select2-search__field" type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="textbox" aria-autocomplete="list" placeholder="" style="width: 0.75em;">

Thats the code ..

I want to get text "List" which I bold .

alert( $("ul > li > .select2-selection__choice").text() );

still can't get the text .
Thanks

Body:
From HERE - this gives you just '**List**

alert($('.select2-selection__choice').contents().filter(function() {
  return this.nodeType == 3;
})[0].nodeValue);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="select2-selection__rendered">
  <li class="select2-selection__choice" title="List"><span class="select2-selection__choice__remove" role="presentation">×</span>**List**</li>
  <li class="select2-search select2-search--inline">
    <input class="select2-search__field" type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="textbox" aria-autocomplete="list" placeholder="" style="width: 0.75em;">
  </li>
</ul>


问:
Difference between HttpModule and HttpClientModule
Which one to use to build a mock web service to test the Angular 4 app?</p>

答:
Don't want to be repetitive, but just to summarize in other way (features added in new HttpClient):

Automatic conversion from JSON to an object

Response type definition

Event firing

Simplified syntax for headers

Interceptors

I wrote an article, where I covered the difference between old "http" and new "HttpClient". The goal was to explain it in the easiest way possible.

Simply about new HttpClient in Angular

ContentLicense: CC BY-SA 4.0


问:
git cherry-pick failing because of merge conflict
I am using git cherry-pick to add specific commit SHAs to a particular branch:

```<code>git cherry-pick 12345
error: commit 12345 is a merge but no -m option was given.
fatal: cherry-pick failed
</code>```

(Pretend 12345 is a commit SHA.)

I've tried several other variations but they all fail:

```<code>git cherry-pick 12345 -m
git cherry-pick -m 12345
etc.
</code>```

Not sure how to interpret the error message or figure out what the fix is. Any ideas?

答:
Yes, the sequence of commits passed to git cherry-pick indeed matters.

Consider your first commit A introduced a new line, and the next commit B modified the same line. if the commits are picked in the wrong order, then commit B has nothing to patch, even if that didn't fail, then commit A would add the un-patched line back, probably not what you want, right?

And regarding merge commits, if it introduced changes, then it must be included, too.

Also, usually you don't pass a long list of commits to git cherry-pick, you can use revision range syntax to specify a series of commits, please refer to the EXAMPLES section in the manual: https://git-scm.com/docs/git-cherry-pick

Body:
I am using git cherry-pick to add specific commit SHAs to a particular branch:

git cherry-pick 12345
error: commit 12345 is a merge but no -m option was given.
fatal: cherry-pick failed

(Pretend 12345 is a commit SHA.)

I've tried several other variations but they all fail:

git cherry-pick 12345 -m
git cherry-pick -m 12345
etc.

Not sure how to interpret the error message or figure out what the fix is. Any ideas?


问:
Cannot run ionic. receives "No command 'ionic' found"
I want to start using the ionic framework, but unfortunately I'm already failing on the first step.

I am running Ubuntu 13.04 and I have node v0.10.25 installed.
I've installed ionic, at described in their docs:

```<code>sudo npm install -g cordova
sudo npm install -g ionic
</code>```

The installation went well, no errors or warnings, but after the installation I type

```<code>ionic
</code>```

and I get the error:

```<code>No command 'ionic' found, did you mean:
 Command 'ionice' from package 'util-linux' (main)
 Command 'sonic' from package 'sonic' (universe)
ionic: command not found
</code>```

I'm pretty new to ubuntu so I might have something not configured correctly, but I can't find what.

Thanks

答:
First Solution

I recently ran into this issue and the only solution that worked for me was to uninstall both ionic and cordova.

```<code>npm uninstall -g cordova
npm uninstall -g ionic
</code>```

Then just reinstall

```<code>npm install -g cordova
npm install -g ionic
</code>```

Second Solution

I ran into this issue again! This time check your environmental variables.

Run npm bin -g and check if the path returned is in your environmental variables. For me, it prompted that it was not found in the terminal output. I added that path to the environmental variables and restarted the terminal. From there everything started to work again. (source)

Body:
I want to start using the ionic framework, but unfortunately I'm already failing on the first step.

I am running Ubuntu 13.04 and I have node v0.10.25 installed.
I've installed ionic, at described in their docs:

sudo npm install -g cordova
sudo npm install -g ionic

The installation went well, no errors or warnings, but after the installation I type

ionic

and I get the error:

No command 'ionic' found, did you mean:
 Command 'ionice' from package 'util-linux' (main)
 Command 'sonic' from package 'sonic' (universe)
ionic: command not found

I'm pretty new to ubuntu so I might have something not configured correctly, but I can't find what.

Thanks

Body:
First Solution

I recently ran into this issue and the only solution that worked for me was to uninstall both ionic and cordova.

npm uninstall -g cordova
npm uninstall -g ionic

Then just reinstall

npm install -g cordova
npm install -g ionic

Second Solution

I ran into this issue again! This time check your environmental variables.

Run npm bin -g and check if the path returned is in your environmental variables. For me, it prompted that it was not found in the terminal output. I added that path to the environmental variables and restarted the terminal. From there everything started to work again. (source)


问:
What does [Max tasks per child setting] exactly mean in Celery?
The doc is:

With this option you can configure the maximum number of tasks a worker can execute before it’s replaced by a new process.

In what condition will a worker be replaced by a new process ? Does this setting make a worker, even with multi processes, can only process one task at one time?

答:
It means that when celery has executed tasks more than the limit on one worker (the "worker" is a process if you use the default process pool), it will restart the worker automatically.

Say if you use celery for database manipulation and you forget to close the database connection, the auto restart mechanism will help you close all pending connections.


问:
Python ORM for massive data set
I have a massive data set of customer information (100s of millions of records, 50+ tables).

I am writing a python (twisted) app that I would like to interact with the dataset, performing table manipulation.  What I really need is an abstraction of 'table', so I can add/remove/alter columns/tables without having to resort to only creating SQL.

Is there an ORM that will not add significant overhead to my application, considering the size of the dataset?

答:
See

What are some good Python ORM solutions?

They seem to be in favor of SQLAlchemy

Title: Python ORM for massive data set


问:
Angular 2/4 prevent user to leave component if changes not saved
I have this interface that i'm using to prevent the user to leave page

```<code>export interface ComponentCanDeactivate {
  canDeactivate: () => boolean;
}

@Injectable()
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
  canDeactivate(component: ComponentCanDeactivate): boolean {
    return  component.canDeactivate() ?
     //code : //more code
  }
}
</code>```

In one of my component i have the following code

```<code>export class DashboardComponent implements ComponentCanDeactivate{
  @HostListener('window:beforeunload')
  canDeactivate(): boolean {
    return !this.isDirty;
  }
</code>```

My problem is that my component -> (component: ComponentCanDeactivate) from PendingChangesGuard  is always null so i get an error saying

Cannot call canDeactivate() of null

I also have this setup in my routing

```<code> path: 'dashboard',
        canDeactivate: [PendingChangesGuard],
        loadChildren: './views/dashboard/dashboard.module#DashboardModule'
</code>```

Can someone tell me what am i doing wrong?

答:
I implement like this

Deactive-guard-service.ts

```<code>export interface CanComponentDeactivate {
  canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}

@Injectable()
export class DeactivateGuardService implements  CanDeactivate<CanComponentDeactivate>{

  canDeactivate(component: CanComponentDeactivate) {
    return component.canDeactivate ? component.canDeactivate() : true;
  }
}
</code>```

Component.ts

```<code>checkSave(): Promise<boolean> {
    var prom = new Promise<boolean>((resolve, reject) => {
      //check saved change
        if(saved) resolve(true);
        else reject(false);
    });
    return prom;
  }

  canDeactivate(): Promise<boolean> {

    return this.checkSave().catch(function () {
      return false;
    });
  }
</code>```

Body:
I have this interface that i'm using to prevent the user to leave page

export interface ComponentCanDeactivate {
  canDeactivate: () => boolean;
}

@Injectable()
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
  canDeactivate(component: ComponentCanDeactivate): boolean {
    return  component.canDeactivate() ?
     //code : //more code
  }
}

In one of my component i have the following code

export class DashboardComponent implements ComponentCanDeactivate{
  @HostListener('window:beforeunload')
  canDeactivate(): boolean {
    return !this.isDirty;
  }

My problem is that my component -> (component: ComponentCanDeactivate) from PendingChangesGuard  is always null so i get an error saying

Cannot call canDeactivate() of null

I also have this setup in my routing

 path: 'dashboard',
        canDeactivate: [PendingChangesGuard],
        loadChildren: './views/dashboard/dashboard.module#DashboardModule'

Can someone tell me what am i doing wrong?

Body:
I implement like this

Deactive-guard-service.ts

export interface CanComponentDeactivate {
  canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}

@Injectable()
export class DeactivateGuardService implements  CanDeactivate<CanComponentDeactivate>{

  canDeactivate(component: CanComponentDeactivate) {
    return component.canDeactivate ? component.canDeactivate() : true;
  }
}

Component.ts

checkSave(): Promise<boolean> {
    var prom = new Promise<boolean>((resolve, reject) => {
      //check saved change
        if(saved) resolve(true);
        else reject(false);
    });
    return prom;
  }

  canDeactivate(): Promise<boolean> {

    return this.checkSave().catch(function () {
      return false;
    });
  }


问:
Bash-shell after matching one file from another file, print out both match content and not match content at one time
```<code>cat fiel1.txt
cheng 600
huang 500
pan 400
yin 300

cat file2.txt
600 a
300 c
</code>```

After I execute

```<code>awk 'NR==FNR{a[$1]=$2;next}($2 in a){print $1,$2,a[$2]}' f2.txt f1.txt
</code>```

The result as below:

```<code>cheng 600 a
yin 300 c
</code>```

and I also want to print the column that not in array a . like below:

```<code>cheng 600 a
huang 500
pan 400
yin 300 c
</code>```

How can I get the result. I try command like below:

```<code>awk 'NR==FNR{a[$1]=$2;next}($2 in a){print $1,$2,a[$2]}($2 not in a){print $1,$2,a[$2]}' f2.txt f1.txt
</code>```

But it was failed.

答:
```<code>$ awk 'NR==FNR{a[$1]=$2;next} {if($2 in a)print $1,$2,a[$2]; else print $1,$2}' f2.txt f1.txt
cheng 600 a
huang 500
pan 400
yin 300 c
</code>```

Discussion

You had:

```<code>($2 in a){print $1,$2,a[$2]}
</code>```

This prints only if $2 is in a.  We replaced that with:

```<code>if($2 in a)print $1,$2,a[$2]; else print $1,$2
</code>```

This prints $1,$2,a[$2] is $2 is in a.  Otherwise, it just prints $1,$2.

Simpler version

If you mind some extraneous trailing blanks, we can use the still simpler:

```<code>$ awk 'NR==FNR{a[$1]=$2;next} {print $1,$2,a[$2]}' f2.txt f1.txt
cheng 600 a
huang 500
pan 400
yin 300 c
</code>```

Body:
cat fiel1.txt
cheng 600
huang 500
pan 400
yin 300

cat file2.txt
600 a
300 c

After I execute

awk 'NR==FNR{a[$1]=$2;next}($2 in a){print $1,$2,a[$2]}' f2.txt f1.txt

The result as below:

cheng 600 a
yin 300 c

and I also want to print the column that not in array a . like below:

cheng 600 a
huang 500
pan 400
yin 300 c

How can I get the result. I try command like below:

awk 'NR==FNR{a[$1]=$2;next}($2 in a){print $1,$2,a[$2]}($2 not in a){print $1,$2,a[$2]}' f2.txt f1.txt

But it was failed.

Body:
$ awk 'NR==FNR{a[$1]=$2;next} {if($2 in a)print $1,$2,a[$2]; else print $1,$2}' f2.txt f1.txt
cheng 600 a
huang 500
pan 400
yin 300 c

Discussion

You had:

($2 in a){print $1,$2,a[$2]}

This prints only if $2 is in a.  We replaced that with:

if($2 in a)print $1,$2,a[$2]; else print $1,$2

This prints $1,$2,a[$2] is $2 is in a.  Otherwise, it just prints $1,$2.

Simpler version

If you mind some extraneous trailing blanks, we can use the still simpler:

$ awk 'NR==FNR{a[$1]=$2;next} {print $1,$2,a[$2]}' f2.txt f1.txt
cheng 600 a
huang 500
pan 400
yin 300 c


问:
API request Weather Underground
Hello I am trying to get a API request with python 3 for weather underground to just do a simple print of the weather conditions, can someone give me a tip what I am doing wrong? I have a lot to learn here, so the learning curve is steep! Sorry if the question is super basic, what is the better code to use between the two? At least with one that I could get working and then build off of... Thank you. Both of these codes below are example scripts that I got from WU website & Github. The first code gives me an error "for observation in data (['history']['observations']):
TypeError: list indices must be integers or slices, not str"

```<code>from urllib.request import urlopen
import json

api_key = ""
date = "20170901"
zip_code = "53711"

response = urlopen("http://api.wunderground.com/api/%s/history_%s/q/%s.json"
% (api_key, date, zip_code))

json_data = response.read().decode('utf-8', 'replace')

data = json.loads(json_data)

for observation in data (['history']['observations']):
     print("Date/Time:    " + observation['date']['pretty'])
     print("Temperature:  " + observation['tempi'])
     print("Humidity:     " + observation['hum'])
</code>```

This is a second attempt at my first API request, but it give me an error "TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'"

```<code>from urllib.request import urlopen
import json

f = urlopen('http://api.wunderground.com/api//geolookup/conditions/q/IA/Cedar_Rapids.json')

json_string = f.read()

parsed_json = json.loads(json_string)

location = parsed_json['location']['city']

temp_f = parsed_json['current_observation']['temp_f']

print ("Current temperature in %s is: %s") % (location, temp_f)
f.close()
</code>```

Any tip that a pro can give a newb on self teaching topics like this is greatly appreciated... I can see from WU that my API key is working... But the code is wrong :(

答:
The reason for the error you were encountering in your second example is because that appears to be invalid syntax. I think what you are looking for is something similar to the following.

```<code>print("this is a %s" % ("my string",))
</code>```

That being said, I put together a package a little while ago to help with getting started with Weather Underground if you want to take a look for some pointers. Or just pip install WunderWeather. Here's the doc.

Title: API request Weather Underground

Body:
Hello I am trying to get a API request with python 3 for weather underground to just do a simple print of the weather conditions, can someone give me a tip what I am doing wrong? I have a lot to learn here, so the learning curve is steep! Sorry if the question is super basic, what is the better code to use between the two? At least with one that I could get working and then build off of... Thank you. Both of these codes below are example scripts that I got from WU website & Github. The first code gives me an error "for observation in data (['history']['observations']):
TypeError: list indices must be integers or slices, not str"

from urllib.request import urlopen
import json

api_key = ""
date = "20170901"
zip_code = "53711"

response = urlopen("http://api.wunderground.com/api/%s/history_%s/q/%s.json"
% (api_key, date, zip_code))

json_data = response.read().decode('utf-8', 'replace')

data = json.loads(json_data)

for observation in data (['history']['observations']):
     print("Date/Time:    " + observation['date']['pretty'])
     print("Temperature:  " + observation['tempi'])
     print("Humidity:     " + observation['hum'])

This is a second attempt at my first API request, but it give me an error "TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'"

from urllib.request import urlopen
import json

f = urlopen('http://api.wunderground.com/api//geolookup/conditions/q/IA/Cedar_Rapids.json')

json_string = f.read()

parsed_json = json.loads(json_string)

location = parsed_json['location']['city']

temp_f = parsed_json['current_observation']['temp_f']

print ("Current temperature in %s is: %s") % (location, temp_f)
f.close()

Any tip that a pro can give a newb on self teaching topics like this is greatly appreciated... I can see from WU that my API key is working... But the code is wrong :(

Body:
The reason for the error you were encountering in your second example is because that appears to be invalid syntax. I think what you are looking for is something similar to the following.

print("this is a %s" % ("my string",))

That being said, I put together a package a little while ago to help with getting started with Weather Underground if you want to take a look for some pointers. Or just pip install WunderWeather. Here's the doc.


问:
PCL App Development - Button not clickable following splash screen transition
I am working on an app with a group of friends for a Twitch project.  I have recently integrated a splash animation when the app starts up. The only issue is, this splash animation renders my login button on the main page useless.  Now, if I move the button code, the button appears before the transition is complete (undesired result), but the button will work.  If I keep the code in place where the button shows up post transition (desired result), it isn't clickable (undesired result).  I'm sure you can see my frustration. The code is pasted below.  Please keep in mind I am very new to coding in general, so if this seems like a no-brainer, please have mercy.

XAML for LoginPage:

```<code>  <Grid>
    <Image x:Name="image" Aspect="AspectFit"/>
    <Button     HorizontalOptions="Center"
                VerticalOptions="Center"
                BackgroundColor="#008b8b"
                Image="twitchtwo.png"
                Text="  Login using Twitch!"
                FontSize="14"
                TextColor="White"
                Clicked="Button_Clicked"/>
    <Grid x:Name="SplashGrid" BackgroundColor="#007272">
      <Image  x:Name="Logo"
              Source="logo"
              HorizontalOptions="Center"
              VerticalOptions="Center">
        <Image.TranslationY>
          <OnPlatform x:TypeArguments="x:Double">
            <On Platform="iOS">0</On>
            <On Platform="Android">-12</On>
          </OnPlatform>
        </Image.TranslationY>
      </Image>
    </Grid>
  </Grid>
</code>```

C# code behind for LoginPage:

```<code>{
  [XamlCompilation(XamlCompilationOptions.Compile)]
  public partial class LoginPage : ContentPage
  {
    public LoginPage()
    {
      InitializeComponent();
      image.Source = ImageSource.FromResource("CCG.Images.ccgtext.png");
    }
    protected override async void OnAppearing()
    {
      base.OnAppearing();
      await Task.Delay(2000);
      await Task.WhenAll(
        SplashGrid.FadeTo(0, 2000),
        Logo.ScaleTo(0, 250)
        );
    }
    private async void Button_Clicked(object sender, EventArgs e)
    {
      await Navigation.PushModalAsync(new TwitchAuth());
    }
  }
}
</code>```

答:
You're fading your SplashGrid element, fading will set its opacity to whatever you specify it (0). The element is still over your page, but its opacity is 0. Just set the Visibility to Collapsed or Hidden after the fading is done.

```<code>protected override async void OnAppearing()
{
  base.OnAppearing();
  await Task.Delay(2000);
  await Task.WhenAll(
    SplashGrid.FadeTo(0, 2000),
    Logo.ScaleTo(0, 250)
    );
  SplashGrid.Visibility = Visibility.Hidden;
}
</code>```

Body:
I am working on an app with a group of friends for a Twitch project.  I have recently integrated a splash animation when the app starts up. The only issue is, this splash animation renders my login button on the main page useless.  Now, if I move the button code, the button appears before the transition is complete (undesired result), but the button will work.  If I keep the code in place where the button shows up post transition (desired result), it isn't clickable (undesired result).  I'm sure you can see my frustration. The code is pasted below.  Please keep in mind I am very new to coding in general, so if this seems like a no-brainer, please have mercy.

XAML for LoginPage:

  <Grid>
    <Image x:Name="image" Aspect="AspectFit"/>
    <Button     HorizontalOptions="Center"
                VerticalOptions="Center"
                BackgroundColor="#008b8b"
                Image="twitchtwo.png"
                Text="  Login using Twitch!"
                FontSize="14"
                TextColor="White"
                Clicked="Button_Clicked"/>
    <Grid x:Name="SplashGrid" BackgroundColor="#007272">
      <Image  x:Name="Logo"
              Source="logo"
              HorizontalOptions="Center"
              VerticalOptions="Center">
        <Image.TranslationY>
          <OnPlatform x:TypeArguments="x:Double">
            <On Platform="iOS">0</On>
            <On Platform="Android">-12</On>
          </OnPlatform>
        </Image.TranslationY>
      </Image>
    </Grid>
  </Grid>

C# code behind for LoginPage:

{
  [XamlCompilation(XamlCompilationOptions.Compile)]
  public partial class LoginPage : ContentPage
  {
    public LoginPage()
    {
      InitializeComponent();
      image.Source = ImageSource.FromResource("CCG.Images.ccgtext.png");
    }
    protected override async void OnAppearing()
    {
      base.OnAppearing();
      await Task.Delay(2000);
      await Task.WhenAll(
        SplashGrid.FadeTo(0, 2000),
        Logo.ScaleTo(0, 250)
        );
    }
    private async void Button_Clicked(object sender, EventArgs e)
    {
      await Navigation.PushModalAsync(new TwitchAuth());
    }
  }
}

Body:
You're fading your SplashGrid element, fading will set its opacity to whatever you specify it (0). The element is still over your page, but its opacity is 0. Just set the Visibility to Collapsed or Hidden after the fading is done.

protected override async void OnAppearing()
{
  base.OnAppearing();
  await Task.Delay(2000);
  await Task.WhenAll(
    SplashGrid.FadeTo(0, 2000),
    Logo.ScaleTo(0, 250)
    );
  SplashGrid.Visibility = Visibility.Hidden;
}


问:
WSE 3.0 and SoapExtensions
I'm trying to consume an Axis web service with a .NET client and I'm having some trouble setting up the WSE configuration to work with it. I know that WSE 3.0 is an outdated technology, but I'm stuck with a VS2005 and .NET 2.0 environment, so I'll have to work with this.

Currently I've created a new ASP.NET Website application and enabled WSE on it. It generages a bunch of sections like the WS:Addressing and WS:Timestamp sections from it that the server cannot handle and I'm looking to remove them. I couldn't find a config setting to do it, so after some searching on SO, I've started working with SoapExtensions to intercept the message and remove the sections manually.

My problem currently seems to be that the code in the SoapExtensions isn't getting executed at all. Here's my web.config -

```<code><configuration>
  <configSections>
    <section name="microsoft.web.services3" type="Microsoft.Web.Services3.Configuration.WebServicesConfiguration, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  </configSections>
  <appSettings>
    <add key="WebSvc.SecureService" value="<Trimmed>" />
  </appSettings>
  <connectionStrings />
  <system.web>
    <compilation debug="true">
      <assemblies>
        <add assembly="Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>
    <authentication mode="Windows" />
    <webServices>
      <soapExtensionImporterTypes>
        <add type="Microsoft.Web.Services3.Description.WseExtensionImporter, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      </soapExtensionImporterTypes>
      <soapServerProtocolFactory type="Microsoft.Web.Services3.WseProtocolFactory, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </webServices>
  </system.web>
  <microsoft.web.services3>
    <security>
      <x509 verifyTrust="false" />
      <defaultTtlInSeconds value="0" />
      <timeToleranceInSeconds value="0" />
    </security>
    <diagnostics>
      <trace enabled="true" input="InputTrace.webinfo" output="OutputTrace.webinfo" />
    </diagnostics>
    <policy fileName="wse3policyCache.config" />
  </microsoft.web.services3>
</configuration>
</code>```

And my web service method -

```<code>[WebMethod]
[TestApplication.TraceExtensionAttribute]
public void SendTestMessage()
{
    WebSvc.B2BSecureServiceServiceWse svcClient = new WebSvc.B2BSecureServiceServiceWse();
    svcClient.SetPolicy("Policy1");
    WebSvc.B2BRequest request = new WebSvc.B2BRequest();
    WebSvc.B2BRequestHeader WebSvc= new WebSvc.B2BRequestHeader();
    // Set Request header properties
    request.header = requestHeader;
    request.msgPayload = ""; // Text removed

    try
    {
        WebSvc.Response response = svcClient.processRequest(request);
    }
    catch (Exception ex)
    {

    }
}
</code>```

And here's my SoapExtension Class -

```<code>public class Snoop : SoapExtension
{
    Stream oldStream;
    Stream newStream;
    string filename;

    // Save the Stream representing the SOAP request or SOAP response into
    // a local memory buffer.
    public override Stream ChainStream(Stream stream)
    {
        oldStream = stream;
        newStream = new MemoryStream();
        return newStream;
    }

    // When the SOAP extension is accessed for the first time, the XML Web
    // service method it is applied to is accessed to store the file
    // name passed in, using the corresponding SoapExtensionAttribute.
    public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
    {
        return ((TraceExtensionAttribute)attribute).Filename;
    }
    // The SOAP extension was configured to run using a configuration file
    // instead of an attribute applied to a specific XML Web service
    // method.
    public override object GetInitializer(Type WebServiceType)
    {
        // Return a file name to log the trace information to, based on the
        // type.
        return "C:\\" + WebServiceType.FullName + ".log";
    }
    // Receive the file name stored by GetInitializer and store it in a
    // member variable for this specific instance.
    public override void Initialize(object initializer)
    {
        filename = (string)initializer;
    }
    //  If the SoapMessageStage is such that the SoapRequest or
    //  SoapResponse is still in the SOAP format to be sent or received,
    //  save it out to a file.
    public override void ProcessMessage(SoapMessage message)
    {
        switch (message.Stage)
        {
            case SoapMessageStage.BeforeSerialize:
                break;
            case SoapMessageStage.AfterSerialize:
                WriteOutput(message);
                break;
            case SoapMessageStage.BeforeDeserialize:
                WriteInput(message);
                break;
            case SoapMessageStage.AfterDeserialize:
                break;
        }
    }

    public void WriteOutput(SoapMessage message)
    {
        newStream.Position = 0;
        FileStream fs = new FileStream(filename, FileMode.Append,
            FileAccess.Write);
        StreamWriter w = new StreamWriter(fs);

        string soapString = (message is SoapServerMessage) ? "SoapResponse" : "SoapRequest";
        w.WriteLine("-----" + soapString + " at " + DateTime.Now);
        w.Flush();
        Copy(newStream, fs);
        w.Close();
        newStream.Position = 0;
        Copy(newStream, oldStream);
    }

    public void WriteInput(SoapMessage message)
    {
        Copy(oldStream, newStream);
        FileStream fs = new FileStream(filename, FileMode.Append,
            FileAccess.Write);
        StreamWriter w = new StreamWriter(fs);

        string soapString = (message is SoapServerMessage) ?
            "SoapRequest" : "SoapResponse";
        w.WriteLine("-----" + soapString +
            " at " + DateTime.Now);
        w.Flush();
        newStream.Position = 0;
        Copy(newStream, fs);
        w.Close();
        newStream.Position = 0;
    }

    void Copy(Stream from, Stream to)
    {
        TextReader reader = new StreamReader(from);
        TextWriter writer = new StreamWriter(to);
        writer.WriteLine(reader.ReadToEnd());
        writer.Flush();
    }

}
// Create a SoapExtensionAttribute for the SOAP Extension that can be
// applied to an XML Web service method.
[AttributeUsage(AttributeTargets.Method)]
public class TraceExtensionAttribute : SoapExtensionAttribute
{

    private string filename = "c:\\log.txt";
    private int priority;

    public override Type ExtensionType
    {
        get { return typeof(Snoop); }
    }

    public override int Priority
    {
        get { return priority; }
        set { priority = value; }
    }

    public string Filename
    {
        get
        {
            return filename;
        }
        set
        {
            filename = value;
        }
    }
}
</code>```

I'm guessing I'm doing something wrong while trying to assign the SoapExtension to that method call, so any help is much appreciated!

答: For anyone who comes across this problem, here's how I've solved it using SoapFilters. Here's the process from MSDN - http://msdn.microsoft.com/en-us/library/aa528788.aspx</p>

Title: WSE 3.0 and SoapExtensions

Body:
I'm trying to consume an Axis web service with a .NET client and I'm having some trouble setting up the WSE configuration to work with it. I know that WSE 3.0 is an outdated technology, but I'm stuck with a VS2005 and .NET 2.0 environment, so I'll have to work with this.

Currently I've created a new ASP.NET Website application and enabled WSE on it. It generages a bunch of sections like the WS:Addressing and WS:Timestamp sections from it that the server cannot handle and I'm looking to remove them. I couldn't find a config setting to do it, so after some searching on SO, I've started working with SoapExtensions to intercept the message and remove the sections manually.

My problem currently seems to be that the code in the SoapExtensions isn't getting executed at all. Here's my web.config -

<configuration>
  <configSections>

  </configSections>
  <appSettings>
    <add key="WebSvc.SecureService" value="<Trimmed>" />
  </appSettings>
  <connectionStrings />
  <system.web>
    <compilation debug="true">
      <assemblies>
        <add assembly="Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>
    <authentication mode="Windows" />
    <webServices>
      <soapExtensionImporterTypes>
        <add type="Microsoft.Web.Services3.Description.WseExtensionImporter, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      </soapExtensionImporterTypes>
      <soapServerProtocolFactory type="Microsoft.Web.Services3.WseProtocolFactory, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </webServices>
  </system.web>
  <microsoft.web.services3>
    <security>
      <x509 verifyTrust="false" />
      <defaultTtlInSeconds value="0" />
      <timeToleranceInSeconds value="0" />
    </security>
    <diagnostics>
      <trace enabled="true" input="InputTrace.webinfo" output="OutputTrace.webinfo" />
    </diagnostics>
    <policy fileName="wse3policyCache.config" />
  </microsoft.web.services3>
</configuration>

And my web service method -

[WebMethod]
[TestApplication.TraceExtensionAttribute]
public void SendTestMessage()
{
    WebSvc.B2BSecureServiceServiceWse svcClient = new WebSvc.B2BSecureServiceServiceWse();
    svcClient.SetPolicy("Policy1");
    WebSvc.B2BRequest request = new WebSvc.B2BRequest();
    WebSvc.B2BRequestHeader WebSvc= new WebSvc.B2BRequestHeader();
    // Set Request header properties
    request.header = requestHeader;
    request.msgPayload = ""; // Text removed

    try
    {
        WebSvc.Response response = svcClient.processRequest(request);
    }
    catch (Exception ex)
    {

    }
}

And here's my SoapExtension Class -

public class Snoop : SoapExtension
{
    Stream oldStream;
    Stream newStream;
    string filename;

    // Save the Stream representing the SOAP request or SOAP response into
    // a local memory buffer.
    public override Stream ChainStream(Stream stream)
    {
        oldStream = stream;
        newStream = new MemoryStream();
        return newStream;
    }

    // When the SOAP extension is accessed for the first time, the XML Web
    // service method it is applied to is accessed to store the file
    // name passed in, using the corresponding SoapExtensionAttribute.
    public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
    {
        return ((TraceExtensionAttribute)attribute).Filename;
    }
    // The SOAP extension was configured to run using a configuration file
    // instead of an attribute applied to a specific XML Web service
    // method.
    public override object GetInitializer(Type WebServiceType)
    {
        // Return a file name to log the trace information to, based on the
        // type.
        return "C:\\" + WebServiceType.FullName + ".log";
    }
    // Receive the file name stored by GetInitializer and store it in a
    // member variable for this specific instance.
    public override void Initialize(object initializer)
    {
        filename = (string)initializer;
    }
    //  If the SoapMessageStage is such that the SoapRequest or
    //  SoapResponse is still in the SOAP format to be sent or received,
    //  save it out to a file.
    public override void ProcessMessage(SoapMessage message)
    {
        switch (message.Stage)
        {
            case SoapMessageStage.BeforeSerialize:
                break;
            case SoapMessageStage.AfterSerialize:
                WriteOutput(message);
                break;
            case SoapMessageStage.BeforeDeserialize:
                WriteInput(message);
                break;
            case SoapMessageStage.AfterDeserialize:
                break;
        }
    }

    public void WriteOutput(SoapMessage message)
    {
        newStream.Position = 0;
        FileStream fs = new FileStream(filename, FileMode.Append,
            FileAccess.Write);
        StreamWriter w = new StreamWriter(fs);

        string soapString = (message is SoapServerMessage) ? "SoapResponse" : "SoapRequest";
        w.WriteLine("-----" + soapString + " at " + DateTime.Now);
        w.Flush();
        Copy(newStream, fs);
        w.Close();
        newStream.Position = 0;
        Copy(newStream, oldStream);
    }

    public void WriteInput(SoapMessage message)
    {
        Copy(oldStream, newStream);
        FileStream fs = new FileStream(filename, FileMode.Append,
            FileAccess.Write);
        StreamWriter w = new StreamWriter(fs);

        string soapString = (message is SoapServerMessage) ?
            "SoapRequest" : "SoapResponse";
        w.WriteLine("-----" + soapString +
            " at " + DateTime.Now);
        w.Flush();
        newStream.Position = 0;
        Copy(newStream, fs);
        w.Close();
        newStream.Position = 0;
    }

    void Copy(Stream from, Stream to)
    {
        TextReader reader = new StreamReader(from);
        TextWriter writer = new StreamWriter(to);
        writer.WriteLine(reader.ReadToEnd());
        writer.Flush();
    }

}
// Create a SoapExtensionAttribute for the SOAP Extension that can be
// applied to an XML Web service method.
[AttributeUsage(AttributeTargets.Method)]
public class TraceExtensionAttribute : SoapExtensionAttribute
{

    private string filename = "c:\\log.txt";
    private int priority;

    public override Type ExtensionType
    {
        get { return typeof(Snoop); }
    }

    public override int Priority
    {
        get { return priority; }
        set { priority = value; }
    }

    public string Filename
    {
        get
        {
            return filename;
        }
        set
        {
            filename = value;
        }
    }
}

I'm guessing I'm doing something wrong while trying to assign the SoapExtension to that method call, so any help is much appreciated!


问:
How to disable sass --watch initiated folder
Got my SASS working - great - amazing documentation everywhere. http://sass-lang.com/guide was the guide I followed.

```<code>sass --watch myfolder/css
</code>```

Ran a command of sort, worked great - every change to .scss resulted in a fully packaged & minified .css. Great!

However I installed phpStorm IDE, and because it has built-in file watchers for SASS, jsUglify etc., I no longer need the SASS to run its own watches within a specific directory. Not to mention, when a sync happens (when another developer in my firm commits an update and it rolls back to my desktop) it runs automatically and sometimes due to relative SCSS file inputs, a .css file that was perfectly fine on a co-worker's station becomes an error file on my desktop saying it's missing a required .scss file.

It's not only a CPU drain but also causing errors.

Anyway long story short, that separate watcher I set up on Mac OSX through terminal has to be REMOVED/DISABLED and my searches through Google & the documentation did not help at all.

答:
Okay, it sounds like you have a couple of issues here.

The first is more of a workflow problem, and it's the easiest to solve so I'll go into that first.

Not to mention, when a sync happens (when another developer in my firm commits an update and it rolls back to my desktop)

Presumably you're using version control....in which case - why are you working on the same branch as another dev? You're setting yourself up for issues doing that. I noticed you used the term "sync" which makes me wonder if you're using "GitHub Desktop". If so, I'd recommend something perhaps a little less opaque. I don't care for the way it hides away push/pull behind "Sync" - perhaps Git Kraken, or the command line? Either way, try to avoid working on the same branch as someone else...

Now to deal with the issue of sas watchers. Sass (as far as I'm aware) does not by default have watch functionality unless you explicitly invoke that when you run the sass command with the watch flag. If you're not doing that - it sounds like there's something else odd going on behind the scenes that you're not aware of that's watching and re-compiling the sass...

Body:
Got my SASS working - great - amazing documentation everywhere. http://sass-lang.com/guide was the guide I followed.

sass --watch myfolder/css

Ran a command of sort, worked great - every change to .scss resulted in a fully packaged & minified .css. Great!

However I installed phpStorm IDE, and because it has built-in file watchers for SASS, jsUglify etc., I no longer need the SASS to run its own watches within a specific directory. Not to mention, when a sync happens (when another developer in my firm commits an update and it rolls back to my desktop) it runs automatically and sometimes due to relative SCSS file inputs, a .css file that was perfectly fine on a co-worker's station becomes an error file on my desktop saying it's missing a required .scss file.

It's not only a CPU drain but also causing errors.

Anyway long story short, that separate watcher I set up on Mac OSX through terminal has to be REMOVED/DISABLED and my searches through Google & the documentation did not help at all.


问:
html5 mode with grunt serve not working
In grunt file, livereload block looks like this:

livereload: {
  options: {
    open: true,
    middleware: function(connect, options, middleware) {
      var optBase = (typeof options.base === 'string') ? [options.base] : options.base;
      return [
        [require('connect-modrewrite')(['!(\\..+)$ / [L]'])].concat(
          optBase.map(function(path) {
            return connect.static(path);
          })),
        connect.static('.tmp'),
        connect().use(
          '/bower_components',
          connect.static('./bower_components')
        ),
        connect().use(
          '/app/styles',
          connect.static('./app/styles')
        ),
        connect.static(appConfig.app)
      ];
    }
  }
},
```

<p>Adding:</p>

``` [require('connect-modrewrite')(['!(\\..+)$ / [L]'])].concat(
                    optBase.map(function(path){ return connect.static(path); })),
```

did use to work for me to enable html5 mode, otherwise, my routes do not load without #! when I try to reload via the browser.

I do have base href='/' added and html5Mode(true) in config. Is there anything else I can try? Why would it really stop working?

Note: Turns out that my URL has a dot in it and that is not being handled by connect-mod rewrite rule so well. Any idea how to change that and enable it to handle dot in URL?

答:
I believe the dot problem is a side effect of the general problem. Have the same setup, more or less. I simply reset the html5Mode in .config() like this :

```<code>if (window.location.host == 'localhost:9000') {
   $locationProvider.html5Mode(false);
   $locationProvider.hashPrefix('');
} else {
   $locationProvider.html5Mode(true);
}
</code>```

The app will still prefix all urls with #/ in development mode, making urls, linking and livereload a pain. Solved this by a small directive that changes regular /urls to /#/urls :

```<code>var isLocalHost = (location.hostname === "localhost" || location.hostname === "127.0.0.1");
angular.module('myApp').directive('debugLink', function($timeout) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      $timeout(function() {
        var href = element.attr('href');
        if (href && isLocalHost && href.charAt(0) == '/') {
          element.attr('href', '#'+href);
        }
      }, 100);
    }
  }
});
</code>```

Now linking can be done by link

Finally I use the .htaccess redirect from https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode on the production server

```<code>RewriteEngine on

# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]
</code>```

I use this approach in several angularjs+grunt projects. It prevent the livereload from breaking, i.e when I hit Ctrl-S the page is refreshed, and I can use the correct urls anywhere. I guess no one is interested in having prefixes or hashes in production mode.

Title: html5 mode with grunt serve not working

Body:
In grunt file, livereload block looks like this:

livereload: {
  options: {
    open: true,
    middleware: function(connect, options, middleware) {
      var optBase = (typeof options.base === 'string') ? [options.base] : options.base;
      return [
        [require('connect-modrewrite')(['!(\\..+)$ / [L]'])].concat(
          optBase.map(function(path) {
            return connect.static(path);
          })),
        connect.static('.tmp'),
        connect().use(
          '/bower_components',
          connect.static('./bower_components')
        ),
        connect().use(
          '/app/styles',
          connect.static('./app/styles')
        ),
        connect.static(appConfig.app)
      ];
    }
  }
},

Adding:

 [require('connect-modrewrite')(['!(\\..+)$ / [L]'])].concat(
                    optBase.map(function(path){ return connect.static(path); })),

did use to work for me to enable html5 mode, otherwise, my routes do not load without #! when I try to reload via the browser.

I do have base href='/' added and html5Mode(true) in config. Is there anything else I can try? Why would it really stop working?

Note: Turns out that my URL has a dot in it and that is not being handled by connect-mod rewrite rule so well. Any idea how to change that and enable it to handle dot in URL?

Body:
I believe the dot problem is a side effect of the general problem. Have the same setup, more or less. I simply reset the html5Mode in .config() like this :

if (window.location.host == 'localhost:9000') {
   $locationProvider.html5Mode(false);
   $locationProvider.hashPrefix('');
} else {
   $locationProvider.html5Mode(true);
}

The app will still prefix all urls with #/ in development mode, making urls, linking and livereload a pain. Solved this by a small directive that changes regular /urls to /#/urls :

var isLocalHost = (location.hostname === "localhost" || location.hostname === "127.0.0.1");
angular.module('myApp').directive('debugLink', function($timeout) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      $timeout(function() {
        var href = element.attr('href');
        if (href && isLocalHost && href.charAt(0) == '/') {
          element.attr('href', '#'+href);
        }
      }, 100);
    }
  }
});

Now linking can be done by <a href="/url" debug-link>link</a>

Finally I use the .htaccess redirect from https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode on the production server

RewriteEngine on

# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]

I use this approach in several angularjs+grunt projects. It prevent the livereload from breaking, i.e when I hit Ctrl-S the page is refreshed, and I can use the correct urls anywhere. I guess no one is interested in having prefixes or hashes in production mode.


问:
Pandas: Calculate remaining time in grouping
I have a requirement to sort a table by date starting from the oldest. Total field is created by grouping name and kind fields and applying sum. Now for each row I need to calculate the remaining time in the same name-kind grouping.

The csv looks like that:

```<code>date       name kind duration total remaining
1-1-2017   a    1    10       100   ? should be 90
2-1-2017   b    1    5        35    ? should be 30
3-1-2017   a    2    3        50    ? should be 47
4-1-2017   b    2    1        25    ? should be 24
5-1-2017   a    1    8        100   ? should be 82
6-1-2017   b    1    2        35    ? should be 33
7-1-2017   a    2    3        50    ? should be 44
8-1-2017   b    2    6        25    ? should be 18
...
</code>```

My question is how do I calculate the remaining value while having the DataFrame grouped by name and kind?

My initial approach was to shift the column and add the values from duration to each other like that:

```<code>df['temp'] = df.groupby(['name', 'kind'])['duration'].apply(lambda x: x.shift() + x)
</code>```

and then:

```<code>df['duration'] = df.apply(lambda x: x['total'] - x['temp'], axis=1)
</code>```

But it did not work as expected.

Is there a clean way to do it, or using the iloc, ix, loc somehow is the way to go?

Thanks.

答:
You could do something like:

```<code>df["cumsum"] = df.groupby(['name', 'kind'])["duration"].cumsum()
df["remaining"] = df["total"] - df["cumsum"]
</code>```

Being careful with resetting the index maybe.

Body:
I have a requirement to sort a table by date starting from the oldest. Total field is created by grouping name and kind fields and applying sum. Now for each row I need to calculate the remaining time in the same name-kind grouping.

The csv looks like that:

date       name kind duration total remaining
1-1-2017   a    1    10       100   ? should be 90
2-1-2017   b    1    5        35    ? should be 30
3-1-2017   a    2    3        50    ? should be 47
4-1-2017   b    2    1        25    ? should be 24
5-1-2017   a    1    8        100   ? should be 82
6-1-2017   b    1    2        35    ? should be 33
7-1-2017   a    2    3        50    ? should be 44
8-1-2017   b    2    6        25    ? should be 18
...

My question is how do I calculate the remaining value while having the DataFrame grouped by name and kind?

My initial approach was to shift the column and add the values from duration to each other like that:

df['temp'] = df.groupby(['name', 'kind'])['duration'].apply(lambda x: x.shift() + x)

and then:

df['duration'] = df.apply(lambda x: x['total'] - x['temp'], axis=1)

But it did not work as expected.

Is there a clean way to do it, or using the iloc, ix, loc somehow is the way to go?

Thanks.

Body:
You could do something like:

df["cumsum"] = df.groupby(['name', 'kind'])["duration"].cumsum()
df["remaining"] = df["total"] - df["cumsum"]

Being careful with resetting the index maybe.


问:
Ruby: PUT Request with JSON body?
I need to create an HTTP PUT request using ruby.

The request has a JSON body

I was able to generate the JSON body using:

```<code>require 'rubygems'
require 'json'
jsonbody = JSON.generate["message"=>"test","user"=>"user1"]
</code>```

I need to send this PUT request to the url:

```<code>require 'open-uri'
url = URI.parse('http://www.data.com?access_token=123')
</code>```

Can someone please tell me how I can do this in Ruby?

答:
Using restclient (gem install rest-client) like this:

```<code>require 'rubygems'
require 'rest_client'
require 'json'

jdata = JSON.generate(["test"])
RestClient.put 'http://localhost:4567/users/123', jdata, {:content_type => :json}
</code>```

against the following sinatra service:

```<code>require 'sinatra'
require 'json'

put '/users/:id' do |n|
  data = JSON.parse(request.body.read)
  "Got #{data} for user #{n}"
end
</code>```

works on my computer.

Title: Ruby: PUT Request with JSON body?

Body:
I need to create an HTTP PUT request using ruby.

The request has a JSON body

I was able to generate the JSON body using:

require 'rubygems'
require 'json'
jsonbody = JSON.generate["message"=>"test","user"=>"user1"]

I need to send this PUT request to the url:

require 'open-uri'
url = URI.parse('http://www.data.com?access_token=123')

Can someone please tell me how I can do this in Ruby?

Body:
Using restclient (gem install rest-client) like this:

require 'rubygems'
require 'rest_client'
require 'json'

jdata = JSON.generate(["test"])
RestClient.put 'http://localhost:4567/users/123', jdata, {:content_type => :json}

against the following sinatra service:

require 'sinatra'
require 'json'

put '/users/:id' do |n|
  data = JSON.parse(request.body.read)
  "Got #{data} for user #{n}"
end

works on my computer.


问:
Why does this C# function exist in Visual Studio 2015 but not Visual Studio 2017
Just someone can explain me why this work on Visual Studio 2015 but not on Visual Studio 2017 ?

```<code>public static TConvert DynamicPop<TObject, TConvert>(this IEnumerable<TObject> obj, Converter<TObject, TConvert> converter, long @default = 1)
    {
        if (obj.Count() == 0)
        {
            dynamic _defaut = @default;
            return (TConvert)_defaut;
        }
        var collection = obj.ConvertAll<TConvert>(converter);
        collection.Sort();
        dynamic lastValue = collection.Last();
        return (TConvert)(lastValue + 1);
    }
</code>```

That said to me that ConvertAll doesn't exist.

答:
As mentioned in the comments, the method ConvertAll is defined on MSDN as a method of List<t>, not IEnumerable<T>. See here.

I can't tell you why this is working in Visual Studio 2015, but there is an easy fix to the code you can implement to make it work in Visual Studio 2017. Just change the convert line to:

```<code>var collection = obj.ToList().ConvertAll<TConvert>(converter);
</code>```

Note that you'll need to have using System.Linq; at the top of your file.

Body:
Just someone can explain me why this work on Visual Studio 2015 but not on Visual Studio 2017 ?

public static TConvert DynamicPop<TObject, TConvert>(this IEnumerable<TObject> obj, Converter<TObject, TConvert> converter, long @default = 1)
    {
        if (obj.Count() == 0)
        {
            dynamic _defaut = @default;
            return (TConvert)_defaut;
        }
        var collection = obj.ConvertAll<TConvert>(converter);
        collection.Sort();
        dynamic lastValue = collection.Last();
        return (TConvert)(lastValue + 1);
    }

That said to me that ConvertAll doesn't exist.

Body:
As mentioned in the comments, the method ConvertAll is defined on MSDN as a method of List<t>, not IEnumerable<T>. See here.

I can't tell you why this is working in Visual Studio 2015, but there is an easy fix to the code you can implement to make it work in Visual Studio 2017. Just change the convert line to:

var collection = obj.ToList().ConvertAll<TConvert>(converter);

Note that you'll need to have using System.Linq; at the top of your file.


问:
SSDT installation issue (Failed to execute EXE package.)
I am having an issue with the SSDT installation for VS2017.

I have ran the installer three times, once basic, once following VS update and the last following some minor windows updates.

All 3 times the logs stumble at the same point, anyone know what this .exe it is trying to run is (I am running the installer with Admin...). I read somewhere for a similar error that it might be the SDK but I am able to run this locally, any nice workarounds to having this installed out there?

```<code>[29BC:A138][2017-09-26T09:28:00]i000: MainViewModel.OnPackageActionProgress: Percent completed: 50, Overall progress: 4
[1EC4:6DB0][2017-09-26T09:28:00]e000: Error 0x800703e9: Process returned error: 0x3e9
[1EC4:6DB0][2017-09-26T09:28:00]e000: Error 0x800703e9: Failed to execute EXE package.
[29BC:A138][2017-09-26T09:28:00]e000: Error 0x800703e9: Failed to configure per-machine EXE package.
[29BC:A138][2017-09-26T09:28:00]i000: MainViewModel.OnPackageAction: Install Completed for package SQL Server Analysis Services (id: Microsoft.DataTools.AnalysisServices)
[29BC:A138][2017-09-26T09:28:00]i319: Applied execute package: Microsoft.DataTools.AnalysisServices, result: 0x800703e9, restart: None
[29BC:A138][2017-09-26T09:28:00]e000: Error 0x800703e9: Failed to execute EXE package.
[1EC4:6DB0][2017-09-26T09:28:00]i351: Removing cached package: Microsoft.DataTools.AnalysisServices, from path: C:\ProgramData\Package Cache\9864EE5369359DB622D0234B6C6B7640B949140C\
[29BC:A138][2017-09-26T09:28:00]i000: MainViewModel.OnPackageActionProgress: Percent completed: 100, Overall progress: 100
[1EC4:6DB0][2017-09-26T09:28:00]i372: Session end, registration key: SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{5d5d6235-5c8c-4377-9a75-1b6368850657}, resume: None, restart: None, disable resume: No
[1EC4:6DB0][2017-09-26T09:28:00]i330: Removed bundle dependency provider: {5d5d6235-5c8c-4377-9a75-1b6368850657}
[1EC4:6DB0][2017-09-26T09:28:00]i352: Removing cached bundle: {5d5d6235-5c8c-4377-9a75-1b6368850657}, from path: C:\ProgramData\Package Cache\{5d5d6235-5c8c-4377-9a75-1b6368850657}\
[1EC4:6DB0][2017-09-26T09:28:00]i371: Updating session, registration key: SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{5d5d6235-5c8c-4377-9a75-1b6368850657}, resume: None, restart initiated: No, disable resume: No
[29BC:A138][2017-09-26T09:28:00]e000: MainViewModel.OnBundleAction: Bundle action failed: Recursion too deep; the stack overflowed (0x800703E9)
[29BC:A138][2017-09-26T09:28:00]i399: Apply complete, result: 0x800703e9, restart: None, ba requested restart:  No
[29BC:6724][2017-09-26T09:28:04]i000: MainViewModel.OpenUrl: Opening url: C:\Users\RTOMPS~1\AppData\Local\Temp\SsdtSetup\SSDT-Setup-ENU_20170926092556.log
</code>```

答:
This is the most likely link I came to when I got the same message in my log:

```<code>Applying execute package: Microsoft.DataTools.AnalysisServices, action: Install, path: C:\ProgramData\Package Cache\9864EE5369359DB622D0234B6C6B7640B949140C\VSIXBootstrapper.exe, arguments: '"C:\ProgramData\Package Cache\9864EE5369359DB622D0234B6C6B7640B949140C\VSIXBootstrapper.exe" /q /admin /instanceIds:"fc3f0e2c" /logFile:"C:\Users\a_nzchuk\AppData\Local\Temp\SsdtSetup\SSDT-Setup-ENU_20171205113839_002_Microsoft.DataTools.AnalysisServices.log" "payload\Microsoft.DataTools.AnalysisServices.vsix"'
MainViewModel.OnPackageActionProgress: Percent completed: 50, Overall progress: 17
MainViewModel.OnPackageActionProgress: Percent completed: 50, Overall progress: 17
...........
...
Error 0x800707d3: Process returned error: 0x7d3
Error 0x800707d3: Failed to execute EXE package.
Error 0x800707d3: Failed to configure per-machine EXE package.
MainViewModel.OnPackageAction: Install Completed for package SQL Server Analysis Services (id: Microsoft.DataTools.AnalysisServices)
Applied execute package: Microsoft.DataTools.AnalysisServices, result: 0x800707d3, restart: None
</code>```

So I'll document my findings here.

In my start menu I had Visual Studio 2017 (SSDT). It ran OK but didn't have any BI projects available

This is what I did from an Administrator elevated command prompt:

Copied SSDT-Setup-ENU.exe into C:\temp (rather than a user specific download folder which the admin user may not have access to)

Ran SSDT-Setup-ENU.exe /layout to pre-download support and redist files (this was after a required restart)

Ran SSDT-Setup-ENU.exe /repair to try and repair the install. It gave me a button Repair that I clicked.

Ran SSDT-Setup-ENU.exe /repair again. Selected Modify. Noted that only SQL Server Database was ticked, but none of the others (SSAS, SSIS, SSRS)

Ticked SQL Server Analysis Services and pressed Modify. It proceeded to do it. Got stuck at 50% for a few minutes but eventually worked

Repeated for SQL Server Reporting Services and SQL Server Integration Services

After this, when I reran VS2017, it had the BI projects and allowed me to create a 1400 SSAS solution

Body:
I am having an issue with the SSDT installation for VS2017.

I have ran the installer three times, once basic, once following VS update and the last following some minor windows updates.

All 3 times the logs stumble at the same point, anyone know what this .exe it is trying to run is (I am running the installer with Admin...). I read somewhere for a similar error that it might be the SDK but I am able to run this locally, any nice workarounds to having this installed out there?

[29BC:A138][2017-09-26T09:28:00]i000: MainViewModel.OnPackageActionProgress: Percent completed: 50, Overall progress: 4
[1EC4:6DB0][2017-09-26T09:28:00]e000: Error 0x800703e9: Process returned error: 0x3e9
[1EC4:6DB0][2017-09-26T09:28:00]e000: Error 0x800703e9: Failed to execute EXE package.
[29BC:A138][2017-09-26T09:28:00]e000: Error 0x800703e9: Failed to configure per-machine EXE package.
[29BC:A138][2017-09-26T09:28:00]i000: MainViewModel.OnPackageAction: Install Completed for package SQL Server Analysis Services (id: Microsoft.DataTools.AnalysisServices)
[29BC:A138][2017-09-26T09:28:00]i319: Applied execute package: Microsoft.DataTools.AnalysisServices, result: 0x800703e9, restart: None
[29BC:A138][2017-09-26T09:28:00]e000: Error 0x800703e9: Failed to execute EXE package.
[1EC4:6DB0][2017-09-26T09:28:00]i351: Removing cached package: Microsoft.DataTools.AnalysisServices, from path: C:\ProgramData\Package Cache\9864EE5369359DB622D0234B6C6B7640B949140C\
[29BC:A138][2017-09-26T09:28:00]i000: MainViewModel.OnPackageActionProgress: Percent completed: 100, Overall progress: 100
[1EC4:6DB0][2017-09-26T09:28:00]i372: Session end, registration key: SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{5d5d6235-5c8c-4377-9a75-1b6368850657}, resume: None, restart: None, disable resume: No
[1EC4:6DB0][2017-09-26T09:28:00]i330: Removed bundle dependency provider: {5d5d6235-5c8c-4377-9a75-1b6368850657}
[1EC4:6DB0][2017-09-26T09:28:00]i352: Removing cached bundle: {5d5d6235-5c8c-4377-9a75-1b6368850657}, from path: C:\ProgramData\Package Cache\{5d5d6235-5c8c-4377-9a75-1b6368850657}\
[1EC4:6DB0][2017-09-26T09:28:00]i371: Updating session, registration key: SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{5d5d6235-5c8c-4377-9a75-1b6368850657}, resume: None, restart initiated: No, disable resume: No
[29BC:A138][2017-09-26T09:28:00]e000: MainViewModel.OnBundleAction: Bundle action failed: Recursion too deep; the stack overflowed (0x800703E9)
[29BC:A138][2017-09-26T09:28:00]i399: Apply complete, result: 0x800703e9, restart: None, ba requested restart:  No
[29BC:6724][2017-09-26T09:28:04]i000: MainViewModel.OpenUrl: Opening url: C:\Users\RTOMPS~1\AppData\Local\Temp\SsdtSetup\SSDT-Setup-ENU_20170926092556.log

Body:
This is the most likely link I came to when I got the same message in my log:

Applying execute package: Microsoft.DataTools.AnalysisServices, action: Install, path: C:\ProgramData\Package Cache\9864EE5369359DB622D0234B6C6B7640B949140C\VSIXBootstrapper.exe, arguments: '"C:\ProgramData\Package Cache\9864EE5369359DB622D0234B6C6B7640B949140C\VSIXBootstrapper.exe" /q /admin /instanceIds:"fc3f0e2c" /logFile:"C:\Users\a_nzchuk\AppData\Local\Temp\SsdtSetup\SSDT-Setup-ENU_20171205113839_002_Microsoft.DataTools.AnalysisServices.log" "payload\Microsoft.DataTools.AnalysisServices.vsix"'
MainViewModel.OnPackageActionProgress: Percent completed: 50, Overall progress: 17
MainViewModel.OnPackageActionProgress: Percent completed: 50, Overall progress: 17
...........
...
Error 0x800707d3: Process returned error: 0x7d3
Error 0x800707d3: Failed to execute EXE package.
Error 0x800707d3: Failed to configure per-machine EXE package.
MainViewModel.OnPackageAction: Install Completed for package SQL Server Analysis Services (id: Microsoft.DataTools.AnalysisServices)
Applied execute package: Microsoft.DataTools.AnalysisServices, result: 0x800707d3, restart: None

So I'll document my findings here.

In my start menu I had Visual Studio 2017 (SSDT). It ran OK but didn't have any BI projects available

This is what I did from an Administrator elevated command prompt:

Copied SSDT-Setup-ENU.exe into C:\temp (rather than a user specific download folder which the admin user may not have access to)

Ran SSDT-Setup-ENU.exe /layout to pre-download support and redist files (this was after a required restart)

Ran SSDT-Setup-ENU.exe /repair to try and repair the install. It gave me a button Repair that I clicked.

Ran SSDT-Setup-ENU.exe /repair again. Selected Modify. Noted that only SQL Server Database was ticked, but none of the others (SSAS, SSIS, SSRS)

Ticked SQL Server Analysis Services and pressed Modify. It proceeded to do it. Got stuck at 50% for a few minutes but eventually worked

Repeated for SQL Server Reporting Services and SQL Server Integration Services

After this, when I reran VS2017, it had the BI projects and allowed me to create a 1400 SSAS solution


问:
Making only a part of the legend title bold in R
I have a legend title spread over two lines, I would like to make only the first line bold. I have the following code:

```<code>pre_legend_title = expression(paste(bold("PRE-ELECTION HATE CRIME RATES"),
                                    "\nAverage annual hate crimes per 100,000 residents, 2010-15"))
</code>```

However, when I try adding it to my ggplot using:

```<code>labs(fill = pre_legend_title)
</code>```

The title doesn't break into two lines despite using \n. Is there another way to do this?

答:
As far as I know, expression doesn't recognize linebreak characters. However, you can use the atop function:

```<code>library(ggplot2)

pre_legend_title = expression(atop(bold("PRE-ELECTION HATE CRIME RATES"),
                                   "Average annual hate crimes per 100,000 residents, 2010-15"))

ggplot(mtcars, aes(mpg, wt, fill=factor(cyl))) +
  geom_point(shape=21) +
  labs(fill = pre_legend_title)
</code>```

Body:
I have a legend title spread over two lines, I would like to make only the first line bold. I have the following code:

pre_legend_title = expression(paste(bold("PRE-ELECTION HATE CRIME RATES"),
                                    "\nAverage annual hate crimes per 100,000 residents, 2010-15"))

However, when I try adding it to my ggplot using:

labs(fill = pre_legend_title)

The title doesn't break into two lines despite using \n. Is there another way to do this?

Body:
As far as I know, expression doesn't recognize linebreak characters. However, you can use the atop function:

library(ggplot2)

pre_legend_title = expression(atop(bold("PRE-ELECTION HATE CRIME RATES"),
                                   "Average annual hate crimes per 100,000 residents, 2010-15"))

ggplot(mtcars, aes(mpg, wt, fill=factor(cyl))) +
  geom_point(shape=21) +
  labs(fill = pre_legend_title)


问:
Change view controller on click UIButton Swift (without storyboard)
How do you change the view controller when a button is clicked. I am not using the Storyboard. The views were  all created programmatically.

I tried adding a target to the button and then calling the following method to push the new View Controller:

```<code>func switchView() {
   print(123)
   let prodListController = ProductListController()
   self.navigationController?.pushViewController(prodListController, animated: true)
}
</code>```

This was called from within the UIviewController class.

Any help will be greatly appreciated. Thanks!!

EDIT:
Made the following modifications:

```<code>window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
window?.rootViewController = UINavigationController(rootViewController: ProductListController())
</code>```

答:
Are you using navigationController? It looks like it is "nil"...

You can do it with "show" instead:

```<code>self.show(ProductListController(), sender: self)
</code>```

However, if you want to use navigationController, you have to set it up first.
For example (supposing you will start your app with a navigationController):

on didFinishLaunchingWithOptions (AppDelegate.swift):

```<code>// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.main.bounds)

let initialViewController = NavViewController()

self.window?.rootViewController = initialViewController
self.window?.makeKeyAndVisible()

return true
</code>```

on viewDidLoad of NavViewController.swift:

```<code>self.pushViewController(ViewController(), animated: true)
</code>```

and then, you can use your code for the button:

```<code>func switchView() {
    print(123)
    let prodListController = ProductListController()
    self.navigationController?.pushViewController(prodListController, animated: true)
}
</code>```

Body:
How do you change the view controller when a button is clicked. I am not using the Storyboard. The views were  all created programmatically.

I tried adding a target to the button and then calling the following method to push the new View Controller:

func switchView() {
   print(123)
   let prodListController = ProductListController()
   self.navigationController?.pushViewController(prodListController, animated: true)
}

This was called from within the UIviewController class.

Any help will be greatly appreciated. Thanks!!

EDIT:
Made the following modifications:

window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
window?.rootViewController = UINavigationController(rootViewController: ProductListController())

Body:
Are you using navigationController? It looks like it is "nil"...

You can do it with "show" instead:

self.show(ProductListController(), sender: self)

However, if you want to use navigationController, you have to set it up first.
For example (supposing you will start your app with a navigationController):

on didFinishLaunchingWithOptions (AppDelegate.swift):

// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.main.bounds)

let initialViewController = NavViewController()

self.window?.rootViewController = initialViewController
self.window?.makeKeyAndVisible()

return true

on viewDidLoad of NavViewController.swift:

self.pushViewController(ViewController(), animated: true)

and then, you can use your code for the button:

func switchView() {
    print(123)
    let prodListController = ProductListController()
    self.navigationController?.pushViewController(prodListController, animated: true)
}


问:
Can I generate script of a migration with EF code first and .net core
I'm building a MVC application with .Net Core and I need to generate the script of a migration.

With EF6 I did run the command

```<code>update-database -script
</code>```

but when I try to do the same with .net Core is throwing the next exception:

Update-Database : A parameter cannot be found that matches parameter
name 'script'

Do you know if there is an equivalent for EF Core?

答:
You can use dotnet core cli to generate script

```<code>dotnet ef migrations script
</code>```

Also you can put this to file with new power shell out-file command.

```<code>dotnet ef migrations script | out-file ./script.sql
</code>```

Body:
I'm building a MVC application with .Net Core and I need to generate the script of a migration.

With EF6 I did run the command

update-database -script

but when I try to do the same with .net Core is throwing the next exception:

Update-Database : A parameter cannot be found that matches parameter
name 'script'

Do you know if there is an equivalent for EF Core?

Body:
You can use dotnet core cli to generate script

dotnet ef migrations script

Also you can put this to file with new power shell out-file command.

dotnet ef migrations script | out-file ./script.sql