问:
Converting string with time to minutes
I am working on an Android app that gets a time (duration) value as string.

For example, the app can get a value like: 6 hours 43 mins

or a value like: 15 mins

I am looking for a way to convert this strings to an integer value in minutes.

I have tried using this function, but I can´t extract the needed values:

```<code>str = str.replaceAll("[^\\d.]", "");
</code>```

Edit:

it could be possible a result like 6 hours, the only known condition is that minutes are always rounded to an integer, the minimum value is 1 min

答:
Either String split() or Pattern Matcher, as earlier answers suggest, will work. I'm not sure which will be more efficient though, but it's probably irrelevant in this case. My version:</p>

```<code>String timeStr = "2 hours 15 mins";
String[] parts = timeStr.split(" ");

int totalMins = 0;
for(int i=1; i< parts.length; i+=2) {
    // Add checking for "days", etc., if necessary.
    if(parts[i].equals("hours")) {
        int h = Integer.parseInt(parts[i-1]);
        totalMins += 60 * h;
    } else if(parts[i].equals("mins")) {
        int m = Integer.parseInt(parts[i-1]);
        totalMins += m;
    }
}

System.out.println("totalMins = " + totalMins);
>> totalMins = 135
</code>```

Title: Converting string with time to minutes

Body:
I am working on an Android app that gets a time (duration) value as string.

For example, the app can get a value like: 6 hours 43 mins

or a value like: 15 mins

I am looking for a way to convert this strings to an integer value in minutes.

I have tried using this function, but I can´t extract the needed values:

str = str.replaceAll("[^\\d.]", "");

Edit:

it could be possible a result like 6 hours, the only known condition is that minutes are always rounded to an integer, the minimum value is 1 min

Body:
Either String split() or Pattern Matcher, as earlier answers suggest, will work. I'm not sure which will be more efficient though, but it's probably irrelevant in this case. My version:

String timeStr = "2 hours 15 mins";
String[] parts = timeStr.split(" ");

int totalMins = 0;
for(int i=1; i< parts.length; i+=2) {
    // Add checking for "days", etc., if necessary.
    if(parts[i].equals("hours")) {
        int h = Integer.parseInt(parts[i-1]);
        totalMins += 60 * h;
    } else if(parts[i].equals("mins")) {
        int m = Integer.parseInt(parts[i-1]);
        totalMins += m;
    }
}

System.out.println("totalMins = " + totalMins);
>> totalMins = 135


来源: stackexchange

问:
leaflet how to setView according to multiple point
The setView() function accept a center coordinate and . I've fetch bunch of points from Google place API, and I want to set the view to include those point in the view.

I've calculated a appropriate bounding box (int lat and lng), but no idea how to set the view aligned with lat and lng, as the setView() only accept center coordinate and zoom, the zoom seems to be measured in pixel

答:
Use map.fitBounds():

Sets a map view that contains the given geographical bounds with the maximum zoom level possible.

Additionally, you can automatically compute the appropriate bounding box of your POI's using a Feature Group then group.getBounds():

Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).

var map = L.map("map").setView([48.85, 2.35], 10);

var markers = [
  L.marker([48.84, 2.34]),
  L.marker([48.85, 2.35]),
  L.marker([48.86, 2.36])
];

var group = L.featureGroup(markers).addTo(map);

setTimeout(function () {
  map.fitBounds(group.getBounds());
}, 1000);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '© OpenStreetMap contributors'
}).addTo(map);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css">
<script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet-src.js"></script>

<div id="map" style="height: 200px;"></div></code>```

ContentLicense: CC BY-SA 3.0

Body:
Use map.fitBounds():

Sets a map view that contains the given geographical bounds with the maximum zoom level possible.

Additionally, you can automatically compute the appropriate bounding box of your POI's using a Feature Group then group.getBounds():

Returns the LatLngBounds of the Feature Group (created from bounds and coordinates of its children).

var map = L.map("map").setView([48.85, 2.35], 10);

var markers = [
  L.marker([48.84, 2.34]),
  L.marker([48.85, 2.35]),
  L.marker([48.86, 2.36])
];

var group = L.featureGroup(markers).addTo(map);

setTimeout(function () {
  map.fitBounds(group.getBounds());
}, 1000);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css">
<script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet-src.js"></script>

<div id="map" style="height: 200px;"></div>


问:
Responsive Table layout for different size screen android
When I am try to develop a simple table layout it's occur a problem. The layout is works fine for big screen. But when I'm use that in small phone then the problem create. The full rows aren't visible.

Can anyone help me out? I just want to make a simple table layout like that:

here what I made xml layout

```<code>               <TableLayout
                android:layout_below="@+id/jonosonkha"
                android:layout_width="match_parent"
                android:layout_height="250dp"
                android:stretchColumns="5">
                <TableRow>
                    <TextView
                        android:textColor="#000"
                        android:background="#ffea00"
                        android:textSize="20sp"
                        android:text="পরিবার"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#000"
                        android:textColor="#fff"
                        android:textSize="20sp"
                        android:text="পুরুষ"
                        android:gravity="left"
                        android:paddingLeft="5dp"/>
                    <TextView
                        android:background="#ffea00"
                        android:textSize="20sp"
                        android:text="মহিলা"
                        android:textColor="#000"
                        android:gravity="center"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#000"
                        android:textSize="20sp"
                        android:text="গড় সদস্য"
                        android:gravity="left"
                        android:textColor="#fff"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#ffea00"
                        android:textColor="#000"
                        android:textSize="20sp"
                        android:text="ঘনত্ব/কি.মি"
                        android:gravity="left"
                        android:paddingLeft="5dp" />
                </TableRow>

                <TableRow
                    android:layout_marginTop="2dp"
                    >
                    <TextView
                        android:textColor="#000"
                        android:background="#ffea00"
                        android:textSize="16sp"
                        android:text="৮৯৮৬৩"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#000"
                        android:textColor="#fff"
                        android:textSize="16sp"
                        android:text="২০৫০৭৫"
                        android:gravity="center"
                        android:paddingLeft="5dp"/>
                    <TextView
                        android:background="#ffea00"
                        android:textSize="16sp"
                        android:text="২০৯১১৩"
                        android:textColor="#000"
                        android:gravity="center"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#000"
                        android:textSize="16sp"
                        android:text="৪.৫৪"
                        android:gravity="center"
                        android:textColor="#fff"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#ffea00"
                        android:textColor="#000"
                        android:textSize="16sp"
                        android:text="২১৩৮"
                        android:gravity="left"
                        android:paddingLeft="5dp" />
                </TableRow>
            </TableLayout>
