问:
Android Studio - Images Expand Buttons (and break weight rules?)
I have been working around an issue for far too long. Any time I drop an image into an ImageButton, the button expands to be very large. To try to fix this, I created a TableLayout with TableRows, where the TableLayout has a weightSum and the rows each have their own layout_weight. However, regardless of how much weight that I assign a row, the image blows up and compresses all of my other rows. In other words, the TableRows do not respect the layout_weight assigned to them.

Below, I have four rows with weights 4, 5, 3, 1, respectively. The ImageButton is in the 3rd row with layout_weight="3". However, as you can see, the row expands to fit the button image.

At any rate, this is a major issue when I have multiple buttons on the screen. I have created many buttons of the same exact size thinking that I would make them large, so they will scale well with larger devices. Once again, the problem is that they don't scale down to fit inside of a button, but they expand the button, destroying all of the layout_weights in the process.

```<code><?xml version="1.0" encoding="utf-8"?>
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:weightSum="13"
        android:background="@drawable/edit_users_view">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="4"/>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="5">
            <ScrollView>
                <!-- Figure out button first -->
            </ScrollView>
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="3">
            <ImageButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/selector_cancel_button"/>

        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1">
        </TableRow>
</TableLayout>
</code>```

In addition - This issue may be in part with how I am storing my images. I have saved everything into my drawable folder, but nothing inside my mipmap folders. Though, I did try saving this cancel button into the mipmap-mdpi folder and loading it into the ImageButton, but the effect was exactly the same. Mipmap folders probably just set resolution, not size? I didn't expand my drawable folder because there are maybe 50 images/selectors inside.

答:
```<code><ImageButton
android:layout_width="XXdp"
android:layout_height="XXdp"
android:background="@drawable/selector_cancel_button"/>
</code>```

Set a specific density pixel for your ImageButton, it will limit it from expanding.

This answer is more like a HACK. The right way to do it is to have respective different images for all your screen sizes.

ldpi, mdpi, hdpi, xhpdi, xxhdpi, xxxhdpi. There are multiple open threads here on Stack on how to achieve that. Hope that helps.

Body:
I have been working around an issue for far too long. Any time I drop an image into an ImageButton, the button expands to be very large. To try to fix this, I created a TableLayout with TableRows, where the TableLayout has a weightSum and the rows each have their own layout_weight. However, regardless of how much weight that I assign a row, the image blows up and compresses all of my other rows. In other words, the TableRows do not respect the layout_weight assigned to them.

Below, I have four rows with weights 4, 5, 3, 1, respectively. The ImageButton is in the 3rd row with layout_weight="3". However, as you can see, the row expands to fit the button image.

At any rate, this is a major issue when I have multiple buttons on the screen. I have created many buttons of the same exact size thinking that I would make them large, so they will scale well with larger devices. Once again, the problem is that they don't scale down to fit inside of a button, but they expand the button, destroying all of the layout_weights in the process.

<?xml version="1.0" encoding="utf-8"?>
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:weightSum="13"
        android:background="@drawable/edit_users_view">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="4"/>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="5">
            <ScrollView>

            </ScrollView>
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="3">
            <ImageButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/selector_cancel_button"/>

        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1">
        </TableRow>
</TableLayout>

In addition - This issue may be in part with how I am storing my images. I have saved everything into my drawable folder, but nothing inside my mipmap folders. Though, I did try saving this cancel button into the mipmap-mdpi folder and loading it into the ImageButton, but the effect was exactly the same. Mipmap folders probably just set resolution, not size? I didn't expand my drawable folder because there are maybe 50 images/selectors inside.

Body:
<ImageButton
android:layout_width="XXdp"
android:layout_height="XXdp"
android:background="@drawable/selector_cancel_button"/>

Set a specific density pixel for your ImageButton, it will limit it from expanding.

This answer is more like a HACK. The right way to do it is to have respective different images for all your screen sizes.

ldpi, mdpi, hdpi, xhpdi, xxhdpi, xxxhdpi. There are multiple open threads here on Stack on how to achieve that. Hope that helps.


来源: stackexchange

问:
C# How to automatically navigate to {GUID} Directory?
I have a program which utilizes a 3rd party tool to create a log text file.

However the tool requires the restore point directory of windows XP. The directory that stores the Restore points is the "C:\System Volume Information_restore{GUID}".

The _restore{GUID} folder would contain all the restore points. However the {GUID} are totally random numbers and are different for each computers. The "C:\System Volume Information" directory would only usually contain 1 folder which is the "_random{GUID}" folder.

Therefore is there a way for the C# program to use any codes or methods to automatically fill in the command arguments for the tool?

May someone please advise on the codes? Thanks!

The codes:

```<code>        Process process = new Process();
        process.StartInfo.FileName = @"C:\test\ftk\ripxp\ripxp.exe";
        // How to automatically navigate to the {GUID} folder?
        process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\_restore{GUID} -p runmru";
        process.StartInfo.CreateNoWindow = false;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardInput = true;
        process.StartInfo.RedirectStandardError = true;
        process.Start();
</code>```

The 3rd party tool (2008 H. Carvey) Arguments:

```<code>C:\>ripxp -r d:\cases\ntuser.dat -d d:\cases\svi -p userassist
</code>```

答:
Why not query that folder location and loop through the list of directories to find the folder that starts with "_restore" and then plug that into your argument?

```<code>DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\System Volume Information\");
DirectoryInfo restoreFolder = directoryInfo.GetDirectories().FirstOrDefault(d =>
    d.Name.StartsWith("_restore"));

if (restoreFolder == null)
    throw new DirectoryNotFoundException();
</code>```

Then you should be able to plug that folder value into your argument

```<code>process.StartInfo.Arguments = string.Format(
    @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\{0} -p runmru",
    restoreFolder.Name);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a program which utilizes a 3rd party tool to create a log text file.

However the tool requires the restore point directory of windows XP. The directory that stores the Restore points is the "C:\System Volume Information_restore{GUID}".

The _restore{GUID} folder would contain all the restore points. However the {GUID} are totally random numbers and are different for each computers. The "C:\System Volume Information" directory would only usually contain 1 folder which is the "_random{GUID}" folder.

Therefore is there a way for the C# program to use any codes or methods to automatically fill in the command arguments for the tool?

May someone please advise on the codes? Thanks!

The codes:

        Process process = new Process();
        process.StartInfo.FileName = @"C:\test\ftk\ripxp\ripxp.exe";
        // How to automatically navigate to the {GUID} folder?
        process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\_restore{GUID} -p runmru";
        process.StartInfo.CreateNoWindow = false;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardInput = true;
        process.StartInfo.RedirectStandardError = true;
        process.Start();

The 3rd party tool (2008 H. Carvey) Arguments:

C:\>ripxp -r d:\cases\ntuser.dat -d d:\cases\svi -p userassist

Body:
Why not query that folder location and loop through the list of directories to find the folder that starts with "_restore" and then plug that into your argument?

DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\System Volume Information\");
DirectoryInfo restoreFolder = directoryInfo.GetDirectories().FirstOrDefault(d =>
    d.Name.StartsWith("_restore"));

if (restoreFolder == null)
    throw new DirectoryNotFoundException();

Then you should be able to plug that folder value into your argument

process.StartInfo.Arguments = string.Format(
    @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\{0} -p runmru",
    restoreFolder.Name);


问:
jsdom: Cannot read property '_location' of null
I'm getting test failed when I test epic via jest.

```<code>Test Failed
/.../node_modules/jsdom/lib/jsdom/browser/Window.js:148

return idlUtils.wrapperForImpl(idlUtils.implForWrapper(window._document)._location);

TypeError: Cannot read property '_location' of null
    at Window.get location [as location] (/.../node_modules/jsdom/lib/jsdom/browser/Window.js:148:79)
    at Timeout.callback [as _onTimeout] (/.../node_modules/jsdom/lib/jsdom/browser/Window.js:525:40)
    at ontimeout (timers.js:380:14)
    at tryOnTimeout (timers.js:244:5)
    at Timer.listOnTimeout (timers.js:214:5)
