问:
ListView inside ScrollView is not scrolling on Android
I am having trouble with a scrolling ListView inside a ScrollView. I have an Activity which has some EditTexts in the top part and then a tab host with two tabs which have one ListView each. When the EditText views are focused, the soft keyboard comes up and as I  have a ScrollView, the content is scrollable. But the problem comes when there are more items in ListViews (ones in tabs), I am not able to scroll the ListView, even if there are more items.

The following is the layout XML:

```<code><?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="?backgroundImage"
    android:orientation="vertical">

  <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="50dip"
        android:layout_alignParentBottom="true"
        android:layout_margin="10dip"
        android:id="@+id/buttons">
    <Button
            android:text="Save"
            android:layout_margin="2dip"
            android:textSize="20dip"
            android:id="@+id/btnSaveorUpdate"
            android:layout_height="wrap_content"
            android:layout_width="145dip"></Button>
    <Button
            android:text="Cancel"
            android:layout_margin="2dip"
            android:textSize="20dip"
            android:id="@+id/btnCancelorDelete"
            android:layout_height="wrap_content"
            android:layout_width="145dip"></Button>
  </LinearLayout>
  <ScrollView
        android:layout_above="@id/buttons"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fillViewport="true"
        android:layout_margin="10dip">
    <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_margin="10dip">
      <TextView
                android:text="Bill details"
                android:textColor="?textColorDark"
                android:layout_alignParentTop="true"
                android:id="@+id/txtEnterDetails"
                android:textSize="25dip"
                android:textStyle="bold"
                android:layout_height="wrap_content"
                android:layout_width="fill_parent"
                android:layout_marginBottom="2dip"></TextView>
      <LinearLayout
                android:focusable="true"
                android:focusableInTouchMode="true"
                android:layout_width="0dip"
                android:layout_height="0dip" />
      <EditText
                android:layout_width="fill_parent"
                android:hint="Enter data"
                android:inputType="numberDecimal"
                android:id="@+id/txtSample"
                android:textSize="@dimen/editText"
                android:layout_height="@dimen/editTextHeight"
                android:text=""></EditText>
      <EditText
                android:layout_width="fill_parent"
                android:id="@+id/txtDescription"
                android:hint="Enter description"
                android:textSize="@dimen/editText"
                android:layout_height="@dimen/editTextHeight"
                android:inputType="text"
                android:text=""></EditText>
      <EditText
                android:layout_width="fill_parent"
                android:id="@+id/txtComment"
                android:hint="Enter comment (if any)"
                android:textSize="@dimen/editText"
                android:layout_height="@dimen/editTextHeight"
                android:inputType="text"
                android:text=""></EditText>
      <LinearLayout
                android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">
        <TextView
                    android:id="@+id/txtDate"
                    android:layout_width="wrap_content"
                    android:text=""
                    android:textSize="20dip"
                    android:textColor="?textColorDark"
                    android:layout_marginLeft="10dip"
                    android:layout_height="@dimen/editTextHeight"
                    android:layout_gravity="center_vertical" />
        <Button
                    android:id="@+id/btnPickDate"
                    android:layout_width="wrap_content"
                    android:layout_height="@dimen/editTextHeight"
                    android:text="Select date"
                    android:layout_margin="2dip"
                    android:textSize="15dip"
                    android:layout_gravity="center_vertical" />
      </LinearLayout>
      <TabHost
                android:id="@+id/tabhost"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">
        <LinearLayout
                    android:id="@+id/linearLayout1"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:orientation="vertical">
          <TabWidget
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:id="@android:id/tabs"></TabWidget>
          <FrameLayout
                        android:layout_width="fill_parent"
                        android:layout_height="fill_parent"
                        android:id="@android:id/tabcontent">
            <ScrollView
                            android:layout_above="@id/buttons"
                            android:layout_width="fill_parent"
                            android:layout_height="fill_parent"
                            android:fillViewport="true"
                            android:id="@+id/tab1">
              <LinearLayout
                                android:layout_width="fill_parent"
                                android:layout_height="wrap_content"
                                android:orientation="vertical">
                <TableLayout
                                    android:layout_height="wrap_content"
                                    android:layout_width="fill_parent">
                  <TableRow
                                        android:id="@+id/tableRow1"
                                        android:layout_marginLeft="2dip"
                                        android:layout_marginRight="5dip"
                                        android:layout_width="fill_parent"
                                        android:layout_height="wrap_content">
                    <LinearLayout
                                            android:layout_width="fill_parent"
                                            android:layout_height="wrap_content"
                                            android:orientation="horizontal">
                      <ImageView
                                                android:src="@drawable/ic_menu_invite"
                                                android:layout_width="40dip"
                                                android:layout_height="40dip"
                                                android:layout_gravity="center_vertical"></ImageView>
                      <TextView
                                                android:text="Add friend"
                                                android:layout_height="wrap_content"
                                                android:layout_width="fill_parent"
                                                android:layout_centerVertical="true"
                                                android:textColor="?textColorDark"
                                                android:textSize="@dimen/editText"
                                                android:layout_gravity="center_vertical" />
                    </LinearLayout>
                  </TableRow>
                  <TableRow
                                        android:layout_width="fill_parent"
                                        android:layout_height="wrap_content"
                                        android:layout_marginLeft="5dip"
                                        android:layout_marginRight="5dip">
                    <TextView
                                            android:id="@+id/txtData1"
                                            android:layout_width="170dip"
                                            android:layout_height="wrap_content"
                                            android:text="Data"
                                            android:textSize="14dip"
                                            android:textStyle="bold"
                                            android:textColor="#000000">
                    </TextView>
                    <TextView
                                            android:id="@+id/txtData2"
                                            android:layout_width="wrap_content"
                                            android:layout_height="wrap_content"
                                            android:text="Sample"
                                            android:textSize="13dip"
                                            android:textColor="#000000"></TextView>

                  </TableRow>
                </TableLayout>
                <ListView
                                    android:cacheColorHint="#00000000"
                                    android:id="@+id/ListView01"
                                    android:layout_height="wrap_content"
                                    android:layout_width="fill_parent" />
              </LinearLayout>
            </ScrollView>
            <LinearLayout
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:gravity="center_horizontal"
                            android:id="@+id/tab2"
                            android:orientation="vertical">
              <TableLayout
                                android:layout_height="wrap_content"
                                android:layout_width="fill_parent">
                <TableRow
                                    android:id="@+id/tableRow2"
                                    android:layout_marginLeft="2dip"
                                    android:layout_marginRight="5dip"
                                    android:layout_width="fill_parent"
                                    android:layout_height="wrap_content">
                  <LinearLayout
                                        android:layout_width="fill_parent"
                                        android:layout_height="wrap_content"
                                        android:orientation="horizontal">
                    <ImageView
                                            android:src="@drawable/ic_menu_invite"
                                            android:layout_width="40dip"
                                            android:layout_height="40dip"
                                            android:layout_gravity="center_vertical"></ImageView>
                    <TextView
                                            android:text="Sample"
                                            android:layout_height="wrap_content"
                                            android:layout_width="fill_parent"
                                            android:layout_centerVertical="true"
                                            android:textColor="?textColorDark"
                                            android:textSize="@dimen/editText"
                                            android:layout_gravity="center_vertical" />
                  </LinearLayout>
                </TableRow>
                <TableRow
                                    android:layout_width="fill_parent"
                                    android:layout_height="wrap_content"
                                    android:layout_marginLeft="5dip"
                                    android:layout_marginRight="5dip">
                  <TextView
                                        android:id="@+id/txtUser1"
                                        android:layout_width="170dip"
                                        android:layout_height="wrap_content"
                                        android:text="User"
                                        android:textSize="14dip"
                                        android:textStyle="bold"
                                        android:textColor="#000000">
                  </TextView>
                  <TextView
                                        android:id="@+id/txtUserData"
                                        android:layout_width="wrap_content"
                                        android:layout_height="wrap_content"
                                        android:text="UserData"
                                        android:textSize="13dip"
                                        android:textColor="#000000"></TextView>
                </TableRow>
              </TableLayout>

              <ListView
                                android:cacheColorHint="#00000000"
                                android:id="@+id/ListView02"
                                android:layout_height="wrap_content"
                                android:layout_width="fill_parent" />

            </LinearLayout>

          </FrameLayout>
        </LinearLayout>
      </TabHost>
    </LinearLayout>
  </ScrollView>
</RelativeLayout>
</code>```

Please can anyone tell me what the problem is here? I have another post on the ListView inside ScrollView problem, but they were of no use in my case.

答:
You shouldn't put a ListView inside a ScrollView because the ListView class implements its own scrolling and it just doesn't receive gestures because they all are handled by the parent ScrollView. I strongly recommend you to simplify your layout somehow. For example you can add views you want to be scrolled to the ListView as headers or footers.

UPDATE:

Starting from API Level 21 (Lollipop) nested scroll containers are officially supported by Android SDK. There're a bunch of methods in View and ViewGroup classes which provide this functionality. To make nested scrolling work on the Lollipop you have to enable it for a child scroll view by adding android:nestedScrollingEnabled="true" to its XML declaration or by explicitly calling setNestedScrollingEnabled(true).

If you want to make nested scrolling work on pre-Lollipop devices, which you probably do, you have to use corresponding utility classes from the Support library. First you have to replace you ScrollView with NestedScrollView. The latter implements both NestedScrollingParent and NestedScrollingChild so it can be used as a parent or a child scroll container.

But ListView doesn't support nested scrolling, therefore you need to subclass it and implement NestedScrollingChild. Fortunately, the Support library provides NestedScrollingChildHelper class, so you just have to create an instance of this class and call its methods from the corresponding methods of your view class.