</code>```

It's works fine for big screen but the problem is some of rows are covered by the small screen. Any solution please.

答:
You want to divide five TextView .

You can add android:layout_width="0dp" 、android:layout_height="match_parent" and android:layout_weight="1" in your TextView .

You can try this .

```<code><TableLayout
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:layout_below="@+id/jonosonkha"
    android:stretchColumns="5">

    <TableRow>

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#ffea00"
            android:paddingLeft="5dp"
            android:text="পরিবার"
            android:textColor="#000"
            android:textSize="20sp"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#000"
            android:gravity="left"
            android:paddingLeft="5dp"
            android:text="পুরুষ"
            android:textColor="#fff"
            android:textSize="20sp"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#ffea00"
            android:gravity="center"
            android:paddingLeft="5dp"
            android:text="মহিলা"
            android:textColor="#000"
            android:textSize="20sp"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#000"
            android:gravity="left"
            android:paddingLeft="5dp"
            android:text="গড় সদস্য"
            android:textColor="#fff"
            android:textSize="20sp"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#ffea00"
            android:gravity="left"
            android:paddingLeft="5dp"
            android:text="ঘনত্ব/কি.মি"
            android:textColor="#000"
            android:textSize="20sp"/>
    </TableRow>

    <TableRow
        android:layout_marginTop="2dp">

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#ffea00"
            android:paddingLeft="5dp"
            android:text="৮৯৮৬৩"
            android:textColor="#000"
            android:textSize="16sp"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#000"
            android:gravity="center"
            android:paddingLeft="5dp"
            android:text="২০৫০৭৫"
            android:textColor="#fff"
            android:textSize="16sp"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#ffea00"
            android:gravity="center"
            android:paddingLeft="5dp"
            android:text="২০৯১১৩"
            android:textColor="#000"
            android:textSize="16sp"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#000"
            android:gravity="center"
            android:paddingLeft="5dp"
            android:text="৪.৫৪"
            android:textColor="#fff"
            android:textSize="16sp"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#ffea00"
            android:gravity="left"
            android:paddingLeft="5dp"
            android:text="২১৩৮"
            android:textColor="#000"
            android:textSize="16sp"/>
    </TableRow>
</TableLayout>
</code>```

Output

Body:
When I am try to develop a simple table layout it's occur a problem. The layout is works fine for big screen. But when I'm use that in small phone then the problem create. The full rows aren't visible.

Can anyone help me out? I just want to make a simple table layout like that:

here what I made xml layout

               <TableLayout
                android:layout_below="@+id/jonosonkha"
                android:layout_width="match_parent"
                android:layout_height="250dp"
                android:stretchColumns="5">
                <TableRow>
                    <TextView
                        android:textColor="#000"
                        android:background="#ffea00"
                        android:textSize="20sp"
                        android:text="পরিবার"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#000"
                        android:textColor="#fff"
                        android:textSize="20sp"
                        android:text="পুরুষ"
                        android:gravity="left"
                        android:paddingLeft="5dp"/>
                    <TextView
                        android:background="#ffea00"
                        android:textSize="20sp"
                        android:text="মহিলা"
                        android:textColor="#000"
                        android:gravity="center"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#000"
                        android:textSize="20sp"
                        android:text="গড় সদস্য"
                        android:gravity="left"
                        android:textColor="#fff"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#ffea00"
                        android:textColor="#000"
                        android:textSize="20sp"
                        android:text="ঘনত্ব/কি.মি"
                        android:gravity="left"
                        android:paddingLeft="5dp" />
                </TableRow>

                <TableRow
                    android:layout_marginTop="2dp"
                    >
                    <TextView
                        android:textColor="#000"
                        android:background="#ffea00"
                        android:textSize="16sp"
                        android:text="৮৯৮৬৩"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#000"
                        android:textColor="#fff"
                        android:textSize="16sp"
                        android:text="২০৫০৭৫"
                        android:gravity="center"
                        android:paddingLeft="5dp"/>
                    <TextView
                        android:background="#ffea00"
                        android:textSize="16sp"
                        android:text="২০৯১১৩"
                        android:textColor="#000"
                        android:gravity="center"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#000"
                        android:textSize="16sp"
                        android:text="৪.৫৪"
                        android:gravity="center"
                        android:textColor="#fff"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#ffea00"
                        android:textColor="#000"
                        android:textSize="16sp"
                        android:text="২১৩৮"
                        android:gravity="left"
                        android:paddingLeft="5dp" />
                </TableRow>
            </TableLayout>

It's works fine for big screen but the problem is some of rows are covered by the small screen. Any solution please.

Body:
You want to divide five TextView .

You can add android:layout_width="0dp" 、android:layout_height="match_parent" and android:layout_weight="1" in your TextView .

You can try this .

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:layout_below="@+id/jonosonkha"
    android:stretchColumns="5">

    <TableRow>

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#ffea00"
            android:paddingLeft="5dp"
            android:text="পরিবার"
            android:textColor="#000"
            android:textSize="20sp"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#000"
            android:gravity="left"
            android:paddingLeft="5dp"
            android:text="পুরুষ"
            android:textColor="#fff"
            android:textSize="20sp"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#ffea00"
            android:gravity="center"
            android:paddingLeft="5dp"
            android:text="মহিলা"
            android:textColor="#000"
            android:textSize="20sp"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#000"
            android:gravity="left"
            android:paddingLeft="5dp"
            android:text="গড় সদস্য"
            android:textColor="#fff"
            android:textSize="20sp"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#ffea00"
            android:gravity="left"
            android:paddingLeft="5dp"
            android:text="ঘনত্ব/কি.মি"
            android:textColor="#000"
            android:textSize="20sp"/>
    </TableRow>

    <TableRow
        android:layout_marginTop="2dp">

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#ffea00"
            android:paddingLeft="5dp"
            android:text="৮৯৮৬৩"
            android:textColor="#000"
            android:textSize="16sp"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#000"
            android:gravity="center"
            android:paddingLeft="5dp"
            android:text="২০৫০৭৫"
            android:textColor="#fff"
            android:textSize="16sp"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#ffea00"
            android:gravity="center"
            android:paddingLeft="5dp"
            android:text="২০৯১১৩"
            android:textColor="#000"
            android:textSize="16sp"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#000"
            android:gravity="center"
            android:paddingLeft="5dp"
            android:text="৪.৫৪"
            android:textColor="#fff"
            android:textSize="16sp"/>

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#ffea00"
            android:gravity="left"
            android:paddingLeft="5dp"
            android:text="২১৩৮"
            android:textColor="#000"
            android:textSize="16sp"/>
    </TableRow>
</TableLayout>

Output


问:
Android screen orientation to sensor
I want to force the screen orientation to landscape on button click by setting

```<code> setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
</code>```

It works fine. Now I want the application to follow the sensor so that orientation is brought back to portrait when tilted back to portrait. I know this is possible by setting setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); but don't know where to set it. If the orientation is forced to landscape, orientation will remain in landscape no matter you tilt in any direction. Can anyone specify how to reset the orientation flag?

答:
It depends on when you want the sensor to detect rotation again.

Personally in an app I'm developping I have one specific activity where I need to be in portrait mode, so I use setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); in the onResume() of this activity and setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); in onPause() and it works just fine, when I enter the activity it sets to portrait if it's not and doesn't allow to change and on exitting the sensor works again...

Where are you trying to enable and disable the sensor?

Title: Android screen orientation to sensor

Body:
I want to force the screen orientation to landscape on button click by setting

 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

It works fine. Now I want the application to follow the sensor so that orientation is brought back to portrait when tilted back to portrait. I know this is possible by setting setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); but don't know where to set it. If the orientation is forced to landscape, orientation will remain in landscape no matter you tilt in any direction. Can anyone specify how to reset the orientation flag?

ContentLicense: CC BY-SA 2.5


问:
How to fix conflict of Swipers with Bootstrap tab-panes? Only 1st works correctly
It's interesting that by putting each Swiper inside a tab-pane, only first one works correctly. Second one behaves very strange, like each slide width as 100%. But when I take them out of panes they work correctly.
I tried many different and possible approaches!

Is there any solution for this?

HTML:

```<code><ul class="nav nav-tabs">
    <li class="active"><a data-toggle="tab" href="#brands">Brands</a></li>
    <li><a data-toggle="tab" href="#categories">Categories</a></li>
