问:
Screen Layout doesn't scroll
I have one outer ScrollView in which there is one RecyclerView and three tabs. Every tab has a fragment and that fragment loads in corresponding tab using ViewPager but outer ScrollView does not scroll my layout. I used nested ScrollView but it also does not scroll. Maybe I did something wrong. Does any one have a suggestion? Please share with me.
Here is my xml code structure</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/parent_scroll"
    android:layout_weight="1"
    android:background="@color/business_price_bg"
    android:focusableInTouchMode="false">

    <RelativeLayout
        android:id="@+id/business_detail_main_rl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/activity_main_search_top_main_ll"
            android:layout_width="match_parent"
            android:layout_height="@dimen/activity_main_search_top_main_ll_height"
            android:background="@color/location_setting_bottom_button_color"
            android:gravity="center"
            android:orientation="vertical">

        </LinearLayout>

        <RelativeLayout
            android:id="@+id/business_detail_activity_business_slider_main_rl"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:layout_below="@+id/activity_main_search_top_main_ll">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/business_detail_activity_slider_recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scrollbars="vertical" />
        </RelativeLayout>

        <TextView
            android:id="@+id/business_detail_activity_business_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/business_detail_activity_business_slider_main_rl"
            android:layout_margin="10dp"
            android:text=""
            android:textColor="@android:color/black"
            android:textSize="14sp" />

        <TextView
            android:id="@+id/business_detail_activity_business_description"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/business_detail_activity_business_title"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="10dp"
            android:text=""
            android:textSize="13sp" />

        <android.support.design.widget.TabLayout
            android:id="@+id/business_detail_activity_tabslayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/business_detail_activity_business_description"
            android:background="@android:color/transparent"
            app:tabIndicatorColor="@color/pencilin_orange_color"
            app:tabIndicatorHeight="5dp"
            app:tabTextAppearance="@style/MyTabLayoutTextAppearance" />

        <android.support.v4.view.ViewPager
            android:id="@+id/business_detail_activity_viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/business_detail_activity_tabslayout"
            android:background="@android:color/white" />

    </RelativeLayout>
</ScrollView>
</code>```

答:
I changed my screen Layout Structure and finally ScrollView is working
  Here is solution:

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusableInTouchMode="true">

    <LinearLayout
        android:id="@+id/business_detail_main_rl"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:nestedScrollingEnabled="true"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:weightSum="1">

            <LinearLayout
                android:id="@+id/activity_main_search_top_main_ll"
                android:layout_width="match_parent"
                android:layout_height="@dimen/activity_main_search_top_main_ll_height"
                android:layout_weight="0."
                android:background="@color/location_setting_bottom_button_color"
                android:gravity="center"
                android:orientation="vertical">

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="0.45"
                android:orientation="vertical">

                <RelativeLayout
                    android:id="@+id/business_detail_activity_business_slider_main_rl"
                    android:layout_width="match_parent"
                    android:layout_height="200dp"
                    android:layout_below="@+id/activity_main_search_top_main_ll">

                    <android.support.v7.widget.RecyclerView
                        android:id="@+id/business_detail_activity_slider_recycler_view"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_alignParentStart="true"
                        android:layout_alignParentTop="true"
                        android:scrollbars="vertical" />
                </RelativeLayout>

                <TextView
                    android:id="@+id/business_detail_activity_business_title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/business_detail_activity_business_slider_main_rl"
                    android:layout_margin="10dp"
                    android:text=""
                    android:textColor="@android:color/black"
                    android:textSize="14sp" />

                <TextView
                    android:id="@+id/business_detail_activity_business_description"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/business_detail_activity_business_title"
                    android:layout_marginBottom="10dp"
                    android:layout_marginLeft="10dp"
                    android:text=""
                    android:textSize="13sp" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="0.2"
                android:orientation="horizontal"
                android:weightSum="3">

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:orientation="vertical"
                    android:weightSum="1">

                    <Button
                        android:id="@+id/business_preview_screen_services_btn"
                        android:layout_width="match_parent"
                        android:layout_height="0dp"
                        android:layout_weight="0.88"
                        android:background="@android:color/transparent"
                        android:text="@string/business_preview_screen_services_btn_str"
                        android:textAllCaps="false" />

                    <View
                        android:id="@+id/business_preview_screen_service_btn_seperator"
                        android:layout_width="match_parent"
                        android:layout_height="0dp"
                        android:layout_weight="0.12"
                        android:background="@color/location_setting_bottom_button_color" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:orientation="vertical"
                    android:weightSum="1">

                    <Button
                        android:id="@+id/business_preview_screen_about_btn"
                        android:layout_width="match_parent"
                        android:layout_height="0dp"
                        android:layout_weight="0.88"
                        android:background="@android:color/transparent"
                        android:text="@string/business_preview_screen_services_btn_about_btn_str"
                        android:textAllCaps="false" />

                    <View
                        android:id="@+id/business_preview_screen_about_btn_seperator"
                        android:layout_width="match_parent"
                        android:layout_height="0dp"
                        android:layout_weight="0.13"
                        android:background="@color/light_gray_section_cell_seperator" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:orientation="vertical"
                    android:weightSum="1">

                    <Button
                        android:id="@+id/business_preview_screen_staff_btn"
                        android:layout_width="match_parent"
                        android:layout_height="0dp"
                        android:layout_weight="0.88"
                        android:background="@android:color/transparent"
                        android:text="@string/business_preview_screen_services_btn_staff_btn_str"
                        android:textAllCaps="false" />

                    <View
                        android:id="@+id/business_preview_screen_staff_btn_seperator"
                        android:layout_width="match_parent"
                        android:layout_height="0dp"
                        android:layout_weight="0.13"
                        android:background="@color/light_gray_section_cell_seperator" />
                </LinearLayout>
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="0.2"
                android:orientation="vertical">

                <FrameLayout
                    android:id="@+id/fragment_container"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                </FrameLayout>

            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</ScrollView>
</code>```

Title: Screen Layout doesn't scroll

Body:
I have one outer ScrollView in which there is one RecyclerView and three tabs. Every tab has a fragment and that fragment loads in corresponding tab using ViewPager but outer ScrollView does not scroll my layout. I used nested ScrollView but it also does not scroll. Maybe I did something wrong. Does any one have a suggestion? Please share with me.
Here is my xml code structure

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/parent_scroll"
    android:layout_weight="1"
    android:background="@color/business_price_bg"
    android:focusableInTouchMode="false">

    <RelativeLayout
        android:id="@+id/business_detail_main_rl"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/activity_main_search_top_main_ll"
            android:layout_width="match_parent"
            android:layout_height="@dimen/activity_main_search_top_main_ll_height"
            android:background="@color/location_setting_bottom_button_color"
            android:gravity="center"
            android:orientation="vertical">

        </LinearLayout>

        <RelativeLayout
            android:id="@+id/business_detail_activity_business_slider_main_rl"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:layout_below="@+id/activity_main_search_top_main_ll">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/business_detail_activity_slider_recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scrollbars="vertical" />
        </RelativeLayout>

        <TextView
            android:id="@+id/business_detail_activity_business_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/business_detail_activity_business_slider_main_rl"
            android:layout_margin="10dp"
            android:text=""
            android:textColor="@android:color/black"
            android:textSize="14sp" />

        <TextView
            android:id="@+id/business_detail_activity_business_description"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/business_detail_activity_business_title"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="10dp"
            android:text=""
            android:textSize="13sp" />

        <android.support.design.widget.TabLayout
            android:id="@+id/business_detail_activity_tabslayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/business_detail_activity_business_description"
            android:background="@android:color/transparent"
            app:tabIndicatorColor="@color/pencilin_orange_color"
            app:tabIndicatorHeight="5dp"
            app:tabTextAppearance="@style/MyTabLayoutTextAppearance" />

        <android.support.v4.view.ViewPager
            android:id="@+id/business_detail_activity_viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/business_detail_activity_tabslayout"
            android:background="@android:color/white" />

    </RelativeLayout>
</ScrollView>