Body:
I am having trouble with a scrolling ListView inside a ScrollView. I have an Activity which has some EditTexts in the top part and then a tab host with two tabs which have one ListView each. When the EditText views are focused, the soft keyboard comes up and as I  have a ScrollView, the content is scrollable. But the problem comes when there are more items in ListViews (ones in tabs), I am not able to scroll the ListView, even if there are more items.

The following is the layout XML:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="?backgroundImage"
    android:orientation="vertical">

  <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="50dip"
        android:layout_alignParentBottom="true"
        android:layout_margin="10dip"
        android:id="@+id/buttons">
    <Button
            android:text="Save"
            android:layout_margin="2dip"
            android:textSize="20dip"
            android:id="@+id/btnSaveorUpdate"
            android:layout_height="wrap_content"
            android:layout_width="145dip"></Button>
    <Button
            android:text="Cancel"
            android:layout_margin="2dip"
            android:textSize="20dip"
            android:id="@+id/btnCancelorDelete"
            android:layout_height="wrap_content"
            android:layout_width="145dip"></Button>
  </LinearLayout>
  <ScrollView
        android:layout_above="@id/buttons"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fillViewport="true"
        android:layout_margin="10dip">
    <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_margin="10dip">
      <TextView
                android:text="Bill details"
                android:textColor="?textColorDark"
                android:layout_alignParentTop="true"
                android:id="@+id/txtEnterDetails"
                android:textSize="25dip"
                android:textStyle="bold"
                android:layout_height="wrap_content"
                android:layout_width="fill_parent"
                android:layout_marginBottom="2dip"></TextView>
      <LinearLayout
                android:focusable="true"
                android:focusableInTouchMode="true"
                android:layout_width="0dip"
                android:layout_height="0dip" />
      <EditText
                android:layout_width="fill_parent"
                android:hint="Enter data"
                android:inputType="numberDecimal"
                android:id="@+id/txtSample"
                android:textSize="@dimen/editText"
                android:layout_height="@dimen/editTextHeight"
                android:text=""></EditText>
      <EditText
                android:layout_width="fill_parent"
                android:id="@+id/txtDescription"
                android:hint="Enter description"
                android:textSize="@dimen/editText"
                android:layout_height="@dimen/editTextHeight"
                android:inputType="text"
                android:text=""></EditText>
      <EditText
                android:layout_width="fill_parent"
                android:id="@+id/txtComment"
                android:hint="Enter comment (if any)"
                android:textSize="@dimen/editText"
                android:layout_height="@dimen/editTextHeight"
                android:inputType="text"
                android:text=""></EditText>
      <LinearLayout
                android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">
        <TextView
                    android:id="@+id/txtDate"
                    android:layout_width="wrap_content"
                    android:text=""
                    android:textSize="20dip"
                    android:textColor="?textColorDark"
                    android:layout_marginLeft="10dip"
                    android:layout_height="@dimen/editTextHeight"
                    android:layout_gravity="center_vertical" />
        <Button
                    android:id="@+id/btnPickDate"
                    android:layout_width="wrap_content"
                    android:layout_height="@dimen/editTextHeight"
                    android:text="Select date"
                    android:layout_margin="2dip"
                    android:textSize="15dip"
                    android:layout_gravity="center_vertical" />
      </LinearLayout>
      <TabHost
                android:id="@+id/tabhost"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">
        <LinearLayout
                    android:id="@+id/linearLayout1"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:orientation="vertical">
          <TabWidget
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:id="@android:id/tabs"></TabWidget>
          <FrameLayout
                        android:layout_width="fill_parent"
                        android:layout_height="fill_parent"
                        android:id="@android:id/tabcontent">
            <ScrollView
                            android:layout_above="@id/buttons"
                            android:layout_width="fill_parent"
                            android:layout_height="fill_parent"
                            android:fillViewport="true"
                            android:id="@+id/tab1">
              <LinearLayout
                                android:layout_width="fill_parent"
                                android:layout_height="wrap_content"
                                android:orientation="vertical">
                <TableLayout
                                    android:layout_height="wrap_content"
                                    android:layout_width="fill_parent">
                  <TableRow
                                        android:id="@+id/tableRow1"
                                        android:layout_marginLeft="2dip"
                                        android:layout_marginRight="5dip"
                                        android:layout_width="fill_parent"
                                        android:layout_height="wrap_content">
                    <LinearLayout
                                            android:layout_width="fill_parent"
                                            android:layout_height="wrap_content"
                                            android:orientation="horizontal">
                      <ImageView
                                                android:src="@drawable/ic_menu_invite"
                                                android:layout_width="40dip"
                                                android:layout_height="40dip"
                                                android:layout_gravity="center_vertical"></ImageView>
                      <TextView
                                                android:text="Add friend"
                                                android:layout_height="wrap_content"
                                                android:layout_width="fill_parent"
                                                android:layout_centerVertical="true"
                                                android:textColor="?textColorDark"
                                                android:textSize="@dimen/editText"
                                                android:layout_gravity="center_vertical" />
                    </LinearLayout>
                  </TableRow>
                  <TableRow
                                        android:layout_width="fill_parent"
                                        android:layout_height="wrap_content"
                                        android:layout_marginLeft="5dip"
                                        android:layout_marginRight="5dip">
                    <TextView
                                            android:id="@+id/txtData1"
                                            android:layout_width="170dip"
                                            android:layout_height="wrap_content"
                                            android:text="Data"
                                            android:textSize="14dip"
                                            android:textStyle="bold"
                                            android:textColor="#000000">
                    </TextView>
                    <TextView
                                            android:id="@+id/txtData2"
                                            android:layout_width="wrap_content"
                                            android:layout_height="wrap_content"
                                            android:text="Sample"
                                            android:textSize="13dip"
                                            android:textColor="#000000"></TextView>

                  </TableRow>
                </TableLayout>
                <ListView
                                    android:cacheColorHint="#00000000"
                                    android:id="@+id/ListView01"
                                    android:layout_height="wrap_content"
                                    android:layout_width="fill_parent" />
              </LinearLayout>
            </ScrollView>
            <LinearLayout
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:gravity="center_horizontal"
                            android:id="@+id/tab2"
                            android:orientation="vertical">
              <TableLayout
                                android:layout_height="wrap_content"
                                android:layout_width="fill_parent">
                <TableRow
                                    android:id="@+id/tableRow2"
                                    android:layout_marginLeft="2dip"
                                    android:layout_marginRight="5dip"
                                    android:layout_width="fill_parent"
                                    android:layout_height="wrap_content">
                  <LinearLayout
                                        android:layout_width="fill_parent"
                                        android:layout_height="wrap_content"
                                        android:orientation="horizontal">
                    <ImageView
                                            android:src="@drawable/ic_menu_invite"
                                            android:layout_width="40dip"
                                            android:layout_height="40dip"
                                            android:layout_gravity="center_vertical"></ImageView>
                    <TextView
                                            android:text="Sample"
                                            android:layout_height="wrap_content"
                                            android:layout_width="fill_parent"
                                            android:layout_centerVertical="true"
                                            android:textColor="?textColorDark"
                                            android:textSize="@dimen/editText"
                                            android:layout_gravity="center_vertical" />
                  </LinearLayout>
                </TableRow>
                <TableRow
                                    android:layout_width="fill_parent"
                                    android:layout_height="wrap_content"
                                    android:layout_marginLeft="5dip"
                                    android:layout_marginRight="5dip">
                  <TextView
                                        android:id="@+id/txtUser1"
                                        android:layout_width="170dip"
                                        android:layout_height="wrap_content"
                                        android:text="User"
                                        android:textSize="14dip"
                                        android:textStyle="bold"
                                        android:textColor="#000000">
                  </TextView>
                  <TextView
                                        android:id="@+id/txtUserData"
                                        android:layout_width="wrap_content"
                                        android:layout_height="wrap_content"
                                        android:text="UserData"
                                        android:textSize="13dip"
                                        android:textColor="#000000"></TextView>
                </TableRow>
              </TableLayout>

              <ListView
                                android:cacheColorHint="#00000000"
                                android:id="@+id/ListView02"
                                android:layout_height="wrap_content"
                                android:layout_width="fill_parent" />

            </LinearLayout>

          </FrameLayout>
        </LinearLayout>
      </TabHost>
    </LinearLayout>
  </ScrollView>
</RelativeLayout>

Please can anyone tell me what the problem is here? I have another post on the ListView inside ScrollView problem, but they were of no use in my case.


来源: stackexchange

问:
Forcing a Tkinter.ttk Treeview widget to resize after shrinking its column widths
Background

Python-2.7.14 x64, Tk-8.5.15 (bundled)

It is well-documented that the Treeview widget in Tk has a lot of issues, and Tkinter, being a thin wrapper, doesn't do much to deal with them.  A common problem is getting a Treeview in browse mode to work correctly with a horizontal scrollbar.  Setting the width of the overall Treeview requires setting the width of each column.  But if one has a lot of columns, this stretches the parent container out horizontally, and doesn't activate the horizontal scrollbar.

The solution that I have found is, at design time, for each column, to set width to the desired size you want and cache this value somewhere safe.  When you add, edit, or delete a row, you need to walk the columns and query their current width value, and if it's larger than your cached width, set width back to the original cached value and also set minwidth to the current column width.  The last column needs its stretch property set to "True" as well, so it can consume any remaining space left over.  This activates the horizontal scrollbar and allows it to pan the contents of the Treeview appropriately, without changing the width of the overall widget.

Caveat: At some point, Tk internally resets width to equal minwidth, but does not force a redraw right away.  You get surprised later on when you change the widget, such as by adding or deleting a row, so you have to repeat the above every time the widget is changed.  This is not a really big issue if you catch all of the places where a redraw can happen.