</code>```

And this is some of my test. I used fetch() and promise in fetchCategoriesEpic.

```<code>it('test epic', () => {
    ...
    const action$ = ActionsObservable.of({ type: FETCH_CATEGORIES })

    fetchCategoriesEpic(action$)
      .toArray() // collects everything in an array until our epic completes
      .subscribe((actions) => {
        expect(actions).toEqual([
          { type: FETCH_CATEGORIES },
          { type: FETCH_CATEGORIES_SUCCESS, payload: List(payload.data).map((category) => new Category(category)) }
        ])
      })
    ...
}
</code>```

How can I solve this?

答:
I ran into this issue when attempting to use document.documentElement while testing in an environment where document was undefined.

I added a conditional to that part of application code and my tests ran fine after that.

Make sure your application code rather than your test code is attempting to accessing ONLY elements that exist in your test environment.

ContentLicense: CC BY-SA 3.0

Body:
I'm getting test failed when I test epic via jest.

Test Failed
/.../node_modules/jsdom/lib/jsdom/browser/Window.js:148

return idlUtils.wrapperForImpl(idlUtils.implForWrapper(window._document)._location);

TypeError: Cannot read property '_location' of null
    at Window.get location [as location] (/.../node_modules/jsdom/lib/jsdom/browser/Window.js:148:79)
    at Timeout.callback [as _onTimeout] (/.../node_modules/jsdom/lib/jsdom/browser/Window.js:525:40)
    at ontimeout (timers.js:380:14)
    at tryOnTimeout (timers.js:244:5)
    at Timer.listOnTimeout (timers.js:214:5)

And this is some of my test. I used fetch() and promise in fetchCategoriesEpic.

it('test epic', () => {
    ...
    const action$ = ActionsObservable.of({ type: FETCH_CATEGORIES })

    fetchCategoriesEpic(action$)
      .toArray() // collects everything in an array until our epic completes
      .subscribe((actions) => {
        expect(actions).toEqual([
          { type: FETCH_CATEGORIES },
          { type: FETCH_CATEGORIES_SUCCESS, payload: List(payload.data).map((category) => new Category(category)) }
        ])
      })
    ...
}

How can I solve this?


问:
log4j configuration does not work for a specific class
I have a class which I want to redirect its log output to a file. But no matter what I do, it always outputs to the console. Here is my log4j.properties file.

```<code>log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %C %l %-5p %c{1}:%L - %t - %m%n

log4j.logger.io.opentracing.impl.LoggingEventBuilder=INFO, ul
log4j.additivity.io.opentracing.impl.LoggingEventBuilder=false
log4j.appender.ul=org.apache.log4j.RollingFileAppender
log4j.appender.ul.maxFileSize=50MB
log4j.appender.ul.file=${catalina.home}/logs/mylogs.log
log4j.appender.ul.layout=org.apache.log4j.PatternLayout
log4j.appender.ul.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %t - %m%n
</code>```

Here io.opentracing.impl.LoggingEventBuilder is the class whose output I want to redirect. The interesting thing is that I tried to redirect output from other classes to a file using the same code pattern and it worked. Only for this class it does not work.

I am using slf4j-log4j12. What am I missing?

答:
Thanks a lot for the hint. That pointed me to the correct solution. Apparently the authors of that library defined their logger as something like FooLogging. So I changed these two lines:

```<code>log4j.logger.io.opentracing.impl.LoggingEventBuilder=INFO, ul
log4j.additivity.io.opentracing.impl.LoggingEventBuilder=false
</code>```

to

```<code>log4j.logger.FooLogging=INFO, ul
log4j.additivity.FooLogging=false
</code>```

and that solved the problem.

Body:
I have a class which I want to redirect its log output to a file. But no matter what I do, it always outputs to the console. Here is my log4j.properties file.

log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %C %l %-5p %c{1}:%L - %t - %m%n

log4j.logger.io.opentracing.impl.LoggingEventBuilder=INFO, ul
log4j.additivity.io.opentracing.impl.LoggingEventBuilder=false
log4j.appender.ul=org.apache.log4j.RollingFileAppender
log4j.appender.ul.maxFileSize=50MB
log4j.appender.ul.file=${catalina.home}/logs/mylogs.log
log4j.appender.ul.layout=org.apache.log4j.PatternLayout
log4j.appender.ul.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %t - %m%n

Here io.opentracing.impl.LoggingEventBuilder is the class whose output I want to redirect. The interesting thing is that I tried to redirect output from other classes to a file using the same code pattern and it worked. Only for this class it does not work.

I am using slf4j-log4j12. What am I missing?

Body:
Thanks a lot for the hint. That pointed me to the correct solution. Apparently the authors of that library defined their logger as something like FooLogging. So I changed these two lines:

log4j.logger.io.opentracing.impl.LoggingEventBuilder=INFO, ul
log4j.additivity.io.opentracing.impl.LoggingEventBuilder=false

to

log4j.logger.FooLogging=INFO, ul
log4j.additivity.FooLogging=false

and that solved the problem.


问:
How to sum results of case formulas
I have a few case formulas in NetSuite saved search that pulls in available quantities for member items (components) of products in specific locations. I would like to create a formula to show all quantities for these components available for specific locations (or exclude specific locations) as 1 result for each component in the search.

```<code>case when {memberitem.inventorylocation} = 'Location 1' then {memberitem.locationquantityavailable} else null end
case when {memberitem.inventorylocation} = 'Location 2' then {memberitem.locationquantityavailable} else null end
case when {memberitem.inventorylocation} = 'Location 3' then {memberitem.locationquantityavailable} else null end
</code>```

How do I find the sum for the {memberitem.locationquantityavailable} for these 3 locations in 1 formula?

答:
You must SUM in the Summary Type of the NetSuite Item search but, here is an example of how to use the sum of case formulas with other formulas.

This is used to calculate an available quantity for kits based on the available quantities of member items, Demand (Calculated elsewhere and populated in a custom field) and % allocated to the kit (Calculated elsewhere and populated in a custom field). The FLOOR is used to round down (so you don't get results like 1.11111111111111111):

```<code>(Floor((case {memberitem.inventorylocation}
    when 'Location 1' then{memberitem.locationquantityavailable}
    when 'Location 2' then {memberitem.locationquantityavailable}
    when 'Location 3' then {memberitem.locationquantityavailable}
    when 'Location 4' then {memberitem.locationquantityavailable}
    when 'Locatoin 5' then {memberitem.locationquantityavailable}
 else 0 end)
    *(({custitem_kit_demand}
    *{memberquantity})
    /NULLIF({memberitem.custitem_aggregate_component_demand},0))))
    /NULLIF({memberquantity},0)
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to sum results of case formulas

Body:
I have a few case formulas in NetSuite saved search that pulls in available quantities for member items (components) of products in specific locations. I would like to create a formula to show all quantities for these components available for specific locations (or exclude specific locations) as 1 result for each component in the search.

case when {memberitem.inventorylocation} = 'Location 1' then {memberitem.locationquantityavailable} else null end
case when {memberitem.inventorylocation} = 'Location 2' then {memberitem.locationquantityavailable} else null end
case when {memberitem.inventorylocation} = 'Location 3' then {memberitem.locationquantityavailable} else null end

How do I find the sum for the {memberitem.locationquantityavailable} for these 3 locations in 1 formula?

Body:
You must SUM in the Summary Type of the NetSuite Item search but, here is an example of how to use the sum of case formulas with other formulas.

This is used to calculate an available quantity for kits based on the available quantities of member items, Demand (Calculated elsewhere and populated in a custom field) and % allocated to the kit (Calculated elsewhere and populated in a custom field). The FLOOR is used to round down (so you don't get results like 1.11111111111111111):

(Floor((case {memberitem.inventorylocation}
    when 'Location 1' then{memberitem.locationquantityavailable}
    when 'Location 2' then {memberitem.locationquantityavailable}
    when 'Location 3' then {memberitem.locationquantityavailable}
    when 'Location 4' then {memberitem.locationquantityavailable}
    when 'Locatoin 5' then {memberitem.locationquantityavailable}
 else 0 end)
    *(({custitem_kit_demand}
    *{memberquantity})
    /NULLIF({memberitem.custitem_aggregate_component_demand},0))))
    /NULLIF({memberquantity},0)


问:
ng2-datepicker how to change the date from typescript code?
I am using the ng2-datepicker in my angular app and I want to update the date from the typescript file.

In the html template:

```<code><ng2-datepicker [options]="optionsForMenuDate" [(ngModel)]="selectedDate" name="selectedDate"></ng2-datepicker>
</code>```

It is binding to a moment object, so I am trying to update it like this (I have included moment in the angular solution):

```<code>this.selectedDate = this.moment(date);
</code>```

Where date it the js Date object that I want to set the date to. This just sets the component to null though, even this this.selectedDate is not null.

```<code>console.log(this.selectedDate); // logs a moment object
</code>```

Any ideas on how to achieve this?

答:
I was having the same issue and I got it working by following way.

The problem with your code is at below line,

```<code>[(ngModel)]="selectedDate"
</code>```

Here, property 'selectedDate' should be of type 'DateModel' and not the moment object.  The DateModel is defined at,

```<code>import {DateModel} from "ng2-datepicker";
</code>```

And it has a following properties,

```<code>export declare class DateModel {
    day: string;
    month: string;
    year: string;
    formatted: string;
    momentObj: moment.Moment;
    constructor(obj?: IDateModel);
}
</code>```

Now you need to set momentObj and formatted properties to get it working.

Here is the sample code,

```<code>let dateModel:DateModel = new DateModel();
let momentObj = moment('05-11-1986', "MM-DD-YYYY");
dateModel.momentObj = momentObj;
dateModel.formatted = momentObj.format();
this.selectedDate = dateModel;
</code>```

Body:
I am using the ng2-datepicker in my angular app and I want to update the date from the typescript file.

In the html template:

<ng2-datepicker [options]="optionsForMenuDate" [(ngModel)]="selectedDate" name="selectedDate"></ng2-datepicker>

It is binding to a moment object, so I am trying to update it like this (I have included moment in the angular solution):

this.selectedDate = this.moment(date);

Where date it the js Date object that I want to set the date to. This just sets the component to null though, even this this.selectedDate is not null.

console.log(this.selectedDate); // logs a moment object

Any ideas on how to achieve this?

Body:
I was having the same issue and I got it working by following way.

The problem with your code is at below line,

[(ngModel)]="selectedDate"

Here, property 'selectedDate' should be of type 'DateModel' and not the moment object.  The DateModel is defined at,

import {DateModel} from "ng2-datepicker";

And it has a following properties,

export declare class DateModel {
    day: string;
    month: string;
    year: string;
    formatted: string;
    momentObj: moment.Moment;
    constructor(obj?: IDateModel);
}

Now you need to set momentObj and formatted properties to get it working.

Here is the sample code,

let dateModel:DateModel = new DateModel();
let momentObj = moment('05-11-1986', "MM-DD-YYYY");
dateModel.momentObj = momentObj;
dateModel.formatted = momentObj.format();
this.selectedDate = dateModel;


问:
AngularJS watching property of factory objects - unexpected behavior
I would like to understand a certain behavior of AngularJS when it comes to watching changes of objects provided by a factory.

There is a different behavior depending on whether I read a property of a factory-provided object in the controller or in the html.

Compare the following 2 ways of displaying the property in the view:

```<code>app.controller("testController", function($scope, testFactory){
    $scope.test_obj = testFactory.read();
    $scope.test_prop = testFactory.read().prop;
});

<div>{{test_obj.prop}}</div>
<div>{{test_prop}}</div>
</code>```

When the property changes in the testFactory, the change is updated in the view only in the first case, when the whole object is declared to scope and the property is called in the view. When the property is directly declared to the scope, it doesn't update automatically in the view.

This behavior can be observed in the following jsfiddle: https://jsfiddle.net/fb86p4fm/

What's the reason for this behavior?

答:
I would say that $scope.test_obj is a reference to the factory's obj while $scope.test_prop is a copied value of obj.prop.

If you add the following to your example :

```<code>console.log(testFactory.read()); // output : Object {prop: 0}
console.log(testFactory.read().prop); // output 0
</code>```

You'd see that the read method would return an object and the read().prop would return a value.

Body:
I would like to understand a certain behavior of AngularJS when it comes to watching changes of objects provided by a factory.

There is a different behavior depending on whether I read a property of a factory-provided object in the controller or in the html.

Compare the following 2 ways of displaying the property in the view:

app.controller("testController", function($scope, testFactory){
    $scope.test_obj = testFactory.read();
    $scope.test_prop = testFactory.read().prop;
});

{{test_obj.prop}}

{{test_prop}}

When the property changes in the testFactory, the change is updated in the view only in the first case, when the whole object is declared to scope and the property is called in the view. When the property is directly declared to the scope, it doesn't update automatically in the view.

This behavior can be observed in the following jsfiddle: https://jsfiddle.net/fb86p4fm/

What's the reason for this behavior?

Body:
I would say that $scope.test_obj is a reference to the factory's obj while $scope.test_prop is a copied value of obj.prop.

If you add the following to your example :

console.log(testFactory.read()); // output : Object {prop: 0}
console.log(testFactory.read().prop); // output 0

You'd see that the read method would return an object and the read().prop would return a value.


问:
How to create dynamic tag based on props with Vue 2
How can I make a component similar to vue-router router-link where I get the tag via props to render my template ?

```<code><my-component tag="ul">
</my-component>
</code>```

Would render:

```<code><ul>
  anything inside my-component
</ul>
</code>```

答:
You can use a built-in component element like so:

<component is="ul" class="foo" style="color:red">
  anything inside component
</component>
```

See: https://v2.vuejs.org/v2/guide/components.html#Dynamic-Components

Body:
How can I make a component similar to vue-router router-link where I get the tag via props to render my template ?

<my-component tag="ul">
</my-component>

Would render:

  anything inside my-component

Body:
You can use a built-in component element like so:

<component is="ul" class="foo" style="color:red">
  anything inside component
</component>

See: https://v2.vuejs.org/v2/guide/components.html#Dynamic-Components


问:
Get devexpress gridview selected rows on button click in .net web forms
I have this devexpress aspxgridview:

```<code><dxwgv:ASPxGridView ID="grid" ClientInstanceName="grid" runat="server"
            KeyFieldName="childUserId">
            <Columns>
                <dx:GridViewCommandColumn ShowSelectCheckbox="True">
                </dx:GridViewCommandColumn>
                <dx:GridViewDataColumn FieldName="childUserName" />
                <dx:GridViewDataColumn FieldName="childFirstName"/>
                <dx:GridViewDataColumn FieldName="childLastName" />
            </Columns>
            <ClientSideEvents SelectionChanged="grid_SelectionChanged" />
        </dxwgv:ASPxGridView>
</code>```

Then I have normal asp button which has click event. I want to know how I can get the selected rows in the gridview, this is the layout I have

DevExpress version I use is DevExpress.Web.v14.1

答:
In the server event, you should be able to use the

```<code>grid.GetSelectedRows()
</code>```

method to get the selected rows.

Body:
I have this devexpress aspxgridview:

<dxwgv:ASPxGridView ID="grid" ClientInstanceName="grid" runat="server"
            KeyFieldName="childUserId">
            <Columns>
                <dx:GridViewCommandColumn ShowSelectCheckbox="True">
                </dx:GridViewCommandColumn>
                <dx:GridViewDataColumn FieldName="childUserName" />
                <dx:GridViewDataColumn FieldName="childFirstName"/>
                <dx:GridViewDataColumn FieldName="childLastName" />
            </Columns>
            <ClientSideEvents SelectionChanged="grid_SelectionChanged" />
        </dxwgv:ASPxGridView>

Then I have normal asp button which has click event. I want to know how I can get the selected rows in the gridview, this is the layout I have

DevExpress version I use is DevExpress.Web.v14.1

Body:
In the server event, you should be able to use the

grid.GetSelectedRows()

method to get the selected rows.


问:
How do I use custom keys with Swift 4's Decodable protocol?
Swift 4 introduced support for native JSON encoding and decoding via the Decodable protocol. How do I use custom keys for this?

E.g., say I have a struct

```<code>struct Address:Codable {
    var street:String
    var zip:String
    var city:String
    var state:String
}
</code>```

I can encode this to JSON.

```<code>let address = Address(street: "Apple Bay Street", zip: "94608", city: "Emeryville", state: "California")

if let encoded = try? encoder.encode(address) {
    if let json = String(data: encoded, encoding: .utf8) {
        // Print JSON String
        print(json)

        // JSON string is
           { "state":"California",
             "street":"Apple Bay Street",
             "zip":"94608",
             "city":"Emeryville"
           }
    }
}
</code>```

I can encode this back to an object.

```<code>    let newAddress: Address = try decoder.decode(Address.self, from: encoded)
</code>```

But If I had a json object that was

```<code>{
   "state":"California",
   "street":"Apple Bay Street",
   "zip_code":"94608",
   "city":"Emeryville"
}
</code>```

How would I tell the decoder on Address that zip_code maps to zip? I believe you use the new CodingKey protocol, but I can't figure out how to use this.

答:
Manually customising coding keys

In your example, you're getting an auto-generated conformance to Codable as all your properties also conform to Codable. This conformance automatically creates a key type that simply corresponds to the property names – which is then used in order to encode to/decode from a single keyed container.

However one really neat feature of this auto-generated conformance is that if you define a nested enum in your type called "CodingKeys" (or use a typealias with this name) that conforms to the CodingKey protocol – Swift will automatically use this as the key type. This therefore allows you to easily customise the keys that your properties are encoded/decoded with.

So what this means is you can just say:

```<code>struct Address : Codable {

    var street: String
    var zip: String
    var city: String
    var state: String

    private enum CodingKeys : String, CodingKey {
        case street, zip = "zip_code", city, state
    }
}
</code>```

The enum case names need to match the property names, and the raw values of these cases need to match the keys that you're encoding to/decoding from (unless specified otherwise, the raw values of a String enumeration will the same as the case names). Therefore, the zip property will now be encoded/decoded using the key "zip_code".

The exact rules for the auto-generated Encodable/Decodable conformance are detailed by the evolution proposal (emphasis mine):

In addition to automatic CodingKey requirement synthesis for
  enums, Encodable & Decodable requirements can be automatically
  synthesized for certain types as well:

Types conforming to Encodable whose properties are all Encodable get an automatically generated String-backed CodingKey enum mapping
  properties to case names. Similarly for Decodable types whose
  properties are all Decodable

Types falling into (1) — and types which manually provide a CodingKey enum (named CodingKeys, directly, or via a typealias) whose
  cases map 1-to-1 to Encodable/Decodable properties by name — get
  automatic synthesis of init(from:) and encode(to:) as appropriate,
  using those properties and keys

Types which fall into neither (1) nor (2) will have to provide a custom key type if needed and provide their own init(from:) and
  encode(to:), as appropriate

Example encoding:

```<code>import Foundation

let address = Address(street: "Apple Bay Street", zip: "94608",
                      city: "Emeryville", state: "California")

do {
    let encoded = try JSONEncoder().encode(address)
    print(String(decoding: encoded, as: UTF8.self))
} catch {
    print(error)
}
//{"state":"California","street":"Apple Bay Street","zip_code":"94608","city":"Emeryville"}
</code>```

Example decoding:

```<code>// using the """ multi-line string literal here, as introduced in SE-0168,
// to avoid escaping the quotation marks
let jsonString = """
{"state":"California","street":"Apple Bay Street","zip_code":"94608","city":"Emeryville"}
"""

do {
    let decoded = try JSONDecoder().decode(Address.self, from: Data(jsonString.utf8))
    print(decoded)
} catch {
    print(error)
}

// Address(street: "Apple Bay Street", zip: "94608",
// city: "Emeryville", state: "California")
</code>```

Automatic snake_case JSON keys for camelCase property names

In Swift 4.1, if you rename your zip property to zipCode, you can take advantage of the key encoding/decoding strategies on JSONEncoder and JSONDecoder in order to automatically convert coding keys between camelCase and snake_case.

Example encoding:

```<code>import Foundation

struct Address : Codable {
  var street: String
  var zipCode: String
  var city: String
  var state: String
}

let address = Address(street: "Apple Bay Street", zipCode: "94608",
                      city: "Emeryville", state: "California")

do {
  let encoder = JSONEncoder()
  <b>encoder.keyEncodingStrategy = .convertToSnakeCase</b>
  let encoded = try encoder.encode(address)
  print(String(decoding: encoded, as: UTF8.self))
} catch {
  print(error)
}
//{"state":"California","street":"Apple Bay Street","zip_code":"94608","city":"Emeryville"}</code>```

Example decoding:

```<code>let jsonString = """
{"state":"California","street":"Apple Bay Street","zip_code":"94608","city":"Emeryville"}
"""

do {
  let decoder = JSONDecoder()
  <b>decoder.keyDecodingStrategy = .convertFromSnakeCase</b>
  let decoded = try decoder.decode(Address.self, from: Data(jsonString.utf8))
  print(decoded)
} catch {
  print(error)
}

// Address(street: "Apple Bay Street", zipCode: "94608",
// city: "Emeryville", state: "California")</code>```

One important thing to note about this strategy however is that it won't be able to round-trip some property names with acronyms or initialisms which, according to the Swift API design guidelines, should be uniformly upper or lower case (depending on the position).

For example, a property named someURL will be encoded with the key some_url, but on decoding, this will be transformed to someUrl.

To fix this, you'll have to manually specify the coding key for that property to be string that the decoder expects, e.g someUrl in this case (which will still be transformed to some_url by the encoder):

```<code>struct S : Codable {

  private enum CodingKeys : String, CodingKey {
    case someURL = "someUrl", someOtherProperty
  }

  var someURL: String
  var someOtherProperty: String
}
</code>```

(This doesn't strictly answer your specific question, but given the canonical nature of this Q&A, I feel it's worth including)

Custom automatic JSON key mapping

In Swift 4.1, you can take advantage of the custom key encoding/decoding strategies on JSONEncoder and JSONDecoder, allowing you to provide a custom function to map coding keys.

The function you provide takes a [CodingKey], which represents the coding path for the current point in encoding/decoding (in most cases, you'll only need to consider the last element; that is, the current key). The function returns a CodingKey that will replace the last key in this array.

For example, UpperCamelCase JSON keys for lowerCamelCase property names:

```<code>import Foundation

// wrapper to allow us to substitute our mapped string keys.
struct AnyCodingKey : CodingKey {

  var stringValue: String
  var intValue: Int?

  init(_ base: CodingKey) {
    self.init(stringValue: base.stringValue, intValue: base.intValue)
  }

  init(stringValue: String) {
    self.stringValue = stringValue
  }

  init(intValue: Int) {
    self.stringValue = "\(intValue)"
    self.intValue = intValue
  }

  init(stringValue: String, intValue: Int?) {
    self.stringValue = stringValue
    self.intValue = intValue
  }
}
</code>```

```<code>extension JSONEncoder.KeyEncodingStrategy {

  static var convertToUpperCamelCase: JSONEncoder.KeyEncodingStrategy {
    return .custom { codingKeys in

      var key = AnyCodingKey(codingKeys.last!)

      // uppercase first letter
      if let firstChar = key.stringValue.first {
        let i = key.stringValue.startIndex
        key.stringValue.replaceSubrange(
          i ... i, with: String(firstChar).uppercased()
        )
      }
      return key
    }
  }
}
</code>```

```<code>extension JSONDecoder.KeyDecodingStrategy {

  static var convertFromUpperCamelCase: JSONDecoder.KeyDecodingStrategy {
    return .custom { codingKeys in

      var key = AnyCodingKey(codingKeys.last!)

      // lowercase first letter
      if let firstChar = key.stringValue.first {
        let i = key.stringValue.startIndex
        key.stringValue.replaceSubrange(
          i ... i, with: String(firstChar).lowercased()
        )
      }
      return key
    }
  }
}
</code>```

You can now encode with the .convertToUpperCamelCase key strategy:

```<code>let address = Address(street: "Apple Bay Street", zipCode: "94608",
                      city: "Emeryville", state: "California")

do {
  let encoder = JSONEncoder()
  encoder.keyEncodingStrategy = .convertToUpperCamelCase
  let encoded = try encoder.encode(address)
  print(String(decoding: encoded, as: UTF8.self))
} catch {
  print(error)
}
//{"Street":"Apple Bay Street","City":"Emeryville","State":"California","ZipCode":"94608"}
</code>```

and decode with the .convertFromUpperCamelCase key strategy:

```<code>import Foundation

let address = Address(street: "Apple Bay Street", zip: "94608",
                      city: "Emeryville", state: "California")

do {
    let encoded = try JSONEncoder().encode(address)
    print(String(decoding: encoded, as: UTF8.self))
} catch {
    print(error)
}
//{"state":"California","street":"Apple Bay Street","zip_code":"94608","city":"Emeryville"}
</code>```0

Body:
Swift 4 introduced support for native JSON encoding and decoding via the Decodable protocol. How do I use custom keys for this?

E.g., say I have a struct

struct Address:Codable {
    var street:String
    var zip:String
    var city:String
    var state:String
}

I can encode this to JSON.

let address = Address(street: "Apple Bay Street", zip: "94608", city: "Emeryville", state: "California")

if let encoded = try? encoder.encode(address) {
    if let json = String(data: encoded, encoding: .utf8) {
        // Print JSON String
        print(json)

        // JSON string is
           { "state":"California",
             "street":"Apple Bay Street",
             "zip":"94608",
             "city":"Emeryville"
           }
    }
}

I can encode this back to an object.

    let newAddress: Address = try decoder.decode(Address.self, from: encoded)

But If I had a json object that was

{
   "state":"California",
   "street":"Apple Bay Street",
   "zip_code":"94608",
   "city":"Emeryville"
}

How would I tell the decoder on Address that zip_code maps to zip? I believe you use the new CodingKey protocol, but I can't figure out how to use this.

Body:
Manually customising coding keys

In your example, you're getting an auto-generated conformance to Codable as all your properties also conform to Codable. This conformance automatically creates a key type that simply corresponds to the property names – which is then used in order to encode to/decode from a single keyed container.

However one really neat feature of this auto-generated conformance is that if you define a nested enum in your type called "CodingKeys" (or use a typealias with this name) that conforms to the CodingKey protocol – Swift will automatically use this as the key type. This therefore allows you to easily customise the keys that your properties are encoded/decoded with.

So what this means is you can just say:

struct Address : Codable {

    var street: String
    var zip: String
    var city: String
    var state: String

    private enum CodingKeys : String, CodingKey {
        case street, zip = "zip_code", city, state
    }
}

The enum case names need to match the property names, and the raw values of these cases need to match the keys that you're encoding to/decoding from (unless specified otherwise, the raw values of a String enumeration will the same as the case names). Therefore, the zip property will now be encoded/decoded using the key "zip_code".

The exact rules for the auto-generated Encodable/Decodable conformance are detailed by the evolution proposal (emphasis mine):

In addition to automatic CodingKey requirement synthesis for
  enums, Encodable & Decodable requirements can be automatically
  synthesized for certain types as well:

Types conforming to Encodable whose properties are all Encodable get an automatically generated String-backed CodingKey enum mapping
  properties to case names. Similarly for Decodable types whose
  properties are all Decodable

Types falling into (1) — and types which manually provide a CodingKey enum (named CodingKeys, directly, or via a typealias) whose
  cases map 1-to-1 to Encodable/Decodable properties by name — get
  automatic synthesis of init(from:) and encode(to:) as appropriate,
  using those properties and keys

Types which fall into neither (1) nor (2) will have to provide a custom key type if needed and provide their own init(from:) and
  encode(to:), as appropriate

Example encoding:

import Foundation

let address = Address(street: "Apple Bay Street", zip: "94608",
                      city: "Emeryville", state: "California")

do {
    let encoded = try JSONEncoder().encode(address)
    print(String(decoding: encoded, as: UTF8.self))
} catch {
    print(error)
}
//{"state":"California","street":"Apple Bay Street","zip_code":"94608","city":"Emeryville"}

Example decoding:

// using the """ multi-line string literal here, as introduced in SE-0168,
// to avoid escaping the quotation marks
let jsonString = """
{"state":"California","street":"Apple Bay Street","zip_code":"94608","city":"Emeryville"}
"""

do {
    let decoded = try JSONDecoder().decode(Address.self, from: Data(jsonString.utf8))
    print(decoded)
} catch {
    print(error)
}

// Address(street: "Apple Bay Street", zip: "94608",
// city: "Emeryville", state: "California")

Automatic snake_case JSON keys for camelCase property names

In Swift 4.1, if you rename your zip property to zipCode, you can take advantage of the key encoding/decoding strategies on JSONEncoder and JSONDecoder in order to automatically convert coding keys between camelCase and snake_case.

Example encoding:

import Foundation

struct Address : Codable {
  var street: String
  var zipCode: String
  var city: String
  var state: String
}

let address = Address(street: "Apple Bay Street", zipCode: "94608",
                      city: "Emeryville", state: "California")

do {
  let encoder = JSONEncoder()
  encoder.keyEncodingStrategy = .convertToSnakeCase
  let encoded = try encoder.encode(address)
  print(String(decoding: encoded, as: UTF8.self))
} catch {
  print(error)
}
//{"state":"California","street":"Apple Bay Street","zip_code":"94608","city":"Emeryville"}

Example decoding:

let jsonString = """
{"state":"California","street":"Apple Bay Street","zip_code":"94608","city":"Emeryville"}
"""

do {
  let decoder = JSONDecoder()
  decoder.keyDecodingStrategy = .convertFromSnakeCase
  let decoded = try decoder.decode(Address.self, from: Data(jsonString.utf8))
  print(decoded)
} catch {
  print(error)
}

// Address(street: "Apple Bay Street", zipCode: "94608",
// city: "Emeryville", state: "California")

One important thing to note about this strategy however is that it won't be able to round-trip some property names with acronyms or initialisms which, according to the Swift API design guidelines, should be uniformly upper or lower case (depending on the position).

For example, a property named someURL will be encoded with the key some_url, but on decoding, this will be transformed to someUrl.

To fix this, you'll have to manually specify the coding key for that property to be string that the decoder expects, e.g someUrl in this case (which will still be transformed to some_url by the encoder):

struct S : Codable {

  private enum CodingKeys : String, CodingKey {
    case someURL = "someUrl", someOtherProperty
  }

  var someURL: String
  var someOtherProperty: String
}

(This doesn't strictly answer your specific question, but given the canonical nature of this Q&A, I feel it's worth including)

Custom automatic JSON key mapping

In Swift 4.1, you can take advantage of the custom key encoding/decoding strategies on JSONEncoder and JSONDecoder, allowing you to provide a custom function to map coding keys.

The function you provide takes a [CodingKey], which represents the coding path for the current point in encoding/decoding (in most cases, you'll only need to consider the last element; that is, the current key). The function returns a CodingKey that will replace the last key in this array.

For example, UpperCamelCase JSON keys for lowerCamelCase property names:

import Foundation

// wrapper to allow us to substitute our mapped string keys.
struct AnyCodingKey : CodingKey {

  var stringValue: String
  var intValue: Int?

  init(_ base: CodingKey) {
    self.init(stringValue: base.stringValue, intValue: base.intValue)
  }

  init(stringValue: String) {
    self.stringValue = stringValue
  }

  init(intValue: Int) {
    self.stringValue = "\(intValue)"
    self.intValue = intValue
  }

  init(stringValue: String, intValue: Int?) {
    self.stringValue = stringValue
    self.intValue = intValue
  }
}

extension JSONEncoder.KeyEncodingStrategy {

  static var convertToUpperCamelCase: JSONEncoder.KeyEncodingStrategy {
    return .custom { codingKeys in

      var key = AnyCodingKey(codingKeys.last!)

      // uppercase first letter
      if let firstChar = key.stringValue.first {
        let i = key.stringValue.startIndex
        key.stringValue.replaceSubrange(
          i ... i, with: String(firstChar).uppercased()
        )
      }
      return key
    }
  }
}

extension JSONDecoder.KeyDecodingStrategy {

  static var convertFromUpperCamelCase: JSONDecoder.KeyDecodingStrategy {
    return .custom { codingKeys in

      var key = AnyCodingKey(codingKeys.last!)

      // lowercase first letter
      if let firstChar = key.stringValue.first {
        let i = key.stringValue.startIndex
        key.stringValue.replaceSubrange(
          i ... i, with: String(firstChar).lowercased()
        )
      }
      return key
    }
  }
}

You can now encode with the .convertToUpperCamelCase key strategy:

let address = Address(street: "Apple Bay Street", zipCode: "94608",
                      city: "Emeryville", state: "California")

do {
  let encoder = JSONEncoder()
  encoder.keyEncodingStrategy = .convertToUpperCamelCase
  let encoded = try encoder.encode(address)
  print(String(decoding: encoded, as: UTF8.self))
} catch {
  print(error)
}
//{"Street":"Apple Bay Street","City":"Emeryville","State":"California","ZipCode":"94608"}

and decode with the .convertFromUpperCamelCase key strategy:

let jsonString = """
{"Street":"Apple Bay Street","City":"Emeryville","State":"California","ZipCode":"94608"}
"""

do {
  let decoder = JSONDecoder()
  decoder.keyDecodingStrategy = .convertFromUpperCamelCase
  let decoded = try decoder.decode(Address.self, from: Data(jsonString.utf8))
  print(decoded)
} catch {
  print(error)
}

// Address(street: "Apple Bay Street", zipCode: "94608",
// city: "Emeryville", state: "California")


问:
How can I call distinct on entities in ASP.NET MVC 4
I have two tables where users save data for cities. I want to count the total number of cities in both tables using a Distinct on the join query.

```<code>Table 1       Table 2

ID City       ID City
--------      ----------
1  CHD        1  PUT
2  PUT        2  CHD
3  LUD        3  MALK
4  CHD        4  PUT
5  PUT        5  APC
</code>```

I want to join both tables and get the total count of Cities, but I want to make sure that cites will not be repeated in the count. That is, if CHD exists in table 1 and Table 2 then only count it once.

I don't want to count cities repeatedly. I want to be able to filter my results and get the total count.

I have written this code for Table 1 but I want the same result with a joined query.

```<code>public int Locations()
{
    int Locations = 0;

    using (var db = new Entities())
        Locations = db.Table1.Select(o => o.City).Distinct().Count();

    int Locations = 0;

    using (var db = new Entities())
        Locations = db.Table2.Select(o => o.City).Distinct().Count();

    return Locations;
}
</code>```

How can I do this with 2 tables?

答:
Do a LINQ Union, which will automatically only take uniques from each component list:

```<code>var locations = table1Locations.Union(table2Locations);
</code>```

Bear in mind that this will only work because you're selecting just the City from each table. That means you're effectively combining two IEnumerable<string>s. If you were to try to combine the objects directly it would fail, because you'd essentially have an IEnumerable<Table1Entity> and IEnumerable<Table2Entity>, which cannot be unioned.

Body:
I have two tables where users save data for cities. I want to count the total number of cities in both tables using a Distinct on the join query.

Table 1       Table 2

ID City       ID City
--------      ----------
1  CHD        1  PUT
2  PUT        2  CHD
3  LUD        3  MALK
4  CHD        4  PUT
5  PUT        5  APC

I want to join both tables and get the total count of Cities, but I want to make sure that cites will not be repeated in the count. That is, if CHD exists in table 1 and Table 2 then only count it once.

I don't want to count cities repeatedly. I want to be able to filter my results and get the total count.

I have written this code for Table 1 but I want the same result with a joined query.

public int Locations()
{
    int Locations = 0;

    using (var db = new Entities())
        Locations = db.Table1.Select(o => o.City).Distinct().Count();

    int Locations = 0;

    using (var db = new Entities())
        Locations = db.Table2.Select(o => o.City).Distinct().Count();

    return Locations;
}

How can I do this with 2 tables?

Body:
Do a LINQ Union, which will automatically only take uniques from each component list:

var locations = table1Locations.Union(table2Locations);

Bear in mind that this will only work because you're selecting just the City from each table. That means you're effectively combining two IEnumerable<string>s. If you were to try to combine the objects directly it would fail, because you'd essentially have an IEnumerable<Table1Entity> and IEnumerable<Table2Entity>, which cannot be unioned.


问:
JCo Server - JCoServerFunctionHandler - handleRequest - endless call and TID
Implemented JCo Server at Java, according to sample codes (StepByStepServer).

Created a function inside repository of the JCo Server.

JCo Server is starting normally.

And I can catch requests inside following function handler.

Question 1) Is it normal that handleRequest method in StfcConnectionHandler (implementation of JCoServerFunctionHandler) is called continuously like inside an infinite loop?

Question 2) Inside handleRequest TID of request ( serverCtx.getTID() ) is always Null.

Is TID sent from SAP side?

```<code>public class StfcConnectionHandler implements JCoServerFunctionHandler {

//Properties

@Override
public void handleRequest(JCoServerContext serverCtx, JCoFunction function) throws AbapException
{
        …// Endless call to this method
}

}
</code>```

答:
Your question does not contain enough information for giving a more sophisticated answer.

Question 1:
No, this is not normal, of course. Every remote function call from ABAP side shall result in a single invocation of handleRequest(...). Only in case of tRFC, qRFC or bgRFC it may occur that the ABAP backend will retry a previously failed invocation.
Please check, if it is your own coding who is doing these repeated invocations, either from ABAP or in Java. Switching on JCo traces and looking into them might be helpful here.

Question 2:
A TID will only be set for tRFC and qRFC calls, but not for the default sRFC calls. For bgRFCs the so called UnitIdentifier will be set instead of a TID.

I hope this helps nevertheless.

```<code>*) Legend:
   sRFC  = synchronous RFC
   tRFC  = transactional RFC
   qRFC  = queued RFC
   bgRFC = background RFC
</code>```

Body:
Implemented JCo Server at Java, according to sample codes (StepByStepServer).

Created a function inside repository of the JCo Server.

JCo Server is starting normally.

And I can catch requests inside following function handler.

Question 1) Is it normal that handleRequest method in StfcConnectionHandler (implementation of JCoServerFunctionHandler) is called continuously like inside an infinite loop?

Question 2) Inside handleRequest TID of request ( serverCtx.getTID() ) is always Null.