Body:
I changed my screen Layout Structure and finally ScrollView is working
  Here is solution:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusableInTouchMode="true">

    <LinearLayout
        android:id="@+id/business_detail_main_rl"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:nestedScrollingEnabled="true"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:weightSum="1">

            <LinearLayout
                android:id="@+id/activity_main_search_top_main_ll"
                android:layout_width="match_parent"
                android:layout_height="@dimen/activity_main_search_top_main_ll_height"
                android:layout_weight="0."
                android:background="@color/location_setting_bottom_button_color"
                android:gravity="center"
                android:orientation="vertical">

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="0.45"
                android:orientation="vertical">

                <RelativeLayout
                    android:id="@+id/business_detail_activity_business_slider_main_rl"
                    android:layout_width="match_parent"
                    android:layout_height="200dp"
                    android:layout_below="@+id/activity_main_search_top_main_ll">

                    <android.support.v7.widget.RecyclerView
                        android:id="@+id/business_detail_activity_slider_recycler_view"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_alignParentStart="true"
                        android:layout_alignParentTop="true"
                        android:scrollbars="vertical" />
                </RelativeLayout>

                <TextView
                    android:id="@+id/business_detail_activity_business_title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/business_detail_activity_business_slider_main_rl"
                    android:layout_margin="10dp"
                    android:text=""
                    android:textColor="@android:color/black"
                    android:textSize="14sp" />

                <TextView
                    android:id="@+id/business_detail_activity_business_description"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/business_detail_activity_business_title"
                    android:layout_marginBottom="10dp"
                    android:layout_marginLeft="10dp"
                    android:text=""
                    android:textSize="13sp" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="0.2"
                android:orientation="horizontal"
                android:weightSum="3">

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:orientation="vertical"
                    android:weightSum="1">

                    <Button
                        android:id="@+id/business_preview_screen_services_btn"
                        android:layout_width="match_parent"
                        android:layout_height="0dp"
                        android:layout_weight="0.88"
                        android:background="@android:color/transparent"
                        android:text="@string/business_preview_screen_services_btn_str"
                        android:textAllCaps="false" />

                    <View
                        android:id="@+id/business_preview_screen_service_btn_seperator"
                        android:layout_width="match_parent"
                        android:layout_height="0dp"
                        android:layout_weight="0.12"
                        android:background="@color/location_setting_bottom_button_color" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:orientation="vertical"
                    android:weightSum="1">

                    <Button
                        android:id="@+id/business_preview_screen_about_btn"
                        android:layout_width="match_parent"
                        android:layout_height="0dp"
                        android:layout_weight="0.88"
                        android:background="@android:color/transparent"
                        android:text="@string/business_preview_screen_services_btn_about_btn_str"
                        android:textAllCaps="false" />

                    <View
                        android:id="@+id/business_preview_screen_about_btn_seperator"
                        android:layout_width="match_parent"
                        android:layout_height="0dp"
                        android:layout_weight="0.13"
                        android:background="@color/light_gray_section_cell_seperator" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:orientation="vertical"
                    android:weightSum="1">

                    <Button
                        android:id="@+id/business_preview_screen_staff_btn"
                        android:layout_width="match_parent"
                        android:layout_height="0dp"
                        android:layout_weight="0.88"
                        android:background="@android:color/transparent"
                        android:text="@string/business_preview_screen_services_btn_staff_btn_str"
                        android:textAllCaps="false" />

                    <View
                        android:id="@+id/business_preview_screen_staff_btn_seperator"
                        android:layout_width="match_parent"
                        android:layout_height="0dp"
                        android:layout_weight="0.13"
                        android:background="@color/light_gray_section_cell_seperator" />
                </LinearLayout>
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="0.2"
                android:orientation="vertical">

                <FrameLayout
                    android:id="@+id/fragment_container"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                </FrameLayout>

            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</ScrollView>


来源: stackexchange

问:
angular material md-country-select not binding with ng-model
I am using angular material and md-country-select for countries dropdown but it is not binding with ng-model.

```<code><md-country-select ng-model="user.country"></md-country-select>
</code>```

Is this a bug or I am doing something wrong.

I already used ng-country-select and it is working great but I need md-country-select because of some design dependencies with angular material. Any thoughts ?

答:
This directive uses controller as syntax, so you should be able to retrieve the selected country using something like this:

```<code><md-country-select></md-country-select>
<md-card>
     {{vm.country.name}}
</md-card>
</code>```

In your controller you can use $watch:

```<code> $scope.$watch('vm.country', function(val) {
    console.log(val); // returns object: {code: "AS", name: "American Samoa"}
 });
</code>```

I actually cannot find any documentation on this directive, but I have created a quick demo. Perhaps someone else knows of better way to acheive this...

ContentLicense: CC BY-SA 3.0

Body:
I am using angular material and md-country-select for countries dropdown but it is not binding with ng-model.

<md-country-select ng-model="user.country"></md-country-select>

Is this a bug or I am doing something wrong.

I already used ng-country-select and it is working great but I need md-country-select because of some design dependencies with angular material. Any thoughts ?

Body:
This directive uses controller as syntax, so you should be able to retrieve the selected country using something like this:

<md-country-select></md-country-select>
<md-card>
     {{vm.country.name}}
</md-card>

In your controller you can use $watch:

 $scope.$watch('vm.country', function(val) {
    console.log(val); // returns object: {code: "AS", name: "American Samoa"}
 });

I actually cannot find any documentation on this directive, but I have created a quick demo. Perhaps someone else knows of better way to acheive this...


问:
WebApi with backslash (%2f) in ID parameter causes 404 not found
I am calling a WebAPI method with a parameter containing a / (%2f).  If I call this with a parameter without this character it works fine.

Following advice in this link Escape characters in WebApi call I tried the following, but it hasn't made any difference.

```<code><httpRuntime targetFramework="4.5.1" relaxedUrlToFileSystemMapping="true"/>
</code>```

The code i am using to call the WebAPI method is below

```<code>var id = "AA/F1"; // This causes a problem of 404 not found
var workingId = "BB-F2"; // This works fine
using (var client = new HttpClient(new HttpClientHandler {AutomaticDecompression = DecompressionMethods.GZip}))
{
    var uri = new Uri(string.Format("http://[testServer]/[Controller]/Get/{0}", WebUtility.UrlEncode(id)));
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
    var response = client.GetAsync(uri).GetAwaiter().GetResult();
    if (response.IsSuccessStatusCode)
        return JsonConvert.DeserializeObject<ReturnType>(response.Content.ReadAsStringAsync().GetAwaiter().GetResult());

    throw new Exception(response.ReasonPhrase);
}
</code>```

I only have one route configured - as so:

```<code>GlobalConfiguration.Configuration.Routes.MapHttpRoute("Default", "{controller}/{action}/{id}", new { id = RouteParameter.Optional });
</code>```

I have also tried hitting it directly using Fiddler and get the same error.

答:
You can encode the full url before sending it

```<code>WebUtility.UrlEncode(string.Format("http://[testServer]/[Controller]/Get/{0}", id))
</code>```

check if this helps

Body:
I am calling a WebAPI method with a parameter containing a / (%2f).  If I call this with a parameter without this character it works fine.

Following advice in this link Escape characters in WebApi call I tried the following, but it hasn't made any difference.

<httpRuntime targetFramework="4.5.1" relaxedUrlToFileSystemMapping="true"/>

The code i am using to call the WebAPI method is below

var id = "AA/F1"; // This causes a problem of 404 not found
var workingId = "BB-F2"; // This works fine
using (var client = new HttpClient(new HttpClientHandler {AutomaticDecompression = DecompressionMethods.GZip}))
{
    var uri = new Uri(string.Format("http://[testServer]/[Controller]/Get/{0}", WebUtility.UrlEncode(id)));
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
    var response = client.GetAsync(uri).GetAwaiter().GetResult();
    if (response.IsSuccessStatusCode)
        return JsonConvert.DeserializeObject<ReturnType>(response.Content.ReadAsStringAsync().GetAwaiter().GetResult());

    throw new Exception(response.ReasonPhrase);
}

I only have one route configured - as so:

GlobalConfiguration.Configuration.Routes.MapHttpRoute("Default", "{controller}/{action}/{id}", new { id = RouteParameter.Optional });

I have also tried hitting it directly using Fiddler and get the same error.

Body:
You can encode the full url before sending it

WebUtility.UrlEncode(string.Format("http://[testServer]/[Controller]/Get/{0}", id))

check if this helps


问:
Colorpicker Spectrum doesn't show on focus
I'm using colorpicker Spectrum and what I'm trying to do is to open the colorpicker window when the input is focused. But the problem is that the colorpicker only shows for a split second and then closes. JSfiddle

HTML:

```<code><input type="text">
</code>```

Javascript:

```<code>$('input').spectrum().show();
$('input').focus(function() {
  $(this).spectrum('show');
});
</code>```

答:
Use this code:

```<code>  $('input').spectrum().show();
  $("input").bind('focus click', function() {
      $(this).spectrum("show");
      return false;
   });
</code>```

jsfiddle

Body:
I'm using colorpicker Spectrum and what I'm trying to do is to open the colorpicker window when the input is focused. But the problem is that the colorpicker only shows for a split second and then closes. JSfiddle

HTML:

<input type="text">

Javascript:

$('input').spectrum().show();
$('input').focus(function() {
  $(this).spectrum('show');
});

Body:
Use this code:

  $('input').spectrum().show();
  $("input").bind('focus click', function() {
      $(this).spectrum("show");
      return false;
   });

jsfiddle


问:
How to make CSS in an external stylesheet inline (for email)?
I have been using bits of the Foundation for Email HTML and CSS.

The CSS is in an external stylesheet. It is linked to in the HTML file. I've just used the Foundation inliner tool, expecting it to inline the (external) CSS, but it doesn't. I've also tried the MailChimp inliner tool.

Do I have to manually copy and paste the CSS into the HTML

答: Sorry. I've just gone back to Foundation for Email inline tool and much to my surprise it is now allowing me to copy in my CSS stylesheet. Solved.</p>


问:
Session manager for emacs (with high ssh usage)
I'm interested in using a session manager in emacs with the possibility of saving sessions by name.

The problem is that I almost exclusively use emacs to edit remote files. For this, I use tramp, which also works perfectly.

I want to have my sessions saved, including remote files and term buffers.

Does anyone know of a good way of saving sessions? I don't really care about windows sizes or splits

I have tried the following, which does not work:

Followed the instructions in this post, and tried out desktop.el. Searching and saving by name works perfectly.

Like this post recommends, I added this line so tramps are saved too:

```<code>(setq desktop-buffers-not-to-save "^$")
</code>```

But, as I said, this does not work.

答:
Ok, now it works. I'll post what I did, but I don't really know which was the problem.

Apparently, the line

```<code>(setq desktop-buffers-not-to-save "^$")
</code>```