Problem

Changing a property of a Ttk style triggers a forced redraw of the entire application, so the caveat I mentioned above pops up, the Treeview widget expands horizonatlly, and the horizontal scrollbar deactivates.

Walkthrough

The below code demonstrates:

# imports
from Tkinter import *
from ttk import *
from tkFont import *

# root
root=Tk()

# font config
ff10=Font(family="Consolas", size=10)
ff10b=Font(family="Consolas", size=10, weight=BOLD)

# style config
s=Style()
s.configure("Foo2.Treeview", font=ff10, padding=1)
s.configure("Foo2.Treeview.Heading", font=ff10b, padding=1)

# init a treeview
tv=Treeview(root, selectmode=BROWSE, height=8, show="tree headings", columns=("key", "value"), style="Foo2.Treeview")
tv.heading("key", text="Key", anchor=W)
tv.heading("value", text="Value", anchor=W)
tv.column("#0", width=0, stretch=False)
tv.column("key", width=78, stretch=False)
tv.column("value", width=232, stretch=False)
tv.grid(padx=8, pady=(8,0))

# init a scrollbar
sb=Scrollbar(root, orient=HORIZONTAL)
sb.grid(row=1, sticky=EW, padx=8, pady=(0,8))
tv.configure(xscrollcommand=sb.set)
sb.configure(command=tv.xview)

# insert a row that has data longer than the initial column width and
# then update width/minwidth to activate the scrollbar.
tv.insert("", END, values=("foobar", "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"))
tv.column("key", width=78, stretch=False, minwidth=78)
tv.column("value", width=232, stretch=True, minwidth=372)
```

<p><br/>
The resulting window will look something like this:</p>

<p><img src="https://i.stack.imgur.com/7bv4P.png" alt="Example Treeview widget w/ horizontal scrollbar"></p>

<p><br/>
Note that the horizontal scrollbar is active, and that there is a slight overflow of the last column beyond the widget's edge.  The last two calls to <code>tv.column</code> are what enable this, but dumping the column properties of the last column, we see that Tk has silently updated <code>width</code> and <code>minwidth</code> to be the same:</p>

<pre class="lang-python prettyprint-override"><code>tv.column("value")
{'minwidth': 372, 'width': 372, 'id': 'value', 'anchor': u'w', 'stretch': 1}
</code>```

Changing any property of any style will trigger a forced redraw of the widget.  For example, the next line sets the foreground color to red for a derived Checkbutton style class:

s.configure("Foo2.TCheckbutton", foreground="red")
```

<p><br/>
This is the Treeview widget now:</p>

<p><img src="https://i.stack.imgur.com/7NU1P.png" alt="Treeview widget after changing a ttk.Style property"></p>

<p><br/>
The problem now is <strong>shrinking</strong> the entire widget back.  The last column can be forced back to its original size by setting <code>width</code> to the originally-cached size, <code>stretch</code> to "False", and <code>minwidth</code> to the maximum column size:</p>

<pre class="lang-python prettyprint-override"><code>tv.column("value", width=232, stretch=False, minwidth=372)
</code>```

But the width of the Treeview widget did not shrink back.

I've found two possible solutions, both in a bind to the <Configure> event, using the last display column:

Indicate a change of themes:

```<code>tv.column("value", width=232, stretch=True, minwidth=372)
tv.event_generate("<<ThemeChanged>>")
</code>```

Hide and re-show:

```<code>tv.grid_remove()
tv.column("value", width=232, stretch=True, minwidth=372)
tv.grid()
</code>```

Both work because they are the only ways I can find to invoke the internal Tk function TtkResizeWidget().  The first works because <<ThemeChanged>> forces a complete recalculation of the widget's geometry, while the second works because Treeview will call TtkResizeWidget() if it is in an unmapped state when the column is reconfigured.

The downside to both methods is you can sometimes see the window expand for a single frame and then contract back.  This is why I consider both unoptimal and am hoping that someone else knows of a better approach.  Or at least of a bindable event that happens either before <Configure> or before the expansion happens, from which I can use one of the above methods with.

Some references indicating that this has been an issue in Tk for a long time:

Treeview's issues w/ a horizontal scrollbar on the Tcl Wiki (search for [ofv] 2009-05-30).

Ticket #3519160.

Message on Tkinter-discuss mailing list.

And, the issue is still reproducible on Python-3.6.4, which includes Tk-8.6.6.

答:
Your instinct of resetting the column widths to initial values is good. Instead of binding those calls to <Configure>, which causes flickering because it redraws the screen a second time right after the first call, let's reset the column widths before the first screen redraw so nothing gets changed and no second call is necessary:

```<code># imports
from tkinter import *
from tkinter.ttk import *
from tkinter.font import *

# subclass treeview for the convenience of overriding the column method
class ScrollableTV(Treeview):
  def __init__(self, master, **kw):
    super().__init__(master, **kw)
    self.columns=[]

  # column now records the name and details of each column in the TV just before they're added
  def column(self, column, **kw):
    if column not in [column[0] for column in self.columns]:
      self.columns.append((column, kw))
    super().column(column, **kw)

  # keep a modified, heavier version of Style around that you can use in cases where ScrollableTVs are involved
  class ScrollableStyle(Style):
    def __init__(self, tv, *args, **kw):
      super().__init__(*args, **kw)
      self.tv = tv

    # override Style's configure method to reset all its TV's columns to their initial settings before it returns into TtkResizeWidget(). since we undo the TV's automatic changes before the screen redraws, there's no need to cause flickering by redrawing a second time after the width is reset
    def configure(self, item, **kw):
      super().configure(item, **kw)
      for column in self.tv.columns:
        name, kw = column
        self.tv.column(name, **kw)

# root
root=Tk()

# font config
ff10=Font(family="Consolas", size=10)
ff10b=Font(family="Consolas", size=10, weight=BOLD)

# init a scrollabletv
tv=ScrollableTV(root, selectmode=BROWSE, height=8, show="tree headings", columns=("key", "value"), style="Foo2.Treeview")
tv.heading("key", text="Key", anchor=W)
tv.heading("value", text="Value", anchor=W)
tv.column("#0", width=0, stretch=False)
tv.column("key", width=78, stretch=False)
tv.column("value", minwidth=372, width=232, stretch=True)
tv.grid(padx=8, pady=(8,0))

# style config. use a ScrollableStyle and pass in the ScrollableTV whose configure needs to be managed. if you had more than one ScrollableTV, you could modify ScrollableStyle to store a list of them and operate configure on each of them
s=ScrollableTV.ScrollableStyle(tv)
s.configure("Foo2.Treeview", font=ff10, padding=1)
s.configure("Foo2.Treeview.Heading", font=ff10b, padding=1)

# init a scrollbar
sb=Scrollbar(root, orient=HORIZONTAL)
sb.grid(row=1, sticky=EW, padx=8, pady=(0,8))
tv.configure(xscrollcommand=sb.set)
sb.configure(command=tv.xview)

# insert a row that has data longer than the initial column width and
# then update width/minwidth to activate the scrollbar.
tv.insert("", END, values=("foobar", "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"))
# we don't need to meddle with the stretch and minwidth values here

#click in the TV to test
def conf(event):
  s.configure("Foo2.TCheckbutton", foreground="red")
tv.bind("<Button-1>", conf, add="+")
root.mainloop()
</code>```

Tested on python 3.8.2, tkinter 8.6

ContentLicense: CC BY-SA 3.0

Body:
Background

Python-2.7.14 x64, Tk-8.5.15 (bundled)

It is well-documented that the Treeview widget in Tk has a lot of issues, and Tkinter, being a thin wrapper, doesn't do much to deal with them.  A common problem is getting a Treeview in browse mode to work correctly with a horizontal scrollbar.  Setting the width of the overall Treeview requires setting the width of each column.  But if one has a lot of columns, this stretches the parent container out horizontally, and doesn't activate the horizontal scrollbar.

The solution that I have found is, at design time, for each column, to set width to the desired size you want and cache this value somewhere safe.  When you add, edit, or delete a row, you need to walk the columns and query their current width value, and if it's larger than your cached width, set width back to the original cached value and also set minwidth to the current column width.  The last column needs its stretch property set to "True" as well, so it can consume any remaining space left over.  This activates the horizontal scrollbar and allows it to pan the contents of the Treeview appropriately, without changing the width of the overall widget.

Caveat: At some point, Tk internally resets width to equal minwidth, but does not force a redraw right away.  You get surprised later on when you change the widget, such as by adding or deleting a row, so you have to repeat the above every time the widget is changed.  This is not a really big issue if you catch all of the places where a redraw can happen.

Problem

Changing a property of a Ttk style triggers a forced redraw of the entire application, so the caveat I mentioned above pops up, the Treeview widget expands horizonatlly, and the horizontal scrollbar deactivates.

Walkthrough

The below code demonstrates:

# imports
from Tkinter import *
from ttk import *
from tkFont import *

# root
root=Tk()

# font config
ff10=Font(family="Consolas", size=10)
ff10b=Font(family="Consolas", size=10, weight=BOLD)

# style config
s=Style()
s.configure("Foo2.Treeview", font=ff10, padding=1)
s.configure("Foo2.Treeview.Heading", font=ff10b, padding=1)

# init a treeview
tv=Treeview(root, selectmode=BROWSE, height=8, show="tree headings", columns=("key", "value"), style="Foo2.Treeview")
tv.heading("key", text="Key", anchor=W)
tv.heading("value", text="Value", anchor=W)
tv.column("#0", width=0, stretch=False)
tv.column("key", width=78, stretch=False)
tv.column("value", width=232, stretch=False)
tv.grid(padx=8, pady=(8,0))