</ul>
<div class="tab-content">
    <div id="brands" class="tab-pane fade in active">
        <div class="swiper-container swiper_brands">
            <div class="swiper-wrapper">
                <div class="swiper-slide">a1</div>
                <div class="swiper-slide">a2</div>...
            </div>
        </div>
    </div>
    <div id="categories" class="tab-pane fade">
        <div class="swiper-container swiper_categories">
            <div class="swiper-wrapper">
                <div class="swiper-slide">b1</div>
                <div class="swiper-slide">b2</div>...
            </div>
        </div>
    </div>
</div>
</code>```

JS:

```<code>$('.swiper_brands').swiper({
    slidesPerView: 5,
    mode: 'horizontal',
    autoplay: 0,
    spaceBetween: 15
});

$('.swiper_categories').swiper({
    slidesPerView: 5,
    mode: 'horizontal',
    autoplay: 0,
    spaceBetween: 15
});
</code>```

http://jsfiddle.net/xFW8t/2896/

答:
Not sure of the exact issue, but if you put second tab items under timeout to enable the swipe it works fine, I think dom is not ready as items are not displaying in dom.
Updated fiddle:
http://jsfiddle.net/xFW8t/2897/

```<code>  setTimeout(function() {
    $('.swiper_categories').swiper({
        slidesPerView: 3,
        mode: 'horizontal',
        autoplay: 0,
        spaceBetween: 15
    });
  }, 1000);