was not working. So I enter the customization interactively (M-x customize-gruop RET desktop RET, changed the value of Desktop Buffers Not To Save to none, reload .emacs, and it worked.

Body:
I'm interested in using a session manager in emacs with the possibility of saving sessions by name.

The problem is that I almost exclusively use emacs to edit remote files. For this, I use tramp, which also works perfectly.

I want to have my sessions saved, including remote files and term buffers.

Does anyone know of a good way of saving sessions? I don't really care about windows sizes or splits

I have tried the following, which does not work:

Followed the instructions in this post, and tried out desktop.el. Searching and saving by name works perfectly.

Like this post recommends, I added this line so tramps are saved too:

(setq desktop-buffers-not-to-save "^$")

But, as I said, this does not work.

Body:
Ok, now it works. I'll post what I did, but I don't really know which was the problem.

Apparently, the line

(setq desktop-buffers-not-to-save "^$")

was not working. So I enter the customization interactively (M-x customize-gruop RET desktop RET, changed the value of Desktop Buffers Not To Save to none, reload .emacs, and it worked.


问:
TDD demos/guides/videos including fake repositories or domain models
I have to rewrite an old application and I would like to start using the repository pattern for data access and also write as many tests as possible for the required functionalities.

Can you recommend some videos/guides with more complex examples of TDD including fake repositories or domain models (preferably starting from scratch)?

答: The Full Stack, Part 3: Building a Repository using TDD</p>

ContentLicense: CC BY-SA 2.5


问:
Calculate the mean based on the previous consecutive trials
I would like to calculate the mean of every SACCADIC_RT for which COMMISSION_ERROR =1, that follows every 5 consecutive HITS=1, per ID per condition.

```<code>ID  | TRIAL | TRIAL_TYPE| CONDITION | COMMISSION_ERROR  | HITS| SACCADIC_RT
1     183     nogo        square_1     1                  -1    175
1     54      go          square_1    -1                   1    259
1     26      nogo        square_1     1                  -1    365
1     3       nogo        square_1     1                  -1    346
1     100     nogo        square_1     1                  -1    287
1     11      go          square_1    -1                   1    164
1     52      go          square_1    -1                   1    244
1     8       go          square_1    -1                   1    223
1     10      go          square_1    -1                   1    183
1     21      go          square_1    -1                   1    234
1     32      go          square_1     1                  -1    221
1     2       go          square_1    -1                   1    183
1    13       nogo        square_1     0                  -1    -1
1    87       nogo        square_2     1                  -1    228
1    95       nogo        square_2     1                  -1    274
1    111      go          square_2    -1                   1    305
1    28       nogo        square_2     0                  -1    309
1    65       go          square_2    -1                   0    -1
1    40       nogo        square_1     0                  -1    199
1    19       nogo        square_1     0                  -1    207
1    28       go          square_1    -1                   1    257
2    45       nogo        square_1     1                  -1    169
2    197      nogo        square_1     1                  -1    350
2    115      nogo        square_1     1                  -1    321
2    65       go          square_2    -1                   1    298
2    24       go          square_2    -1                   0    -1
2    1        nogo        square_2     1                  -1    183
2    77       go          square_2    -1                   1    225
2    90       go          square_2    -1                   1    305
2    89       go          square_2    -1                   1    210
2    104      go          square_2    -1                   1    199
2    116      go          square_2    -1                   1    175
2    29       nogo        square_2     1                  -1    99
2    41       go          square_2    -1                   1    104
</code>```

The sample table can be recreated in r as:

```<code>structure(list(ID = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                              1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
                              2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), X..TRIAL.. = c(183L, 54L, 26L,
                                                                              3L, 100L, 11L, 52L, 8L, 10L, 21L, 32L, 2L, 13L, 87L, 95L, 111L,
                                                                              28L, 65L, 40L, 19L, 28L, 45L, 197L, 115L, 65L, 24L, 1L, 77L,
                                                                              90L, 89L, 104L, 116L, 29L, 41L), TRIAL_TYPE. = structure(c(2L,
                                                                                1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 2L,
                                                                                1L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L,
                                                                                1L), .Label = c("go", "nogo"), class = "factor"), CONDITION = structure(c(1L,
                                                                                1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
                                                                                2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
                                                                                2L), .Label = c("square_1", "square_2"), class = "factor"), X..COMMISSION_ERROR = c(1L,
                                                                                -1L, 1L, 1L, 1L, -1L, -1L, -1L, -1L, -1L, 1L, -1L, 0L, 1L, 1L,
                                                                                -1L, 0L, -1L, 0L, 0L, -1L, 1L, 1L, 1L, -1L, -1L, 1L, -1L, -1L,
                                                                                -1L, -1L, -1L, 1L, -1L), X..HITS. = c(-1L, 1L, -1L, -1L, -1L,
                                                                                1L, 1L, 1L, 1L, 1L, -1L, 1L, -1L, -1L, -1L, 1L, -1L, 0L, -1L,
                                                                                -1L, 1L, -1L, -1L, -1L, 1L, 0L, -1L, 1L, 1L, 1L, 1L, 1L, -1L,
                                                                                1L), SACCADIC_RT = c(175L, 259L, 365L, 346L, 287L, 164L, 244L,
                                                                                223L, 183L, 234L, 221L, 183L, -1L, 228L, 274L, 305L, 309L, -1L,
                                                                                199L, 207L, 257L, 169L, 350L, 321L, 298L, -1L, 183L, 225L, 305L,
                                                                                210L, 199L, 175L, 99L, 104L)), .Names = c("ID", "X..TRIAL..",
                                                                                "TRIAL_TYPE.", "CONDITION", "X..COMMISSION_ERROR", "X..HITS.",
                                                                                "SACCADIC_RT"), class = "data.frame", row.names = c(NA, -34L))
</code>```

So the result from this example will be like:

```<code>ID | CONDITION |  x
1    square_1    221
2    square_2    99
</code>```

答:
You can use the package data.table to perform this task.

The steps are then as follows:

1) for each ID and condition calculate the rolling sum of hits

2) take only rows which satisfy 2 conditions: commision_error = 1 on previous row, there is number 5 in rolling sum column

3) calculate mean for each ID and condition in the table created in step 2

```<code># load your data
data <- read.csv("./yourData.csv")

# load data table library
library(data.table)

# convert your data to data.table object
data <- data.table(data)

# group data by ID and Condition, calculate rolling sum over 5 rows
data[, roll := Reduce('+', shift(HITS, 0:4)), by = list(ID, CONDITION)]

# take only rows where there were 5 hits in a row and commission error is 1
newData <- data[shift(roll, 1) == 5 & COMMISSION_ERROR == 1]

# calculate mean of SACCADIC_RT for each ID and Condition in the new dataset
newData[, meanSacc := mean(SACCADIC_RT), by = list(ID, CONDITION)]
</code>```

Code Explained:

roll := Reduce('+', shift(HITS, 0:4))

The shift function allows you to calculate value in current row based on the value in some previous row. Here the 'Reduce('+', shift(HITS, 0:4)) 'take value of hits on a given row and add to that the value of hits on 3 previous rows. This value is then written to the new column called roll.

newData <- data[shift(roll, 1) == 5 & COMMISSION_ERROR == 1]

The above code keeps only rows from the original dataset, where there is value 5 in the previous row of the column roll and the value of COMISSION_ERROR on the current line is equal to 1.

newData[, meanSacc := mean(SACCADIC_RT), by = list(ID, CONDITION)]

The above snip calculate mean of SACCADIC_RT for each ID and CONDITION and the mean is calculated only from rows in the new dataset created above. The means are then written to a new value called meanSacc

Body:
I would like to calculate the mean of every SACCADIC_RT for which COMMISSION_ERROR =1, that follows every 5 consecutive HITS=1, per ID per condition.

ID  | TRIAL | TRIAL_TYPE| CONDITION | COMMISSION_ERROR  | HITS| SACCADIC_RT
1     183     nogo        square_1     1                  -1    175
1     54      go          square_1    -1                   1    259
1     26      nogo        square_1     1                  -1    365
1     3       nogo        square_1     1                  -1    346
1     100     nogo        square_1     1                  -1    287
1     11      go          square_1    -1                   1    164
1     52      go          square_1    -1                   1    244
1     8       go          square_1    -1                   1    223
1     10      go          square_1    -1                   1    183
1     21      go          square_1    -1                   1    234
1     32      go          square_1     1                  -1    221
1     2       go          square_1    -1                   1    183
1    13       nogo        square_1     0                  -1    -1
1    87       nogo        square_2     1                  -1    228
1    95       nogo        square_2     1                  -1    274
1    111      go          square_2    -1                   1    305
1    28       nogo        square_2     0                  -1    309
1    65       go          square_2    -1                   0    -1
1    40       nogo        square_1     0                  -1    199
1    19       nogo        square_1     0                  -1    207
1    28       go          square_1    -1                   1    257
2    45       nogo        square_1     1                  -1    169
2    197      nogo        square_1     1                  -1    350
2    115      nogo        square_1     1                  -1    321
2    65       go          square_2    -1                   1    298
2    24       go          square_2    -1                   0    -1
2    1        nogo        square_2     1                  -1    183
2    77       go          square_2    -1                   1    225
2    90       go          square_2    -1                   1    305
2    89       go          square_2    -1                   1    210
2    104      go          square_2    -1                   1    199
2    116      go          square_2    -1                   1    175
2    29       nogo        square_2     1                  -1    99
2    41       go          square_2    -1                   1    104

The sample table can be recreated in r as:

structure(list(ID = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
                              1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
                              2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), X..TRIAL.. = c(183L, 54L, 26L,
                                                                              3L, 100L, 11L, 52L, 8L, 10L, 21L, 32L, 2L, 13L, 87L, 95L, 111L,
                                                                              28L, 65L, 40L, 19L, 28L, 45L, 197L, 115L, 65L, 24L, 1L, 77L,
                                                                              90L, 89L, 104L, 116L, 29L, 41L), TRIAL_TYPE. = structure(c(2L,
                                                                                1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 2L,
                                                                                1L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L,
                                                                                1L), .Label = c("go", "nogo"), class = "factor"), CONDITION = structure(c(1L,
                                                                                1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
                                                                                2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
                                                                                2L), .Label = c("square_1", "square_2"), class = "factor"), X..COMMISSION_ERROR = c(1L,
                                                                                -1L, 1L, 1L, 1L, -1L, -1L, -1L, -1L, -1L, 1L, -1L, 0L, 1L, 1L,
                                                                                -1L, 0L, -1L, 0L, 0L, -1L, 1L, 1L, 1L, -1L, -1L, 1L, -1L, -1L,
                                                                                -1L, -1L, -1L, 1L, -1L), X..HITS. = c(-1L, 1L, -1L, -1L, -1L,
                                                                                1L, 1L, 1L, 1L, 1L, -1L, 1L, -1L, -1L, -1L, 1L, -1L, 0L, -1L,
                                                                                -1L, 1L, -1L, -1L, -1L, 1L, 0L, -1L, 1L, 1L, 1L, 1L, 1L, -1L,
                                                                                1L), SACCADIC_RT = c(175L, 259L, 365L, 346L, 287L, 164L, 244L,
                                                                                223L, 183L, 234L, 221L, 183L, -1L, 228L, 274L, 305L, 309L, -1L,
                                                                                199L, 207L, 257L, 169L, 350L, 321L, 298L, -1L, 183L, 225L, 305L,
                                                                                210L, 199L, 175L, 99L, 104L)), .Names = c("ID", "X..TRIAL..",
                                                                                "TRIAL_TYPE.", "CONDITION", "X..COMMISSION_ERROR", "X..HITS.",
                                                                                "SACCADIC_RT"), class = "data.frame", row.names = c(NA, -34L))

So the result from this example will be like:

ID | CONDITION |  x
1    square_1    221
2    square_2    99

Body:
You can use the package data.table to perform this task.

The steps are then as follows:

1) for each ID and condition calculate the rolling sum of hits

2) take only rows which satisfy 2 conditions: commision_error = 1 on previous row, there is number 5 in rolling sum column

3) calculate mean for each ID and condition in the table created in step 2

# load your data
data <- read.csv("./yourData.csv")

# load data table library
library(data.table)

# convert your data to data.table object
data <- data.table(data)

# group data by ID and Condition, calculate rolling sum over 5 rows
data[, roll := Reduce('+', shift(HITS, 0:4)), by = list(ID, CONDITION)]

# take only rows where there were 5 hits in a row and commission error is 1
newData <- data[shift(roll, 1) == 5 & COMMISSION_ERROR == 1]

# calculate mean of SACCADIC_RT for each ID and Condition in the new dataset
newData[, meanSacc := mean(SACCADIC_RT), by = list(ID, CONDITION)]

Code Explained:

roll := Reduce('+', shift(HITS, 0:4))

The shift function allows you to calculate value in current row based on the value in some previous row. Here the 'Reduce('+', shift(HITS, 0:4)) 'take value of hits on a given row and add to that the value of hits on 3 previous rows. This value is then written to the new column called roll.

newData <- data[shift(roll, 1) == 5 & COMMISSION_ERROR == 1]

The above code keeps only rows from the original dataset, where there is value 5 in the previous row of the column roll and the value of COMISSION_ERROR on the current line is equal to 1.

newData[, meanSacc := mean(SACCADIC_RT), by = list(ID, CONDITION)]

The above snip calculate mean of SACCADIC_RT for each ID and CONDITION and the mean is calculated only from rows in the new dataset created above. The means are then written to a new value called meanSacc


问:
Entity Framework Code First and Firebird - Foreign Key name issue
I'm trying to create new database with 2 tables (Districts and Databases) using EF code-first and this simple code:

```<code>using (var db = new FirebirdDBContext(_connectionString))
{
    db.Database.CreateIfNotExists();
}
</code>```

My classes:

```<code>public class District
{
    [Key]
    public int District_id { get; set; }

    [Column(TypeName = "VARCHAR")]
    [StringLength(50)]
    public string District_name { get; set; }

    [ForeignKey("DataBase")]
    public int DataBase_id { get; set; }

    public DataBase DataBase { get; set; }
}

public class DataBase
{
    [Key]
    public int DataBase_id { get; set; }

    [Column(TypeName = "VARCHAR")]
    [StringLength(50)]
    public string DataBase_name { get; set; }

    public ICollection<District> District { get; set; }

    public DataBase()
    {
        District = new List<District>();
    }
}
</code>```

But unfortunately it throws an error:

Specified argument was out of the range of valid values.

  Parameter name: The name 'FK_Districts_DataBases_DataBase_id' is longer than Firebird's 31 characters limit for object names.

I know about Firebird's 31 characters limit but how I can solve this problem if I use Entity Framework code-first?

答:
After you've added migration you can modify your migration class file to change foreign key name like this:

```<code>.PrimaryKey(t => t.ID)
            .ForeignKey("dbo.CONTESTS", t => t.CONTEST_ID, cascadeDelete: true, name:"FK_CONTESTS_ID")
            .Index(t => t.CONTEST_ID);
</code>```

Just add name:"your_key",  and in Down method like this to awoid errors for autogenerated field name

```<code>DropForeignKey("dbo.BIBLIO_LIST","FK_CONTESTS_ID");
</code>```

Body:
I'm trying to create new database with 2 tables (Districts and Databases) using EF code-first and this simple code:

using (var db = new FirebirdDBContext(_connectionString))
{
    db.Database.CreateIfNotExists();
}

My classes:

public class District
{
    [Key]
    public int District_id { get; set; }

    [Column(TypeName = "VARCHAR")]
    [StringLength(50)]
    public string District_name { get; set; }

    [ForeignKey("DataBase")]
    public int DataBase_id { get; set; }

    public DataBase DataBase { get; set; }
}

public class DataBase
{
    [Key]
    public int DataBase_id { get; set; }

    [Column(TypeName = "VARCHAR")]
    [StringLength(50)]
    public string DataBase_name { get; set; }

    public ICollection<District> District { get; set; }

    public DataBase()
    {
        District = new List<District>();
    }
}

But unfortunately it throws an error:

Specified argument was out of the range of valid values.

  Parameter name: The name 'FK_Districts_DataBases_DataBase_id' is longer than Firebird's 31 characters limit for object names.

I know about Firebird's 31 characters limit but how I can solve this problem if I use Entity Framework code-first?

Body:
After you've added migration you can modify your migration class file to change foreign key name like this:

.PrimaryKey(t => t.ID)
            .ForeignKey("dbo.CONTESTS", t => t.CONTEST_ID, cascadeDelete: true, name:"FK_CONTESTS_ID")
            .Index(t => t.CONTEST_ID);

Just add name:"your_key",  and in Down method like this to awoid errors for autogenerated field name

DropForeignKey("dbo.BIBLIO_LIST","FK_CONTESTS_ID");


问:
Typescript extend any type
Ive googled and tried a lot and cannot find something.

Is there a way to extend "any" object in typescript like
in c# where i can write a extension method for the "object"
type.

It would make it possible to implement e.g. a cast<T> method which casts any object to the typescript type T.

e.g. i can do...

```<code>declare global {
    interface Array {
       doSomething();
    }
}

Array.prototype.doSomething = function() {
    console.log(this);
};
</code>```

but i cant

```<code>declare global {
    interface any {
       doSomething();
    }
}

any.prototype.doSomething = function() {
    console.log(this);
};
</code>```

I know that this is not possible but maybe there is a workaround
or trick i can use to extend "any" or "{}" or...

答: any and {} are not the same. any be a primitive value or an Object, whereas {} is an Object. If you only need this extension for objects, your could extend Object.

Title: Typescript extend any type

Body:
Ive googled and tried a lot and cannot find something.

Is there a way to extend "any" object in typescript like
in c# where i can write a extension method for the "object"
type.

It would make it possible to implement e.g. a cast<T> method which casts any object to the typescript type T.

e.g. i can do...

declare global {
    interface Array {
       doSomething();
    }
}

Array.prototype.doSomething = function() {
    console.log(this);
};

but i cant

declare global {
    interface any {
       doSomething();
    }
}

any.prototype.doSomething = function() {
    console.log(this);
};

I know that this is not possible but maybe there is a workaround
or trick i can use to extend "any" or "{}" or...


问:
how to find a submatrix with primes in matlab
```<code>Enter n: 3
Enter range: 50  // range of prime numbers

A =  1 12 37
     24 45 11
     2  34 10

matrix sum = 48

solution submatrix = 37   //largest rectangle of primes
                     11

coordinates are= 1 3 2 3
</code>```

First program gives a random matrix and finds largest rectangle consists of primes(submatrix) and then displaying their sum and coordiantes.

how can i write a program like this in matlab?

答:
I assume you are looking at a 3 x 3 matrix:

```<code> 1 12 37
24 45 11
 2 34 10
</code>```

Start by finding all the prime numbers in the matrix.  In this case 37, 11, 2.

Quite what you want to do then is not clear from your question.  Do you want a submatrix with those three number and others or do you want submatrices with all prime numbers?