# init a scrollbar
sb=Scrollbar(root, orient=HORIZONTAL)
sb.grid(row=1, sticky=EW, padx=8, pady=(0,8))
tv.configure(xscrollcommand=sb.set)
sb.configure(command=tv.xview)

# insert a row that has data longer than the initial column width and
# then update width/minwidth to activate the scrollbar.
tv.insert("", END, values=("foobar", "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"))
tv.column("key", width=78, stretch=False, minwidth=78)
tv.column("value", width=232, stretch=True, minwidth=372)

The resulting window will look something like this:

Note that the horizontal scrollbar is active, and that there is a slight overflow of the last column beyond the widget's edge.  The last two calls to tv.column are what enable this, but dumping the column properties of the last column, we see that Tk has silently updated width and minwidth to be the same:

tv.column("value")
{'minwidth': 372, 'width': 372, 'id': 'value', 'anchor': u'w', 'stretch': 1}

Changing any property of any style will trigger a forced redraw of the widget.  For example, the next line sets the foreground color to red for a derived Checkbutton style class:

s.configure("Foo2.TCheckbutton", foreground="red")

This is the Treeview widget now:

The problem now is shrinking the entire widget back.  The last column can be forced back to its original size by setting width to the originally-cached size, stretch to "False", and minwidth to the maximum column size:

tv.column("value", width=232, stretch=False, minwidth=372)

But the width of the Treeview widget did not shrink back.

I've found two possible solutions, both in a bind to the <Configure> event, using the last display column:

Indicate a change of themes:

tv.column("value", width=232, stretch=True, minwidth=372)
tv.event_generate("<<ThemeChanged>>")

Hide and re-show:

tv.grid_remove()
tv.column("value", width=232, stretch=True, minwidth=372)
tv.grid()

Both work because they are the only ways I can find to invoke the internal Tk function TtkResizeWidget().  The first works because <<ThemeChanged>> forces a complete recalculation of the widget's geometry, while the second works because Treeview will call TtkResizeWidget() if it is in an unmapped state when the column is reconfigured.

The downside to both methods is you can sometimes see the window expand for a single frame and then contract back.  This is why I consider both unoptimal and am hoping that someone else knows of a better approach.  Or at least of a bindable event that happens either before <Configure> or before the expansion happens, from which I can use one of the above methods with.

Some references indicating that this has been an issue in Tk for a long time:

Treeview's issues w/ a horizontal scrollbar on the Tcl Wiki (search for [ofv] 2009-05-30).

Ticket #3519160.

Message on Tkinter-discuss mailing list.

And, the issue is still reproducible on Python-3.6.4, which includes Tk-8.6.6.

Body:
Your instinct of resetting the column widths to initial values is good. Instead of binding those calls to <Configure>, which causes flickering because it redraws the screen a second time right after the first call, let's reset the column widths before the first screen redraw so nothing gets changed and no second call is necessary:

# imports
from tkinter import *
from tkinter.ttk import *
from tkinter.font import *

# subclass treeview for the convenience of overriding the column method
class ScrollableTV(Treeview):
  def __init__(self, master, **kw):
    super().__init__(master, **kw)
    self.columns=[]

  # column now records the name and details of each column in the TV just before they're added
  def column(self, column, **kw):
    if column not in [column[0] for column in self.columns]:
      self.columns.append((column, kw))
    super().column(column, **kw)

  # keep a modified, heavier version of Style around that you can use in cases where ScrollableTVs are involved
  class ScrollableStyle(Style):
    def __init__(self, tv, *args, **kw):
      super().__init__(*args, **kw)
      self.tv = tv

    # override Style's configure method to reset all its TV's columns to their initial settings before it returns into TtkResizeWidget(). since we undo the TV's automatic changes before the screen redraws, there's no need to cause flickering by redrawing a second time after the width is reset
    def configure(self, item, **kw):
      super().configure(item, **kw)
      for column in self.tv.columns:
        name, kw = column
        self.tv.column(name, **kw)

# root
root=Tk()

# font config
ff10=Font(family="Consolas", size=10)
ff10b=Font(family="Consolas", size=10, weight=BOLD)

# init a scrollabletv
tv=ScrollableTV(root, selectmode=BROWSE, height=8, show="tree headings", columns=("key", "value"), style="Foo2.Treeview")
tv.heading("key", text="Key", anchor=W)
tv.heading("value", text="Value", anchor=W)
tv.column("#0", width=0, stretch=False)
tv.column("key", width=78, stretch=False)
tv.column("value", minwidth=372, width=232, stretch=True)
tv.grid(padx=8, pady=(8,0))

# style config. use a ScrollableStyle and pass in the ScrollableTV whose configure needs to be managed. if you had more than one ScrollableTV, you could modify ScrollableStyle to store a list of them and operate configure on each of them
s=ScrollableTV.ScrollableStyle(tv)
s.configure("Foo2.Treeview", font=ff10, padding=1)
s.configure("Foo2.Treeview.Heading", font=ff10b, padding=1)

# init a scrollbar
sb=Scrollbar(root, orient=HORIZONTAL)
sb.grid(row=1, sticky=EW, padx=8, pady=(0,8))
tv.configure(xscrollcommand=sb.set)
sb.configure(command=tv.xview)

# insert a row that has data longer than the initial column width and
# then update width/minwidth to activate the scrollbar.
tv.insert("", END, values=("foobar", "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"))
# we don't need to meddle with the stretch and minwidth values here

#click in the TV to test
def conf(event):
  s.configure("Foo2.TCheckbutton", foreground="red")
tv.bind("<Button-1>", conf, add="+")
root.mainloop()

Tested on python 3.8.2, tkinter 8.6

ContentLicense: CC BY-SA 4.0


问:
Postgresql Container is not running in docker-compose file - Why is this?
I am trying to figure out why I am getting an error about postgresql not running in my project.
It is not connecting through Flask, nor when I try to access it through bash using the command
docker-compose run postgres bash then psql returns the error:

```<code>bash-5.0# psql
psql: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
</code>```

I tried running --force-recreate and to drop all abandoned orphan containers but this has not seemed to work. Similarly, I made sure it does not interfere with my local postgresql installation by uninstalling the local one and removing all files. I am pretty stumped on this.

Here is my docker-compose file:

```<code>version: "3"

services:

  webapp:
    build: .
    container_name: webapp
    ports:
      - "5000:5000"

  postgres:
    image: postgres:11-alpine
    container_name: postgres
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_DB=tmp
      - POSTGRES_USER=tmp
      - POSTGRES_PASSWORD=tmp_password
    volumes:  # Persist the db data
      - database-data:/var/lib/postgresql/data

volumes:
  database-data:

</code>```

Any help is appreciated.

答:
Please try the below docker-compose.yml in which depends_on, healthcheck and links are added as web service depends on db service.

```<code>version: "3"
services:
  webapp:
    build: .
    container_name: webapp
    ports:
      - "5000:5000"
    links:
      - postgres
    depends_on:
      - postgres

  postgres:
    image: postgres:11-alpine
    container_name: postgres
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_DB=tmp
      - POSTGRES_USER=tmp
      - POSTGRES_PASSWORD=tmp_password
    volumes:  # Persist the db data
      - database-data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  database-data:

</code>```

Body:
I am trying to figure out why I am getting an error about postgresql not running in my project.
It is not connecting through Flask, nor when I try to access it through bash using the command
docker-compose run postgres bash then psql returns the error:

bash-5.0# psql
psql: could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

I tried running --force-recreate and to drop all abandoned orphan containers but this has not seemed to work. Similarly, I made sure it does not interfere with my local postgresql installation by uninstalling the local one and removing all files. I am pretty stumped on this.

Here is my docker-compose file:

version: "3"

services:

  webapp:
    build: .
    container_name: webapp
    ports:
      - "5000:5000"

  postgres:
    image: postgres:11-alpine
    container_name: postgres
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_DB=tmp
      - POSTGRES_USER=tmp
      - POSTGRES_PASSWORD=tmp_password
    volumes:  # Persist the db data
      - database-data:/var/lib/postgresql/data

volumes:
  database-data:

Any help is appreciated.

Body:
Please try the below docker-compose.yml in which depends_on, healthcheck and links are added as web service depends on db service.

version: "3"
services:
  webapp:
    build: .
    container_name: webapp
    ports:
      - "5000:5000"
    links:
      - postgres
    depends_on:
      - postgres

  postgres:
    image: postgres:11-alpine
    container_name: postgres
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_DB=tmp
      - POSTGRES_USER=tmp
      - POSTGRES_PASSWORD=tmp_password
    volumes:  # Persist the db data
      - database-data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  database-data:


问:
Model gives great training and testing accuracy but not working well when doing prediction
Hi there I am doing transfer learning with deep learning using VGG16 pre-trained model. I want to extract features from VGG16 to build my own model as I only have access to CPU. Here is my build and train setup.