Is TID sent from SAP side?

public class StfcConnectionHandler implements JCoServerFunctionHandler {

//Properties

@Override
public void handleRequest(JCoServerContext serverCtx, JCoFunction function) throws AbapException
{
        …// Endless call to this method
}

}

Body:
Your question does not contain enough information for giving a more sophisticated answer.

Question 1:
No, this is not normal, of course. Every remote function call from ABAP side shall result in a single invocation of handleRequest(...). Only in case of tRFC, qRFC or bgRFC it may occur that the ABAP backend will retry a previously failed invocation.
Please check, if it is your own coding who is doing these repeated invocations, either from ABAP or in Java. Switching on JCo traces and looking into them might be helpful here.

Question 2:
A TID will only be set for tRFC and qRFC calls, but not for the default sRFC calls. For bgRFCs the so called UnitIdentifier will be set instead of a TID.

I hope this helps nevertheless.

*) Legend:
   sRFC  = synchronous RFC
   tRFC  = transactional RFC
   qRFC  = queued RFC
   bgRFC = background RFC


问:
How can I update a variable using Observable without render DOM in Angular 2, like a real-time page
I am new to Angular2 + and need to create a page in real time. When I load my component, I call a service using Observable and I save the result in a variable that I use in a ngFor in my model. After loading it, I need to refresh the data every minute and need to refine the changed data.