</code>```

Let know if it helps.

Body:
It's interesting that by putting each Swiper inside a tab-pane, only first one works correctly. Second one behaves very strange, like each slide width as 100%. But when I take them out of panes they work correctly.
I tried many different and possible approaches!

Is there any solution for this?

HTML:

Brands

Categories

a1

a2
...

b1

b2
...

JS:

$('.swiper_brands').swiper({
    slidesPerView: 5,
    mode: 'horizontal',
    autoplay: 0,
    spaceBetween: 15
});

$('.swiper_categories').swiper({
    slidesPerView: 5,
    mode: 'horizontal',
    autoplay: 0,
    spaceBetween: 15
});

http://jsfiddle.net/xFW8t/2896/

Body:
Not sure of the exact issue, but if you put second tab items under timeout to enable the swipe it works fine, I think dom is not ready as items are not displaying in dom.
Updated fiddle:
http://jsfiddle.net/xFW8t/2897/

  setTimeout(function() {
    $('.swiper_categories').swiper({
        slidesPerView: 3,
        mode: 'horizontal',
        autoplay: 0,
        spaceBetween: 15
    });
  }, 1000);

Let know if it helps.


答:
```<code>String time = "6 hours 43 mins";//or (43 mins) or (6 hours)
int h, m;
String[] parts = time.split(" ");
if (parts.length == 4) {
    h = parts[1];
    m = parts[3];
} else if (parts.length == 2) {
    if (parts[1].isEqualTo("hours") {
        h = parts[0];
    } else if (parts[1].isEqualTo("mins") {
        m = parts[0];
    }
}
return h*60+m;
</code>```

Title: Converting string with time to minutes


问:
pandas DataFrame selecting list of rows from DateTimeIndex - KeyError. Understanding why
I'm trying to understand why I get this error. I already have a solution for this issue and it was actually solved here, just need to understand why it doesn't work as I was expecting.

I would like to understand why this throws a KeyError:

```<code>dates = pd.date_range('20130101', periods=4)
df = pd.DataFrame(np.identity(4), index=dates, columns=list('ABCD'))
df.loc[['20130102', '20130103'],:]
</code>```

with the following feedback:

```<code>KeyError: "None of [['20130102', '20130103']] are in the [index]"
</code>```

As explained here, the solution is just to do:

```<code>df.loc[pd.to_datetime(['20130102','20130104']),:]
</code>```

So the problem is definitely with the way loc takes the string list as argument for selecting from a DateTimeIndex. However, I can see that the following calls are ok for this function:

```<code>df.loc['20130102':'20130104',:]
</code>```

and

```<code>df.loc['20130102']
</code>```

I would like to understand how this works and would appreciate any resources I can use to predict the behavior of this function depending of how it is being called. I read Indexing and Selecting Data and Time Series/Date functionality from pandas documentation but couldn't find an explanation for this.

答:
Typically, when you pass an array like object to loc, Pandas is going to try to locate each element of that array in the index.  If it doesn't find it, you'll get a KeyError.  And! you passed an array of strings when the values in the index are Timestamps... so those strings definitely aren't in the index.

However, Pandas also tries to make things easier for you.  In particular, with a DatetimeIndex, If you were to pass a string scalar

```<code>df.loc['20130102']

A    0.0
B    1.0
C    0.0
D    0.0
Name: 2013-01-02 00:00:00, dtype: float64
</code>```

Pandas will attempt to parse that scalar as a Timestamp and see if that value is in the index.

If you were to pass a slice object

```<code>df.loc['20130102':'20130104']

              A    B    C    D
2013-01-02  0.0  1.0  0.0  0.0
2013-01-03  0.0  0.0  1.0  0.0
2013-01-04  0.0  0.0  0.0  1.0
</code>```

Pandas will also attempt to parse the bits of the slice object as Timestamp and return an appropriately sliced dataframe.

Your KeyError is simply passed the limits of how much helpfulness the Pandas Devs had time to code.

Body:
I'm trying to understand why I get this error. I already have a solution for this issue and it was actually solved here, just need to understand why it doesn't work as I was expecting.

I would like to understand why this throws a KeyError:

dates = pd.date_range('20130101', periods=4)
df = pd.DataFrame(np.identity(4), index=dates, columns=list('ABCD'))
df.loc[['20130102', '20130103'],:]

with the following feedback:

KeyError: "None of [['20130102', '20130103']] are in the [index]"

As explained here, the solution is just to do:

df.loc[pd.to_datetime(['20130102','20130104']),:]

So the problem is definitely with the way loc takes the string list as argument for selecting from a DateTimeIndex. However, I can see that the following calls are ok for this function:

df.loc['20130102':'20130104',:]

and

df.loc['20130102']

I would like to understand how this works and would appreciate any resources I can use to predict the behavior of this function depending of how it is being called. I read Indexing and Selecting Data and Time Series/Date functionality from pandas documentation but couldn't find an explanation for this.

Body:
Typically, when you pass an array like object to loc, Pandas is going to try to locate each element of that array in the index.  If it doesn't find it, you'll get a KeyError.  And! you passed an array of strings when the values in the index are Timestamps... so those strings definitely aren't in the index.

However, Pandas also tries to make things easier for you.  In particular, with a DatetimeIndex, If you were to pass a string scalar

df.loc['20130102']

A    0.0
B    1.0
C    0.0
D    0.0
Name: 2013-01-02 00:00:00, dtype: float64

Pandas will attempt to parse that scalar as a Timestamp and see if that value is in the index.

If you were to pass a slice object

df.loc['20130102':'20130104']

              A    B    C    D
2013-01-02  0.0  1.0  0.0  0.0
2013-01-03  0.0  0.0  1.0  0.0
2013-01-04  0.0  0.0  0.0  1.0

Pandas will also attempt to parse the bits of the slice object as Timestamp and return an appropriately sliced dataframe.

Your KeyError is simply passed the limits of how much helpfulness the Pandas Devs had time to code.


问:
Persisting objects with Realm (error: Changing Realm data can only be done from inside a transaction)
I am having difficulties getting Realm to work.

```<code>RealmConfiguration realmConfig = new RealmConfiguration.Builder(this).build();
Realm.setDefaultConfiguration(realmConfig);
Realm realm = Realm.getDefaultInstance();

MyObjectExtendingRealmObject myObject = new MyObjectExtendingRealmObject("John");
realm.beginTransaction();
realm.copyToRealm(myObject);
realm.commitTransaction();
</code>```

Error:  java.lang.IllegalStateException: Changing Realm data can only be done from inside a transaction

Call me crazy but aren't I doing the data persistence inside the transaction, which is exactly how it's done in the docs? See the example using copyToRealm here: https://realm.io/docs/java/latest/#creating-objects

What am I doing wrong?

Edit: What, Realm doesn't support autoincrementing primary key ids? Dealbreaker for me. I'll leave this question up in case it helps others though.

Edit: My class

```<code>public class MyObjectExtendingRealmObject extends RealmObject {
    private String name;

    public MyObjectExtendingRealmObject() {

    }

    public MyObjectExtendingRealmObject(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

}
</code>```

答:
I have a helper class named RealmHelper and above is one of its methods.

```<code> public static void saveObject(RealmObject objectToSave) {

    Realm realm = getRealm();
    realm.beginTransaction();
    realm.copyToRealmOrUpdate(objectToSave);
    realm.commitTransaction();
}
</code>```

Bacause of this, my code structure is this, no realm methods or object shouldn't be in activity or fragment.

For overcoming this error, everytime i create new object with same id, and realm can overwrite old object.

Body:
I am having difficulties getting Realm to work.

RealmConfiguration realmConfig = new RealmConfiguration.Builder(this).build();
Realm.setDefaultConfiguration(realmConfig);
Realm realm = Realm.getDefaultInstance();

MyObjectExtendingRealmObject myObject = new MyObjectExtendingRealmObject("John");
realm.beginTransaction();
realm.copyToRealm(myObject);
realm.commitTransaction();

Error:  java.lang.IllegalStateException: Changing Realm data can only be done from inside a transaction

Call me crazy but aren't I doing the data persistence inside the transaction, which is exactly how it's done in the docs? See the example using copyToRealm here: https://realm.io/docs/java/latest/#creating-objects

What am I doing wrong?

Edit: What, Realm doesn't support autoincrementing primary key ids? Dealbreaker for me. I'll leave this question up in case it helps others though.

Edit: My class

public class MyObjectExtendingRealmObject extends RealmObject {
    private String name;

    public MyObjectExtendingRealmObject() {

    }

    public MyObjectExtendingRealmObject(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Body:
I have a helper class named RealmHelper and above is one of its methods.

 public static void saveObject(RealmObject objectToSave) {

    Realm realm = getRealm();
    realm.beginTransaction();
    realm.copyToRealmOrUpdate(objectToSave);
    realm.commitTransaction();
}

Bacause of this, my code structure is this, no realm methods or object shouldn't be in activity or fragment.

For overcoming this error, everytime i create new object with same id, and realm can overwrite old object.


问:
DRF Serializer Relations / JSON API Framework
*Update 1: Attempts with corresponding errors now shown in serializer code

*Update 2: I've narrowed the issue to a conflict with the JSON Api framework I'm using

I'm fairly new to Python and Django and I'm struggling quite a bit with relations. I'm able to create the relations in the database however I've been unable to serialize the models together for a response object, despite trying every method in the documentation which seems very straightforward. My goal is to return both models from an APIView on login and if this code doesn't error I get a response with just the user model. The errors vary based on the different techniques and are similar to what other users get when having trouble with relations, however their fixes haven't solved my problem.

I'm wondering if there's something obvious I'm not doing right. I'm happy to share more code but I'm really at a loss as to how to proceed.

Fyi: My models are in different apps which is why the fk reference is users.User

Models:

```<code>class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=50, unique=True)
    password = models.CharField(max_length=100)
    name = models.CharField(max_length=50)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    has_business = models.BooleanField(default=False)

    objects = UserManager()
    USERNAME_FIELD = 'email'

    REQUIRED_FIELDS = ['password']

    def get_full_name(self):
        return self.name

    def get_short_name(self):
        return self.name

    def __str__(self):
        return self.email

class Business(models.Model):
    name = models.CharField(max_length=50, unique=True)
    address = models.CharField(max_length=100)
    phone = models.CharField(max_length=20)
    description = models.CharField(max_length=500)
    user = models.ForeignKey(
        'users.User',
        related_name='business',
        unique=False,
        on_delete=models.CASCADE
        )
    has_driver = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
</code>```

Serializer:

```<code>class UserSerializer(serializers.ModelSerializer):

    token = srs.SerializerMethodField()

biz = BusinessSerializer(many=True, read_only=True,
source='business.id')
error: just returns user model

biz = BusinessSerializer(read_only=True, many=True, source='business')
error: ForeignKey' object has no attribute

biz = serializers.RelatedField(many=True, read_only=True)
error: 'User' object has no attribute 'biz'

biz = serializers.ReadOnlyField(source='businesses.id')
error: RelatedManager object at 0x7fed496fe208> is not JSON
serializable

biz = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
error:'User' object has no attribute 'biz'

    class Meta:
        model = models.User
        fields = ('id', 'email', 'password', 'name', 'token', 'has_business', 'biz')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):

        user = models.User(
                email = validated_data['email'],
                name = validated_data['name'],
                phone = validated_data['phone'],
                location = validated_data['location'],
            )
        user.set_password(validated_data['password'])
        user.save()

        return user
</code>```

View:

```<code>class LoginUser(APIView):
    permission_classes = (permissions.AllowAny,)
    resource_name = 'users'

    def post(self, request):
        email = request.POST.get('email', False)
        password = request.POST.get('password', False)

        if(email and password):

            lu = UserAuth()
            authenticated_user = lu.auth(email=email, password=password)

            if authenticated_user is not None:
                if authenticated_user.is_active:

                    serializer = serializers.UserSerializer(authenticated_user, context={'request': request})
                    return Response(serializer.data, status=status.HTTP_200_OK)
</code>```

答:
You have to use the related_name in your serializer.

You can take a look here

In this example you can see that the Track Model (analog to your Business Model) has the field called album with related_name='tracks'

Then in the AlbumSerializer (the analog to your User Model):

```<code>class AlbumSerializer(serializers.ModelSerializer):
    tracks = serializers.StringRelatedField(many=True)

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')
</code>```

So, in summary you have to use your related_name business

This is the example with a StringRelatedField, but you can of course return the complete object using this

Body:
*Update 1: Attempts with corresponding errors now shown in serializer code

*Update 2: I've narrowed the issue to a conflict with the JSON Api framework I'm using

I'm fairly new to Python and Django and I'm struggling quite a bit with relations. I'm able to create the relations in the database however I've been unable to serialize the models together for a response object, despite trying every method in the documentation which seems very straightforward. My goal is to return both models from an APIView on login and if this code doesn't error I get a response with just the user model. The errors vary based on the different techniques and are similar to what other users get when having trouble with relations, however their fixes haven't solved my problem.

I'm wondering if there's something obvious I'm not doing right. I'm happy to share more code but I'm really at a loss as to how to proceed.

Fyi: My models are in different apps which is why the fk reference is users.User

Models:

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=50, unique=True)
    password = models.CharField(max_length=100)
    name = models.CharField(max_length=50)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    has_business = models.BooleanField(default=False)

    objects = UserManager()
    USERNAME_FIELD = 'email'

    REQUIRED_FIELDS = ['password']

    def get_full_name(self):
        return self.name

    def get_short_name(self):
        return self.name

    def __str__(self):
        return self.email

class Business(models.Model):
    name = models.CharField(max_length=50, unique=True)
    address = models.CharField(max_length=100)
    phone = models.CharField(max_length=20)
    description = models.CharField(max_length=500)
    user = models.ForeignKey(
        'users.User',
        related_name='business',
        unique=False,
        on_delete=models.CASCADE
        )
    has_driver = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)

Serializer:

class UserSerializer(serializers.ModelSerializer):

    token = srs.SerializerMethodField()

biz = BusinessSerializer(many=True, read_only=True,
source='business.id')
error: just returns user model

biz = BusinessSerializer(read_only=True, many=True, source='business')
error: ForeignKey' object has no attribute

biz = serializers.RelatedField(many=True, read_only=True)
error: 'User' object has no attribute 'biz'

biz = serializers.ReadOnlyField(source='businesses.id')
error: RelatedManager object at 0x7fed496fe208> is not JSON
serializable

biz = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
error:'User' object has no attribute 'biz'

    class Meta:
        model = models.User
        fields = ('id', 'email', 'password', 'name', 'token', 'has_business', 'biz')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):

        user = models.User(
                email = validated_data['email'],
                name = validated_data['name'],
                phone = validated_data['phone'],
                location = validated_data['location'],
            )
        user.set_password(validated_data['password'])
        user.save()

        return user

View:

class LoginUser(APIView):
    permission_classes = (permissions.AllowAny,)
    resource_name = 'users'

    def post(self, request):
        email = request.POST.get('email', False)
        password = request.POST.get('password', False)

        if(email and password):

            lu = UserAuth()
            authenticated_user = lu.auth(email=email, password=password)

            if authenticated_user is not None:
                if authenticated_user.is_active:

                    serializer = serializers.UserSerializer(authenticated_user, context={'request': request})
                    return Response(serializer.data, status=status.HTTP_200_OK)

Body:
You have to use the related_name in your serializer.

You can take a look here

In this example you can see that the Track Model (analog to your Business Model) has the field called album with related_name='tracks'

Then in the AlbumSerializer (the analog to your User Model):

class AlbumSerializer(serializers.ModelSerializer):
    tracks = serializers.StringRelatedField(many=True)

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')

So, in summary you have to use your related_name business

This is the example with a StringRelatedField, but you can of course return the complete object using this


问:
how to get selectedvalue from DataGridViewComboBoxColumn?
i have a datagridview which has a DataGridViewComboBoxColumn for unit i want to get the selectedvalue of each DataGridViewComboBoxColumn how could i get this?</p>

答:
If you are looping through the grid then you should be interested in getting the FormattedValue of the Combobox cell since that would be actual persisted value of the selected combobox item</p>

```<code>dataGridView1[colIndex,rowIndx].FormattedValue
</code>```

Body:
If you are looping through the grid then you should be interested in getting the FormattedValue of the Combobox cell since that would be actual persisted value of the selected combobox item

dataGridView1[colIndex,rowIndx].FormattedValue


问:
System.nanotime return wildly different times
So i'm trying to implement a sort of day-night cycle in my game, and I'm using System.nanotime() to get the approximate time passed between frames, the problem is that it sometimes jumps huge amounts of time

Using lwjgl, and calling Timer.update() before swapBuffers with vsync enabled should be around 16.6ms increase to the current time each loop shouldnt it? Yet it can be much much higher than that with no actual slowdown for rendering

Here's the code : Time class

```<code>public class Time
{
    public static final long SECOND = 1000000000L;

    private static long lastTime;

    public static long getTime()
    {
        return System.nanoTime();
    }

    public static double getDelta()
    {
        return (double)(getTime() - lastTime) / SECOND;
    }

    public static void update()
    {
        Time.lastTime = Time.getTime();
    }
}
</code>```

Update method

```<code>    while ( !glfwWindowShouldClose(window) )
    {
        input();
        update();
        render();
    }

public void update()
{
    //System.out.println("Time since last update " + Time.getDelta());
    Time.update();
}
</code>```

And where i'm using the delta time :

```<code>    if ((timeOfDay + Time.getDelta()) < timeDayTotal)
        timeOfDay += Time.getDelta();
    else
        timeOfDay += Time.getDelta() - timeDayTotal;
    System.out.println("Time of day " + timeOfDay);
</code>```

Ignoring the fact that the precision seems to be waaaay off for now, here's some sample output

```<code>Time of day 0.0077873133
Time of day 0.0077988105
Time of day 0.0078120963
Time of day 0.007860638
Time of day 0.015185255
Time of day 0.01879608
Time of day 0.01880809
Time of day 0.018820863
Time of day 0.018835938
Time of day 0.018851267
</code>```

It seems to mostly increment the correct amount (by a factor of 10^-4, but close enough, thats not the problem), but then it has these massive jumps up that I can't explain

So finally, a) whats the problem with system.nanoTime and b) is there a fix or viable replacement?

Edit : Switched to currentTimeMillis(), the precision is gone which is no big deal, but the jumps are still there

```<code>Time of day 0.03
Time of day 0.03
Time of day 0.03
Time of day 0.03
Time of day 0.06
Time of day 0.06
Time of day 0.06
Time of day 0.06
</code>```

答:
From the code you posted, it looks like you update() the Time on each frame before rendering, so then when you use getDelta() you only measure the time it took to get there, rather than the whole frame time?

I think it should look more like this:

```<code>public class Time
{
    public static final long SECOND = 1000000000L;
    public static final double timeDayTotal = 100.0; // ?

    private static final long start = System.nanoTime();
    private static double timeOfDay;

    public static void update() {
        long now = System.nanoTime();
        timeOfDay = (now - start) / (double)SECOND % timeDayTotal;
    }

    public static double getTimeOfDay()
    {
        return timeOfDay;
    }
}
</code>```

Body:
So i'm trying to implement a sort of day-night cycle in my game, and I'm using System.nanotime() to get the approximate time passed between frames, the problem is that it sometimes jumps huge amounts of time

Using lwjgl, and calling Timer.update() before swapBuffers with vsync enabled should be around 16.6ms increase to the current time each loop shouldnt it? Yet it can be much much higher than that with no actual slowdown for rendering

Here's the code : Time class

public class Time
{
    public static final long SECOND = 1000000000L;

    private static long lastTime;

    public static long getTime()
    {
        return System.nanoTime();
    }

    public static double getDelta()
    {
        return (double)(getTime() - lastTime) / SECOND;
    }

    public static void update()
    {
        Time.lastTime = Time.getTime();
    }
}

Update method

    while ( !glfwWindowShouldClose(window) )
    {
        input();
        update();
        render();
    }

public void update()
{
    //System.out.println("Time since last update " + Time.getDelta());
    Time.update();
}

And where i'm using the delta time :

    if ((timeOfDay + Time.getDelta()) < timeDayTotal)
        timeOfDay += Time.getDelta();
    else
        timeOfDay += Time.getDelta() - timeDayTotal;
    System.out.println("Time of day " + timeOfDay);

Ignoring the fact that the precision seems to be waaaay off for now, here's some sample output

Time of day 0.0077873133
Time of day 0.0077988105
Time of day 0.0078120963
Time of day 0.007860638
Time of day 0.015185255
Time of day 0.01879608
Time of day 0.01880809
Time of day 0.018820863
Time of day 0.018835938
Time of day 0.018851267

It seems to mostly increment the correct amount (by a factor of 10^-4, but close enough, thats not the problem), but then it has these massive jumps up that I can't explain

So finally, a) whats the problem with system.nanoTime and b) is there a fix or viable replacement?

Edit : Switched to currentTimeMillis(), the precision is gone which is no big deal, but the jumps are still there

Time of day 0.03
Time of day 0.03
Time of day 0.03
Time of day 0.03
Time of day 0.06
Time of day 0.06
Time of day 0.06
Time of day 0.06

Body:
From the code you posted, it looks like you update() the Time on each frame before rendering, so then when you use getDelta() you only measure the time it took to get there, rather than the whole frame time?

I think it should look more like this:

public class Time
{
    public static final long SECOND = 1000000000L;
    public static final double timeDayTotal = 100.0; // ?

    private static final long start = System.nanoTime();
    private static double timeOfDay;

    public static void update() {
        long now = System.nanoTime();
        timeOfDay = (now - start) / (double)SECOND % timeDayTotal;
    }

    public static double getTimeOfDay()
    {
        return timeOfDay;
    }
}


问:
Android: How do I scale a bitmap to fit the screen size using canvas/draw bitmap?
I am taking an image and drawing it to the screen using canvas. I want to scale it based on the screen size.

This is what I tried, but it cuts off a large chunk of the image:

```<code>DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;

Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),R.drawable.myimage);
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);