```<code>import os
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from sklearn.metrics import confusion_matrix

from keras.applications import Xception, VGG16, ResNet50
conv_base = VGG16(weights='imagenet',include_top=False,input_shape=(224, 224, 3))

conv_base.summary()
base_dir = 'NewDCDatatset'

train_dir = os.path.join(base_dir, 'Train')
validation_dir = os.path.join(base_dir, 'Validation')
test_dir = os.path.join(base_dir, 'Test')

datagen = ImageDataGenerator(rescale=1./255)
batch_size = 5

def extract_features(directory, sample_count):
    features = np.zeros(shape=(sample_count, 7 , 7 , 512))
    labels = np.zeros(shape=(sample_count,2))
    generator = datagen.flow_from_directory(directory,target_size=(224, 224),batch_size=batch_size,class_mode='categorical')
    i = 0
    for inputs_batch, labels_batch in generator:
        features_batch = conv_base.predict(inputs_batch)
        features[i * batch_size : (i + 1) * batch_size] = features_batch
        labels[i * batch_size : (i + 1) * batch_size] = labels_batch
        i += 1
        if i * batch_size >= sample_count:
            break
    return features, labels

train_features, train_labels = extract_features(train_dir, 2000)
validation_features, validation_labels = extract_features(validation_dir,420 )
test_features, test_labels = extract_features(test_dir, 420)

train_features = np.reshape(train_features, (2000, 7 * 7 * 512))
validation_features = np.reshape(validation_features, (420, 7 * 7 * 512))
test_features = np.reshape(test_features, (420, 7 * 7 * 512))

from keras import models
from keras import layers
from keras import optimizers
model = models.Sequential()
model.add(layers.Dense(64, activation='relu', input_dim=7 * 7 * 512))
model.add(layers.Dense(2, activation='softmax'))
model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['acc'])
history = model.fit(train_features, train_labels,epochs=2,batch_size=5,shuffle=True)
print(model.evaluate(test_features,test_labels))

model.save('TLFACE.h5')

#predictions = model.predict_generator(test_features,steps = 5)

#print(predictions)
</code>```

And here is the setup for the way I am predicting the new images through my model to classify cat and dog but I am not getting that much accurate results that seldom I am able to correctly classify any image. I don't what mistake I am doing, is it matter of resizing image or what when predicting.

```<code>from keras.models import load_model
deep = load_model('TLFACE.h5')

from PIL import Image
import numpy as np
import cv2

file_nam = '4705.jpg'
img = cv2.imread(file_nam)
img = cv2.imshow('frame',img)
cv2.waitKey(1000)

img = Image.open(file_nam).convert("L")

img = img.resize((256,98))
im2arr = np.array(img)
im2arr = im2arr.reshape(1,25088)
# Predicting the Test set r1esults
y_pred = deep.predict(im2arr)
print(y_pred)
print(y_pred[0][0])
</code>```

答:
According to your code, your model receives a feature vector of size 1 x 7*7*512 = 1 x 25088. This features is the encoding of an image in the conv_base model (implemented in your extract_features method).

However in your example at prediction time you just take an image, reshape it to (256,98), then flatten to (1,25088). You totally skip the extract_features phase. In other words, you try to predict on a totally different data then you use during training (and the automated testing under the fit method). You need to use the exact same preprocessing method for testing, which means first rescale the image to size 224x224x3, then extracting the features using the conv_base model, and finally use your new model to perform the prediction over the extracted features.

Having said that, I want to suggest that you use very "dirty" implementation, this is not organized properly and it easy to get confused that way. You actually want to build a single model that perform classification on an image, and not do all the heavy coding of extracting features etc. to do so you can just use something like:

pretrained_vgg16 = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
pretrained_vgg16.trainable = False  # This is important if you don't want to modify your base model weights during training.
new_model = models.Sequential([pretrained_vgg16,
                               layers.Flatten(),
                               layers.Dense(64, activation='relu'),
                               layers.Dense(2,activation='softmax')])
```

In addition, please note that it is very importnat to decide if you want to modify the pre-trained model weights during training or not. if not, you need to envoke the pretrained_vgg16.trainable = False line.

Now you can use new_model.fit with a generator that load the images and rescale them to 224x224x3, without explicitly extracting the features. Another important comment is that the original VGG16 model was probably trained on a normalized data (which means pixels values were normalized to be in range [0,1]), you also need to perform the same preprocessing to your images for ideal results.

Body:
Hi there I am doing transfer learning with deep learning using VGG16 pre-trained model. I want to extract features from VGG16 to build my own model as I only have access to CPU. Here is my build and train setup.

import os
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from sklearn.metrics import confusion_matrix

from keras.applications import Xception, VGG16, ResNet50
conv_base = VGG16(weights='imagenet',include_top=False,input_shape=(224, 224, 3))

conv_base.summary()
base_dir = 'NewDCDatatset'

train_dir = os.path.join(base_dir, 'Train')
validation_dir = os.path.join(base_dir, 'Validation')
test_dir = os.path.join(base_dir, 'Test')

datagen = ImageDataGenerator(rescale=1./255)
batch_size = 5

def extract_features(directory, sample_count):
    features = np.zeros(shape=(sample_count, 7 , 7 , 512))
    labels = np.zeros(shape=(sample_count,2))
    generator = datagen.flow_from_directory(directory,target_size=(224, 224),batch_size=batch_size,class_mode='categorical')
    i = 0
    for inputs_batch, labels_batch in generator:
        features_batch = conv_base.predict(inputs_batch)
        features[i * batch_size : (i + 1) * batch_size] = features_batch
        labels[i * batch_size : (i + 1) * batch_size] = labels_batch
        i += 1
        if i * batch_size >= sample_count:
            break
    return features, labels

train_features, train_labels = extract_features(train_dir, 2000)
validation_features, validation_labels = extract_features(validation_dir,420 )
test_features, test_labels = extract_features(test_dir, 420)

train_features = np.reshape(train_features, (2000, 7 * 7 * 512))
validation_features = np.reshape(validation_features, (420, 7 * 7 * 512))
test_features = np.reshape(test_features, (420, 7 * 7 * 512))

from keras import models
from keras import layers
from keras import optimizers
model = models.Sequential()
model.add(layers.Dense(64, activation='relu', input_dim=7 * 7 * 512))
model.add(layers.Dense(2, activation='softmax'))
model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['acc'])
history = model.fit(train_features, train_labels,epochs=2,batch_size=5,shuffle=True)
print(model.evaluate(test_features,test_labels))

model.save('TLFACE.h5')

#predictions = model.predict_generator(test_features,steps = 5)

#print(predictions)

And here is the setup for the way I am predicting the new images through my model to classify cat and dog but I am not getting that much accurate results that seldom I am able to correctly classify any image. I don't what mistake I am doing, is it matter of resizing image or what when predicting.

from keras.models import load_model
deep = load_model('TLFACE.h5')

from PIL import Image
import numpy as np
import cv2

file_nam = '4705.jpg'
img = cv2.imread(file_nam)
img = cv2.imshow('frame',img)
cv2.waitKey(1000)

img = Image.open(file_nam).convert("L")

img = img.resize((256,98))
im2arr = np.array(img)
im2arr = im2arr.reshape(1,25088)
# Predicting the Test set r1esults
y_pred = deep.predict(im2arr)
print(y_pred)
print(y_pred[0][0])

Body:
According to your code, your model receives a feature vector of size 1 x 7*7*512 = 1 x 25088. This features is the encoding of an image in the conv_base model (implemented in your extract_features method).

However in your example at prediction time you just take an image, reshape it to (256,98), then flatten to (1,25088). You totally skip the extract_features phase. In other words, you try to predict on a totally different data then you use during training (and the automated testing under the fit method). You need to use the exact same preprocessing method for testing, which means first rescale the image to size 224x224x3, then extracting the features using the conv_base model, and finally use your new model to perform the prediction over the extracted features.

Having said that, I want to suggest that you use very "dirty" implementation, this is not organized properly and it easy to get confused that way. You actually want to build a single model that perform classification on an image, and not do all the heavy coding of extracting features etc. to do so you can just use something like:

pretrained_vgg16 = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
pretrained_vgg16.trainable = False  # This is important if you don't want to modify your base model weights during training.
new_model = models.Sequential([pretrained_vgg16,
                               layers.Flatten(),
                               layers.Dense(64, activation='relu'),
                               layers.Dense(2,activation='softmax')])

In addition, please note that it is very importnat to decide if you want to modify the pre-trained model weights during training or not. if not, you need to envoke the pretrained_vgg16.trainable = False line.

Now you can use new_model.fit with a generator that load the images and rescale them to 224x224x3, without explicitly extracting the features. Another important comment is that the original VGG16 model was probably trained on a normalized data (which means pixels values were normalized to be in range [0,1]), you also need to perform the same preprocessing to your images for ideal results.


问:
Xamarin Forms webview does not accept or send cookies sent by webpages
Trying to use a webview in Xamarin Forms project for iOS and Android.

In Android, upon navigating to a webpage that sets cookies, no cookies are set in the webview.

Due to this, cookies are not sent also along with the subsequent requests.

Do I need to do anything to enable the "normal" browser cookie behaviour for webview ?

Currently initializing as follows:

vw1.Cookies = New CookieContainer(), where vw1 is the instance of WebView

答:
Take a look at xamarin forms 4.6
https://github.com/xamarin/Xamarin.Forms/issues/3262</p>


问:
Can't get <select> input from form?
I can figure out how to loop through input and select. My function below does not include select lists.

Any help welcome.

```<code>$('input', '#consumer_form').each(function(key, value)
{
    if ((this.type === "radio" || this.type === "checkbox") && this.checked === false) {
        return;
    } else {
         val = this.value;
    }

         //alert($('#'+this.id).attr('name')+'='+replaceAmp(val));
             formData += '&'+this.name+'='+replaceAmp(val);

});
</code>```

Thanks

答: I believe it's $(":input") you're need if you want to loop through all the elements in the form http://api.jquery.com/input-selector/    (you don't have a colon there).</p>

Title: Can't get <select> input from form?

Body:
I can figure out how to loop through input and select. My function below does not include select lists.

Any help welcome.

$('input', '#consumer_form').each(function(key, value)
{
    if ((this.type === "radio" || this.type === "checkbox") && this.checked === false) {
        return;
    } else {
         val = this.value;
    }

         //alert($('#'+this.id).attr('name')+'='+replaceAmp(val));
             formData += '&'+this.name+'='+replaceAmp(val);

});

Thanks


问:
What does Early termination of worker puma log mean and why is it happening?
For my Elastic Beanstalk instance, I am getting a 504 status code response whenever I visit it. When I tail the logs I see the following log on the puma app server:

```<code>==> /var/log/puma/puma.log <==
[27240] Early termination of worker
[27245] Early termination of worker
[27249] Early termination of worker
[27253] Early termination of worker
[27257] Early termination of worker
[27261] Early termination of worker
[27265] Early termination of worker
[27269] Early termination of worker
[27273] Early termination of worker
[27277] Early termination of worker
</code>```

What does Early termination of worker mean and why is it happening? Moreover, could the log be indicating the cause of my timeout error I am facing in my remote environment? The rails app and puma run perfectly on my local machine (Mac OS Catalina 10.15). However, in my remote Elastic beanstalk environment as stated above I am getting a timeout 504 error and the only thing I see in the logs is the above puma log.

This is my gemfile:

```<code>source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.0.1'
# Use mysql as the database for Active Record
gem 'mysql2', '>= 0.4.4'
# Use Puma as the app server
gem 'puma', '~> 4.1'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '~> 4.0'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.7'
# Use haml view syntax
gem 'haml-rails'

