问:
How to remove empty tags AND line breaks with xslt?
I want to remove empty tags as well as line breaks from an XML file via XSLT.

Criteria 1:
Line breaks should only be removed within text nodes, i.e. the XML should remain indented.

Criteria 2:
Should work on any OS.

Criteria 3:
If possible there wouldn't be any other changes to the XML.

An example XML would be:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Container xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <tag1>22</tag1>
    <tag2>33</tag2>
    <tag3/>
    <minimalValue/>
    <maximalValue/>
    <minimalFee/>
    <maximalFee/>
    <tag4>This is text with a
        line break.
    </tag4>
</Container>
</code>```

The result should be:

```<code><Container xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <tag1>22</tag1>
   <tag2>33</tag2>
   <tag4>This is text with a line break.</tag4>
</Container>
</code>```

答:
I am not sure if this is the best way to do that. But I've achieved the above with the following template: </p>

```<code><xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="child::node()[not(self::text())]|@*">
        <xsl:if test="normalize-space(string(.)) != ''">
            <xsl:copy>
                <xsl:apply-templates select="node()|@*"/>
            </xsl:copy>
        </xsl:if>
    </xsl:template>

    <xsl:template match="text()">
        <xsl:value-of select="normalize-space(.)"/>
    </xsl:template>
</xsl:stylesheet>
</code>```

Body:
I want to remove empty tags as well as line breaks from an XML file via XSLT.

Criteria 1:
Line breaks should only be removed within text nodes, i.e. the XML should remain indented.

Criteria 2:
Should work on any OS.

Criteria 3:
If possible there wouldn't be any other changes to the XML.

An example XML would be:

<?xml version="1.0" encoding="UTF-8"?>
<Container xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <tag1>22</tag1>
    <tag2>33</tag2>
    <tag3/>
    <minimalValue/>
    <maximalValue/>
    <minimalFee/>
    <maximalFee/>
    <tag4>This is text with a
        line break.
    </tag4>
</Container>

The result should be:

<Container xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <tag1>22</tag1>
   <tag2>33</tag2>
   <tag4>This is text with a line break.</tag4>
</Container>

Body:
I am not sure if this is the best way to do that. But I've achieved the above with the following template:

<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="child::node()[not(self::text())]|@*">
        <xsl:if test="normalize-space(string(.)) != ''">
            <xsl:copy>
                <xsl:apply-templates select="node()|@*"/>
            </xsl:copy>
        </xsl:if>
    </xsl:template>

    <xsl:template match="text()">
        <xsl:value-of select="normalize-space(.)"/>
    </xsl:template>
</xsl:stylesheet>


来源: stackexchange

问:
Matching keywords in a dictionary to a list in Python
The following dictionary gives the word and its value:

```<code>keywords = {'alone': 1, 'amazed': 10, 'amazing': 10, 'bad': 1, 'best': 10, 'better': 7, 'excellent': 10, 'excited': 10, 'excite': 10}
</code>```

Following the dictionary are two tweets in a list in a list.
For each tweet, we need to find which of the words from keywords are present in it.

```<code>tweets = [['work', 'needs', 'to', 'fly', 'by', '', "i'm", 'so', 'excited', 'to', 'see', 'spy', 'kids', '4', 'with', 'then', 'love', 'of', 'my', 'life', '', 'arreic'], ['today', 'is', 'going', 'to', 'be', 'the', 'greatest', 'day', 'of', 'my', 'life', 'hired', 'to', 'take', 'pictures', 'at', 'my', 'best', "friend's", 'gparents', '50th', 'anniversary', '60', 'old', 'people', 'woo']]
</code>```

The target is to find the sum of the keyword values found in each tweet line.

The code created needs to be a loop because there are more than 2 tweets.
I do not understand how I should execute this process.

Appreciate your insight!

答:
First we need to assign a variable for the value and set this to zero, then for each tweet and for every word inside this tweet we use the function dict.get() to get the corresponding value of word (if the word isn't in keywords it returns 0).

```<code>value = 0
for tweet in tweets:
    for word in tweet:
        value += keywords.get(word,0)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The following dictionary gives the word and its value:

keywords = {'alone': 1, 'amazed': 10, 'amazing': 10, 'bad': 1, 'best': 10, 'better': 7, 'excellent': 10, 'excited': 10, 'excite': 10}

Following the dictionary are two tweets in a list in a list.
For each tweet, we need to find which of the words from keywords are present in it.

tweets = [['work', 'needs', 'to', 'fly', 'by', '', "i'm", 'so', 'excited', 'to', 'see', 'spy', 'kids', '4', 'with', 'then', 'love', 'of', 'my', 'life', '', 'arreic'], ['today', 'is', 'going', 'to', 'be', 'the', 'greatest', 'day', 'of', 'my', 'life', 'hired', 'to', 'take', 'pictures', 'at', 'my', 'best', "friend's", 'gparents', '50th', 'anniversary', '60', 'old', 'people', 'woo']]

The target is to find the sum of the keyword values found in each tweet line.

The code created needs to be a loop because there are more than 2 tweets.
I do not understand how I should execute this process.

Appreciate your insight!