Rect frameToDraw = new Rect(0, 0, width, height);
RectF whereToDraw = new RectF(0, 0, width, height);

canvas.drawBitmap(bitmap,frameToDraw,whereToDraw, paint);
</code>```

I know I am doing a few things wrong, but I'm not exactly sure what. This code causes the image to exceed the size of the screen. I want it to be scaled to the size of the screen. I'll be drawing smaller images in too that I also will need to scale according to the size of the screen, though not to the full screen.

答:
dont need creat scale bitmap, instead:

```<code>Bitmap frameBuffer = Bitmap.createBitmap(frameBufferWidth,frameBufferHeight, Config.RGB_565);
</code>```

frameBufferWidth and frameBufferHeight are the sizes that you want to make your app base on those(for example 480*800)

then simply add this code:

```<code>Rect dstRect = new Rect();
canvas.getClipBounds(dstRect); // get canvas size base screen size
canvas.drawBitmap(framebuffer, null, dstRect, null);
</code>```

it draw your final bitmap according to screen size

Body:
I am taking an image and drawing it to the screen using canvas. I want to scale it based on the screen size.

This is what I tried, but it cuts off a large chunk of the image:

DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;

Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),R.drawable.myimage);
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);

Rect frameToDraw = new Rect(0, 0, width, height);
RectF whereToDraw = new RectF(0, 0, width, height);

canvas.drawBitmap(bitmap,frameToDraw,whereToDraw, paint);

I know I am doing a few things wrong, but I'm not exactly sure what. This code causes the image to exceed the size of the screen. I want it to be scaled to the size of the screen. I'll be drawing smaller images in too that I also will need to scale according to the size of the screen, though not to the full screen.

Body:
dont need creat scale bitmap, instead:

Bitmap frameBuffer = Bitmap.createBitmap(frameBufferWidth,frameBufferHeight, Config.RGB_565);

frameBufferWidth and frameBufferHeight are the sizes that you want to make your app base on those(for example 480*800)

then simply add this code:

Rect dstRect = new Rect();
canvas.getClipBounds(dstRect); // get canvas size base screen size
canvas.drawBitmap(framebuffer, null, dstRect, null);

it draw your final bitmap according to screen size


问:
RecyclerView: Inconsistency detected. Invalid item position
Our QA has detected a bug: when rotating the Android device (Droid Turbo), the following RecyclerView-related crash happened:

java.lang.IndexOutOfBoundsException:
      Inconsistency detected. Invalid item position 2(offset:2).state:3

To me, it looks like an internal error inside RecyclerView, as I can't think of any way of this being caused directly by our code...

Has anyone encountered this problem?

What would be the solution?

A brutal workaround could be perhaps to catch the exception when it happens and re-create the RecyclverView instance from scratch, to avoid getting left with a corrupted state.

But, if possible, I would like to understand the problem better (and perhaps fix it at its source), instead of masking it.

The bug is not easy to reproduce, but it is fatal when it happens.

The full stack-trace:

```<code>W/dalvikvm( 7546): threadid=1: thread exiting with uncaught exception (group=0x41987d40)
    E/AndroidRuntime( 7546): FATAL EXCEPTION: main
    E/AndroidRuntime( 7546): Process: com.oblong.mezzedroid, PID: 7546
    E/AndroidRuntime( 7546): java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 2(offset:2).state:3
    E/AndroidRuntime( 7546):    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:3382)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:3340)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1810)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1306)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1269)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:523)
    E/AndroidRuntime( 7546):    at org.liboid.recycler_view.RecyclerViewContainer$LiLinearLayoutManager.onLayoutChildren(RecyclerViewContainer.java:179)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:1942)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:2237)
    E/AndroidRuntime( 7546):    at org.liboid.recycler_view.LiRecyclerView.onLayout(LiRecyclerView.java:30)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
    E/AndroidRuntime( 7546):    at com.oblong.mezzedroid.workspace.content.bins.BinsContainerLayout.onLayout(BinsContainerLayout.java:22)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2132)
    E/AndroidRuntime( 7546):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1872)
    E/AndroidRuntime( 7546):    at andro