# the main komponent gem is broken for Rails 6, see:
# https://github.com/komposable/komponent/issues/133
gem 'komponent', github: '0x2C6/komponent'
gem 'elasticsearch', '~> 6.2'
gem 'redis'

# Use Active Model has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Active Storage variant
# gem 'image_processing', '~> 1.2'

# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.2', require: false

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'pry-rails'
  gem 'rspec-rails', '~> 3.9'
  gem 'dotenv-rails'
  gem 'awesome_print'
end

group :beta, :production do
  gem 'puma_worker_killer'
end

group :development do
  # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
  gem 'spring-commands-rspec'
   # Avoid polling for changes (Windows)
  gem 'wdm', '>= 0.1.0', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
end

group :test do
  gem 'webmock'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
</code>```

答:
The problem for my case was a difference in the patch version of the puma that was used.

Gist of it was AWS Elastic Beanstalk was using puma 4.3.3 while I was using puma 4.3.5.

Had to fix the version of puma used in my Gemfile  to exactly 4.3.3 to match the stack used by AWS Elastic Beanstalk as of today prevent this error.

More details in this answer of mine here for a similar question.

Body:
For my Elastic Beanstalk instance, I am getting a 504 status code response whenever I visit it. When I tail the logs I see the following log on the puma app server:

==> /var/log/puma/puma.log <==
[27240] Early termination of worker
[27245] Early termination of worker
[27249] Early termination of worker
[27253] Early termination of worker
[27257] Early termination of worker
[27261] Early termination of worker
[27265] Early termination of worker
[27269] Early termination of worker
[27273] Early termination of worker
[27277] Early termination of worker

What does Early termination of worker mean and why is it happening? Moreover, could the log be indicating the cause of my timeout error I am facing in my remote environment? The rails app and puma run perfectly on my local machine (Mac OS Catalina 10.15). However, in my remote Elastic beanstalk environment as stated above I am getting a timeout 504 error and the only thing I see in the logs is the above puma log.

This is my gemfile:

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.0.1'
# Use mysql as the database for Active Record
gem 'mysql2', '>= 0.4.4'
# Use Puma as the app server
gem 'puma', '~> 4.1'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '~> 4.0'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.7'
# Use haml view syntax
gem 'haml-rails'

# the main komponent gem is broken for Rails 6, see:
# https://github.com/komposable/komponent/issues/133
gem 'komponent', github: '0x2C6/komponent'
gem 'elasticsearch', '~> 6.2'
gem 'redis'

# Use Active Model has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Active Storage variant
# gem 'image_processing', '~> 1.2'

# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.2', require: false

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'pry-rails'
  gem 'rspec-rails', '~> 3.9'
  gem 'dotenv-rails'
  gem 'awesome_print'
end

group :beta, :production do
  gem 'puma_worker_killer'
end

group :development do
  # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
  gem 'spring-commands-rspec'
   # Avoid polling for changes (Windows)
  gem 'wdm', '>= 0.1.0', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
end

group :test do
  gem 'webmock'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]


问:
How to diplay number of blog posted per category in Django
I am developing a blog website using Django and trying to display the no. of the post made per category on the homepage.

models.py:

```<code>class Category(models.Model):

    CATEGORY = (
        ("Un-categorized", "Un-categorized"),
        ("Machine Learning", "Machine Learning"),
        ("Data Science", "Data Science"),
        ("Programming", "Programming"),
        ("Latest Trends", "Latest Trends")
    )

    category = models.CharField(max_length=20, choices=CATEGORY, default='Un-Categorized',unique=True)

    def __str__(self):
        return self.category

class Post(models.Model):

    title = models.CharField(max_length=20) # title of the post
    content = models.TextField()  # content of the post
    date_posted = models.DateTimeField(auto_now_add=True)  # when the post is created
    date_modified = models.DateTimeField(auto_now=True) # will store the date every time the post is updated and saved.
    author = models.ForeignKey(User, on_delete=models.CASCADE)  # Referring the django's inbuilt User model.
    category = models.ForeignKey(Category, on_delete=models.CASCADE)  # one post can have only one category whereas under one category there can be multiple post.
    img = models.ImageField(default='default.jpg', upload_to='post')
    # tag = to store important tags related to the post

    def __str__(self):
        return self.title
</code>```

views.py :

```<code>def home(request): # Home page of the website.
    post = Post.objects.all().order_by('-date_posted') # To display all the post in desc order.
    categories = Category.objects.all()

    '''categories_count = []
    i = 1
    for item in categories.count():
        categories_count[item] = Categories.objects.filter(id=i).count()
        i += 1
    '''
    context = {
        'posts':post,
        # 'count' : categories_count,
        'categories': categories,
        # 'categories_count': categories_count
    }

    return render(request,'post/home.html',context=context)
</code>```

.html file:

```<code><div class="widget widget_categories group">
    <h3>Categories</h3>
        <ul>
            {% for category in categories %}
            <li>
                <a href="{% url 'post-category' category.category %}" title="">
                    {{ category }}
                </a>
                (<!--count of post made per category-->>)
            </li>
            {% endfor %}
        </ul>
</div>
</code>```

I tried to implement this in my view but I couldn't able to complete it. I am not sure how to access the categories_count list under the context dic. from the template.

答: You can add 'post_count' = posts.count() to context dict in view. Then just use it in html {{ post_count }}

Body:
I am developing a blog website using Django and trying to display the no. of the post made per category on the homepage.

models.py:

class Category(models.Model):

    CATEGORY = (
        ("Un-categorized", "Un-categorized"),
        ("Machine Learning", "Machine Learning"),
        ("Data Science", "Data Science"),
        ("Programming", "Programming"),
        ("Latest Trends", "Latest Trends")
    )

    category = models.CharField(max_length=20, choices=CATEGORY, default='Un-Categorized',unique=True)

    def __str__(self):
        return self.category

class Post(models.Model):

    title = models.CharField(max_length=20) # title of the post
    content = models.TextField()  # content of the post
    date_posted = models.DateTimeField(auto_now_add=True)  # when the post is created
    date_modified = models.DateTimeField(auto_now=True) # will store the date every time the post is updated and saved.
    author = models.ForeignKey(User, on_delete=models.CASCADE)  # Referring the django's inbuilt User model.
    category = models.ForeignKey(Category, on_delete=models.CASCADE)  # one post can have only one category whereas under one category there can be multiple post.
    img = models.ImageField(default='default.jpg', upload_to='post')
    # tag = to store important tags related to the post

    def __str__(self):
        return self.title

views.py :

def home(request): # Home page of the website.
    post = Post.objects.all().order_by('-date_posted') # To display all the post in desc order.
    categories = Category.objects.all()

    '''categories_count = []
    i = 1
    for item in categories.count():
        categories_count[item] = Categories.objects.filter(id=i).count()
        i += 1
    '''
    context = {
        'posts':post,
        # 'count' : categories_count,
        'categories': categories,
        # 'categories_count': categories_count
    }

    return render(request,'post/home.html',context=context)

.html file:

Categories

            {% for category in categories %}

                    {{ category }}

                (>)

            {% endfor %}

I tried to implement this in my view but I couldn't able to complete it. I am not sure how to access the categories_count list under the context dic. from the template.


问:
Chartjs scaleLabel position
Trying to get the Y axis scale labels to look like the image, to be position on top of the scale and not rotated.

scale options currently look like:

```<code>    scales: {
  yAxes: [{
    id: 'temp',
    scaleLabel: {
      display: true,
      labelString: '°C'
    },
    type: 'linear',
    position: 'left'
  }, {
    id: 'ppm',
    scaleLabel: {
      display: true,
      labelString: 'ppm',
    },
    type: 'linear',
    position: 'left',
    ticks: {
      stepSize: 500
    }
  }, {
    id: '%',
    scaleLabel: {
      display: true,
      labelString: '%',
    },
    type: 'linear',
    position: 'right',
    ticks: {
      max: 100,
      min: 0
    }
  }]
}
</code>```

https://jsfiddle.net/3a7qvtwz/2/

答:
You can use the Plugin Core API that offers a range of hooks that may be used for performing custom code. To draw the scale labels on top of the different yAxes in your code sample, the afterDraw hook could be defined as follows. It uses CanvasRenderingContext2D.fillText() to draw text directly on the canvas.

```<code>plugins:[{
  afterDraw: chart => {
    var ctx = chart.chart.ctx;
    ctx.save();
    ctx.font = "bold 14px Arial";
    ctx.fillStyle = "gray";
    var y = 50;

    ctx.textAlign = 'left';
    ctx.fillText('CO2', 5, y);
    ctx.fillText('°C', 46, y);

    ctx.textAlign = 'right';
    ctx.fillText('%', chart.chart.width - 10, y);
    ctx.restore();
  }
}],
</code>```

Please have a look at your amended JSFiddle

Title: Chartjs scaleLabel position

Body:
Trying to get the Y axis scale labels to look like the image, to be position on top of the scale and not rotated.

scale options currently look like:

    scales: {
  yAxes: [{
    id: 'temp',
    scaleLabel: {
      display: true,
      labelString: '°C'
    },
    type: 'linear',
    position: 'left'
  }, {
    id: 'ppm',
    scaleLabel: {
      display: true,
      labelString: 'ppm',
    },
    type: 'linear',
    position: 'left',
    ticks: {
      stepSize: 500
    }
  }, {
    id: '%',
    scaleLabel: {
      display: true,
      labelString: '%',
    },
    type: 'linear',
    position: 'right',
    ticks: {
      max: 100,
      min: 0
    }
  }]
}

https://jsfiddle.net/3a7qvtwz/2/

Body:
You can use the Plugin Core API that offers a range of hooks that may be used for performing custom code. To draw the scale labels on top of the different yAxes in your code sample, the afterDraw hook could be defined as follows. It uses CanvasRenderingContext2D.fillText() to draw text directly on the canvas.

plugins:[{
  afterDraw: chart => {
    var ctx = chart.chart.ctx;
    ctx.save();
    ctx.font = "bold 14px Arial";
    ctx.fillStyle = "gray";
    var y = 50;

    ctx.textAlign = 'left';
    ctx.fillText('CO2', 5, y);
    ctx.fillText('°C', 46, y);

    ctx.textAlign = 'right';
    ctx.fillText('%', chart.chart.width - 10, y);
    ctx.restore();
  }
}],

Please have a look at your amended JSFiddle


问:
setVisibility for menu action item
Can you help me?
I'm trying to create a menu where items appear at the touch of a button. I think I should make the menu items visible:false, and then switch this property in MainActivity. But I can't do it rightly. I need 3 new menu items.

```<code>public class MainActivity extends AppCompatActivity implements OnClickListener {

    private static final String TAG = "myLogs";
    Button button;
    TextView textView4;
    EditText editText;
    private Object Menu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(this);
        Button button2 = (Button) findViewById(R.id.button2);
        editText = (EditText) findViewById(R.id.editText);
        textView4 = (TextView) findViewById(R.id.textView4);
        final Menu action_item4 = (Menu) findViewById(R.id.action_item4);

        button2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                Menu action_item4 = (Menu) findViewById(R.id.action_item4);
                 action_item4.setVisibility(View.VISIBLE);
                          }
        });
    }