Does anyone know how to do this?

答:
I think you need to combine socket.io with RxJs Observables to achieve this task </p>

<p>check this </p>

Body:
I think you need to combine socket.io with RxJs Observables to achieve this task

check this


问:
How to show a progress bar when a user attempts to download a file
I have a site that downloads a pdf when the user clicks a button. Only thing is that it takes about 15 seconds to produce that pdf server side, so in the mean time the user is wondering why it is so slow. How can I display a progress bar that will show while the server is spool the pdf and then go away when the download has started (or stopped, whatever).

** edited **

I'm using jquery and so far what I did is on click i added a class and applied a background image. The background image is an animated gif and shows up. I was hoping that after you click to download the pdf it would redirect the browser to the pdf and then back to the page after it starts downloading, there by refreshing the page and removing the background image. No dice on this one :(

I will try the uniqid approach as described below.

Ideas??

答: Your server-side code should give each PDF a unique ID. When the user clicks to download a PDF, the unique ID is retrieved by AJAX. The AJAX can then access a server-side page (progress.php?pdf-id=4) which will return the progress. jQuery UI has a progress bar which is already set up, so you don't need to create it yourself.</p>


问:
Transparent Background Image with a Gradient
Today I was designing a transparent PNG background that would only sit in the top left of a div, and the rest of the div would maintain a gradient background for all transparent areas of the PNG, and the rest of the div itself.