</code>```

答:
Just remove all views of your layout Manager before notify. like:</p>

```<code>myLayoutmanager.removeAllViews();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Our QA has detected a bug: when rotating the Android device (Droid Turbo), the following RecyclerView-related crash happened:

java.lang.IndexOutOfBoundsException:
      Inconsistency detected. Invalid item position 2(offset:2).state:3

To me, it looks like an internal error inside RecyclerView, as I can't think of any way of this being caused directly by our code...

Has anyone encountered this problem?

What would be the solution?

A brutal workaround could be perhaps to catch the exception when it happens and re-create the RecyclverView instance from scratch, to avoid getting left with a corrupted state.

But, if possible, I would like to understand the problem better (and perhaps fix it at its source), instead of masking it.

The bug is not easy to reproduce, but it is fatal when it happens.

The full stack-trace:

W/dalvikvm( 7546): threadid=1: thread exiting with uncaught exception (group=0x41987d40)
    E/AndroidRuntime( 7546): FATAL EXCEPTION: main
    E/AndroidRuntime( 7546): Process: com.oblong.mezzedroid, PID: 7546
    E/AndroidRuntime( 7546): java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 2(offset:2).state:3
    E/AndroidRuntime( 7546):    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:3382)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:3340)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1810)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1306)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1269)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:523)
    E/AndroidRuntime( 7546):    at org.liboid.recycler_view.RecyclerViewContainer$LiLinearLayoutManager.onLayoutChildren(RecyclerViewContainer.java:179)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:1942)
    E/AndroidRuntime( 7546):    at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:2237)
    E/AndroidRuntime( 7546):    at org.liboid.recycler_view.LiRecyclerView.onLayout(LiRecyclerView.java:30)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
    E/AndroidRuntime( 7546):    at com.oblong.mezzedroid.workspace.content.bins.BinsContainerLayout.onLayout(BinsContainerLayout.java:22)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
    E/AndroidRuntime( 7546):    at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
    E/AndroidRuntime( 7546):    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
    E/AndroidRuntime( 7546):    at android.view.View.layout(View.java:14946)
    E/AndroidRuntime( 7546):    at android.view.ViewGroup.layout(ViewGroup.java:4651)
    E/AndroidRuntime( 7546):    at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2132)
    E/AndroidRuntime( 7546):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1872)
    E/AndroidRuntime( 7546):    at andro

Body:
Just remove all views of your layout Manager before notify. like:

myLayoutmanager.removeAllViews();