</code>```

I see an error: Cannot resolve method setVisibility(int)

答:
That's not the right way of creating a custom menu.
If you want to show a custom menu on click of a button then,

Create a file poupup_menu.xml

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/one"
        android:title="One"/>

    <item
        android:id="@+id/two"
        android:title="Two"/>

    <item
        android:id="@+id/three"
        android:title="Three"/>

</menu>
</code>```

In your button click

```<code>button2.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {

             //Creating the instance of PopupMenu
        PopupMenu popup = new PopupMenu(MainActivity.this, button1);
        //Inflating the Popup using xml file
        popup.getMenuInflater()
            .inflate(R.menu.popup_menu, popup.getMenu());

        //registering popup with OnMenuItemClickListener
        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                Toast.makeText(
                    MainActivity.this,
                    "You Clicked : " + item.getTitle(),
                    Toast.LENGTH_SHORT
                ).show();
                return true;
            }
        });

        popup.show(); //showing popup menu
    }
});
</code>```

You can add more items to the menu as follows

```<code>popup.getMenu().add("title");
</code>```

Title: setVisibility for menu action item

Body:
Can you help me?
I'm trying to create a menu where items appear at the touch of a button. I think I should make the menu items visible:false, and then switch this property in MainActivity. But I can't do it rightly. I need 3 new menu items.

public class MainActivity extends AppCompatActivity implements OnClickListener {

    private static final String TAG = "myLogs";
    Button button;
    TextView textView4;
    EditText editText;
    private Object Menu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(this);
        Button button2 = (Button) findViewById(R.id.button2);
        editText = (EditText) findViewById(R.id.editText);
        textView4 = (TextView) findViewById(R.id.textView4);
        final Menu action_item4 = (Menu) findViewById(R.id.action_item4);

        button2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                Menu action_item4 = (Menu) findViewById(R.id.action_item4);
                 action_item4.setVisibility(View.VISIBLE);
                          }
        });
    }

I see an error: Cannot resolve method setVisibility(int)

Body:
That's not the right way of creating a custom menu.
If you want to show a custom menu on click of a button then,

Create a file poupup_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/one"
        android:title="One"/>

    <item
        android:id="@+id/two"
        android:title="Two"/>

    <item
        android:id="@+id/three"
        android:title="Three"/>

</menu>

In your button click

button2.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {

             //Creating the instance of PopupMenu
        PopupMenu popup = new PopupMenu(MainActivity.this, button1);
        //Inflating the Popup using xml file
        popup.getMenuInflater()
            .inflate(R.menu.popup_menu, popup.getMenu());

        //registering popup with OnMenuItemClickListener
        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                Toast.makeText(
                    MainActivity.this,
                    "You Clicked : " + item.getTitle(),
                    Toast.LENGTH_SHORT
                ).show();
                return true;
            }
        });

        popup.show(); //showing popup menu
    }
});

You can add more items to the menu as follows

popup.getMenu().add("title");


问:
php string addition, double quote and single quote print and echo confusion
In php, why "1"+"1" when added and echo gives 2
isn't putting inside a double quote makes the number string? </p>

```<code><?php
$x = "1";
$y = "3";

$z = $x + $y;

echo($z); // this print 4

?>
</code>```

<p>Also, if we take this example, since, the value in the variable is inside the double quote and if you use a single quote to print the below expression why it prints $x + $y = $z </p>

```<code><?php
$x = "1";
$y = "3";

$z = $x + $y;

echo '$x + $y = $z'; // prints  $x + $y = $z

?>
</code>```

答:
Because you are using "+" here:

```<code>$z = $x + $y;
</code>```

When you are doing this PHP will convert to int if possible to make the addition. If you want to store "1 + 3" instead you can go like that:

```<code>$z = $x . ' + ' . $y;
</code>```

Body:
In php, why "1"+"1" when added and echo gives 2
isn't putting inside a double quote makes the number string?

<?php
$x = "1";
$y = "3";

$z = $x + $y;

echo($z); // this print 4

?>

Also, if we take this example, since, the value in the variable is inside the double quote and if you use a single quote to print the below expression why it prints $x + $y = $z

<?php
$x = "1";
$y = "3";

$z = $x + $y;

echo '$x + $y = $z'; // prints  $x + $y = $z

?>

Body:
Because you are using "+" here:

$z = $x + $y;

When you are doing this PHP will convert to int if possible to make the addition. If you want to store "1 + 3" instead you can go like that:

$z = $x . ' + ' . $y;


问:
Add 5 time tap event to container in Flutter
I want to add 5 time tap event to container. I am using GestureDetector to get tap event. But I dont know how to achieve 5 time taps event in it. I want when user tap 5 times on container then I want to perform some operation in my app. </p>

答:
you can easily use a piece of state to achieve this, in the example below i used an Opacity widget to display an icon if _counter == 5, this may not be exactly what you want but based on the context of your question this is what i can give.

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int _counter = 0;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => setState(() => _counter++),
      child: Container(
          child: Column(
        children: <Widget>[
          Text('Tap me'),
          Opacity(
            opacity: _counter == 5 ? 1 : 0,
            child: Icon(
              Icons.whatshot
            ),
          )
        ],
      )),
    );
  }
}
```


问:
My answer to edx CS1301xII question 3.2.8 has a problem
I am trying to find whether I should by a diamond or not in this code. I expect to do this:

Do not buy the diamond is a cut they like

Do not buy if I cannot afford it
This is my code:

```<code>cut = "Emerald"
clarity = "VS"
color = "I"
carat = 3.3
budget = 1271
preferred_cuts = ["Emerald", "Cushion", "Princess", "Oval"]

#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.

#Diamonds are typically evaluated according to four aspects:
# - Cut: The way the diamond is cut
# - Clarity: How clear or flawless the diamond is, rated
#   as F (the best), IF, VVS, VS, SI, or I (the worst)
# - Color: How colorless the diamond is, rated from "D" (the
#   best) to "Z" (the worst)
# - Carat: How large the diamond is, weighed in carats
#
#Cut is usually a matter of personal preference. Clarity,
#color, and carat are matters of value: the clearer, more
#colorless, and larger a diamond is, the greater its value.
#
#Imagine you're shopping for a diamond. You have your
#preferred cuts, and you have a budget in mind. You're shown
#a diamond whose characteristics are represented by the cut,
#color, clarity, and carat variables above. You'll buy the
#diamond if its cost is less than your budget, and if its
#cut is one of your preferred cuts.
#
#At this store, every diamond has a base cost of 100.
#
#For every color rating worse than "D", the cost decreases by
#2%. An "F" color diamond would be worth 0.96 * the diamond
#cost otherwise because "F" is two colors worse than "D".
#
#A diamond's value is doubled for every level of clarity above
#I. A "VVS"-clarity diamond is worth 8 * the diamond cost
#otherwise because "VVS" is three levels higher than I, and
#doubling its value three times raises its value by 8x total.
#
#After finding its price based on color and clarity, its price
#is multiplied by its weight in carats.
#
#Your program should print "I'll take it!" if you will buy the
#diamond, "No thanks" if you will not. To purchase it, its price
#must be less than your budget and its cut must be one of your
#preferred cuts.
#
#HINT: You can find the number of characters between two
#characters by using the ord() function. ord("E") - ord("D")
#is 1; ord("Z") - ord("D") is 22.
#
#HINT 2: We haven't covered lists, but we did cover how to
#see if an item is present in a list using the 'in' operator
#in chapter 2.3.