It might be better to explain through the code I thought might work:

```<code>#mydiv .isawesome {
    /* Basic color for old browsers, and a small image that sits in the top left corner of the div */
    background: #B1B8BD url('../images/sidebar_angle.png') 0 0 no-repeat;

    /* The gradient I would like to have applied to the whole div, behind the PNG mentioned above */
    background: -moz-linear-gradient(top, #ADB2B6 0%, #ABAEB3 100%);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ADB2B6), color-stop(100%,#ABAEB3));
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ADB2B6', endColorstr='#ABAEB3',GradientType=0 );
}
</code>```

What I've been finding is that most browsers pick one or the other - most choosing the gradient since its further down the CSS file.

I know some of the guys around here will say "just apply the gradient to the PNG you're making" - but thats not ideal because the div will maintain a dynamic height - sometimes being very short, sometimes being very tall. I know this gradient isn't essential but I thought it might be worth asking y'all what you thought.

Is it possible to have a background image, while keeping the rest of the background as a gradient?

答:
You can use Transparency and gradients. Gradients support transparency. You can use this, for example, when stacking multiple backgrounds, to create fading effects on background images.

```<code>background: linear-gradient(to right, rgba(255,255,255,0) 20%,
              rgba(255,255,255,1)), url(http://foo.com/image.jpg);
</code>```

Body:
Today I was designing a transparent PNG background that would only sit in the top left of a div, and the rest of the div would maintain a gradient background for all transparent areas of the PNG, and the rest of the div itself.

It might be better to explain through the code I thought might work:

#mydiv .isawesome {
    /* Basic color for old browsers, and a small image that sits in the top left corner of the div */
    background: #B1B8BD url('../images/sidebar_angle.png') 0 0 no-repeat;

    /* The gradient I would like to have applied to the whole div, behind the PNG mentioned above */
    background: -moz-linear-gradient(top, #ADB2B6 0%, #ABAEB3 100%);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ADB2B6), color-stop(100%,#ABAEB3));
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ADB2B6', endColorstr='#ABAEB3',GradientType=0 );
}

What I've been finding is that most browsers pick one or the other - most choosing the gradient since its further down the CSS file.

I know some of the guys around here will say "just apply the gradient to the PNG you're making" - but thats not ideal because the div will maintain a dynamic height - sometimes being very short, sometimes being very tall. I know this gradient isn't essential but I thought it might be worth asking y'all what you thought.

Is it possible to have a background image, while keeping the rest of the background as a gradient?

Body:
You can use Transparency and gradients. Gradients support transparency. You can use this, for example, when stacking multiple backgrounds, to create fading effects on background images.

background: linear-gradient(to right, rgba(255,255,255,0) 20%,
              rgba(255,255,255,1)), url(http://foo.com/image.jpg);


问:
Libreoffice soffice always trigger document recovery dialog box though no file to be recovered
I am using Libreoffice 5.2.7.2 on Ubuntu 14.04.

When I do soffice --show filename.odp it always trigger document recovery dialog box even though there is no file to be recovered.

After hitting ok, it will prompt me to select filename.odp to load which defeat the purpose of using soffice --show.

I had edited registrymodifications.xcu on recovery entries.  Removed /usr/bin/soffice and reinstall libreoffice.

Still the document recovery dialog box persist with soffice.  Any advice is appreciated.

Thank you.

答:
Have you tried resetting the LibreOffice User Profile?

To test --show, create filename.odp as a new presentation and see if the problem still occurs.


问:
text input field alignment
I'm having a problem trying to align text inputs. Here's what my page looks like initially:

After adding the following css code:

```<code>#items{
    float: right;
    position: relative;
    right: 500px;
    clear: both;
}
</code>```

I now get this:

Notice that the inputs under "Poids Total(kg)" disappear.

Any ideas as to what might be causing this?

Thanks in advance :)