问:
How to get a Control byId from a SAPUI5 Fragment
I have a dialog which is in a Fragment. So after entering the details into it and clicking the submit button, the text which was filled into the input should be displayed as a MessageToast. But I am getting the error : ' Cannot read property 'getValue' of undefined '.

Below is the code :

```<code>    onAddMovie: function() {
        var view = this.getView();
        var createDialog = view.byId("CreateDialog");
        var oDummyController = {
            // This is when I clicked the Submit button in dialog
            submitDialog: function() {
            var user = sap.ui.core.Fragment.byId("createDialog", "movie_name").getValue();
                MessageToast.show(user);
                createDialog.close();
            },
            closeDialog: function() {
                createDialog.close();
            }
        };

        if (!createDialog) {
            createDialog = sap.ui.xmlfragment(view.getId(), "Admin.view.Dialog", oDummyController);
        }
        view.addDependent(createDialog);
        createDialog.open();
        if (!createDialog.isOpen()) {
            //do sth
        }
    },
</code>```

Above is the function in which the dialog is getting displayed and after pressing submit button , the text in the input should be displayed in a MessageToast.

XML :

```<code>        <core:FragmentDefinition  xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:l="sap.ui.layout">

        <Dialog id="createDialog" title="Input Movie Details" width="100%" class="sapuiMediumMargin" confirm="handleClose" close="handleClose">
            <l:VerticalLayout class="sapUiContentPadding" width="100%">
            <l:content>
                <Input width="100%" placeholder="Movie Name" id="movie_name"/>
                <HBox alignItems="Center" renderType="Bare">
                    <Label text="Year of Release" width="50%"/>
                    <ActionSelect selectedItem="Element sap.ui.core.ListItem#__item0" selectedKey="item1" class="sapUiLargeMarginBegin" selectedItemId="__item0" id="__select0" width="50%">
                        <items>
                            <core:ListItem text="2017" key="item1" id="__item0"/>
                            <core:ListItem text="2016" key="item2" id="__item1"/>
                            <core:ListItem text="2015" key="item3" id="__item2"/></items>
                    </ActionSelect>
                </HBox>
                <HBox alignItems="Center" renderType="Bare">
                    <Label text="Date of Screening" width="50%"/>
                    <DatePicker class="sapUiLargeMarginBegin" width="50%" id="__picker0"/>
                </HBox>
                <HBox alignItems="Center">
                    <Label text="Movie Rating"/>
                    <RadioButtonGroup width="100%" columns="3" selectedIndex="-1" id="__group0">
                        <buttons>
                            <RadioButton selected="true" groupName="__group0" text="Universal" id="__button0"/>
                            <RadioButton groupName="__group0" text="Adult" id="__button1"/>
                            <RadioButton groupName="__group0" text="U/A" id="__button2"/></buttons>
                    </RadioButtonGroup>
                </HBox>
                        <HBox alignItems="Center" width="100%" renderType="Bare">
                    <Label text="Enable Booking" width="70%"/>
                <CheckBox id="__box0" width="30%" textDirection="LTR"/>
            </HBox>
                <FlexBox alignItems="End" alignContent="Center" justifyContent="End" class="sapUiTinyMarginTop">

                    <SegmentedButton selectedButton="__button3" id="__button21">
                            <buttons>
                                <Button text="Submit" id="__submit" press="submitDialog"/>
                                <Button text="Cancel" id="__button41" press="closeDialog"/></buttons>
                        </SegmentedButton>
                            </FlexBox>
                </l:content>
            </l:VerticalLayout>
        </Dialog>

    </core:FragmentDefinition>
</code>```

答:
Fragment

```<code><core:FragmentDefinition xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:l="sap.ui.layout">
<Dialog id="createDialog" title="Input Movie Details" width="100%" class="sapuiMediumMargin" confirm="handleClose" close="handleClose">
    <l:VerticalLayout class="sapUiContentPadding" width="100%">
        <l:content>
            <Input width="100%" placeholder="Movie Name" id="movie_name"/>
            <HBox alignItems="Center" renderType="Bare">
                <Label text="Year of Release" width="50%"/>
                <ActionSelect selectedKey="item1" class="sapUiLargeMarginBegin" id="select0" width="50%">
                    <items>
                        <core:ListItem text="2017" key="item1" id="item0"/>
                        <core:ListItem text="2016" key="item2" id="item1"/>
                        <core:ListItem text="2015" key="item3" id="item2"/></items>
                </ActionSelect>
            </HBox>
            <HBox alignItems="Center" renderType="Bare">
                <Label text="Date of Screening" width="50%"/>
                <DatePicker class="sapUiLargeMarginBegin" width="50%" id="picker0"/>
            </HBox>
            <HBox alignItems="Center">
                <Label text="Movie Rating"/>
                <RadioButtonGroup width="100%" columns="3" selectedIndex="-1" id="group0">
                    <buttons>
                        <RadioButton selected="true" groupName="group0" text="Universal" id="button0"/>
                        <RadioButton groupName="group0" text="Adult" id="button1"/>
                        <RadioButton groupName="group0" text="U/A" id="button2"/></buttons>
                </RadioButtonGroup>
            </HBox>
            <HBox alignItems="Center" width="100%" renderType="Bare">
                <Label text="Enable Booking" width="70%"/>
                <CheckBox id="box0" width="30%" textDirection="LTR"/>
            </HBox>
            <FlexBox alignItems="End" alignContent="Center" justifyContent="End" class="sapUiTinyMarginTop">
                <SegmentedButton id="button21">
                    <buttons>
                        <Button text="Submit" id="submit" press="submitDialog"/>
                        <Button text="Cancel" id="button41" press="closeDialog"/></buttons>
                </SegmentedButton>
            </FlexBox>
        </l:content>
    </l:VerticalLayout>
</Dialog>
</code>```

```<code>Controller
sap.ui.define([
    "sap/ui/core/mvc/Controller"
], function(Controller) {
    "use strict";
return Controller.extend("test001test001.controller.View1", {
    _oNewProcessDialog:null,
    onAddMovie: function() {
    this._getNewProcessDialog().open();
    },
    submitDialog:function(){

    sap.m.MessageToast.show(sap.ui.getCore().byId("movie_name").getValue());
    },
    closeDialog: function() {
            this._getNewProcessDialog().close();
        },

        _getNewProcessDialog: function() {
        // create dialog lazily
        if (!this._oNewProcessDialog) {
            // create dialog via fragment factory
            this._oNewProcessDialog = sap.ui.xmlfragment("test001test001.view.CreateDialog", this);
            // connect dialog to view (models, lifecycle)
            this.getView().addDependent(this._oNewProcessDialog);
            jQuery.sap.syncStyleClass("sapUiSizeCompact", this.getView(), this._oNewProcessDialog);
        }
        return this._oNewProcessDialog;
    },
});
</code>```

});

Wiew

```<code><Button press="onAddMovie"></Button>
</code>```

Body:
I have a dialog which is in a Fragment. So after entering the details into it and clicking the submit button, the text which was filled into the input should be displayed as a MessageToast. But I am getting the error : ' Cannot read property 'getValue' of undefined '.

Below is the code :

    onAddMovie: function() {
        var view = this.getView();
        var createDialog = view.byId("CreateDialog");
        var oDummyController = {
            // This is when I clicked the Submit button in dialog
            submitDialog: function() {
            var user = sap.ui.core.Fragment.byId("createDialog", "movie_name").getValue();
                MessageToast.show(user);
                createDialog.close();
            },
            closeDialog: function() {
                createDialog.close();
            }
        };

        if (!createDialog) {
            createDialog = sap.ui.xmlfragment(view.getId(), "Admin.view.Dialog", oDummyController);
        }
        view.addDependent(createDialog);
        createDialog.open();
        if (!createDialog.isOpen()) {
            //do sth
        }
    },