#Add your code here!
colorcost = ord(color) - ord("D")
cost = (100 - colorcost * 0.02)
if clarity == "SI":
    cost *= 2
elif clarity == "VS":
    cost *= 4
elif clarity == "VVS":
    cost *= 8
elif clarity == "IF":
    cost *= 16
elif clarity == "F":
    cost *= 32
cost *= carat
if cut not in preferred_cuts:
    print("No thanks")
elif ((budget - cost) >= 0):
    print("I'll take it!")

else:
    print("No thanks")
</code>```

Error message:
We found the following problems with your submission:

We tested your code with cut = "Pear", clarity = "VVS", color = "P", carat = 1.2, budget = 732, preferred_cuts = ["Cushion", "Pear", "Radiant", "Heart", "Emerald"]. We expected your code to print this:

I'll take it!

However, it printed this:

No thanks

答:
Your problem is here:

```<code>cost = (100 - colorcost * 0.02)
</code>```

As stated in the problem, for each rating worse than D, the cost is supposed to decrease by 2% of its original price, which is 100. You're instead multiplying the value of the rating by 0.02.

This can be illustrated by using their example:

```<code>#For every color rating worse than "D", the cost decreases by
#2%. An "F" color diamond would be worth 0.96 * the diamond
#cost otherwise because "F" is two colors worse than "D".

color = "F"
colorcost = ord(color) - ord("D")
cost = 100 - colorcost*0.02 # <-- this equals 96.96
correct_cost = 0.96*100 # <-- correct cost should be 96

assert cost == correct_cost # this test fails
</code>```

As a rule of thumb, when debugging, make sure your code works for given examples, and when problems arise, print out values like print(cost) to check that it's correct, or, better yet, make tests with assert.

Body:
I am trying to find whether I should by a diamond or not in this code. I expect to do this:

Do not buy the diamond is a cut they like

Do not buy if I cannot afford it
This is my code:

cut = "Emerald"
clarity = "VS"
color = "I"
carat = 3.3
budget = 1271
preferred_cuts = ["Emerald", "Cushion", "Princess", "Oval"]

#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.

#Diamonds are typically evaluated according to four aspects:
# - Cut: The way the diamond is cut
# - Clarity: How clear or flawless the diamond is, rated
#   as F (the best), IF, VVS, VS, SI, or I (the worst)
# - Color: How colorless the diamond is, rated from "D" (the
#   best) to "Z" (the worst)
# - Carat: How large the diamond is, weighed in carats
#
#Cut is usually a matter of personal preference. Clarity,
#color, and carat are matters of value: the clearer, more
#colorless, and larger a diamond is, the greater its value.
#
#Imagine you're shopping for a diamond. You have your
#preferred cuts, and you have a budget in mind. You're shown
#a diamond whose characteristics are represented by the cut,
#color, clarity, and carat variables above. You'll buy the
#diamond if its cost is less than your budget, and if its
#cut is one of your preferred cuts.
#
#At this store, every diamond has a base cost of 100.
#
#For every color rating worse than "D", the cost decreases by
#2%. An "F" color diamond would be worth 0.96 * the diamond
#cost otherwise because "F" is two colors worse than "D".
#
#A diamond's value is doubled for every level of clarity above
#I. A "VVS"-clarity diamond is worth 8 * the diamond cost
#otherwise because "VVS" is three levels higher than I, and
#doubling its value three times raises its value by 8x total.
#
#After finding its price based on color and clarity, its price
#is multiplied by its weight in carats.
#
#Your program should print "I'll take it!" if you will buy the
#diamond, "No thanks" if you will not. To purchase it, its price
#must be less than your budget and its cut must be one of your
#preferred cuts.
#
#HINT: You can find the number of characters between two
#characters by using the ord() function. ord("E") - ord("D")
#is 1; ord("Z") - ord("D") is 22.
#
#HINT 2: We haven't covered lists, but we did cover how to
#see if an item is present in a list using the 'in' operator
#in chapter 2.3.

#Add your code here!
colorcost = ord(color) - ord("D")
cost = (100 - colorcost * 0.02)
if clarity == "SI":
    cost *= 2
elif clarity == "VS":
    cost *= 4
elif clarity == "VVS":
    cost *= 8
elif clarity == "IF":
    cost *= 16
elif clarity == "F":
    cost *= 32
cost *= carat
if cut not in preferred_cuts:
    print("No thanks")
elif ((budget - cost) >= 0):
    print("I'll take it!")

else:
    print("No thanks")

Error message:
We found the following problems with your submission:

We tested your code with cut = "Pear", clarity = "VVS", color = "P", carat = 1.2, budget = 732, preferred_cuts = ["Cushion", "Pear", "Radiant", "Heart", "Emerald"]. We expected your code to print this:

I'll take it!

However, it printed this:

No thanks

Body:
Your problem is here:

cost = (100 - colorcost * 0.02)

As stated in the problem, for each rating worse than D, the cost is supposed to decrease by 2% of its original price, which is 100. You're instead multiplying the value of the rating by 0.02.

This can be illustrated by using their example:

#For every color rating worse than "D", the cost decreases by
#2%. An "F" color diamond would be worth 0.96 * the diamond
#cost otherwise because "F" is two colors worse than "D".

color = "F"
colorcost = ord(color) - ord("D")
cost = 100 - colorcost*0.02 # <-- this equals 96.96
correct_cost = 0.96*100 # <-- correct cost should be 96

assert cost == correct_cost # this test fails

As a rule of thumb, when debugging, make sure your code works for given examples, and when problems arise, print out values like print(cost) to check that it's correct, or, better yet, make tests with assert.


问:
How to shift my code in other block in Java?
When I run the whole program, the code always repeats in login activity and shows You do not have the account message in the loop. How do I move to createNewUser? I have attached the image of the code.
https://i.stack.imgur.com/DIqNp.png</p>

答:
Call createNewUser() from loginActivity ()
Ask the user if they want to create a new account. If this is a console application, do something like this:

```<code>if(user != null)
    return user;
Scanner sc = new Scanner(System.in);
System.out.println ("Do you want to create a new account(Y/N)?")
String input = sc.next();
if(input.toLowerCase().equals('y')
    createNewUser();
return null;
</code>```

Body:
Call createNewUser() from loginActivity ()
Ask the user if they want to create a new account. If this is a console application, do something like this:

if(user != null)
    return user;
Scanner sc = new Scanner(System.in);
System.out.println ("Do you want to create a new account(Y/N)?")
String input = sc.next();
if(input.toLowerCase().equals('y')
    createNewUser();
return null;


问:
How do I append a JSON file?
How would I append a JSON file? I know how to append a JSON variable, but how do I append a file? for example, if my JSON file was:

```<code>{"people": [{"name" : "Michael Scott", "city": "Scranton"}]}
</code>```

If I wanted to add another name to people, and that was in a JSON file, how would I do that?

答:
Let's say your destination json is:

```<code># dest.json
{"people": [{"name" : "Michael Scott", "city": "Scranton"}]}
</code>```

and you want to append the following json:

```<code># source.json
{"name" : "Blah Blah", "city": "blah"}
</code>```

Try:

```<code>import json

with open("destination.json") as fd, open("source.json") as fs:
    dest = json.load(fd)
    source = json.load(fs)
    dest["people"].append(source)
with open("destination.json", 'w') as fd:
    json.dump(dest, fd)
</code>```

Title: How do I append a JSON file?

Body:
How would I append a JSON file? I know how to append a JSON variable, but how do I append a file? for example, if my JSON file was:

{"people": [{"name" : "Michael Scott", "city": "Scranton"}]}

If I wanted to add another name to people, and that was in a JSON file, how would I do that?

Body:
Let's say your destination json is:

# dest.json
{"people": [{"name" : "Michael Scott", "city": "Scranton"}]}

and you want to append the following json:

# source.json
{"name" : "Blah Blah", "city": "blah"}

Try:

import json

with open("destination.json") as fd, open("source.json") as fs:
    dest = json.load(fd)
    source = json.load(fs)
    dest["people"].append(source)
with open("destination.json", 'w') as fd:
    json.dump(dest, fd)


问:
javascript using object keys as variable names
I'm trying to use the object keys p1, p2, p3 as variable names, but my knowledge of javascript seems insufficient to get it right. How can I do this, so in the end console.log(p1) is value1 etc.

```<code>var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " -> " + p[key]);
      var key = p[key]
    }
}

console.log(p1,p2,p3) //value1, value2, value3
</code>```

答:
You can do this easily using the global window object like:

```<code>window[key] = p[key]
</code>```

var p = {
  "p1": "value1",
  "p2": "value2",
  "p3": "value3"
};

for (var key in p) {
  if (p.hasOwnProperty(key)) {
    window[key] = p[key]
  }
}

console.log(p1, p2, p3)```

Body:
I'm trying to use the object keys p1, p2, p3 as variable names, but my knowledge of javascript seems insufficient to get it right. How can I do this, so in the end console.log(p1) is value1 etc.

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " -> " + p[key]);
      var key = p[key]
    }
}

console.log(p1,p2,p3) //value1, value2, value3

Body:
You can do this easily using the global window object like:

window[key] = p[key]

var p = {
  "p1": "value1",
  "p2": "value2",
  "p3": "value3"
};

for (var key in p) {
  if (p.hasOwnProperty(key)) {
    window[key] = p[key]
  }
}

console.log(p1, p2, p3)