答:
you css is moving that away with 500px. change it to 5px and see or adjust accordingly</p>

```<code>#items{
    float: right;
    position: relative;
    right: 5px;
    clear: both;
}
</code>```

Title: text input field alignment

Body:
I'm having a problem trying to align text inputs. Here's what my page looks like initially:

After adding the following css code:

#items{
    float: right;
    position: relative;
    right: 500px;
    clear: both;
}

I now get this:

Notice that the inputs under "Poids Total(kg)" disappear.

Any ideas as to what might be causing this?

Thanks in advance :)

Body:
you css is moving that away with 500px. change it to 5px and see or adjust accordingly

#items{
    float: right;
    position: relative;
    right: 5px;
    clear: both;
}


问:
Fill DataFrame, missing data

Description

I read a table with three columns: ID, time and location to create a dataframe. ID is the first index and time is the second index. I want the time frequency is five minute and if there is no data on the corresponding time, set the location to the last location(See the table below).

The dataframe for now

```<code>ID   time          place
001  00:00:00      1
     00:15:00      3
002  00:05:00      2
</code>```

The dataframe I hope to get

```<code>ID   time          place
001  00:00:00      1
     00:05:00      1
     00:10:00      1
     00:15:00      3
#continue to fill the table until 23:55:00

002  00:00:00      2
     00:05:00      2
#continue to fill the table until 23:55:00
</code>```

Code

```<code>def create_table(n):
  table = pd.read_table(n,sep='\x01', header=None, names=['ID','time','place'])
  table['time'] = pd.to_datetime(table['time'], format='%H:%M:%S')
  table = table.set_index('ID','time')
  return table
</code>```

I have no idea how to move on making the ideal dataframe. Can anyone give me some hints? Thanks a lot!!

Title: Fill DataFrame, missing data

Body:
Description

I read a table with three columns: ID, time and location to create a dataframe. ID is the first index and time is the second index. I want the time frequency is five minute and if there is no data on the corresponding time, set the location to the last location(See the table below).

The dataframe for now

ID   time          place
001  00:00:00      1
     00:15:00      3
002  00:05:00      2

The dataframe I hope to get

ID   time          place
001  00:00:00      1
     00:05:00      1
     00:10:00      1
     00:15:00      3
#continue to fill the table until 23:55:00

002  00:00:00      2
     00:05:00      2
#continue to fill the table until 23:55:00

Code

def create_table(n):
  table = pd.read_table(n,sep='\x01', header=None, names=['ID','time','place'])
  table['time'] = pd.to_datetime(table['time'], format='%H:%M:%S')
  table = table.set_index('ID','time')
  return table

I have no idea how to move on making the ideal dataframe. Can anyone give me some hints? Thanks a lot!!

Body:
To get the DataFrame you defined above, we can do:

df = pd.DataFrame({'ID': ['001', '001', '002'], 'time': ['00:00:00', '00:15:00', '00:05:00'], 'place': [1, 3, 2]}).set_index(['ID', 'time'])

In order to be able to work with just time and to apply the same operations to each of the ID values, let's unstack 'ID' so that we have a multi index of columns with our ID at the top level:

In [91]: df = df.unstack(0)

In [92]: df
Out[92]:
         place
ID         001  002
time
00:00:00   1.0  NaN
00:05:00   NaN  2.0
00:15:00   3.0  NaN

Now, let's cast our index (just 'time', now) to a DatetimeIndex:

In [93]: df.index = pd.to_datetime(df.index)

In [94]: df
Out[94]:
                    place
ID                    001  002
time
2017-06-06 00:00:00   1.0  NaN
2017-06-06 00:05:00   NaN  2.0
2017-06-06 00:15:00   3.0  NaN

This adds today's date, but we can remove that later.

Next, let's create another DatetimeIndex consisting of 5-minute increments for today's date:

In [95]: times = pd.date_range("00:00:00", "23:55:00", freq="5min")

In [96]: times
Out[96]:
DatetimeIndex(['2017-06-06 00:00:00', '2017-06-06 00:05:00',
               '2017-06-06 00:10:00', '2017-06-06 00:15:00',
               '2017-06-06 00:20:00', '2017-06-06 00:25:00',
               '2017-06-06 00:30:00', '2017-06-06 00:35:00',
               '2017-06-06 00:40:00', '2017-06-06 00:45:00',
               ...
               '2017-06-06 23:10:00', '2017-06-06 23:15:00',
               '2017-06-06 23:20:00', '2017-06-06 23:25:00',
               '2017-06-06 23:30:00', '2017-06-06 23:35:00',
               '2017-06-06 23:40:00', '2017-06-06 23:45:00',
               '2017-06-06 23:50:00', '2017-06-06 23:55:00'],
              dtype='datetime64[ns]', length=288, freq='5T')

Let's reindex our df's index against this new DatetimeIndex:

In [97]: df = df.reindex(times)

In [98]: df
Out[98]:
                    place
ID                    001  002
2017-06-06 00:00:00   1.0  NaN
2017-06-06 00:05:00   NaN  2.0
2017-06-06 00:10:00   NaN  NaN
2017-06-06 00:15:00   3.0  NaN
2017-06-06 00:20:00   NaN  NaN
...

Now we just need to forward fill so that at each time, the location is the last non-NaN location:

In [99]: df = df.ffill()

In [100]: df
Out[100]:
                    place
ID                    001  002
2017-06-06 00:00:00   1.0  NaN
2017-06-06 00:05:00   1.0  2.0
2017-06-06 00:10:00   1.0  2.0
2017-06-06 00:15:00   3.0  2.0
2017-06-06 00:20:00   3.0  2.0
2017-06-06 00:25:00   3.0  2.0
2017-06-06 00:30:00   3.0  2.0
...

From here, we need to get rid of the dates:

In [101]: df.index = df.index.strftime('%H:%M:%S')

In [102]: df
Out[102]:
         place
ID         001  002
00:00:00   1.0  NaN
00:05:00   1.0  2.0
00:10:00   1.0  2.0
00:15:00   3.0  2.0
00:20:00   3.0  2.0
00:25:00   3.0  2.0
...

We've lost the name on our 'time' index, so let's put it back:

df.index = df.index.set_names('time')

And, finally, put 'ID' back into the index:

In [103]: df.stack(1).swaplevel(0, 1)
Out[103]:
              place
ID  time
001 00:00:00    1.0
    00:05:00    1.0
002 00:05:00    2.0
001 00:10:00    1.0
002 00:10:00    2.0
001 00:15:00    3.0
...


问:
Why does my code raise an error?
I am doing a coding exercise: Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.

So I wrote this code:

```<code>def almostIncreasingSequence(sequence):
    first_list, second_list = sequence, sequence
    for i in range(len(sequence)-1):
        if sequence[i] >= sequence[i+1]:
            first_list.remove(sequence[i])
            second_list.remove(sequence[i+1])
            break

    if first_list == sorted(set(first_list)) or second_list == sorted(set(second_list)):
        return True
    else:
        return False
</code>```

Now this code seems to work on most sequences but this one in particular raises an error:

```<code>print almostIncreasingSequence([1,3,2])
</code>```

The error is as following:

Traceback (most recent call last):
  file.py3 on line ?, in getUserOutputs
    userOutput = _runsppge(testInputs[i])
  file.py3 on line ?, in _runsppge
    return almostIncreasingSequence(*_fArgs_lujxeukjlbwc)
  file.py3 on line 7, in almostIncreasingSequence
    second_list.remove(sequence[i+1])
IndexError: list index out of range
```

I just dont understand how the list index could possibly be out of range.. Anyone got a clue?

答:
Since you are removing items from the same list which you are iterating on

```<code>for i in range(len(sequence)-1):
    if sequence[i] >= sequence[i+1]:
        first_list.remove(sequence[i])     #  <-- removing item
        second_list.remove(sequence[i+1])  #  <-- removing item
        break
</code>```

And, as mentioned in the comments, first_list, second_list = sequence, sequence doesn't create any new lists. first_list, second_list, and sequence all refer to the exact same list object after that line.

EDITED

The list after the first removal (first_list.remove(sequence[i])), has one less element, hence if the i+1 in on the edge at that moment, it would get out of bound.

Think of a list like [1, 2, 3, 5, 4]. The if statement is triggered when i is at the element 5 (i is 3), then the first removal (first_list.remove(sequence[i])) takes place, after that statement, list has 4 elements [1, 2, 3, 4], and the next line tries to access the element (element 4) at i+1 (second_list.remove(sequence[i+1])), hence it gets (i is 4) out of bound.

Title: Why does my code raise an error?

Body:
I am doing a coding exercise: Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.

So I wrote this code:

def almostIncreasingSequence(sequence):
    first_list, second_list = sequence, sequence
    for i in range(len(sequence)-1):
        if sequence[i] >= sequence[i+1]:
            first_list.remove(sequence[i])
            second_list.remove(sequence[i+1])
            break

    if first_list == sorted(set(first_list)) or second_list == sorted(set(second_list)):
        return True
    else:
        return False

Now this code seems to work on most sequences but this one in particular raises an error:

print almostIncreasingSequence([1,3,2])

The error is as following:

Traceback (most recent call last):
  file.py3 on line ?, in getUserOutputs
    userOutput = _runsppge(testInputs[i])
  file.py3 on line ?, in _runsppge
    return almostIncreasingSequence(*_fArgs_lujxeukjlbwc)
  file.py3 on line 7, in almostIncreasingSequence
    second_list.remove(sequence[i+1])
IndexError: list index out of range

I just dont understand how the list index could possibly be out of range.. Anyone got a clue?

Body:
Since you are removing items from the same list which you are iterating on

for i in range(len(sequence)-1):
    if sequence[i] >= sequence[i+1]:
        first_list.remove(sequence[i])     #  <-- removing item
        second_list.remove(sequence[i+1])  #  <-- removing item
        break

And, as mentioned in the comments, first_list, second_list = sequence, sequence doesn't create any new lists. first_list, second_list, and sequence all refer to the exact same list object after that line.

EDITED

The list after the first removal (first_list.remove(sequence[i])), has one less element, hence if the i+1 in on the edge at that moment, it would get out of bound.

Think of a list like [1, 2, 3, 5, 4]. The if statement is triggered when i is at the element 5 (i is 3), then the first removal (first_list.remove(sequence[i])) takes place, after that statement, list has 4 elements [1, 2, 3, 4], and the next line tries to access the element (element 4) at i+1 (second_list.remove(sequence[i+1])), hence it gets (i is 4) out of bound.


问:
Saving data in MongoDB in wrong order
Nodejs app with Express and MongoDB. I have form to insert title, author and body. After submitting data I noticed that instead of title, author and body it looks like body, author and title. So, I wonder is this order important in MongoDB? And why it switch positions. Image shows how it should be and what i got.

Code fragments (mongoose schema, pug view, main):

```<code>// article schema
let articleSchema = new Schema({
    title: String,
    author: String,
    body: String
})

  label Title:
  input.form-control(name='title', type='text')