It is not clear where you get the sum of 48 from.  37 + 11 = 48, but that leaves out the prime 2.  The sum on the three primes is 50.

You need to clarify your question if you want more help.

Body:
Enter n: 3
Enter range: 50  // range of prime numbers

A =  1 12 37
     24 45 11
     2  34 10

matrix sum = 48

solution submatrix = 37   //largest rectangle of primes
                     11

coordinates are= 1 3 2 3

First program gives a random matrix and finds largest rectangle consists of primes(submatrix) and then displaying their sum and coordiantes.

how can i write a program like this in matlab?

Body:
I assume you are looking at a 3 x 3 matrix:

 1 12 37
24 45 11
 2 34 10

Start by finding all the prime numbers in the matrix.  In this case 37, 11, 2.

Quite what you want to do then is not clear from your question.  Do you want a submatrix with those three number and others or do you want submatrices with all prime numbers?

It is not clear where you get the sum of 48 from.  37 + 11 = 48, but that leaves out the prime 2.  The sum on the three primes is 50.

You need to clarify your question if you want more help.


问:
AngularJS 2 select a HTML element and append it to another element on button click
I want to select a HTML element and append it to another div on a click of a button using Angular2.
Startup HMTL

```<code><div class="parent">
<ul class="level1">
    <li>
        <div class="otherdiv">
            This is a test
            <button md-raised-button type="button" color="primary">Clone</button>
        </div>
    </li>
</ul>
</code>```

When the button is clicked I expect to have following structure

```<code><div class="parent">
<ul class="level1">
    <li>
        <div class="otherdiv">
            This is a test
            <button md-raised-button type="button" color="primary">Clone</button>
        </div>
        <ul class="level2">
            <li>
                <div class="otherdiv">
                    This is a test
                    <button md-raised-button type="button" color="primary">Clone</button>
                </div>
            </li>
        </ul>
    </li>
</ul>
</code>```

Not sure how can I achieve this. Any help appreciated.
Thanks

答:
You can use clone() in jquery.

JSFIDDLE

Here is the code:

$('button').click(function() {
  $("#level1").clone().attr('id', 'level2').insertAfter("#level1");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <ul id="level1">
    <li>
      <div class="otherdiv">
        This is a test
        <button md-raised-button type="button" color="primary">Clone</button>
      </div>
    </li>
  </ul></code>```

Using angluarJs also we can do the same by using ng-repeat.You can repeat every time by adding the number.

ANGULAR FIDDLE

var app = angular.module('myapp', []);
app.controller('ctrlParent', function($scope) {
  $scope.myNumber = 1;
  $scope.myFun = function() {
    $scope.myNumber = $scope.myNumber + 1;
  }
  $scope.getNumber = function(num) {
    return new Array(num);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
  <div ng-controller="ctrlParent">
    <ul>
      <li ng-repeat="i in getNumber(myNumber) track by $index"><span>{{$index+1}}</span>
        <button ng-click="myFun()">Click to CLone
            </button>
      </li>
    </ul>
  </div>
</div></code>```

Body:
I want to select a HTML element and append it to another div on a click of a button using Angular2.
Startup HMTL

            This is a test
            <button md-raised-button type="button" color="primary">Clone</button>

When the button is clicked I expect to have following structure

            This is a test
            <button md-raised-button type="button" color="primary">Clone</button>

                    This is a test
                    <button md-raised-button type="button" color="primary">Clone</button>

Not sure how can I achieve this. Any help appreciated.
Thanks

Body:
You can use clone() in jquery.

JSFIDDLE

Here is the code:

$('button').click(function() {
  $("#level1").clone().attr('id', 'level2').insertAfter("#level1");
});

<div class="parent">
  <ul id="level1">
    <li>
      <div class="otherdiv">
        This is a test
        <button md-raised-button type="button" color="primary">Clone</button>
      </div>
    </li>
  </ul>

Using angluarJs also we can do the same by using ng-repeat.You can repeat every time by adding the number.

ANGULAR FIDDLE

var app = angular.module('myapp', []);
app.controller('ctrlParent', function($scope) {
  $scope.myNumber = 1;
  $scope.myFun = function() {
    $scope.myNumber = $scope.myNumber + 1;
  }
  $scope.getNumber = function(num) {
    return new Array(num);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
  <div ng-controller="ctrlParent">
    <ul>
      <li ng-repeat="i in getNumber(myNumber) track by $index"><span>{{$index+1}}</span>
        <button ng-click="myFun()">Click to CLone
            </button>
      </li>
    </ul>
  </div>
</div>


问:
Python json POST request status 200 while expecting status 201
I'm trying to do a POST request to a web server in an attempt to create a new resource. I'm fairly new to both Python and the platform I'm trying to communicate with on the server, so I'm not sure if it's my python skills require a bit more practice or if I'm just not submitting a request correctly to the server. Here's my code:

```<code>import requests

apiKey = "[APIKEY]"
serverUrl = "http://192.168.0.5/api/v1.0/payments"

values = """
  {
    "clientId": 1,
    "method": 3,
    "createdDate": "2016-09-12T00:00:00+0000",
    "amount": 10,
    "note": "",
    "invoiceIds": []
  }
"""

headers = {
  'X-Auth-App-Key': apiKey,
  'Content-Type': 'application/json'
}

r = requests.post(serverUrl, data=values, headers=headers)
r
</code>```

The server responds with a Response 200 (OK) message, but since I'm trying to create a new resource it should respond with a Response 201 (Created) message. Any ideas what I'm doing wrong?

答:
This probably won't result in a different HTTP status code, but you can send JSON encoded dictionaries directly by using the json parameter to requests.post(). So values can be a dictionary, and requests will set the content type so you don't need to in headers:

```<code>values =
  {
    "clientId": 1,
    "method": 3,
    "createdDate": "2016-09-12T00:00:00+0000",
    "amount": 123.45,
    "note": "",
    "invoiceIds": []
  }

headers = {'X-Auth-App-Key': apiKey}

r = requests.post(serverUrl, json=values, headers=headers)
</code>```

It's just a little cleaner.

Regarding the expected 201 response, is the resource actually created? Do you get a 201 response when using other tools such as curl?

Body:
I'm trying to do a POST request to a web server in an attempt to create a new resource. I'm fairly new to both Python and the platform I'm trying to communicate with on the server, so I'm not sure if it's my python skills require a bit more practice or if I'm just not submitting a request correctly to the server. Here's my code:

import requests

apiKey = "[APIKEY]"
serverUrl = "http://192.168.0.5/api/v1.0/payments"

values = """
  {
    "clientId": 1,
    "method": 3,
    "createdDate": "2016-09-12T00:00:00+0000",
    "amount": 10,
    "note": "",
    "invoiceIds": []
  }
"""

headers = {
  'X-Auth-App-Key': apiKey,
  'Content-Type': 'application/json'
}

r = requests.post(serverUrl, data=values, headers=headers)
r

The server responds with a Response 200 (OK) message, but since I'm trying to create a new resource it should respond with a Response 201 (Created) message. Any ideas what I'm doing wrong?

Body:
This probably won't result in a different HTTP status code, but you can send JSON encoded dictionaries directly by using the json parameter to requests.post(). So values can be a dictionary, and requests will set the content type so you don't need to in headers:

values =
  {
    "clientId": 1,
    "method": 3,
    "createdDate": "2016-09-12T00:00:00+0000",
    "amount": 123.45,
    "note": "",
    "invoiceIds": []
  }

headers = {'X-Auth-App-Key': apiKey}

r = requests.post(serverUrl, json=values, headers=headers)

It's just a little cleaner.

Regarding the expected 201 response, is the resource actually created? Do you get a 201 response when using other tools such as curl?


问:
Currency exchange for multiple currencies on different dates
I have a dataframe with amounts in different currencies on different dates, and want to create a new column showing the amount in GBP that it is equal to on that date.

For example my data may be as follows

```<code>data <- data.frame(
  date = seq.Date(from = as.Date('2017-01-01'), to = as.Date('2017-01-10'), length = 10),
  currency = c('EUR', 'GBP', 'USD', 'HKD', 'GBP', 'EUR', 'CAN', 'AUD', 'EUR', 'GBP'),
  amount = 1:10
</code>```

)

However I would like a generic function to do this which would work no matter what date range and currencies are in the dataframe.

I'm pretty sure I would be able to do this using the getFX function in the quantmod package but can't quite work out the best way of doing it!

I'm sure this has been done before so any help would be appreciated.

Thanks

答:
With functions ?merge,?lapply and following the steps mentioned below:

Steps:

1) create currency pairs EUR/GBP,USD/GBP

2) get FX data

3) reshape/modify FX data

4) merge with original data and calculate fx translated amount

```<code>library("quantmod")
library("reshape2") #for melt function

#replaced CAN by CAD for Canadian Dollar

currDF  <- data.frame(
date = seq.Date(from = as.Date('2017-01-01'), to = as.Date('2017-01-10'), length = 10),
currency = c('EUR', 'GBP', 'USD', 'HKD', 'GBP', 'EUR', 'CAD', 'AUD', 'EUR', 'GBP'),
amount = 1:10,stringsAsFactors=FALSE)
currDF
</code>```

FX Data:

```<code>#Set start and end dates
startDt = as.Date("2017-01-01")
endDt = as.Date("2017-01-10")

#create currency pair combinations i.e. EUR/GBP, USDGBP
currCombinations = paste(setdiff(unique(currDF$currency),"GBP"),"GBP",sep="/")

currCombinations
#[1] "EUR/GBP" "USD/GBP" "HKD/GBP" "CAD/GBP" "AUD/GBP"

#get FX data for each currency pair and merge them into a single xts dataset
#see ?lapply, ?do.call and ?merge.xts
#note auto.assign needs to be FALSE

fxData = do.call(merge.xts,lapply(currCombinations,function(x)
   getFX(x,from=startDt,to=endDt,auto.assign=FALSE)))

fxData
#            EUR.GBP  USD.GBP  HKD.GBP  CAD.GBP  AUD.GBP
#2017-01-01 0.852550 0.810242 0.104474 0.602773 0.583503
#2017-01-02 0.852550 0.810242 0.104474 0.602773 0.583503
#2017-01-03 0.850220 0.814326 0.104987 0.606361 0.587630
#2017-01-04 0.850310 0.815139 0.105102 0.609074 0.591082
#2017-01-05 0.853695 0.810205 0.104480 0.610352 0.591940
#2017-01-06 0.855625 0.808914 0.104311 0.610882 0.592583
#2017-01-07 0.857335 0.813948 0.104951 0.614860 0.593995
#2017-01-08 0.857330 0.813942 0.104951 0.614847 0.593990
#2017-01-09 0.864095 0.819833 0.105707 0.619112 0.600639
#2017-01-10 0.870830 0.822656 0.106077 0.622248 0.605533

#remove .GBP from all columns above
colnames(fxData) = gsub("[.]GBP","",colnames(fxData))

#set conversion factor for GBP = 1
fxData$GBP = 1
</code>```

Data Reshape:

```<code>#create data.frame from xts data
fxData_DF = data.frame(date=index(fxData),coredata(fxData),stringsAsFactors=FALSE)

#To make fx dataset(wide format) amenable for merging with currDF
#we convert it to long format by using melt from reshape2 package see,?melt

fxMolten = melt(fxData_DF,id="date",variable.name="currency",value.name="conversionFactor")

head(fxMolten,2)
#        date currency conversionFactor
#1 2017-01-01      EUR          0.85255
#2 2017-01-02      EUR          0.85255
tail(fxMolten,2)
#         date currency conversionFactor
#59 2017-01-09      GBP                1
#60 2017-01-10      GBP                1
</code>```

Merged Data:

```<code>#For each currency and date, we need a conversion factor hence
#we merge both datasets by columns date and currency

fxMerged = merge(currDF,fxMolten,by=c("date","currency"))

#calculate FX translated amount
fxMerged$convAmount = fxMerged$amount * fxMerged$conversionFactor

fxMerged
#         date currency amount conversionFactor convAmount
#1  2017-01-01      EUR      1         0.852550   0.852550
#2  2017-01-02      GBP      2         1.000000   2.000000
#3  2017-01-03      USD      3         0.814326   2.442978
#4  2017-01-04      HKD      4         0.105102   0.420408
#5  2017-01-05      GBP      5         1.000000   5.000000
#6  2017-01-06      EUR      6         0.855625   5.133750
#7  2017-01-07      CAD      7         0.614860   4.304020
#8  2017-01-08      AUD      8         0.593990   4.751920
#9  2017-01-09      EUR      9         0.864095   7.776855
#10 2017-01-10      GBP     10         1.000000  10.000000
</code>```

Body:
I have a dataframe with amounts in different currencies on different dates, and want to create a new column showing the amount in GBP that it is equal to on that date.

For example my data may be as follows

data <- data.frame(
  date = seq.Date(from = as.Date('2017-01-01'), to = as.Date('2017-01-10'), length = 10),
  currency = c('EUR', 'GBP', 'USD', 'HKD', 'GBP', 'EUR', 'CAN', 'AUD', 'EUR', 'GBP'),
  amount = 1:10

)

However I would like a generic function to do this which would work no matter what date range and currencies are in the dataframe.

I'm pretty sure I would be able to do this using the getFX function in the quantmod package but can't quite work out the best way of doing it!

I'm sure this has been done before so any help would be appreciated.

Thanks

Body:
With functions ?merge,?lapply and following the steps mentioned below:

Steps:

1) create currency pairs EUR/GBP,USD/GBP

2) get FX data

3) reshape/modify FX data

4) merge with original data and calculate fx translated amount

library("quantmod")
library("reshape2") #for melt function

#replaced CAN by CAD for Canadian Dollar

currDF  <- data.frame(
date = seq.Date(from = as.Date('2017-01-01'), to = as.Date('2017-01-10'), length = 10),
currency = c('EUR', 'GBP', 'USD', 'HKD', 'GBP', 'EUR', 'CAD', 'AUD', 'EUR', 'GBP'),
amount = 1:10,stringsAsFactors=FALSE)
currDF

FX Data:

#Set start and end dates
startDt = as.Date("2017-01-01")
endDt = as.Date("2017-01-10")

#create currency pair combinations i.e. EUR/GBP, USDGBP
currCombinations = paste(setdiff(unique(currDF$currency),"GBP"),"GBP",sep="/")

currCombinations
#[1] "EUR/GBP" "USD/GBP" "HKD/GBP" "CAD/GBP" "AUD/GBP"

#get FX data for each currency pair and merge them into a single xts dataset
#see ?lapply, ?do.call and ?merge.xts
#note auto.assign needs to be FALSE

fxData = do.call(merge.xts,lapply(currCombinations,function(x)
   getFX(x,from=startDt,to=endDt,auto.assign=FALSE)))

fxData
#            EUR.GBP  USD.GBP  HKD.GBP  CAD.GBP  AUD.GBP
#2017-01-01 0.852550 0.810242 0.104474 0.602773 0.583503
#2017-01-02 0.852550 0.810242 0.104474 0.602773 0.583503
#2017-01-03 0.850220 0.814326 0.104987 0.606361 0.587630
#2017-01-04 0.850310 0.815139 0.105102 0.609074 0.591082
#2017-01-05 0.853695 0.810205 0.104480 0.610352 0.591940
#2017-01-06 0.855625 0.808914 0.104311 0.610882 0.592583
#2017-01-07 0.857335 0.813948 0.104951 0.614860 0.593995
#2017-01-08 0.857330 0.813942 0.104951 0.614847 0.593990
#2017-01-09 0.864095 0.819833 0.105707 0.619112 0.600639
#2017-01-10 0.870830 0.822656 0.106077 0.622248 0.605533

#remove .GBP from all columns above
colnames(fxData) = gsub("[.]GBP","",colnames(fxData))

#set conversion factor for GBP = 1
fxData$GBP = 1

Data Reshape:

#create data.frame from xts data
fxData_DF = data.frame(date=index(fxData),coredata(fxData),stringsAsFactors=FALSE)

#To make fx dataset(wide format) amenable for merging with currDF
#we convert it to long format by using melt from reshape2 package see,?melt

fxMolten = melt(fxData_DF,id="date",variable.name="currency",value.name="conversionFactor")

head(fxMolten,2)
#        date currency conversionFactor
#1 2017-01-01      EUR          0.85255
#2 2017-01-02      EUR          0.85255
tail(fxMolten,2)
#         date currency conversionFactor
#59 2017-01-09      GBP                1
#60 2017-01-10      GBP                1

Merged Data:

#For each currency and date, we need a conversion factor hence
#we merge both datasets by columns date and currency

fxMerged = merge(currDF,fxMolten,by=c("date","currency"))

#calculate FX translated amount
fxMerged$convAmount = fxMerged$amount * fxMerged$conversionFactor

fxMerged
#         date currency amount conversionFactor convAmount
#1  2017-01-01      EUR      1         0.852550   0.852550
#2  2017-01-02      GBP      2         1.000000   2.000000
#3  2017-01-03      USD      3         0.814326   2.442978
#4  2017-01-04      HKD      4         0.105102   0.420408
#5  2017-01-05      GBP      5         1.000000   5.000000
#6  2017-01-06      EUR      6         0.855625   5.133750
#7  2017-01-07      CAD      7         0.614860   4.304020
#8  2017-01-08      AUD      8         0.593990   4.751920
#9  2017-01-09      EUR      9         0.864095   7.776855
#10 2017-01-10      GBP     10         1.000000  10.000000


问:
Form Submission without page refresh
Maybe someone can assist me with this little issue I'm having. I'm trying to submit this form without a page refresh.  But it will skip the post and go directly to the ajax call.  I think I miss understood the preventDefault(). I have searched online but unable to locate what I need for this. Your help would greatly be appreciated or point to another form submission.

HTML below:

```<code><!DOCTYPE html>
 <html>
<head>
<title>AJAX | Project</title>
 <link href="project.css" rel="stylesheet"/>
 <script src="jquery.js"></script>

  </head>
 <body>

<div id="mainCon">

  <h1>Contact Book</h1>
<div id="form_input">
<form id="myform" method="post"    action="addrecord.php">

    <label for="fullname">Name:</label>
    <input type="text" name="fullname" id="fullname"/><span id="NameError">   </span>
    <br/>
    <label for="phonenumber">Phone Number:</label>
    <input type="text" id="phonenumber" name="phonenumber"><span   id="PhoneError"></span>

    <br />

<input id="buttton" type="submit" onClick="addnumber()" value="Add Phone   Number"/>
    <input type="button" id="show" value="the Results"/>
 </form>

</div>

    <div id="form_output">

    </div>

</div>
 <script src="project.js"></script>
 <script type="text/javascript">

 function addnumber(){

 var Fullname = document.getElementById("fullname").value;
var Phonenumber = document.getElementById("phonenumber").value;

 if(Fullname == ""){
document.getElementById("NameError").innerHTML = "Please Enter a valided Name";
}

if(Phonenumber == ""){
document.getElementById("PhoneError").innerHTML = "Please Enter a valided Name";
}

}

</script>
</body>
</html>
</code>```