Above is the function in which the dialog is getting displayed and after pressing submit button , the text in the input should be displayed in a MessageToast.

XML :

        <core:FragmentDefinition  xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:l="sap.ui.layout">

        <Dialog id="createDialog" title="Input Movie Details" width="100%" class="sapuiMediumMargin" confirm="handleClose" close="handleClose">
            <l:VerticalLayout class="sapUiContentPadding" width="100%">
            <l:content>
                <Input width="100%" placeholder="Movie Name" id="movie_name"/>
                <HBox alignItems="Center" renderType="Bare">

                    <ActionSelect selectedItem="Element sap.ui.core.ListItem#__item0" selectedKey="item1" class="sapUiLargeMarginBegin" selectedItemId="__item0" id="__select0" width="50%">
                        <items>
                            <core:ListItem text="2017" key="item1" id="__item0"/>
                            <core:ListItem text="2016" key="item2" id="__item1"/>
                            <core:ListItem text="2015" key="item3" id="__item2"/></items>
                    </ActionSelect>
                </HBox>
                <HBox alignItems="Center" renderType="Bare">

                    <DatePicker class="sapUiLargeMarginBegin" width="50%" id="__picker0"/>
                </HBox>
                <HBox alignItems="Center">

                    <RadioButtonGroup width="100%" columns="3" selectedIndex="-1" id="__group0">
                        <buttons>
                            <RadioButton selected="true" groupName="__group0" text="Universal" id="__button0"/>
                            <RadioButton groupName="__group0" text="Adult" id="__button1"/>
                            <RadioButton groupName="__group0" text="U/A" id="__button2"/></buttons>
                    </RadioButtonGroup>
                </HBox>
                        <HBox alignItems="Center" width="100%" renderType="Bare">

                <CheckBox id="__box0" width="30%" textDirection="LTR"/>
            </HBox>
                <FlexBox alignItems="End" alignContent="Center" justifyContent="End" class="sapUiTinyMarginTop">

                    <SegmentedButton selectedButton="__button3" id="__button21">
                            <buttons>
                                <Button text="Submit" id="__submit" press="submitDialog"/>
                                <Button text="Cancel" id="__button41" press="closeDialog"/></buttons>
                        </SegmentedButton>
                            </FlexBox>
                </l:content>
            </l:VerticalLayout>
        </Dialog>

    </core:FragmentDefinition>

Body:
Fragment

<core:FragmentDefinition xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:l="sap.ui.layout">
<Dialog id="createDialog" title="Input Movie Details" width="100%" class="sapuiMediumMargin" confirm="handleClose" close="handleClose">
    <l:VerticalLayout class="sapUiContentPadding" width="100%">
        <l:content>
            <Input width="100%" placeholder="Movie Name" id="movie_name"/>
            <HBox alignItems="Center" renderType="Bare">
                <Label text="Year of Release" width="50%"/>
                <ActionSelect selectedKey="item1" class="sapUiLargeMarginBegin" id="select0" width="50%">
                    <items>
                        <core:ListItem text="2017" key="item1" id="item0"/>
                        <core:ListItem text="2016" key="item2" id="item1"/>
                        <core:ListItem text="2015" key="item3" id="item2"/></items>
                </ActionSelect>
            </HBox>
            <HBox alignItems="Center" renderType="Bare">
                <Label text="Date of Screening" width="50%"/>
                <DatePicker class="sapUiLargeMarginBegin" width="50%" id="picker0"/>
            </HBox>
            <HBox alignItems="Center">
                <Label text="Movie Rating"/>
                <RadioButtonGroup width="100%" columns="3" selectedIndex="-1" id="group0">
                    <buttons>
                        <RadioButton selected="true" groupName="group0" text="Universal" id="button0"/>
                        <RadioButton groupName="group0" text="Adult" id="button1"/>
                        <RadioButton groupName="group0" text="U/A" id="button2"/></buttons>
                </RadioButtonGroup>
            </HBox>
            <HBox alignItems="Center" width="100%" renderType="Bare">
                <Label text="Enable Booking" width="70%"/>
                <CheckBox id="box0" width="30%" textDirection="LTR"/>
            </HBox>
            <FlexBox alignItems="End" alignContent="Center" justifyContent="End" class="sapUiTinyMarginTop">
                <SegmentedButton id="button21">
                    <buttons>
                        <Button text="Submit" id="submit" press="submitDialog"/>
                        <Button text="Cancel" id="button41" press="closeDialog"/></buttons>
                </SegmentedButton>
            </FlexBox>
        </l:content>
    </l:VerticalLayout>
</Dialog>

Controller
sap.ui.define([
    "sap/ui/core/mvc/Controller"
], function(Controller) {
    "use strict";
return Controller.extend("test001test001.controller.View1", {
    _oNewProcessDialog:null,
    onAddMovie: function() {
    this._getNewProcessDialog().open();
    },
    submitDialog:function(){

    sap.m.MessageToast.show(sap.ui.getCore().byId("movie_name").getValue());
    },
    closeDialog: function() {
            this._getNewProcessDialog().close();
        },

        _getNewProcessDialog: function() {
        // create dialog lazily
        if (!this._oNewProcessDialog) {
            // create dialog via fragment factory
            this._oNewProcessDialog = sap.ui.xmlfragment("test001test001.view.CreateDialog", this);
            // connect dialog to view (models, lifecycle)
            this.getView().addDependent(this._oNewProcessDialog);
            jQuery.sap.syncStyleClass("sapUiSizeCompact", this.getView(), this._oNewProcessDialog);
        }
        return this._oNewProcessDialog;
    },
});

});

Wiew

<Button press="onAddMovie"></Button>


问:
Django how to add a Group model field
i want add a description filed to Group，
how to do it?
edit source code?

```<code>@python_2_unicode_compatible
class Group(models.Model):
    name = models.CharField(_('name'), max_length=80, unique=True)
    description = models.CharField(_('description'), max_length=180,
        null=True, blank=True)  # add
    permissions = models.ManyToManyField(
        Permission,
        verbose_name=_('permissions'),
        blank=True,
    )

    objects = GroupManager()

    class Meta:
        verbose_name = _('group')
        verbose_name_plural = _('groups')

    def __str__(self):
        return self.name

    def natural_key(self):
        return (self.name,)
</code>```

and have other way?

答:
Try using this in your models.py

```<code>from django.contrib.auth.models import Group

Group.add_to_class('description', models.CharField(max_length=180,null=True, blank=True))
</code>```

Title: Django how to add a Group model field

Body:
i want add a description filed to Group，
how to do it?
edit source code?

@python_2_unicode_compatible
class Group(models.Model):
    name = models.CharField(_('name'), max_length=80, unique=True)
    description = models.CharField(_('description'), max_length=180,
        null=True, blank=True)  # add
    permissions = models.ManyToManyField(
        Permission,
        verbose_name=_('permissions'),
        blank=True,
    )

    objects = GroupManager()

    class Meta:
        verbose_name = _('group')
        verbose_name_plural = _('groups')

    def __str__(self):
        return self.name

    def natural_key(self):
        return (self.name,)

and have other way?

Body:
Try using this in your models.py

from django.contrib.auth.models import Group

Group.add_to_class('description', models.CharField(max_length=180,null=True, blank=True))