#form-group
  label Author:
  input.form-control(name='author', type='text')
#form-group
  label Body:
  textarea.form-control(name='body')

article.title = req.body.title
article.author = req.body.author
article.body = req.body.body
</code>```

P.S. App working only confusing order in DB.

P.P.S. My question is similar to that, but not a duplicated, because, they talked about updating existing data in DB, while i'm talking about adding new data to DB. So it's obvious that after updating it will appear in the end. But when I want add new data, I thought it should look like I wrote in mongoose scheme. So, for now, I only know it's not so important, but I would like to know solution to fix this wrong order if one exists.

答:
So, I wonder is this order important in MongoDB?

In most situations, no, the ordering of fields in a document are not important. MongoDB stores data records as BSON documents. BSON is a binary representation of JSON documents (source). Javascript does not guarentee object property order.

However, there are situations in MongoDB where field order is important. When querying embedded documents, the embedded document must exactly match the document specified in the query. More information can be found here.

Title: Saving data in MongoDB in wrong order

Body:
Nodejs app with Express and MongoDB. I have form to insert title, author and body. After submitting data I noticed that instead of title, author and body it looks like body, author and title. So, I wonder is this order important in MongoDB? And why it switch positions. Image shows how it should be and what i got.

Code fragments (mongoose schema, pug view, main):

// article schema
let articleSchema = new Schema({
    title: String,
    author: String,
    body: String
})

  label Title:
  input.form-control(name='title', type='text')
#form-group
  label Author:
  input.form-control(name='author', type='text')
#form-group
  label Body:
  textarea.form-control(name='body')

article.title = req.body.title
article.author = req.body.author
article.body = req.body.body

P.S. App working only confusing order in DB.

P.P.S. My question is similar to that, but not a duplicated, because, they talked about updating existing data in DB, while i'm talking about adding new data to DB. So it's obvious that after updating it will appear in the end. But when I want add new data, I thought it should look like I wrote in mongoose scheme. So, for now, I only know it's not so important, but I would like to know solution to fix this wrong order if one exists.


问:
How to get bottom of user stack under multi threads on Linux
I would like to get user stack information on 64bit Linux.
I know mm->start_stack that indicates a location of an initial stack pointer of user stack.

However, under multi thread applications like a pthread, mm->start_stack is the same values all threads because of using same struct task_struct.

And, I know the way of memory layout by using mm->mmap->vm_start and mm->mmap->vm_end but, I do not know that whether these mmap area are stack or not.

I confirmed memory layout under these with pmap process id and strace.

Could you tell me how to get user stack location all threads like a mm->start_stack?.

```<code>sudo pmap 24074
24074:   ./a.out
0000000000400000      4K r-x-- a.out
0000000000600000      4K r---- a.out
0000000000601000      4K rw--- a.out
0000000000602000    132K rw---   [ anon ]
00007ffff5fee000      4K -----   [ anon ]
00007ffff5fef000   8192K rw---   [ anon ]   <==== Thread Stack
00007ffff67ef000      4K -----   [ anon ]
00007ffff67f0000   8192K rw---   [ anon ]   <==== Thread Stack
00007ffff6ff0000      4K -----   [ anon ]
00007ffff6ff1000   8192K rw---   [ anon ]   <==== Thread Stack
00007ffff77f1000   1792K r-x-- libc-2.23.so
00007ffff79b1000   2044K ----- libc-2.23.so
00007ffff7bb0000     16K r---- libc-2.23.so
00007ffff7bb4000      8K rw--- libc-2.23.so
00007ffff7bb6000     16K rw---   [ anon ]
00007ffff7bba000     96K r-x-- libpthread-2.23.so
00007ffff7bd2000   2044K ----- libpthread-2.23.so
00007ffff7dd1000      4K r---- libpthread-2.23.so
00007ffff7dd2000      4K rw--- libpthread-2.23.so
00007ffff7dd3000     16K rw---   [ anon ]
00007ffff7dd7000    152K r-x-- ld-2.23.so
00007ffff7fda000     12K rw---   [ anon ]
00007ffff7ff6000      8K rw---   [ anon ]
00007ffff7ff8000      8K r----   [ anon ]
00007ffff7ffa000      8K r-x--   [ anon ]
00007ffff7ffc000      4K r---- ld-2.23.so
00007ffff7ffd000      4K rw--- ld-2.23.so
00007ffff7ffe000      4K rw---   [ anon ]
00007ffffffde000    132K rw---   [ stack ]
ffffffffff600000      4K r-x--   [ anon ]
 total            31108K
</code>```

strace results

```<code>clone(child_stack=0x7ffff77efff0,flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7ffff77f09d0, tls=0x7ffff77f0700, child_tidptr=0x7ffff77f09d0) = 24075

clone(pid: 24074 child_stack=0x7ffff6feeff0, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7ffff6fef9d0, tls=0x7ffff6fef700, child_tidptr=0x7ffff6fef9d0) = 24076

clone(child_stack=0x7ffff67edff0, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7ffff67ee9d0, tls=0x7ffff67ee700, child_tidptr=0x7ffff67ee9d0) = 24077
</code>```

答:
Your question isn't completely well-defined. Technically, a user may create a thread using pthread and then switch the new threads sp to another one. So the stack created by pthread_create isn't always the stack used by the process. Hell, the process may even munmap it...

You can, however, access the user's stack at a specific moment (e.g. syscall), in the following manner:

```<code>task_pt_regs(task)->sp
</code>```

However, be sure to validate it, as it may not always be in userspace. The user has complete control over it.

Body:
I would like to get user stack information on 64bit Linux.
I know mm->start_stack that indicates a location of an initial stack pointer of user stack.

However, under multi thread applications like a pthread, mm->start_stack is the same values all threads because of using same struct task_struct.

And, I know the way of memory layout by using mm->mmap->vm_start and mm->mmap->vm_end but, I do not know that whether these mmap area are stack or not.

I confirmed memory layout under these with pmap process id and strace.

Could you tell me how to get user stack location all threads like a mm->start_stack?.

sudo pmap 24074
24074:   ./a.out
0000000000400000      4K r-x-- a.out
0000000000600000      4K r---- a.out
0000000000601000      4K rw--- a.out
0000000000602000    132K rw---   [ anon ]
00007ffff5fee000      4K -----   [ anon ]
00007ffff5fef000   8192K rw---   [ anon ]   <==== Thread Stack
00007ffff67ef000      4K -----   [ anon ]
00007ffff67f0000   8192K rw---   [ anon ]   <==== Thread Stack
00007ffff6ff0000      4K -----   [ anon ]
00007ffff6ff1000   8192K rw---   [ anon ]   <==== Thread Stack
00007ffff77f1000   1792K r-x-- libc-2.23.so
00007ffff79b1000   2044K ----- libc-2.23.so
00007ffff7bb0000     16K r---- libc-2.23.so
00007ffff7bb4000      8K rw--- libc-2.23.so
00007ffff7bb6000     16K rw---   [ anon ]
00007ffff7bba000     96K r-x-- libpthread-2.23.so
00007ffff7bd2000   2044K ----- libpthread-2.23.so
00007ffff7dd1000      4K r---- libpthread-2.23.so
00007ffff7dd2000      4K rw--- libpthread-2.23.so
00007ffff7dd3000     16K rw---   [ anon ]
00007ffff7dd7000    152K r-x-- ld-2.23.so
00007ffff7fda000     12K rw---   [ anon ]
00007ffff7ff6000      8K rw---   [ anon ]
00007ffff7ff8000      8K r----   [ anon ]
00007ffff7ffa000      8K r-x--   [ anon ]
00007ffff7ffc000      4K r---- ld-2.23.so
00007ffff7ffd000      4K rw--- ld-2.23.so
00007ffff7ffe000      4K rw---   [ anon ]
00007ffffffde000    132K rw---   [ stack ]
ffffffffff600000      4K r-x--   [ anon ]
 total            31108K

strace results

clone(child_stack=0x7ffff77efff0,flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7ffff77f09d0, tls=0x7ffff77f0700, child_tidptr=0x7ffff77f09d0) = 24075

clone(pid: 24074 child_stack=0x7ffff6feeff0, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7ffff6fef9d0, tls=0x7ffff6fef700, child_tidptr=0x7ffff6fef9d0) = 24076

clone(child_stack=0x7ffff67edff0, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_SIGHAND|CLONE_THREAD|CLONE_SYSVSEM|CLONE_SETTLS|CLONE_PARENT_SETTID|CLONE_CHILD_CLEARTID, parent_tidptr=0x7ffff67ee9d0, tls=0x7ffff67ee700, child_tidptr=0x7ffff67ee9d0) = 24077

Body:
Your question isn't completely well-defined. Technically, a user may create a thread using pthread and then switch the new threads sp to another one. So the stack created by pthread_create isn't always the stack used by the process. Hell, the process may even munmap it...

You can, however, access the user's stack at a specific moment (e.g. syscall), in the following manner:

task_pt_regs(task)->sp

However, be sure to validate it, as it may not always be in userspace. The user has complete control over it.


问:
how to make sure dots in the slideshow forms are after the forms instead of sitting on the labels and textbox?
I am working on making a slideshow of forms. Here is my working codepen link. As you can see I have two dots on the right side which if I click then it opens another form. Only thing is those dots are just sitting on the right side labels and texbox and that I don't want it.

For example as shown in this image. I am trying to replicate exactly like this image and as you can see those dots are on the form instead but at the very right side of it close to the right border but not lying on the labels and texbox. LAST NAME, PHONE NUMBER , PROVINCE and CITY label and its textbox are just before those dots. I want to do something similar. How can I make sure those forms are just above those dots not lying on them. I tried playing with form width but it is moving those dots as well along with it. Also I want to make dots color to orange if it is on that form (just like in the image I have). As of now it shows black.

Below is my HTML code:

```<code><!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>SlidesJS Standard Code Example</title>
  <meta name="description" content="SlidesJS is a simple slideshow plugin for jQuery. Packed with a useful set of features to help novice and advanced developers alike create elegant and user-friendly slideshows.">
  <meta name="author" content="Nathan Searles">

  <!-- SlidesJS Required (if responsive): Sets the page width to the device width. -->
  <meta name="viewport" content="width=device-width">
  <!-- End SlidesJS Required -->

  <!-- CSS for slidesjs.com example -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <!-- End CSS for slidesjs.com example -->

  <!-- SlidesJS Optional: If you'd like to use this design -->
  <style>
    body {
      -webkit-font-smoothing: antialiased;
      font: normal 15px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;
      color: #232525;
    }

    #slides,
    #slides2,
    #slides3 {
      display: none;
      margin-bottom:50px;
    }

    .slidesjs-navigation {
      margin-top:3px;
    }

    .slidesjs-previous {
      margin-right: 5px;
      float: left;
    }

    .slidesjs-next {
      margin-right: 5px;
      float: left;
    }

    .slidesjs-pagination {
      margin: 6px 0 0;
      float: right;
      list-style: none;
    }

    .slidesjs-pagination li {
      float: left;
      margin: 0 1px;
    }

    .slidesjs-pagination li a {
      display: block;
      width: 13px;
      height: 0;
      padding-top: 13px;
      background-image: url("https://s16.postimg.org/pt4k43i9x/pagination.png");
      background-position: 0 0;
      float: left;
      overflow: hidden;
    }

    .slidesjs-pagination li a.active,
    .slidesjs-pagination li a:hover.active {
      background-position: 0 -13px
    }

    .slidesjs-pagination li a:hover {
      background-position: 0 -26px
    }
    .navbar {
      overflow: hidden
    }
  </style>
  <!-- End SlidesJS Optional-->

  <!-- SlidesJS Required: These styles are required if you'd like a responsive slideshow -->
  <style>
    #slides {
      display: none
    }

    .container {
      margin: 0 auto
    }

    /* For tablets & smart phones */
    @media (max-width: 767px) {
      body {
        padding-left: 20px;
        padding-right: 20px;
      }
      .container {
        width: auto
      }
    }

    /* For smartphones */
    @media (max-width: 480px) {
      .container {
        width: auto
      }
    }

    /* For smaller displays like laptops */
    @media (min-width: 768px) and (max-width: 979px) {
      .container {
        width: 724px
      }
    }

    /* For larger displays */
    @media (min-width: 1200px) {
      .container {
        width: 1170px
      }
    }
  </style>
  <!-- SlidesJS Required: -->