jquery

```<code>$("document").ready(function () {
    $("#buttton").click(function () {
        $('#myform').submit(function (e) {
            e.preventDefault();
            $.ajax({
                url: "listrecord.php",
                type: "GET",
                data: "data",
                success: function (data) {
                    $("#form_output").html(data);
                },
                error: function (jXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                }
            }); // AJAX Get Jquery statment
        });
    }); // Click effect
}); //Begin of Jquery Statement
</code>```

答:
```<code><!-- index.php -->
    <!DOCTYPE html>
    <html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    </head>
    <body>
    <form id="myForm">
        <input type="text" name="fname" id="fname"/>
        <input type="submit" name="click" value="button" />
    </form>
    <script>
    $(document).ready(function(){

         $(function(){
            $("#myForm").submit(function(event){
                event.preventDefault();
                $.ajax({
                    method: 'POST',
                    url: 'submit.php',
                    dataType: "json",
                    contentType: "application/json",
                    data : $('#myForm').serialize(),
                    success: function(data){
                        alert(data);
                    },
                    error: function(xhr, desc, err){
                        console.log(err);
                    }
                });
            });
        });
    });
    </script>
    </body>
    </html>
<!-- submit.php -->
<?php
$value ="call";
header('Content-Type: application/json');
echo json_encode($value);
?>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Form Submission without page refresh

Body:
Maybe someone can assist me with this little issue I'm having. I'm trying to submit this form without a page refresh.  But it will skip the post and go directly to the ajax call.  I think I miss understood the preventDefault(). I have searched online but unable to locate what I need for this. Your help would greatly be appreciated or point to another form submission.

HTML below:

<!DOCTYPE html>

<title>AJAX | Project</title>
 <link href="project.css" rel="stylesheet"/>

Contact Book

<form id="myform" method="post"    action="addrecord.php">

    Name:
    <input type="text" name="fullname" id="fullname"/>

    Phone Number:
    <input type="text" id="phonenumber" name="phonenumber">

<input id="buttton" type="submit" onClick="addnumber()" value="Add Phone   Number"/>
    <input type="button" id="show" value="the Results"/>
 </form>

jquery

$("document").ready(function () {
    $("#buttton").click(function () {
        $('#myform').submit(function (e) {
            e.preventDefault();
            $.ajax({
                url: "listrecord.php",
                type: "GET",
                data: "data",
                success: function (data) {
                    $("#form_output").html(data);
                },
                error: function (jXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                }
            }); // AJAX Get Jquery statment
        });
    }); // Click effect
}); //Begin of Jquery Statement


问:
How to send arguments to Ruby program
I tried this code in order to send arguments to Ruby program:

```<code>namespace :tnx do

  require_relative "transactions.rb"
  include Cnp_transactions_modes

  task :generate, [:clean_all] => [:environment]  do |t, args|

    if args[: clean_all] == 'true'
      // something
    end

    if args[:times]
      Cnp_transactions_modes.create_tnx(args[:times])
    else
     puts "\nSet some number\n"
    end
  end
end
</code>```

When I run the code this way:

```<code>bundle exec rake test:generate['true','30']
</code>```

I get Set some number

Can you give some advice how I can fix the code?

答:
Try declaring like this

```<code>task :generate, [:clean_all, :times] => [:environment]  do |t, args|
</code>```

and calling like this

```<code>bundle exec rake tnx:generate['true','30']
</code>```

Title: How to send arguments to Ruby program

Body:
I tried this code in order to send arguments to Ruby program:

namespace :tnx do

  require_relative "transactions.rb"
  include Cnp_transactions_modes

  task :generate, [:clean_all] => [:environment]  do |t, args|

    if args[: clean_all] == 'true'
      // something
    end

    if args[:times]
      Cnp_transactions_modes.create_tnx(args[:times])
    else
     puts "\nSet some number\n"
    end
  end
end

When I run the code this way:

bundle exec rake test:generate['true','30']

I get Set some number

Can you give some advice how I can fix the code?

Body:
Try declaring like this

task :generate, [:clean_all, :times] => [:environment]  do |t, args|

and calling like this

bundle exec rake tnx:generate['true','30']


问:
Is it possible read XML files that are linked to within another XML file "all in one go"?
I have an XML file stored on a server which contains elements, of which some are refererences to other xml files e.g.

```<code><xml>
<item>value</item>
<data>http://www.example.org/item1.xml</data>
<data>http://www.example.org/item2.xml</data>
</xml>
</code>```

Where item1 and item2 are like this for example:

```<code><item>
  <id>1</id>
  <name>Item One</name>
</item>
</code>```

I want to be able to read the main XML file (which of course I can do) this is done with an Asyncronous web request to download the XML - would it be possible to read the XML files referenced within the XML file in the same "request" rather than spin up, in this case two more seperate webclient requests to download these, as because these would be asyncronous too and therefore this data would not be available until those requests have completed - for binding to a UI in XAML for instance.

This would result in the main xml file being downloaded and completed and then the two xml files being seperately downloaded too.  Is it possible to read the main xml and the "sub xml" files all in one go?

I can only use Async webrequests as this is a platform limitation of Silverlight and I cannot change the data as it is distibuted between many XML files to save server storage and is in a provided format, can the main and sub XML files be downloaded and parsed in one request, using LINQ / XElement / Silverlight supported features - I cannot use XPath as this would not be supported.

答:
No, unless the fetching on the server side is done by ASP.NET or anything 'active'. Differently put, if you're fetching the XML as a static file using HTTP, then of course nothing will work except what you already know - parse the XML on reception, then fire off two more requests.

If you're serving your Silverlight app from an ASP.NET capable server, you can always build a small aspx (even better ashx) which will fetch all of the XML files, merge them and respond with only one XML.

Body:
I have an XML file stored on a server which contains elements, of which some are refererences to other xml files e.g.

<xml>
<item>value</item>
<data>http://www.example.org/item1.xml</data>
<data>http://www.example.org/item2.xml</data>
</xml>

Where item1 and item2 are like this for example:

<item>
  <id>1</id>
  <name>Item One</name>
</item>

I want to be able to read the main XML file (which of course I can do) this is done with an Asyncronous web request to download the XML - would it be possible to read the XML files referenced within the XML file in the same "request" rather than spin up, in this case two more seperate webclient requests to download these, as because these would be asyncronous too and therefore this data would not be available until those requests have completed - for binding to a UI in XAML for instance.

This would result in the main xml file being downloaded and completed and then the two xml files being seperately downloaded too.  Is it possible to read the main xml and the "sub xml" files all in one go?

I can only use Async webrequests as this is a platform limitation of Silverlight and I cannot change the data as it is distibuted between many XML files to save server storage and is in a provided format, can the main and sub XML files be downloaded and parsed in one request, using LINQ / XElement / Silverlight supported features - I cannot use XPath as this would not be supported.


问:
Type casting using string for type
I have table settings with columns:
value - varchar type contains setting value and type - enum type contains variable types "int", "string", "float". How can I use string from type column to cast value to this type?

I'm trying to do it in my model but it doesn't work:

```<code>public function getValueAttribute($value){
    return ($this->type)$value;
}
</code>```

答:
You have to use the settype() function :

```<code><?php