Body:
First we need to assign a variable for the value and set this to zero, then for each tweet and for every word inside this tweet we use the function dict.get() to get the corresponding value of word (if the word isn't in keywords it returns 0).

value = 0
for tweet in tweets:
    for word in tweet:
        value += keywords.get(word,0)


问:
Why Same where clause need to write multiple times in a Linq Query for following SQL
What will be the proper linq syntax of below SQL Query ?

```<code>select a.id, a.AppointmentStatusID, ad.ID as DetailID
from [dbo].[Appointment] a, [dbo].[AppointmentDetail] ad
where a.[ID] = ad.[AppointmentID]
and a.CompanyID = 'a3dea87a-804e-4115-98cf-472988cf1678'
and a.LocationID = '3165caca-2a48-46f0-bbed-578cff29167t'
and ad.AppDateFrom <= {ts '2017-11-14 23:59:31'}
and ad.AppDateTo >= {ts '2017-11-14 00:00:00'}
and ad.[ApprovalStatusID] = 2
</code>```

Problem I faced:

I required to filter Where Condition two times 1st at the time within the join & 2nd time during the object.Select expression, please check bellow

```<code>var results = (from a in appointments
                                   join ad in _appointmentDetailRepository.GetAll() on a.ID equals ad.AppointmentID
                                   where ad.ApprovalStatusID == 2
                                   && DbFunctions.TruncateTime(ad.AppDateFrom) <= DbFunctions.TruncateTime(viewmodel.AppointmentDate)
                                   && DbFunctions.TruncateTime(ad.AppDateTo) >= DbFunctions.TruncateTime(viewmodel.AppointmentDate)
                                   orderby a.ID
                                   select new Appointment
                                   {
                                       ID = a.ID,
                                       CompanyID = a.CompanyID,
                                       LocationID = a.LocationID,
                                       AppointmentDetail = a.AppointmentDetail.Select(ad => new AppointmentDetail
                                       {
                                           ID = ad.ID,
                                           AppDateFrom = ad.AppDateFrom,
                                           AppDateTo = ad.AppDateTo,
                                           AppointmentStatusID = ad.AppointmentStatusID,
}).Where(ad=> ad.ApprovalStatusID == 2
                                        && DbFunctions.TruncateTime(ad.AppDateFrom) <= DbFunctions.TruncateTime(viewmodel.AppointmentDate)
                                        && DbFunctions.TruncateTime(ad.AppDateTo) >= DbFunctions.TruncateTime(viewmodel.AppointmentDate)).ToList()
 }).GroupBy(x => x.ID).Select(x => x.DefaultIfEmpty().FirstOrDefault());
</code>```

Query : Why I required to write Where clause 2 times ?

Required Result

An Appointment Object --> Containing ICollection<AppoinmentDetails> if Details.Where Condition == True

答:
From what I see (without knowing the model you have), it looks like you should use the already joined and filtered Details from ad instead of looking it up again from the Property a.AppointmentDetail...

Untested:

```<code>select new Appointment
{
    ID = a.ID,
    CompanyID = a.CompanyID,
    LocationID = a.LocationID,
    AppointmentDetail = ad.ToList(), // <-- don't you think?
    ...
}
</code>```

Body:
What will be the proper linq syntax of below SQL Query ?

select a.id, a.AppointmentStatusID, ad.ID as DetailID
from [dbo].[Appointment] a, [dbo].[AppointmentDetail] ad
where a.[ID] = ad.[AppointmentID]
and a.CompanyID = 'a3dea87a-804e-4115-98cf-472988cf1678'
and a.LocationID = '3165caca-2a48-46f0-bbed-578cff29167t'
and ad.AppDateFrom <= {ts '2017-11-14 23:59:31'}
and ad.AppDateTo >= {ts '2017-11-14 00:00:00'}
and ad.[ApprovalStatusID] = 2

Problem I faced:

I required to filter Where Condition two times 1st at the time within the join & 2nd time during the object.Select expression, please check bellow

var results = (from a in appointments
                                   join ad in _appointmentDetailRepository.GetAll() on a.ID equals ad.AppointmentID
                                   where ad.ApprovalStatusID == 2
                                   && DbFunctions.TruncateTime(ad.AppDateFrom) <= DbFunctions.TruncateTime(viewmodel.AppointmentDate)
                                   && DbFunctions.TruncateTime(ad.AppDateTo) >= DbFunctions.TruncateTime(viewmodel.AppointmentDate)
                                   orderby a.ID
                                   select new Appointment
                                   {
                                       ID = a.ID,
                                       CompanyID = a.CompanyID,
                                       LocationID = a.LocationID,
                                       AppointmentDetail = a.AppointmentDetail.Select(ad => new AppointmentDetail
                                       {
                                           ID = ad.ID,
                                           AppDateFrom = ad.AppDateFrom,
                                           AppDateTo = ad.AppDateTo,
                                           AppointmentStatusID = ad.AppointmentStatusID,
}).Where(ad=> ad.ApprovalStatusID == 2
                                        && DbFunctions.TruncateTime(ad.AppDateFrom) <= DbFunctions.TruncateTime(viewmodel.AppointmentDate)
                                        && DbFunctions.TruncateTime(ad.AppDateTo) >= DbFunctions.TruncateTime(viewmodel.AppointmentDate)).ToList()
 }).GroupBy(x => x.ID).Select(x => x.DefaultIfEmpty().FirstOrDefault());

Query : Why I required to write Where clause 2 times ?

Required Result

An Appointment Object --> Containing ICollection<AppoinmentDetails> if Details.Where Condition == True

Body:
From what I see (without knowing the model you have), it looks like you should use the already joined and filtered Details from ad instead of looking it up again from the Property a.AppointmentDetail...

Untested:

select new Appointment
{
    ID = a.ID,
    CompanyID = a.CompanyID,
    LocationID = a.LocationID,
    AppointmentDetail = ad.ToList(), // <-- don't you think?
    ...
}


问:
RecyclerView's Width exceeds DeviceWidth and destroys TableLayout
I have a recylcerView inside a Table(Row)Layout, inside a NestedScrollView, all of them have the attribute layout_width set to match_parent. I had the problem that the scrolling of recyclerView didn't work but when trying to get the scrolling done (with NestedScrollView) I figured out that this wasn't the real problem. The problem is the width of my horizontally recylcerView that expands the device widht. I only figured it out, because the row above my recyclerView doesn't display the text correct.

The following image shows the behaviour of RV and the textRow above
screenshot

the image to the left: here you can see that the text in the text row above is missing "h word"

the image marked with 2: this is the expected output.

I only achieve the desired "correct" size, if I set layout_width of the recyclerview to "200dp". But I don't want a fixed size (due to different devices).

I tried setting the layout_width of the RV dynamically with the following code without success:

```<code>LinearLayoutManager llm = new LinearLayoutManager(this.getContext(), LinearLayoutManager.HORIZONTAL, false);
    mRecyclerViewAttachments.setLayoutManager(llm);
    ViewGroup.LayoutParams params = mRecyclerViewAttachments.getLayoutParams();
    int newWidth = (int) (params.width * 0.9);
    mRecyclerViewAttachments.setLayoutParams(params);
</code>```

Can anyone help me how to fix this? Below is the complete layout xml of the dialog (the RV comes at last):

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">

<android.support.v4.widget.NestedScrollView
    android:id="@+id/detail_scroll_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    android:animateLayoutChanges="true">

    <TableLayout
        android:id="@+id/tableLayoutDetail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:stretchColumns="1"
        android:paddingLeft="16dp"
        android:paddingRight="16dp">

        <!-- ROW 1 -->
        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="8dp"
            android:paddingBottom="8dp">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingTop="8dp"
                android:paddingBottom="8dp"
                android:layout_weight="1"
                android:gravity="center"
                android:layout_column="0"
                android:layout_span="2"
                android:text="@string/detail_fragment_entry_header_1"
                android:textAppearance="@style/TextAppearance.AppCompat.Body2"
                tools:text="@string/detail_fragment_entry_header_1"
                android:background="@color/colorPrimary"/>

        </TableRow>

        <!-- ROW 2 -->
        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="8dp"
            android:paddingBottom="8dp">

            <ImageView
                android:src="@drawable/ic_event_black_24dp"
                android:layout_height="wrap_content"
                android:layout_width="48dp"
                android:layout_gravity="left"
                android:layout_column="0"
                />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left"
                android:layout_column="1"
                android:orientation="vertical">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="left"
                    android:textAppearance="@style/ChronlyTextViewHint"
                    android:text="@string/created_entry"
                    tools:text="@string/created_entry" />

                <TextView
                    android:id="@+id/textViewDate"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="left"
                    android:text="@string/detail_dlg_phone_choose"
                    android:textAppearance="@style/TextAppearance.AppCompat.Body2"
                    tools:text="@string/detail_dlg_phone_choose" />
            </LinearLayout>
        </TableRow>

        <!-- ROW 3 -->
        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="8dp"
            android:paddingBottom="8dp">

            <ImageView
                android:id="@+id/imageViewEventType"
                android:src="@drawable/ic_contacts_black_24dp"
                android:layout_height="wrap_content"
                android:layout_width="48dp"
                android:layout_gravity="left"
                android:layout_column="0"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left"
                android:layout_column="1"
                android:orientation="vertical">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="left"
                    android:textAppearance="@style/ChronlyTextViewHint"
                    android:text="@string/detail_dlg_contact"
                    tools:text="@string/detail_dlg_contact" />

                <TextView
                    android:id="@+id/textViewContact"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="left"
                    android:text="@string/detail_dlg_contact_desc"
                    android:textAppearance="@style/TextAppearance.AppCompat.Body2"
                    tools:text="@string/detail_dlg_contact_desc" />
            </LinearLayout>
        </TableRow>

        <!-- ROW 4 -->
        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="2dp"
                android:background="@color/colorDarkGray"
                android:layout_column="0"
                android:layout_span="2">
            </LinearLayout>
        </TableRow>
        <!-- ROW 5 -->
        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingBottom="8dp"
            android:paddingTop="8dp">

            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_span="2">

                <android.support.design.widget.TextInputEditText
                    android:id="@+id/editTextComment"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="top|left"
                    android:inputType="textMultiLine"
                    android:scrollbars="vertical|horizontal"
                    android:scrollHorizontally="false"
                    android:overScrollMode="always"
                    android:scrollbarStyle="insideInset"
                    android:hint="Enter a comment"
                    android:textAppearance="@style/TextAppearance.AppCompat.Body2"
                    tools:text="first word, second word, third word, fourth word, fifth word, sixth word, seventh word" />

            </android.support.design.widget.TextInputLayout>
        </TableRow>
        <!-- ROW 6 -->
        <TableRow
            android:id="@+id/rowDetailLabelAttachment"
            android:layout_width="match_parent"
            android:paddingRight="16dp"
            android:layout_height="wrap_content">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_column="0"
                android:layout_gravity="left"
                android:layout_span="2"
                android:textAppearance="@style/ChronlyTextViewHint"
                android:text="@string/detail_label_attachment"
                tools:text="Attachments"/>
        </TableRow>
        <!-- ROW 7 -->
        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="8dp"
            android:paddingBottom="8dp">

            <ImageView
                android:layout_width="48dp"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_attachment_black_24dp"
                android:layout_column="0"
                android:layout_gravity="left"/>
            <!-- https://stackoverflow.com/questions/27083091/recyclerview-inside-scrollview-is-not-working/37338715#37338715 -->

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recyclerViewAttachments"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_column="1"
                android:scrollbars="horizontal"
                android:overScrollMode="always"
                android:scrollbarStyle="insideInset"
                android:nestedScrollingEnabled="false"
                android:visibility="visible"></android.support.v7.widget.RecyclerView>

        </TableRow>
    </TableLayout>
</android.support.v4.widget.NestedScrollView>
</code>```

答:
Your Tree should be like this</p>

```<code><NestedScrollView>

  <LinearLayout  orientation = vertical>

     <EditText>

     <TextView>

     <Recyclerview>

  </LinearLayout>

</NestedScrollView>
</code>```

Body:
I have a recylcerView inside a Table(Row)Layout, inside a NestedScrollView, all of them have the attribute layout_width set to match_parent. I had the problem that the scrolling of recyclerView didn't work but when trying to get the scrolling done (with NestedScrollView) I figured out that this wasn't the real problem. The problem is the width of my horizontally recylcerView that expands the device widht. I only figured it out, because the row above my recyclerView doesn't display the text correct.

The following image shows the behaviour of RV and the textRow above
screenshot

the image to the left: here you can see that the text in the text row above is missing "h word"

the image marked with 2: this is the expected output.

I only achieve the desired "correct" size, if I set layout_width of the recyclerview to "200dp". But I don't want a fixed size (due to different devices).

I tried setting the layout_width of the RV dynamically with the following code without success:

LinearLayoutManager llm = new LinearLayoutManager(this.getContext(), LinearLayoutManager.HORIZONTAL, false);
    mRecyclerViewAttachments.setLayoutManager(llm);
    ViewGroup.LayoutParams params = mRecyclerViewAttachments.getLayoutParams();
    int newWidth = (int) (params.width * 0.9);
    mRecyclerViewAttachments.setLayoutParams(params);

Can anyone help me how to fix this? Below is the complete layout xml of the dialog (the RV comes at last):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">

<android.support.v4.widget.NestedScrollView
    android:id="@+id/detail_scroll_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    android:animateLayoutChanges="true">

    <TableLayout
        android:id="@+id/tableLayoutDetail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:stretchColumns="1"
        android:paddingLeft="16dp"
        android:paddingRight="16dp">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="8dp"
            android:paddingBottom="8dp">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingTop="8dp"
                android:paddingBottom="8dp"
                android:layout_weight="1"
                android:gravity="center"
                android:layout_column="0"
                android:layout_span="2"
                android:text="@string/detail_fragment_entry_header_1"
                android:textAppearance="@style/TextAppearance.AppCompat.Body2"
                tools:text="@string/detail_fragment_entry_header_1"
                android:background="@color/colorPrimary"/>

        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="8dp"
            android:paddingBottom="8dp">

            <ImageView
                android:src="@drawable/ic_event_black_24dp"
                android:layout_height="wrap_content"
                android:layout_width="48dp"
                android:layout_gravity="left"
                android:layout_column="0"
                />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left"
                android:layout_column="1"
                android:orientation="vertical">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="left"
                    android:textAppearance="@style/ChronlyTextViewHint"
                    android:text="@string/created_entry"
                    tools:text="@string/created_entry" />

                <TextView
                    android:id="@+id/textViewDate"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="left"
                    android:text="@string/detail_dlg_phone_choose"
                    android:textAppearance="@style/TextAppearance.AppCompat.Body2"
                    tools:text="@string/detail_dlg_phone_choose" />
            </LinearLayout>
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="8dp"
            android:paddingBottom="8dp">

            <ImageView
                android:id="@+id/imageViewEventType"
                android:src="@drawable/ic_contacts_black_24dp"
                android:layout_height="wrap_content"
                android:layout_width="48dp"
                android:layout_gravity="left"
                android:layout_column="0"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left"
                android:layout_column="1"
                android:orientation="vertical">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="left"
                    android:textAppearance="@style/ChronlyTextViewHint"
                    android:text="@string/detail_dlg_contact"
                    tools:text="@string/detail_dlg_contact" />

                <TextView
                    android:id="@+id/textViewContact"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="left"
                    android:text="@string/detail_dlg_contact_desc"
                    android:textAppearance="@style/TextAppearance.AppCompat.Body2"
                    tools:text="@string/detail_dlg_contact_desc" />
            </LinearLayout>
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="2dp"
                android:background="@color/colorDarkGray"
                android:layout_column="0"
                android:layout_span="2">
            </LinearLayout>
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingBottom="8dp"
            android:paddingTop="8dp">

            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_span="2">

                <android.support.design.widget.TextInputEditText
                    android:id="@+id/editTextComment"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="top|left"
                    android:inputType="textMultiLine"
                    android:scrollbars="vertical|horizontal"
                    android:scrollHorizontally="false"
                    android:overScrollMode="always"
                    android:scrollbarStyle="insideInset"
                    android:hint="Enter a comment"
                    android:textAppearance="@style/TextAppearance.AppCompat.Body2"
                    tools:text="first word, second word, third word, fourth word, fifth word, sixth word, seventh word" />

            </android.support.design.widget.TextInputLayout>
        </TableRow>

        <TableRow
            android:id="@+id/rowDetailLabelAttachment"
            android:layout_width="match_parent"
            android:paddingRight="16dp"
            android:layout_height="wrap_content">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_column="0"
                android:layout_gravity="left"
                android:layout_span="2"
                android:textAppearance="@style/ChronlyTextViewHint"
                android:text="@string/detail_label_attachment"
                tools:text="Attachments"/>
        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="8dp"
            android:paddingBottom="8dp">

            <ImageView
                android:layout_width="48dp"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_attachment_black_24dp"
                android:layout_column="0"
                android:layout_gravity="left"/>

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recyclerViewAttachments"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_column="1"
                android:scrollbars="horizontal"
                android:overScrollMode="always"
                android:scrollbarStyle="insideInset"
                android:nestedScrollingEnabled="false"
                android:visibility="visible"></android.support.v7.widget.RecyclerView>

        </TableRow>
    </TableLayout>
</android.support.v4.widget.NestedScrollView>

Body:
Your Tree should be like this

<NestedScrollView>

  <LinearLayout  orientation = vertical>

     <EditText>

     <TextView>

     <Recyclerview>

  </LinearLayout>

</NestedScrollView>


问:
Difference in initializing char-array and char with integer literals
On my system (4.13.11-1-ARCH, gcc 7.2.0) char is signed. When initializing an array of char with an integer literal like this:

```<code>const char mydata[] = {
    0x80
};
</code>```

I get the following error:

```<code>error: narrowing conversion of ‘128’ from ‘int’ to ‘char’ inside { } [-Wnarrowing]
</code>```

However, when I instead do const char data = 0x80 the compiler is not worried of any narrowing, although it happens of course. The output is 7F, the highest positive signed char value.

Question

Why is the compiler not equally worried about truncation in both cases?

答: This is actually one of the reasons why {} initialization should be prefered: It does not allow narrowing conversions. In contrast to this, the old way of initalization (as in const char data = 0x80) does allow narrowing conversions.

Body:
On my system (4.13.11-1-ARCH, gcc 7.2.0) char is signed. When initializing an array of char with an integer literal like this:

const char mydata[] = {
    0x80
};

I get the following error:

error: narrowing conversion of ‘128’ from ‘int’ to ‘char’ inside { } [-Wnarrowing]

However, when I instead do const char data = 0x80 the compiler is not worried of any narrowing, although it happens of course. The output is 7F, the highest positive signed char value.

Question

Why is the compiler not equally worried about truncation in both cases?


问:
Radiobutton in Android Quiz app
I am working on quiz app for Android and I use RadioButtons in RadioGroup. I want to achieve that when someone checks the right answer (this case its id/krzyzyk) the score will increase by one point. I made this code:

```<code>int score = 2;

public void onRadioButtonClicked(View view) {
    RadioButton radiobutton1 = (RadioButton) findViewById(R.id.krzyzyk);

    if (radiobutton1.isChecked()) {
        score = score + 1;
    }
}
</code>```

It works but when I run the app and click in another RadioButton and again id/krzyzyk the score will update again. Can you help me to fix this problem?

答:
You have think about logic of your quiz, of course score will  be increase because when you choose right answer and check this in listener ( this method calls on every click on button), it will be wrong result, maybe can you try make isChecked when you click on button (Next, Check) or swipe fragment with question, or you can use some variable like flag of wrong-right indicator,

```<code>int m_rightAnswer =0;
...
public void onRadioButtonClicked(View view) {
   RadioButton radiobutton1 = (RadioButton) findViewById(R.id.krzyzyk);

    if (radiobutton1.isChecked() && m_rightAnswer==0){
        score = score + 1; m_rightAnswer=1 }
              }
</code>```

It's working only once, when you click on right answer, and when you click any radio button and return on right your score don't change, but it doesn't have logic

Title: Radiobutton in Android Quiz app

Body:
I am working on quiz app for Android and I use RadioButtons in RadioGroup. I want to achieve that when someone checks the right answer (this case its id/krzyzyk) the score will increase by one point. I made this code:

int score = 2;

public void onRadioButtonClicked(View view) {
    RadioButton radiobutton1 = (RadioButton) findViewById(R.id.krzyzyk);

    if (radiobutton1.isChecked()) {
        score = score + 1;
    }
}

It works but when I run the app and click in another RadioButton and again id/krzyzyk the score will update again. Can you help me to fix this problem?

Body:
You have think about logic of your quiz, of course score will  be increase because when you choose right answer and check this in listener ( this method calls on every click on button), it will be wrong result, maybe can you try make isChecked when you click on button (Next, Check) or swipe fragment with question, or you can use some variable like flag of wrong-right indicator,

int m_rightAnswer =0;
...
public void onRadioButtonClicked(View view) {
   RadioButton radiobutton1 = (RadioButton) findViewById(R.id.krzyzyk);

    if (radiobutton1.isChecked() && m_rightAnswer==0){
        score = score + 1; m_rightAnswer=1 }
              }

It's working only once, when you click on right answer, and when you click any radio button and return on right your score don't change, but it doesn't have logic


问:
Menu bar is a mess in eclipse neon.3 on Ubuntu 16.10
I just installed eclipse neon.3 on Ubuntu 16.10 but the menu bar is a mess in the Java Perspective:

As you can see from above the menu buttons seems to have been thrown randomly in there and I cannot reorder/drag/move them.

Also save buttons looks like at file is dirty - read to be saved but nothing is changed.

Is Eclipse neon.3 broken on Linux/Ubuntu 16.10?

Resetting the perspective has no effect.

Restarting eclipse and now I have even less buttons in the menu bar:

Works fine on windows 7.

As suggested below I have tried to add the following to the eclipse.ini:

But then I can no longer start eclipse and instead get this error:

Get the impression that eclipse has not been that throughly tested for Linux/Ubuntu.

答:
If you want to use the .ini modification workaround; it needs to be before the vmargs. Like this - </p>

```<code>-startup
plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.550.v20170928-1359
-product
org.eclipse.epp.package.dsl.product
-showsplash
org.eclipse.epp.package.common
--launcher.defaultAction
openFile
--launcher.defaultAction
openFile
--launcher.GTK_version
2
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.8
-Dosgi.instance.area.default=@user.home/eclipse-workspace
-XX:+UseG1GC
-XX:+UseStringDeduplication
--add-modules=ALL-SYSTEM
-Dosgi.requiredJavaVersion=1.8
-Xms256m
-Xmx2024m
--add-modules=ALL-SYSTEM
</code>```

Body:
If you want to use the .ini modification workaround; it needs to be before the vmargs. Like this -

-startup
plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.550.v20170928-1359
-product
org.eclipse.epp.package.dsl.product
-showsplash
org.eclipse.epp.package.common
--launcher.defaultAction
openFile
--launcher.defaultAction
openFile
--launcher.GTK_version
2
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.8
-Dosgi.instance.area.default=@user.home/eclipse-workspace
-XX:+UseG1GC
-XX:+UseStringDeduplication
--add-modules=ALL-SYSTEM
-Dosgi.requiredJavaVersion=1.8
-Xms256m
-Xmx2024m
--add-modules=ALL-SYSTEM


问:
'str' object has no attribute 'message_from_bytes'
I have a piece of code to get emails from messages from my inbox (gmail). Getting emails work correct when I print email_from but I would like to do some operation on data split name and email etc. but then code broke after print first loop step and I got the error:

```<code>Traceback (most recent call last):
  File "C:\Users\loc\Desktop\extract_gmail.py", line 24, in <module>
    email_message_raw = email.message_from_bytes(data[0][1])
AttributeError: 'str' object has no attribute 'message_from_bytes'
</code>```

Can you give me some advice how to solve this problem?

Code:

```<code>import imaplib
import email
from email.header import Header, decode_header, make_header

# Connection settings
HOST = 'imap.gmail.com'
USERNAME = '***'
PASSWORD = '***'

m = imaplib.IMAP4_SSL(HOST, 993)
m.login(USERNAME, PASSWORD)
m.select('INBOX')

result, data = m.uid('search', None, "ALL")
if result == 'OK':
    for num in data[0].split()[:5]:
        result, data = m.uid('fetch', num, '(RFC822)')
        if result == 'OK':
            # Get raw message
            email_message_raw = email.message_from_bytes(data[0][1])

            # Decode headers
            email_from = str(make_header(decode_header(email_message_raw['From'])))

            # Print each name and email
            name, email = email_from.split('<')
            email.replace(">", "")
            print(name + "|" + email)

            # When i swap to just print email_from then works
            # print(email_from)

# Close server connection
m.close()
m.logout()
</code>```

答:
I had the same error [happily solved], my mistake was in the shebang. That should point to python3.</p>

```<code>#! /usr/bin/env python3
</code>```

Body:
I have a piece of code to get emails from messages from my inbox (gmail). Getting emails work correct when I print email_from but I would like to do some operation on data split name and email etc. but then code broke after print first loop step and I got the error:

Traceback (most recent call last):
  File "C:\Users\loc\Desktop\extract_gmail.py", line 24, in <module>
    email_message_raw = email.message_from_bytes(data[0][1])
AttributeError: 'str' object has no attribute 'message_from_bytes'

Can you give me some advice how to solve this problem?

Code:

import imaplib
import email
from email.header import Header, decode_header, make_header

# Connection settings
HOST = 'imap.gmail.com'
USERNAME = '***'
PASSWORD = '***'

m = imaplib.IMAP4_SSL(HOST, 993)
m.login(USERNAME, PASSWORD)
m.select('INBOX')

result, data = m.uid('search', None, "ALL")
if result == 'OK':
    for num in data[0].split()[:5]:
        result, data = m.uid('fetch', num, '(RFC822)')
        if result == 'OK':
            # Get raw message
            email_message_raw = email.message_from_bytes(data[0][1])

            # Decode headers
            email_from = str(make_header(decode_header(email_message_raw['From'])))

            # Print each name and email
            name, email = email_from.split('<')
            email.replace(">", "")
            print(name + "|" + email)

            # When i swap to just print email_from then works
            # print(email_from)

# Close server connection
m.close()
m.logout()

Body:
I had the same error [happily solved], my mistake was in the shebang. That should point to python3.

#! /usr/bin/env python3


问:
Read Int32 from binary at specific position
I have a memorystream reading a specific part of my data. From the binary I want one ReadInt32 value from position 5-8. How do I achieve this in:</p>

```<code>using (var reader = new BinaryReader(stream))
{

  somebyte1
  somebyte2
  somebyte3

  //get only this value
  int v = reader.ReadInt32;

}
</code>```

答:
In .NET there are stream types that are seekable and types that don't allow seek. This is indicated by the CanSeek property. If your stream allows seek (and a MemoryStream does), you can just move the current position and read the data. If the stream does not allow seek, your only choice is to read and discard the data until you reach the stream position where your desired data is at. So the generalized solution to your problem would be:

```<code>const int targetPosition = 4;
BinaryReader reader = new BinaryReader(stream);
using (reader) {
    if (stream.CanSeek) {
        stream.Position = targetPosition;
    }
    else {
        reader.ReadBytes(targetPosition);
    }
    int result = reader.ReadInt32();
}
</code>```

Body:
I have a memorystream reading a specific part of my data. From the binary I want one ReadInt32 value from position 5-8. How do I achieve this in:

using (var reader = new BinaryReader(stream))
{

  somebyte1
  somebyte2
  somebyte3

  //get only this value
  int v = reader.ReadInt32;

}

Body:
In .NET there are stream types that are seekable and types that don't allow seek. This is indicated by the CanSeek property. If your stream allows seek (and a MemoryStream does), you can just move the current position and read the data. If the stream does not allow seek, your only choice is to read and discard the data until you reach the stream position where your desired data is at. So the generalized solution to your problem would be:

const int targetPosition = 4;
BinaryReader reader = new BinaryReader(stream);
using (reader) {
    if (stream.CanSeek) {
        stream.Position = targetPosition;
    }
    else {
        reader.ReadBytes(targetPosition);
    }
    int result = reader.ReadInt32();
}


问:
Adding more than one InputMediaAsset to Job in Azure Media Encoder Standard results in 400
Trying to stitch videos using Azure Media Encoder Standard.

Using this piece of code in Java (com.microsoft.azure:azure-media:0.9.7) to create a job for Azure MES:

```<code>Job.Creator jobCreator = Job.create()
    .setName(outputAssetName)
    .addInputMediaAsset("nb:cid:UUID:ID1")
    .addInputMediaAsset("nb:cid:UUID:ID2")
    .setPriority(2)
    .addTaskCreator(task);
</code>```

When submitting the job, this results in the following error:

```<code>Nov 08, 2017 6:30:03 PM com.microsoft.windowsazure.services.media.implementation.MediaExceptionProcessor processCatch
WARNING: com.sun.jersey.api.client.UniformInterfaceException: Client response status: 400
         com.sun.jersey.api.client.UniformInterfaceException: Client response status: 400
at com.microsoft.windowsazure.services.media.implementation.MediaBatchOperations.parseBatchResult(MediaBatchOperations.java:368)
at com.microsoft.windowsazure.services.media.models.Job$Creator.processResponse(Job.java:190)
at com.microsoft.windowsazure.services.media.entityoperations.EntityRestProxy.create(EntityRestProxy.java:138)
at com.microsoft.windowsazure.services.media.implementation.MediaExceptionProcessor.create(MediaExceptionProcessor.java:140)
...
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.lang.Thread.run(Thread.java:748)
</code>```

With a single InputMediaAsset this works fine.

Two questions:

Do you know the solution of how to submit more than one asset using Java?

If not, is there a way to get a more informative error message than just 400 out of Azure MES?

EDIT

Task config:

```<code>{
  "Version": 1.0,
  "Codecs": [
    {
      "Type": "CopyVideo"
    },
    {
      "Type": "CopyAudio"
    }
  ],
  "Outputs": [
    {
      "FileName": "{Basename}_stitch.mp4",
      "Format": {
        "Type": "MP4Format"
      }
    }
  ],
  "Sources": [
    {
      "AssetID": "nb:cid:UUID:ID1",
      "StartTime": "00:00:00",
      "Duration": "00:00:05"
    },
    {
      "AssetID": "nb:cid:UUID:ID2",
      "StartTime": "00:00:00",
      "Duration": "00:00:05"
    }
  ]
}
</code>```

I dug deeper to see if I can at least get a better error message, and I got this:

```<code>HTTP/1.1 400 Bad Request
Content-ID: 2
X-Content-Type-Options: nosniff
Cache-Control: no-cache
DataServiceVersion: 1.0;
Content-Type: application/xml;charset=utf-8

<?xml version="1.0" encoding="utf-8"?><m:error xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"><m:code /><m:message xml:lang="en-US">Input asset not used - nb:cid:UUID:ID2</m:message></m:error>
</code>```

It is telling me that the second input asset is not used, even though I specify it in the task config - and the task config comes from Azure Media Services Explorer and works there.

答:
In your Java code, you should be making a call to create a Task before invoking the Job.Creator. Something like the following:

```<code> Task.CreateBatchOperation task = Task.create(mediaProcessor.getId(), taskXml).setConfiguration(taskConfiguration).setName("Stitching Task");
</code>```

In the above, the taskXml object should have references to both input Assets. The default Java sample code, such as the one here, will only have a reference to a single JobInputAsset element. Since you are using two (or more) input Assets, you will have to expand taskXml to include the additional JobInputAsset elements.

Body:
Trying to stitch videos using Azure Media Encoder Standard.

Using this piece of code in Java (com.microsoft.azure:azure-media:0.9.7) to create a job for Azure MES:

Job.Creator jobCreator = Job.create()
    .setName(outputAssetName)
    .addInputMediaAsset("nb:cid:UUID:ID1")
    .addInputMediaAsset("nb:cid:UUID:ID2")
    .setPriority(2)
    .addTaskCreator(task);

When submitting the job, this results in the following error:

Nov 08, 2017 6:30:03 PM com.microsoft.windowsazure.services.media.implementation.MediaExceptionProcessor processCatch
WARNING: com.sun.jersey.api.client.UniformInterfaceException: Client response status: 400
         com.sun.jersey.api.client.UniformInterfaceException: Client response status: 400
at com.microsoft.windowsazure.services.media.implementation.MediaBatchOperations.parseBatchResult(MediaBatchOperations.java:368)
at com.microsoft.windowsazure.services.media.models.Job$Creator.processResponse(Job.java:190)
at com.microsoft.windowsazure.services.media.entityoperations.EntityRestProxy.create(EntityRestProxy.java:138)
at com.microsoft.windowsazure.services.media.implementation.MediaExceptionProcessor.create(MediaExceptionProcessor.java:140)
...
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.lang.Thread.run(Thread.java:748)

With a single InputMediaAsset this works fine.

Two questions:

Do you know the solution of how to submit more than one asset using Java?

If not, is there a way to get a more informative error message than just 400 out of Azure MES?

EDIT

Task config:

{
  "Version": 1.0,
  "Codecs": [
    {
      "Type": "CopyVideo"
    },
    {
      "Type": "CopyAudio"
    }
  ],
  "Outputs": [
    {
      "FileName": "{Basename}_stitch.mp4",
      "Format": {
        "Type": "MP4Format"
      }
    }
  ],
  "Sources": [
    {
      "AssetID": "nb:cid:UUID:ID1",
      "StartTime": "00:00:00",
      "Duration": "00:00:05"
    },
    {
      "AssetID": "nb:cid:UUID:ID2",
      "StartTime": "00:00:00",
      "Duration": "00:00:05"
    }
  ]
}

I dug deeper to see if I can at least get a better error message, and I got this:

HTTP/1.1 400 Bad Request
Content-ID: 2
X-Content-Type-Options: nosniff
Cache-Control: no-cache
DataServiceVersion: 1.0;
Content-Type: application/xml;charset=utf-8

<?xml version="1.0" encoding="utf-8"?><m:error xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"><m:code /><m:message xml:lang="en-US">Input asset not used - nb:cid:UUID:ID2</m:message></m:error>

It is telling me that the second input asset is not used, even though I specify it in the task config - and the task config comes from Azure Media Services Explorer and works there.

Body:
In your Java code, you should be making a call to create a Task before invoking the Job.Creator. Something like the following:

 Task.CreateBatchOperation task = Task.create(mediaProcessor.getId(), taskXml).setConfiguration(taskConfiguration).setName("Stitching Task");

In the above, the taskXml object should have references to both input Assets. The default Java sample code, such as the one here, will only have a reference to a single JobInputAsset element. Since you are using two (or more) input Assets, you will have to expand taskXml to include the additional JobInputAsset elements.


问:
How to manage UIbutton in UItableViewCell without using sender.tag method?
I have a cell with a button inside. In my cellForRowAtIndexPath method i refeer to my uibutton in this way:

```<code>UIButton *Button= (UIButton *) [cell viewWithTag:3];
</code>```

I have found a solution, something like this:

```<code>Button.tag = indexPath.row;

[Button addTarget:self action:@selector(yourButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

-(void)yourButtonClicked:(UIButton*)sender
{
     if (sender.tag == 0)
     {
         // Your code here
     }
}
</code>```

But my button.tag is already used to identify the UIbutton view from the others views inside the cell, i can't use it for the indexpath.row. How i can do in my case?

EDIT

Finally i have made a Category for the UIButton, it seems the faster ad reusable solutions but every answers here is a valid option

答:
Another option - use a "call back" block.

This assumes you have a Prototype cell with "btnCell" identifier, containing a UIButton connected to the - (IBAction)buttonTapped:(id)sender method shown below...

Your cell class:

```<code>//
//  WithButtonTableViewCell.h
//
//  Created by Don Mag on 11/15/17.
//

#import <UIKit/UIKit.h>

@interface WithButtonTableViewCell : UITableViewCell

- (void)setButtonTappedBlock:(void (^)(id sender))buttonTappedBlock;

@end

//
//  WithButtonTableViewCell.m
//
//  Created by Don Mag on 11/15/17.
//

#import "WithButtonTableViewCell.h"

@interface WithButtonTableViewCell ()

@property (copy, nonatomic) void (^buttonTappedBlock)(id sender);

@end

@implementation WithButtonTableViewCell

- (IBAction)buttonTapped:(id)sender {
    // call back if the block has been set
    if (self.buttonTappedBlock) {
        self.buttonTappedBlock(self);
    }
}

@end
</code>```

Your table view controller class:

```<code>//
//  WithButtonTableViewController.h
//
//  Created by Don Mag on 7/12/17.
//

#import <UIKit/UIKit.h>

@interface WithButtonTableViewController : UITableViewController

@end

//
//  WithButtonTableViewController.m
//
//  Created by Don Mag on 11/15/17.
//

#import "WithButtonTableViewController.h"
#import "WithButtonTableViewCell.h"

@interface WithButtonTableViewController ()

@end

@implementation WithButtonTableViewController

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    WithButtonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"btnCell" forIndexPath:indexPath];

    [cell setButtonTappedBlock:^(id sender) {

        NSLog(@"Button in cell at row %ld in section: %ld was tapped", (long)indexPath.row, (long)indexPath.section);

        // sender is the cell
        // do whatever else you want here...

    }];

    return cell;

}

@end
</code>```

Now, when the button in the cell is tapped, it will "call back" to the view controller, at which point the code inside the Block will be executed.

Body:
I have a cell with a button inside. In my cellForRowAtIndexPath method i refeer to my uibutton in this way:

UIButton *Button= (UIButton *) [cell viewWithTag:3];

I have found a solution, something like this:

Button.tag = indexPath.row;

[Button addTarget:self action:@selector(yourButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

-(void)yourButtonClicked:(UIButton*)sender
{
     if (sender.tag == 0)
     {
         // Your code here
     }
}

But my button.tag is already used to identify the UIbutton view from the others views inside the cell, i can't use it for the indexpath.row. How i can do in my case?

EDIT

Finally i have made a Category for the UIButton, it seems the faster ad reusable solutions but every answers here is a valid option

Body:
Another option - use a "call back" block.

This assumes you have a Prototype cell with "btnCell" identifier, containing a UIButton connected to the - (IBAction)buttonTapped:(id)sender method shown below...

Your cell class:

//
//  WithButtonTableViewCell.h
//
//  Created by Don Mag on 11/15/17.
//

#import <UIKit/UIKit.h>

@interface WithButtonTableViewCell : UITableViewCell

- (void)setButtonTappedBlock:(void (^)(id sender))buttonTappedBlock;

@end

//
//  WithButtonTableViewCell.m
//
//  Created by Don Mag on 11/15/17.
//

#import "WithButtonTableViewCell.h"

@interface WithButtonTableViewCell ()

@property (copy, nonatomic) void (^buttonTappedBlock)(id sender);

@end

@implementation WithButtonTableViewCell

- (IBAction)buttonTapped:(id)sender {
    // call back if the block has been set
    if (self.buttonTappedBlock) {
        self.buttonTappedBlock(self);
    }
}

@end

Your table view controller class:

//
//  WithButtonTableViewController.h
//
//  Created by Don Mag on 7/12/17.
//

#import <UIKit/UIKit.h>

@interface WithButtonTableViewController : UITableViewController

@end

//
//  WithButtonTableViewController.m
//
//  Created by Don Mag on 11/15/17.
//

#import "WithButtonTableViewController.h"
#import "WithButtonTableViewCell.h"

@interface WithButtonTableViewController ()

@end

@implementation WithButtonTableViewController

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    WithButtonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"btnCell" forIndexPath:indexPath];

    [cell setButtonTappedBlock:^(id sender) {

        NSLog(@"Button in cell at row %ld in section: %ld was tapped", (long)indexPath.row, (long)indexPath.section);

        // sender is the cell
        // do whatever else you want here...

    }];

    return cell;

}

@end

Now, when the button in the cell is tapped, it will "call back" to the view controller, at which point the code inside the Block will be executed.


问:
How to create a mysql db with Laravel
I'm using Laravel 5.2.  I've setup my first migrations and I want to run them.  From the video tutorial it doesn't explain how to create a mysql db.  I know I can do this manually in phpmyadmin but is there a Laravel way to do it?

This will install the migrations table:

```<code>php artisan migrate:install
</code>```

Is there a similar command that will create the DB?

I'm thinking the process should be:

```<code>php artisan DB:install (or similar command)
</code>```

Install the migrations table:

```<code>php artisan migrate:install
</code>```

Run the migrations:

```<code>php artisan migrate
</code>```

and to rollback the migrations:

```<code>php artisan migrate:rollback
</code>```

答:
This answer might be useful if you are using different mysql connection also. I am writing code in laravel 5.5

Step:1  Create command

```<code>php artisan make:command CreateDatabaseCommand
</code>```

Step:2 In app/Console/Kernel.php register the command

```<code>protected $commands = [
    CreateDatabaseCommand::class
];
</code>```

Step:3 Write logic in your CreateDatabaseCommand.php file

```<code>    protected $signature = 'make:database {dbname} {connection?}';

    public function handle()
    {
     try{
         $dbname = $this->argument('dbname');
         $connection = $this->hasArgument('connection') && $this->argument('connection') ? $this->argument('connection'): DB::connection()->getPDO()->getAttribute(PDO::ATTR_DRIVER_NAME);

         $hasDb = DB::connection($connection)->select("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = "."'".$dbname."'");

         if(empty($hasDb)) {
             DB::connection($connection)->select('CREATE DATABASE '. $dbname);
             $this->info("Database '$dbname' created for '$connection' connection");
         }
         else {
             $this->info("Database $dbname already exists for $connection connection");
         }
     }
     catch (\Exception $e){
         $this->error($e->getMessage());
     }
   }
</code>```

That's all. Now run your command

```<code>php artisan make:database {your-database-name} {your-connection-name}:
</code>```

Note ::  You should use second argument only if you want to create database in any different connection from default mysql connection otherwise command will automatically take the default db connection

Hope this will help someone :)

Title: How to create a mysql db with Laravel

Body:
I'm using Laravel 5.2.  I've setup my first migrations and I want to run them.  From the video tutorial it doesn't explain how to create a mysql db.  I know I can do this manually in phpmyadmin but is there a Laravel way to do it?

This will install the migrations table:

php artisan migrate:install

Is there a similar command that will create the DB?

I'm thinking the process should be:

php artisan DB:install (or similar command)

Install the migrations table:

php artisan migrate:install

Run the migrations:

php artisan migrate

and to rollback the migrations:

php artisan migrate:rollback

Body:
This answer might be useful if you are using different mysql connection also. I am writing code in laravel 5.5

Step:1  Create command

php artisan make:command CreateDatabaseCommand

Step:2 In app/Console/Kernel.php register the command

protected $commands = [
    CreateDatabaseCommand::class
];

Step:3 Write logic in your CreateDatabaseCommand.php file

    protected $signature = 'make:database {dbname} {connection?}';

    public function handle()
    {
     try{
         $dbname = $this->argument('dbname');
         $connection = $this->hasArgument('connection') && $this->argument('connection') ? $this->argument('connection'): DB::connection()->getPDO()->getAttribute(PDO::ATTR_DRIVER_NAME);

         $hasDb = DB::connection($connection)->select("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = "."'".$dbname."'");

         if(empty($hasDb)) {
             DB::connection($connection)->select('CREATE DATABASE '. $dbname);
             $this->info("Database '$dbname' created for '$connection' connection");
         }
         else {
             $this->info("Database $dbname already exists for $connection connection");
         }
     }
     catch (\Exception $e){
         $this->error($e->getMessage());
     }
   }

That's all. Now run your command

php artisan make:database {your-database-name} {your-connection-name}:

Note ::  You should use second argument only if you want to create database in any different connection from default mysql connection otherwise command will automatically take the default db connection

Hope this will help someone :)


问:
How to hide input for X and Y axis in plotly.js?
Is it posible to hide or disable the input field which appears when clicking the axis in plotly.js?

plotly.js line chart

答:
As far as I know there is no setting in Plotly but you could hide the editable div in your css settings.

Setting the layout of xaxis to fixedrange: true will hide the input box but won't allow any kind of zooming.

var trace1 = {
  x: [1, 2, 3, 4],
  y: [10, 15, 13, 17],
  type: 'scatter'
};
var trace2 = {
  x: [1, 2, 3, 4],
  y: [16, 5, 11, 9],
  type: 'scatter'
};
var data = [trace1, trace2];
Plotly.newPlot('myDiv', data);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.editable {
  display: none;
}</code>```

```

Body:
As far as I know there is no setting in Plotly but you could hide the editable div in your css settings.

Setting the layout of xaxis to fixedrange: true will hide the input box but won't allow any kind of zooming.

var trace1 = {
  x: [1, 2, 3, 4],
  y: [10, 15, 13, 17],
  type: 'scatter'
};
var trace2 = {
  x: [1, 2, 3, 4],
  y: [16, 5, 11, 9],
  type: 'scatter'
};
var data = [trace1, trace2];
Plotly.newPlot('myDiv', data);

div.editable {
  display: none;
}

<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="myDiv"></div>


问:
Simple Rails Conditional Statement
Pretty simple I'm sure... but I can't figure out why it wouldn't work.

```<code><tr<% if film.viewed == true %> class="viewed"<% end %>>
</code>```

The film.viewed is a boolean but its not rendering the class if its true. Probably a syntax error. Any help? Also is there an easier way to write this without opening and closing? I tried using:

```<code><tr<% if film.viewed == true puts class=\"viewed\" end %>>
</code>```

Again probably a syntax error. I'm coming from PHP so I'm still learning.

Thanks.

答:
I'm guessing film.viewed isn't true, but another value.

try something to the effect of

```<code><tr <%= "class='viewed'" if film.viewed %> >
</code>```

ContentLicense: CC BY-SA 2.5

Title: Simple Rails Conditional Statement

Body:
Pretty simple I'm sure... but I can't figure out why it wouldn't work.

<tr<% if film.viewed == true %> class="viewed"<% end %>>

The film.viewed is a boolean but its not rendering the class if its true. Probably a syntax error. Any help? Also is there an easier way to write this without opening and closing? I tried using:

<tr<% if film.viewed == true puts class=\"viewed\" end %>>

Again probably a syntax error. I'm coming from PHP so I'm still learning.

Thanks.

Body:
I'm guessing film.viewed isn't true, but another value.

try something to the effect of

<tr <%= "class='viewed'" if film.viewed %> >


问:
Is it legal to call memchr with a too-long length, if you know the character will be found before reaching the end of the valid region?
Is the following defined behavior in C11 and C++111?

```<code>bool has4() {
    char buf[10] = {0, 1, 2, 4};
    return memchr(buf, 4, 20);
}
</code>```

Here we pass a too-long length to memchr. The array has 10 elements but we pass 20. The element we are searching for, however, is always found before the end. It is clear to me if this is legal.

If this is allowed, it would limit implementation flexibility, since the implementation cannot rely on the size being a valid indication of the size of the accessible memory region and hence must be careful about reading beyond the found element. An example would be an implementation that wants to do a 16 byte SIMD load starting at the passed-in pointer and then check all the 16 bytes in parallel. If the user passes a length of 16, this would be safe only if the entire length was required to be accessible.

Otherwise (if the above code is legal) the implementation must avoid potentially faulting on elements past the target element, for example by aligning the load (potentially expensive) or checking if the pointer is near the end of a protection boundary.

1 Here's one of those rare questions where I guess tagging both C and C++ is valid: as far as I can tell the C++ standard just defers directly to the C standard here, via reference, in terms of behavior, but if that's not the case I want to know.

答:
In C11 and C++17 (emphasis mine)

void *memchr(const void *s, int c, size_t n);

  The memchr function locates the first occurrence of c (converted to an unsigned char) in the initial n characters (each interpreted as unsigned char) of the object
  pointed to by s. The implementation shall behave as if it reads the characters sequentially
  and stops as soon as a matching character is found.

So long as memchr finds what it's looking for before you step out of bounds, you're okay.

C++11 and C++14 both use C99, which doesn't have such wording. (They refer to ISO/IEC 9899:1999)

C99 wording:

void *memchr(const void *s, int c, size_t n);

The memchr function locates the first occurrence of c (converted to an unsigned char) in the initial n characters (each interpreted as unsigned char) of the object
  pointed to by s.

By not defining what happens if you pass too large of a size, the behavior is undefined in C99

Body:
Is the following defined behavior in C11 and C++111?

bool has4() {
    char buf[10] = {0, 1, 2, 4};
    return memchr(buf, 4, 20);
}

Here we pass a too-long length to memchr. The array has 10 elements but we pass 20. The element we are searching for, however, is always found before the end. It is clear to me if this is legal.

If this is allowed, it would limit implementation flexibility, since the implementation cannot rely on the size being a valid indication of the size of the accessible memory region and hence must be careful about reading beyond the found element. An example would be an implementation that wants to do a 16 byte SIMD load starting at the passed-in pointer and then check all the 16 bytes in parallel. If the user passes a length of 16, this would be safe only if the entire length was required to be accessible.

Otherwise (if the above code is legal) the implementation must avoid potentially faulting on elements past the target element, for example by aligning the load (potentially expensive) or checking if the pointer is near the end of a protection boundary.

1 Here's one of those rare questions where I guess tagging both C and C++ is valid: as far as I can tell the C++ standard just defers directly to the C standard here, via reference, in terms of behavior, but if that's not the case I want to know.


问:
mbind: Operation not permitted when connecting with sequel pro
I'm running MySQL 8.0 inside a docker container for local development. The web container can connect to mysql just fine. When trying to access my database from Sequel Pro, the container gives me an error,

db_1   | mbind: Operation not permitted

It should be noted that connecting with MySQL Workbench does not cause the container to throw that error, but it also doesn't full connect. It does display the database and tables, but fails to query the tables. I've included the error from Sequel Pro below.

```<code>NSInvalidArgumentException

-[_NSInlineData isEqualToString:]: unrecognized selector sent to instance 0x608000039740

(
    0   CoreFoundation                      0x00007fff3cae52fb         __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x00007fff63452c76     objc_exception_throw + 48
    2   CoreFoundation                      0x00007fff3cb7dda4 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
    3   CoreFoundation                      0x00007fff3ca5b670 ___forwarding___ + 1456
    4   CoreFoundation                      0x00007fff3ca5b038 _CF_forwarding_prep_0 + 120
    5   Sequel Pro                          0x000000010002fce3 -[SPDatabaseDocument setDatabases:] + 783
    6   Sequel Pro                          0x000000010002f2a9 -[SPDatabaseDocument setConnection:] + 610
    7   Foundation                          0x00007fff3eb56985 __NSThreadPerformPerform + 334
    8   CoreFoundation                      0x00007fff3ca7d821 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    9   CoreFoundation                      0x00007fff3cb374cc __CFRunLoopDoSource0 + 108
    10  CoreFoundation                      0x00007fff3ca602c0 __CFRunLoopDoSources0 + 208
    11  CoreFoundation                      0x00007fff3ca5f73d __CFRunLoopRun + 1293
    12  CoreFoundation                      0x00007fff3ca5efa3 CFRunLoopRunSpecific + 483
    13  HIToolbox                           0x00007fff3bd7e866 RunCurrentEventLoopInMode + 286
    14  HIToolbox                           0x00007fff3bd7e5d6 ReceiveNextEventCommon + 613
    15  HIToolbox                           0x00007fff3bd7e354 _BlockUntilNextEventMatchingListInModeWithFilter + 64
    16  AppKit                              0x00007fff3a07ba23 _DPSNextEvent + 2085
    17  AppKit                              0x00007fff3a810e6c -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 3044
    18  AppKit                              0x00007fff3a070831 -[NSApplication run] + 764
    19  AppKit                              0x00007fff3a03f9d2 NSApplicationMain + 804
    20  Sequel Pro                          0x0000000100002454 start + 52
</code>```

)

答: I get that error as well from the mysql8 community docker container.  However it has never blocked me from doing anything, so I suspect the problem is elsewhere.</p>

Body:
I'm running MySQL 8.0 inside a docker container for local development. The web container can connect to mysql just fine. When trying to access my database from Sequel Pro, the container gives me an error,

db_1   | mbind: Operation not permitted

It should be noted that connecting with MySQL Workbench does not cause the container to throw that error, but it also doesn't full connect. It does display the database and tables, but fails to query the tables. I've included the error from Sequel Pro below.

NSInvalidArgumentException

-[_NSInlineData isEqualToString:]: unrecognized selector sent to instance 0x608000039740

(
    0   CoreFoundation                      0x00007fff3cae52fb         __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x00007fff63452c76     objc_exception_throw + 48
    2   CoreFoundation                      0x00007fff3cb7dda4 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
    3   CoreFoundation                      0x00007fff3ca5b670 ___forwarding___ + 1456
    4   CoreFoundation                      0x00007fff3ca5b038 _CF_forwarding_prep_0 + 120
    5   Sequel Pro                          0x000000010002fce3 -[SPDatabaseDocument setDatabases:] + 783
    6   Sequel Pro                          0x000000010002f2a9 -[SPDatabaseDocument setConnection:] + 610
    7   Foundation                          0x00007fff3eb56985 __NSThreadPerformPerform + 334
    8   CoreFoundation                      0x00007fff3ca7d821 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    9   CoreFoundation                      0x00007fff3cb374cc __CFRunLoopDoSource0 + 108
    10  CoreFoundation                      0x00007fff3ca602c0 __CFRunLoopDoSources0 + 208
    11  CoreFoundation                      0x00007fff3ca5f73d __CFRunLoopRun + 1293
    12  CoreFoundation                      0x00007fff3ca5efa3 CFRunLoopRunSpecific + 483
    13  HIToolbox                           0x00007fff3bd7e866 RunCurrentEventLoopInMode + 286
    14  HIToolbox                           0x00007fff3bd7e5d6 ReceiveNextEventCommon + 613
    15  HIToolbox                           0x00007fff3bd7e354 _BlockUntilNextEventMatchingListInModeWithFilter + 64
    16  AppKit                              0x00007fff3a07ba23 _DPSNextEvent + 2085
    17  AppKit                              0x00007fff3a810e6c -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 3044
    18  AppKit                              0x00007fff3a070831 -[NSApplication run] + 764
    19  AppKit                              0x00007fff3a03f9d2 NSApplicationMain + 804
    20  Sequel Pro                          0x0000000100002454 start + 52

)


问:
Should I rely on transitive dependencies in Maven if they come from other sub-module of my parent?
Suppose we are working on mortgage sub-module, and we are directly using the Google Guava classes in module code, but the dependcy for the guava is defined in other sub-module under the same parent and we have access to Guava classes only by transitive dependency on "investment" module:

```<code>banking-system (parent pom.xml)
|
|-- investment (pom.xml defines <dependency>guava</dependency>)
|
|-- mortgage (pom.xml defiens <dependency>investment</dependency>)
</code>```

Should we still put a <dependency> to Guava in the mortgage pom.xml?

The cons looks like duplication in our pom.xml, the pros are: if someone developing "investment" will drop guava, then it will not stop our mortgage sub-module from being successfuly build.

If yes, then what <version> shoudle we specify? (none + <dependencyManagement> in parent pom?)

If yes, should we use a <provided> scope in some module then?

Note: Keep in mind, that I am asking in specific situation, when modules have common parent pom (e.g. being an application as whole).

Maybe this structure was not the best example, imagine:

```<code>banking-app
    banking-core (dep.on: guava, commons, spring)
    investment (dep.on: banking-core)
    mortgage (dep.on: banking-core)
</code>```

Should still Investment explicitly declare Spring when it use @Component, and declare Guava if it uses Guava's LoadedCache?

答:
Yes, declare the dep. It's not a duplication!!! That compile dependencies are transitive is not intended by the maven developer, it's forced by the java-language. Because features like class-inheritance forces this behavior. Your already mentioned "pro" is the important fact.
See the (*) note in the transitive-scope-table

Yes, always declare needed third party lib-versions in your reactor parent with dependencyManagement. It's a pain to find errors from different lib-versions at runtime. Avoid declaring versions of third-party libs in sub-modules of large reactors, always use a depMngs in parent.

No, i would use "provided" only for dependencies provided from the runtime, in your example tomcat/jboss/wildfly/.. for things like servlet-api/cdi-api/. But not for third party libraries.
Declare the "provided" scope as late as possible (i.e. your deployment(s) module war/ear) not in your business modules. This makes it easier to write tests.
For example:

investment (depends on guava scope:=provided)

mortgage (depends on investment, but don't need guava himself)

--> mortgage classpath doesn't contain guava.
If you write a unit-test for mortgage where classes involved from investment it will not work -> you need to declare at least guava with scope=test/runtime to run these tests...

Body:
Suppose we are working on mortgage sub-module, and we are directly using the Google Guava classes in module code, but the dependcy for the guava is defined in other sub-module under the same parent and we have access to Guava classes only by transitive dependency on "investment" module:

banking-system (parent pom.xml)
|
|-- investment (pom.xml defines <dependency>guava</dependency>)
|
|-- mortgage (pom.xml defiens <dependency>investment</dependency>)

Should we still put a <dependency> to Guava in the mortgage pom.xml?

The cons looks like duplication in our pom.xml, the pros are: if someone developing "investment" will drop guava, then it will not stop our mortgage sub-module from being successfuly build.

If yes, then what <version> shoudle we specify? (none + <dependencyManagement> in parent pom?)

If yes, should we use a <provided> scope in some module then?

Note: Keep in mind, that I am asking in specific situation, when modules have common parent pom (e.g. being an application as whole).

Maybe this structure was not the best example, imagine:

banking-app
    banking-core (dep.on: guava, commons, spring)
    investment (dep.on: banking-core)
    mortgage (dep.on: banking-core)

Should still Investment explicitly declare Spring when it use @Component, and declare Guava if it uses Guava's LoadedCache?


问:
JavaFX Fix Layout of Pane
I am looking to model a simple microwave using JavaFX by adding gridPanes to a Pane.
 Microwave

Above is what the result should look like but I am having trouble laying out the gridPanes correctly.

Any help on how I could improve this would be appreciated.
Here is what my result looks like and my code to accompany it.

my output

```<code>import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javafx.geometry.Insets;
import javafx.scene.control.TextField;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Pane;
import javafx.scene.control.Label;

public class Microwave extends Application
{
    @Override
    public void start(Stage primaryStage)
    {
        Pane root = new Pane();
        GridPane gPane1 = new GridPane();
        GridPane gPane2 = new GridPane();
        TextField time = new TextField("Time to be displayed here");
        Label food = new Label("Place food here");

        Button start_button = new Button("Start");
        Button stop_button = new Button("Stop");
        Button button_0 = new Button("0");
        Button button_1 = new Button("1");
        Button button_2 = new Button("2");
        Button button_3 = new Button("3");
        Button button_4 = new Button("4");
        Button button_5 = new Button("5");
        Button button_6 = new Button("6");
        Button button_7 = new Button("7");
        Button button_8 = new Button("8");
        Button button_9 = new Button("9");

        gPane1.add(start_button, 1, 3);
        gPane1.add(stop_button, 2, 3);
        gPane1.add(button_0, 0, 3);
        gPane1.add(button_1, 0, 0);
        gPane1.add(button_2, 1, 0);
        gPane1.add(button_3, 2, 0);
        gPane1.add(button_4, 0, 1);
        gPane1.add(button_5, 1, 1);
        gPane1.add(button_6, 2, 1);
        gPane1.add(button_7, 0, 2);
        gPane1.add(button_8, 1, 2);
        gPane1.add(button_9, 2, 2);

        gPane2.add(time,0,0);

        root.getChildren().addAll(gPane1,gPane2,food);

        Scene scene = new Scene(root,200,50);
        primaryStage.setTitle("Microwave Oven");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args)
    {
        launch(args);
    }

}
</code>```

答:
Here is an example created in SceneBuilder. You can use the FXML to figure out how to do this in code.

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

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.layout.VBox?>

<HBox alignment="CENTER" prefHeight="300.0" prefWidth="500.0" style="-fx-border-color: black; -fx-border-width: 3px;" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <Label alignment="CENTER" text="Place Food Here">
         <HBox.margin>
            <Insets left="10.0" right="10.0" />
         </HBox.margin>
      </Label>
      <VBox style="-fx-border-color: black; -fx-border-width: 3px;" HBox.hgrow="ALWAYS">
         <children>
            <TextField prefHeight="50.0" promptText="Time to be displayed here">
               <VBox.margin>
                  <Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
               </VBox.margin>
            </TextField>
            <Pane prefHeight="10.0" style="-fx-background-color: black;" />
            <GridPane VBox.vgrow="ALWAYS">
               <columnConstraints>
                  <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                  <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                  <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
               </columnConstraints>
               <rowConstraints>
                  <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                  <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                  <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                  <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
               </rowConstraints>
               <children>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="1">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="2" GridPane.columnIndex="1">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="3" GridPane.columnIndex="2">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="4" GridPane.rowIndex="1">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="5" GridPane.columnIndex="1" GridPane.rowIndex="1">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="6" GridPane.columnIndex="2" GridPane.rowIndex="1">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="7" GridPane.rowIndex="2">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="8" GridPane.columnIndex="1" GridPane.rowIndex="2">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="9" GridPane.columnIndex="2" GridPane.rowIndex="2">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="0" GridPane.rowIndex="3">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="Start" GridPane.columnIndex="1" GridPane.rowIndex="3">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="Stop" GridPane.columnIndex="2" GridPane.rowIndex="3">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
               </children>
            </GridPane>
         </children>
      </VBox>
   </children>
</HBox>
</code>```

Title: JavaFX Fix Layout of Pane

Body:
I am looking to model a simple microwave using JavaFX by adding gridPanes to a Pane.
 Microwave

Above is what the result should look like but I am having trouble laying out the gridPanes correctly.

Any help on how I could improve this would be appreciated.
Here is what my result looks like and my code to accompany it.

my output

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javafx.geometry.Insets;
import javafx.scene.control.TextField;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Pane;
import javafx.scene.control.Label;

public class Microwave extends Application
{
    @Override
    public void start(Stage primaryStage)
    {
        Pane root = new Pane();
        GridPane gPane1 = new GridPane();
        GridPane gPane2 = new GridPane();
        TextField time = new TextField("Time to be displayed here");
        Label food = new Label("Place food here");

        Button start_button = new Button("Start");
        Button stop_button = new Button("Stop");
        Button button_0 = new Button("0");
        Button button_1 = new Button("1");
        Button button_2 = new Button("2");
        Button button_3 = new Button("3");
        Button button_4 = new Button("4");
        Button button_5 = new Button("5");
        Button button_6 = new Button("6");
        Button button_7 = new Button("7");
        Button button_8 = new Button("8");
        Button button_9 = new Button("9");

        gPane1.add(start_button, 1, 3);
        gPane1.add(stop_button, 2, 3);
        gPane1.add(button_0, 0, 3);
        gPane1.add(button_1, 0, 0);
        gPane1.add(button_2, 1, 0);
        gPane1.add(button_3, 2, 0);
        gPane1.add(button_4, 0, 1);
        gPane1.add(button_5, 1, 1);
        gPane1.add(button_6, 2, 1);
        gPane1.add(button_7, 0, 2);
        gPane1.add(button_8, 1, 2);
        gPane1.add(button_9, 2, 2);

        gPane2.add(time,0,0);

        root.getChildren().addAll(gPane1,gPane2,food);

        Scene scene = new Scene(root,200,50);
        primaryStage.setTitle("Microwave Oven");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args)
    {
        launch(args);
    }

}

Body:
Here is an example created in SceneBuilder. You can use the FXML to figure out how to do this in code.

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

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.layout.VBox?>

<HBox alignment="CENTER" prefHeight="300.0" prefWidth="500.0" style="-fx-border-color: black; -fx-border-width: 3px;" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <Label alignment="CENTER" text="Place Food Here">
         <HBox.margin>
            <Insets left="10.0" right="10.0" />
         </HBox.margin>
      </Label>
      <VBox style="-fx-border-color: black; -fx-border-width: 3px;" HBox.hgrow="ALWAYS">
         <children>
            <TextField prefHeight="50.0" promptText="Time to be displayed here">
               <VBox.margin>
                  <Insets bottom="5.0" left="5.0" right="5.0" top="5.0" />
               </VBox.margin>
            </TextField>
            <Pane prefHeight="10.0" style="-fx-background-color: black;" />
            <GridPane VBox.vgrow="ALWAYS">
               <columnConstraints>
                  <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                  <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                  <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
               </columnConstraints>
               <rowConstraints>
                  <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                  <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                  <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                  <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
               </rowConstraints>
               <children>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="1">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="2" GridPane.columnIndex="1">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="3" GridPane.columnIndex="2">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="4" GridPane.rowIndex="1">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="5" GridPane.columnIndex="1" GridPane.rowIndex="1">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="6" GridPane.columnIndex="2" GridPane.rowIndex="1">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="7" GridPane.rowIndex="2">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="8" GridPane.columnIndex="1" GridPane.rowIndex="2">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="9" GridPane.columnIndex="2" GridPane.rowIndex="2">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="0" GridPane.rowIndex="3">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="Start" GridPane.columnIndex="1" GridPane.rowIndex="3">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
                  <Button maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="Stop" GridPane.columnIndex="2" GridPane.rowIndex="3">
                     <GridPane.margin>
                        <Insets bottom="10.0" left="15.0" right="5.0" top="10.0" />
                     </GridPane.margin>
                  </Button>
               </children>
            </GridPane>
         </children>
      </VBox>
   </children>
</HBox>


问:
Cloudinary widget use in React
I am new to React.  I am looking for a good way to upload photos to Cloudinary.  I saw the Cloudinary widget but I am having trouble implementing it in a React app as described:
https://cloudinary.com/blog/how_to_build_an_image_library_with_react_cloudinary#uploading_images

I put the script tag in index.html body:

```<code><script src="//widget.cloudinary.com/global/all.js" type="text/javascript"></script>
</code>```

then try to use in component:

```<code>class Landing extends Component {
  uploadWidget() {
    cloudinary.openUploadWidget(
      { cloud_name: 'minetoo', upload_preset: 'mine', tags: ['xmas'] },
      function(error, result) {
        console.log(result);
      }
    );
  }
...
</code>```

but I get the error:
'cloudinary' is not defined

My app's boilerplate is generated with create-react-app if that matters.

答:
This is very normal as pointed here and here. You need to access the cloudinary object from the window object:

```<code>window.cloudinary.openUploadWidget(...)
</code>```

Title: Cloudinary widget use in React

Body:
I am new to React.  I am looking for a good way to upload photos to Cloudinary.  I saw the Cloudinary widget but I am having trouble implementing it in a React app as described:
https://cloudinary.com/blog/how_to_build_an_image_library_with_react_cloudinary#uploading_images

I put the script tag in index.html body:

then try to use in component:

class Landing extends Component {
  uploadWidget() {
    cloudinary.openUploadWidget(
      { cloud_name: 'minetoo', upload_preset: 'mine', tags: ['xmas'] },
      function(error, result) {
        console.log(result);
      }
    );
  }
...

but I get the error:
'cloudinary' is not defined

My app's boilerplate is generated with create-react-app if that matters.

Body:
This is very normal as pointed here and here. You need to access the cloudinary object from the window object:

window.cloudinary.openUploadWidget(...)


问:
Cannot ping a variable in Powershell?
I'm still very much a noob in scripting in powershell but I cannot fathom why the following to work. And I believe it why I cannot get some variables to set.</p>

```<code>PS C:\WINDOWS\system32> $s
PC04PA71

PS C:\WINDOWS\system32> ping $s

Ping request could not find host PC04PA71
. Please check the name and try again.

PS C:\WINDOWS\system32> ping PC04PA71

Pinging PC04PA71.xxx.xxx.xxx.com [xxx.xxx.190.160] with 32 bytes of data:
Reply from xxx.xxx.190.160: bytes=32 time=68ms TTL=124
</code>```

答:
try to trim your variable and dont forget you can use Test-Connection in PowerShell</p>

```<code>Test-Connection $s.Trim()
</code>```

Title: Cannot ping a variable in Powershell?

Body:
I'm still very much a noob in scripting in powershell but I cannot fathom why the following to work. And I believe it why I cannot get some variables to set.

PS C:\WINDOWS\system32> $s
PC04PA71

PS C:\WINDOWS\system32> ping $s

Ping request could not find host PC04PA71
. Please check the name and try again.

PS C:\WINDOWS\system32> ping PC04PA71

Pinging PC04PA71.xxx.xxx.xxx.com [xxx.xxx.190.160] with 32 bytes of data:
Reply from xxx.xxx.190.160: bytes=32 time=68ms TTL=124

Body:
try to trim your variable and dont forget you can use Test-Connection in PowerShell

Test-Connection $s.Trim()