</head>
<body>
<div class="topnav">
   <img src="https://s4.postimg.org/ojd13poal/northman_wordmark_CMYK.png">
   <nav>
      <ul>
         <li class="dropdown">
            <a href="#"><b>INSURANCE</b> <i class="fa fa-angle-down"></i></a>
            <ul class="dropdown-content">
               <li><a href="#"><i>INDIVIDUAL</i></a>
               </li>
               <li><a href="#"><i>CORPORATE</i></a>
               </li>
            </ul>
         </li>
         <li class="our-story">OUR STORY</li>
         <li class="login-signup">Log In | Sign up</li>
         <li class="get-covered">GET <strong style="font-style:italic">COVERED</strong>
         </li>
      </ul>
   </nav>
</div>
  <!-- SlidesJS Required: Start Slides -->
  <!-- The container is used to define the width of the slideshow -->
  <div class="container">
   <h3>INSURANCE FORM</h3>
   <h4><i>BASIC DETAILS</i></h4>
   <br>
    <div id="slides" class="container-fluid" >
  <form action="/action_page.php" class="form-horizontal">
      <div class="form-group">
         <div class="col-sm-6">
            <label>FIRST NAME</label>
            <input type="text" class="form-control" name="fname" value="Mickey 1">
         </div>
         <div class="col-sm-6">
            <label>LAST NAME</label>
            <input type="text" class="form-control" name="lname" value="Mouse">
         </div>
      </div>
      <div class="form-group">
         <div class="col-sm-6">
            <label>EMAIL</label>
            <input type="text" class="form-control" name="email" value="abc@host.com">
         </div>
         <div class="col-sm-6">
            <label>PHONE NUMBER</label>
            <input type="text" class="form-control" name="number" value="123-456-789">
         </div>
      </div>
      <div class="form-group">
         <div class="col-sm-6">
            <label>COUNTRY</label>
            <select name="country" class="form-control">
               <option value="canada">Canada</option>
            </select>
         </div>
         <div class="col-sm-3">
            <label>PROVINCE</label>
            <select name="province" class="form-control">
               <option value="ontario">ONTARIO</option>
            </select>
         </div>
         <div class="col-sm-3">
            <label>CITY</label>
            <select name="city" class="form-control">
               <option value="ottawa">OTTAWA</option>
            </select>
         </div>
      </div>
   </form>
  <form action="/action_page.php" class="form-horizontal">
      <div class="form-group">
         <div class="col-sm-6">
            <label>FIRST NAME</label>
            <input type="text" class="form-control" name="fname" value="Mickey 2">
         </div>
         <div class="col-sm-6">
            <label>LAST NAME</label>
            <input type="text" class="form-control" name="lname" value="Mouse">
         </div>
      </div>
      <div class="form-group">
         <div class="col-sm-6">
            <label>EMAIL</label>
            <input type="text" class="form-control" name="email" value="abc@host.com">
         </div>
         <div class="col-sm-6">
            <label>PHONE NUMBER</label>
            <input type="text" class="form-control" name="number" value="123-456-789">
         </div>
      </div>
      <div class="form-group">
         <div class="col-sm-6">
            <label>COUNTRY</label>
            <select name="country" class="form-control">
               <option value="canada">Canada</option>
            </select>
         </div>
         <div class="col-sm-3">
            <label>PROVINCE</label>
            <select name="province" class="form-control">
               <option value="ontario">ONTARIO</option>
            </select>
         </div>
         <div class="col-sm-3">
            <label>CITY</label>
            <select name="city" class="form-control">
               <option value="ottawa">OTTAWA</option>
            </select>
         </div>
      </div>
   </form>
      <a href="#" class="slidesjs-previous slidesjs-navigation"><i class="icon-chevron-left"></i></a>
      <a href="#" class="slidesjs-next slidesjs-navigation"><i class="icon-chevron-right"></i></a>
    </div>
  </div>
  <!-- End SlidesJS Required: Start Slides -->

  <!-- SlidesJS Required: Link to jQuery -->
  <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
  <!-- End SlidesJS Required -->

  <!-- SlidesJS Required: Link to jquery.slides.js -->
  <script src="js/jquery.slides.min.js"></script>
  <!-- End SlidesJS Required -->

  <!-- SlidesJS Required: Initialize SlidesJS with a jQuery doc ready -->
  <script>
    $(function() {
      $('#slides').slidesjs({
        width: 800,
        height: 528,
        navigation: false
      });

      /*
        To have multiple slideshows on the same page
        they just need to have separate IDs
      */
      $('#slides2').slidesjs({
        width: 800,
        height: 528,
        navigation: false,
        start: 3,
        play: {
          auto: true
        }
      });

      $('#slides3').slidesjs({
        width: 800,
        height: 528,
        navigation: false
      });
    });
  </script>
  <!-- End SlidesJS Required -->
</body>
</html>
</code>```

答:
We can do following three things to fix this

First Solution.

Increase the padding of container from 10 to 20px. sothat dots will remain at right side and some will create between form and dots.

Second Solution

Make Dots fixed with respect to screen, I think dots will always show on screen, not movable and after reduce the width of form from 100% to some less around 95%;

Third Solution

Just reduce width of form to 95%.

Provide right padding more than 10px.

Body:
I am working on making a slideshow of forms. Here is my working codepen link. As you can see I have two dots on the right side which if I click then it opens another form. Only thing is those dots are just sitting on the right side labels and texbox and that I don't want it.

For example as shown in this image. I am trying to replicate exactly like this image and as you can see those dots are on the form instead but at the very right side of it close to the right border but not lying on the labels and texbox. LAST NAME, PHONE NUMBER , PROVINCE and CITY label and its textbox are just before those dots. I want to do something similar. How can I make sure those forms are just above those dots not lying on them. I tried playing with form width but it is moving those dots as well along with it. Also I want to make dots color to orange if it is on that form (just like in the image I have). As of now it shows black.

Below is my HTML code:

<!doctype html>

  <meta charset="utf-8">
  <title>SlidesJS Standard Code Example</title>
  <meta name="description" content="SlidesJS is a simple slideshow plugin for jQuery. Packed with a useful set of features to help novice and advanced developers alike create elegant and user-friendly slideshows.">
  <meta name="author" content="Nathan Searles">

  <meta name="viewport" content="width=device-width">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

            INSURANCE

INDIVIDUAL

CORPORATE

OUR STORY

Log In | Sign up

GET COVERED

INSURANCE FORM

BASIC DETAILS

  <form action="/action_page.php" class="form-horizontal">

            FIRST NAME
            <input type="text" class="form-control" name="fname" value="Mickey 1">

            LAST NAME
            <input type="text" class="form-control" name="lname" value="Mouse">

            EMAIL
            <input type="text" class="form-control" name="email" value="abc@host.com">

            PHONE NUMBER
            <input type="text" class="form-control" name="number" value="123-456-789">

            COUNTRY
            <select name="country" class="form-control">
               <option value="canada">Canada</option>
            </select>

            PROVINCE
            <select name="province" class="form-control">
               <option value="ontario">ONTARIO</option>
            </select>

            CITY
            <select name="city" class="form-control">
               <option value="ottawa">OTTAWA</option>
            </select>

   </form>
  <form action="/action_page.php" class="form-horizontal">

            FIRST NAME
            <input type="text" class="form-control" name="fname" value="Mickey 2">

            LAST NAME
            <input type="text" class="form-control" name="lname" value="Mouse">

            EMAIL
            <input type="text" class="form-control" name="email" value="abc@host.com">

            PHONE NUMBER
            <input type="text" class="form-control" name="number" value="123-456-789">

            COUNTRY
            <select name="country" class="form-control">
               <option value="canada">Canada</option>
            </select>

            PROVINCE
            <select name="province" class="form-control">
               <option value="ontario">ONTARIO</option>
            </select>

            CITY
            <select name="city" class="form-control">
               <option value="ottawa">OTTAWA</option>
            </select>

   </form>