$var = 42;
var_dump($var);  //  int 42
$type = 'string';
settype($var, $type);
var_dump($var);  //  string '42'
</code>```

Adapted to your code snippet :

```<code>public function getValueAttribute($value){
    settype($value, $this->type);
    return $value;
}
</code>```

Title: Type casting using string for type

Body:
I have table settings with columns:
value - varchar type contains setting value and type - enum type contains variable types "int", "string", "float". How can I use string from type column to cast value to this type?

I'm trying to do it in my model but it doesn't work:

public function getValueAttribute($value){
    return ($this->type)$value;
}

Body:
You have to use the settype() function :

<?php

$var = 42;
var_dump($var);  //  int 42
$type = 'string';
settype($var, $type);
var_dump($var);  //  string '42'

Adapted to your code snippet :

public function getValueAttribute($value){
    settype($value, $this->type);
    return $value;
}


问:
closedxml sorting by specific number
I have a problem with ClosedXML in C#. I want to sort data but I want the system read column have numbers like 1, 2, 3, 4 and then sort by that.

If I use ws.Sort(1) the title is sorted too.

Here's my code:

```<code>protected void ImportExcel(object sender, EventArgs e)
{
    //Save the uploaded Excel file.
    string filePath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
    FileUpload1.SaveAs(filePath);

//Open the Excel file using ClosedXML.
using (XLWorkbook workBook = new XLWorkbook(filePath))
{
    //Read the first Sheet from Excel file.
    IXLWorksheet workSheet = workBook.Worksheet(1);

    //Create a new DataTable.
    DataTable dt = new DataTable();
    workSheet.sort(1);
    //Loop through the Worksheet rows.
    bool firstRow = true;
    foreach (IXLRow row in workSheet.Rows())
    {
        //Use the first row to add columns to DataTable.
        if (firstRow)
        {
            foreach (IXLCell cell in row.Cells())
            {
                dt.Columns.Add(cell.Value.ToString());
            }
            firstRow = false;
        }
        else
        {
            //Add rows to DataTable.
            dt.Rows.Add();
            int i = 0;
            foreach (IXLCell cell in row.Cells())
            {
                dt.Rows[dt.Rows.Count - 1][i] = cell.Value.ToString();
                i++;
            }
        }

        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}
}
</code>```

is there anyway to sort with specific column with number ?

答:
Select the range of cells that you want to sort, but exclude the headers and call the IXLRange.Sort() method, rather than the IXLWorksheet.Sort() method.

Example:

```<code>var range = wb.Worksheet("Sheet1").Range("A2:C6");
range.Sort(1);
</code>```

Title: closedxml sorting by specific number

Body:
I have a problem with ClosedXML in C#. I want to sort data but I want the system read column have numbers like 1, 2, 3, 4 and then sort by that.

If I use ws.Sort(1) the title is sorted too.

Here's my code:

protected void ImportExcel(object sender, EventArgs e)
{
    //Save the uploaded Excel file.
    string filePath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
    FileUpload1.SaveAs(filePath);

//Open the Excel file using ClosedXML.
using (XLWorkbook workBook = new XLWorkbook(filePath))
{
    //Read the first Sheet from Excel file.
    IXLWorksheet workSheet = workBook.Worksheet(1);

    //Create a new DataTable.
    DataTable dt = new DataTable();
    workSheet.sort(1);
    //Loop through the Worksheet rows.
    bool firstRow = true;
    foreach (IXLRow row in workSheet.Rows())
    {
        //Use the first row to add columns to DataTable.
        if (firstRow)
        {
            foreach (IXLCell cell in row.Cells())
            {
                dt.Columns.Add(cell.Value.ToString());
            }
            firstRow = false;
        }
        else
        {
            //Add rows to DataTable.
            dt.Rows.Add();
            int i = 0;
            foreach (IXLCell cell in row.Cells())
            {
                dt.Rows[dt.Rows.Count - 1][i] = cell.Value.ToString();
                i++;
            }
        }

        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}
}

is there anyway to sort with specific column with number ?

Body:
Select the range of cells that you want to sort, but exclude the headers and call the IXLRange.Sort() method, rather than the IXLWorksheet.Sort() method.

Example:

var range = wb.Worksheet("Sheet1").Range("A2:C6");
range.Sort(1);


问:
Replace multiple strings without overlapping
I have PHP application in which I have to replace a whole bunch of strings with their respective links. Basically I get a list of possible replacements that looks something like that:

```<code>"Table 1" => "<a href='SOME_LINK'>Table 1</a>"
"Table 2" => "<a href='SOME_LINK'>Table 2</a>"
...
"Table 10" => "<a href='SOME_LINK'>Table 10</a>"
"Table 11" => "<a href='SOME_LINK'>Table 11</a>"
</code>```

I go through each pair and I call str_replace which each couple of values. The problem is that even on the first pass I catch the Table 10 strings as well as the Table 1 strings and I replace both which is wrong. So I end up with result that has something like Table 10. Table 10 should not be replaced at all (unless later there's another pair that actually takes care of Table 10).

Any ideas for a work around? I though of adding a blank space after the search part of the string however it's possible to have something in the text like Table 1, which would then not match at all. I also considered using regular expressions to replace but not sure if there's a syntax there that would fix the issue above.

EDIT:
To improve the reading comprehension, here's expected input and output for this problem.
CONDITION:

```<code>"Table 1" => "<a href='SOME_LINK'>Table 1</a>"
"Table 10" => "<a href='SOME_LINK'>Table 10</a>"
</code>```

INPUT:

```<code>We have some text here.
It has words like Table 1, Table 2 and also Table 10.
Those need to be replaced.
</code>```

OUTPUT:

```<code>We have some text here.
It has words like <a href='SOME_LINK'>Table 1</a>, Table 2 and also <a href='SOME_LINK'>Table 10</a>.
Those need to be replaced.
</code>```

答:
As a workaround, how about sorting the array with replacements by key length descending and use regex to only replace strings that are not encapsulated by  tags?

That way you would replace Table 10 before Table 1, and you wouldn't make any double replacements.

Edit:
Here is an example as requested

```<code>$input = "We have some text here.
  It has words like Table 1, Table 2 and also Table 10.
  Those need to be replaced.";

$replacements = [
  "Table 1" => "<a href='SOME_LINK'>Table 1</a>",
  "Table 2" => "<a href='SOME_LINK'>Table 2</a>",
  "Table 10" => "<a href='SOME_LINK'>Table 10</a>",
];

uksort($replacements, function($a, $b) {
  return strlen($b) - strlen($a);
});

foreach ( $replacements as $key => $value ) {
  $input = preg_replace('/([^>])'.$key.'/', '$1'.$value, $input);
}

// Show the result
print($input);
</code>```

<s>This example require a space before the replacement key. It should be possible to modify it if this is prohibitive for the use case.</s>

I've updated the example to be agnostic to the character before the search key.

Body:
I have PHP application in which I have to replace a whole bunch of strings with their respective links. Basically I get a list of possible replacements that looks something like that:

"Table 1" => "Table 1"
"Table 2" => "Table 2"
...
"Table 10" => "Table 10"
"Table 11" => "Table 11"

I go through each pair and I call str_replace which each couple of values. The problem is that even on the first pass I catch the Table 10 strings as well as the Table 1 strings and I replace both which is wrong. So I end up with result that has something like Table 10. Table 10 should not be replaced at all (unless later there's another pair that actually takes care of Table 10).

Any ideas for a work around? I though of adding a blank space after the search part of the string however it's possible to have something in the text like Table 1, which would then not match at all. I also considered using regular expressions to replace but not sure if there's a syntax there that would fix the issue above.

EDIT:
To improve the reading comprehension, here's expected input and output for this problem.
CONDITION:

"Table 1" => "Table 1"
"Table 10" => "Table 10"

INPUT:

We have some text here.
It has words like Table 1, Table 2 and also Table 10.
Those need to be replaced.

OUTPUT:

We have some text here.
It has words like Table 1, Table 2 and also Table 10.
Those need to be replaced.

Body:
As a workaround, how about sorting the array with replacements by key length descending and use regex to only replace strings that are not encapsulated by <a> tags?

That way you would replace Table 10 before Table 1, and you wouldn't make any double replacements.

Edit:
Here is an example as requested

$input = "We have some text here.
  It has words like Table 1, Table 2 and also Table 10.
  Those need to be replaced.";

$replacements = [
  "Table 1" => "<a href='SOME_LINK'>Table 1</a>",
  "Table 2" => "<a href='SOME_LINK'>Table 2</a>",
  "Table 10" => "<a href='SOME_LINK'>Table 10</a>",
];

uksort($replacements, function($a, $b) {
  return strlen($b) - strlen($a);
});

foreach ( $replacements as $key => $value ) {
  $input = preg_replace('/([^>])'.$key.'/', '$1'.$value, $input);
}

// Show the result
print($input);

<s>This example require a space before the replacement key. It should be possible to modify it if this is prohibitive for the use case.</s>

I've updated the example to be agnostic to the character before the search key.


问:
Sort project browser tree view programmatically
I need to know how to set the order of elements shown in EA's project browser programmatically (in order to mimic the green arrows).</p>

答:
The tree view can not be sorted freely. EA puts a couple of constraints on the sorting. So diagrams, packages and a couple of other elements appear always on top and in groups. This is hard coded.

Use Element.TreePos to change the order where appropriate to simulate a manual order.

FWIW: Features have another queer behavior sometimes. You might need to uncheck the following in Tools/Options:


问:
Unable to connect to TFS using Powershell command - get-tfsserver
I am trying to connect to TFS using Powershell commands:

```<code>$tfsCollectionPath = "https://xxx.visualstudio.com"

[string]$username = "xxxx@hotmail.com"
$password = ConvertTo-SecureString 'xxxxx' -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($username, $password)

$tfs = get-tfsserver $tfsCollectionPath -credential $credential
</code>```

However, I get following error

```<code>get-tfsserver : TF30063: You are not authorized to access https://xxxx.visualstudio.com
</code>```

答: Use a Personal Authentication Token for the password.</p>

Body:
I am trying to connect to TFS using Powershell commands:

$tfsCollectionPath = "https://xxx.visualstudio.com"

[string]$username = "xxxx@hotmail.com"
$password = ConvertTo-SecureString 'xxxxx' -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($username, $password)

$tfs = get-tfsserver $tfsCollectionPath -credential $credential

However, I get following error

get-tfsserver : TF30063: You are not authorized to access https://xxxx.visualstudio.com


问:
How to know the size of a file from url befor downloading it?
Hi I am new for android and in my app I have to find the file size before downloading it.

For this I wrote the code below, but it's giving me content length 2588 but the actual size of my file is 745 MB.

Please help me. How can I find the exact file size in MB's?

code:-

```<code>URL url = new URL("mu url");
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int file_size = urlConnection.getContentLength();
</code>```

答:
You're probably using the wrong URL/file to get the size of the file you're expecting:

URL url = new URL("http://adultswim-vodlive.cdn.turner.com/ce8bfc5c729b0587eed7cf08b952c8c4/master.m3u8");

M3U8 files are plain-text playlist files - in your case the file that your URL is pointing to is actually only 2588 bytes.

Body:
Hi I am new for android and in my app I have to find the file size before downloading it.

For this I wrote the code below, but it's giving me content length 2588 but the actual size of my file is 745 MB.

Please help me. How can I find the exact file size in MB's?

code:-

URL url = new URL("mu url");
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int file_size = urlConnection.getContentLength();