问:
Multi line and style Android button with image
My goal is to make button with a rounded image on the left without padding and a multi line text on the right where the 2 lines have different style(color/font). Like this:

My problems are:

I don't know how to implement the multi line button text

The image corners are not rounded on the left

The image is bigger than requested

See my result:

My code is the following:

buttonshape.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
    <corners android:radius="5dp" />
    <solid android:color="#F7F7F7" />
    <padding
        android:left="0dp"
        android:top="0dp"
        android:right="0dp"
        android:bottom="0dp" />
    <size android:width="270dp"
          android:height="60dp" />
</shape>
</code>```

myActivity.xml:

```<code><Button
    android:id="@+id/parkingBtn"
    android:layout_width="0dp"
    android:layout_height="82dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginTop="8dp"
    android:background="@drawable/buttonshape"
    android:drawableStart="@drawable/parking"
    android:drawablePadding="20dp"
    android:text="Parking"
    android:textAlignment="viewStart"
    android:textAllCaps="false"
    android:textColor="@color/colorPrimary"
    android:textDirection="ltr"
    android:textSize="18sp"
    android:cropToPadding="true"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/otherBtn" />
</code>```

Update:
I changed to CardView and the result is almost fine. Thanks the tip for @pouya. The problem is that the rounded corners are not visible on the image.

card_layout.xml:

```<code><android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    card_view:cardCornerRadius="15dp"
    card_view:cardElevation="2dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/buttonshape15"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="24dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:background="@drawable/parking" />

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical"
            android:paddingStart="16dp">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif"
                android:paddingTop="8dp"
                android:text="Parking"
                android:textColor="@color/colorPrimary"
                android:textSize="24sp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingTop="8dp"
                android:text="Pay without coins" />
        </LinearLayout>
    </LinearLayout>

</android.support.v7.widget.CardView>
</code>```

And the result is:

(I have changed the border color and radius for better visibility)

Update 2:
Even closer to the final result. Now border is present, only the shadow is missing:

layout.xml:

```<code><LinearLayout xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@drawable/buttonshape15" >

    <android.support.v7.widget.CardView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        card_view:cardCornerRadius="15dp"
        card_view:cardElevation="0dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <ImageView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:scaleType="fitXY"
                android:background="@drawable/parking" />

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="6"
                android:orientation="vertical"
                android:paddingStart="16dp">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:fontFamily="sans-serif"
                    android:paddingTop="6dp"
                    android:text="Parking"
                    android:textColor="@color/colorPrimary"
                    android:textSize="22sp" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:paddingTop="3dp"
                    android:text="Pay without coins"
                    android:textSize="12sp" />
            </LinearLayout>
        </LinearLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>
</code>```

To solve the shadow problem I have tried to use layer-list in the background.xml but it gives ugly shadows. Wrapping everything again inside a CardView and set the elevation gives better result but not as perfect as the reference layout has.

答:
I would use a CardView as parent view with card_view:cornerRadius=5dp and then in that a LinearLayout so it would look something like this .

```<code><android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="@color/black"
android:id="@+id/root_layout"
android:theme="@style/light_list_item"
card_view:cornerRadius=5dp>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp" >
<ImageView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.5"
    android:background="@mipmap/ic_launcher"/>
<LinearLayout
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="name"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="cost"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="benefit"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</code>```

note that I think you should use background for ImageView.

edit for shadow issue please place a parent for cardView that should be either LinearLayout or RelativeLayout . I haven't test it my self but I am quite sure that it would work.

hope this helps please comment if there is something wrong with this.

Body:
My goal is to make button with a rounded image on the left without padding and a multi line text on the right where the 2 lines have different style(color/font). Like this:

My problems are:

I don't know how to implement the multi line button text

The image corners are not rounded on the left

The image is bigger than requested

See my result:

My code is the following:

buttonshape.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
    <corners android:radius="5dp" />
    <solid android:color="#F7F7F7" />
    <padding
        android:left="0dp"
        android:top="0dp"
        android:right="0dp"
        android:bottom="0dp" />
    <size android:width="270dp"
          android:height="60dp" />
</shape>

myActivity.xml:

<Button
    android:id="@+id/parkingBtn"
    android:layout_width="0dp"
    android:layout_height="82dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginTop="8dp"
    android:background="@drawable/buttonshape"
    android:drawableStart="@drawable/parking"
    android:drawablePadding="20dp"
    android:text="Parking"
    android:textAlignment="viewStart"
    android:textAllCaps="false"
    android:textColor="@color/colorPrimary"
    android:textDirection="ltr"
    android:textSize="18sp"
    android:cropToPadding="true"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/otherBtn" />

Update:
I changed to CardView and the result is almost fine. Thanks the tip for @pouya. The problem is that the rounded corners are not visible on the image.

card_layout.xml:

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    card_view:cardCornerRadius="15dp"
    card_view:cardElevation="2dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/buttonshape15"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="24dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:background="@drawable/parking" />

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical"
            android:paddingStart="16dp">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif"
                android:paddingTop="8dp"
                android:text="Parking"
                android:textColor="@color/colorPrimary"
                android:textSize="24sp" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingTop="8dp"
                android:text="Pay without coins" />
        </LinearLayout>
    </LinearLayout>

</android.support.v7.widget.CardView>

And the result is:

(I have changed the border color and radius for better visibility)

Update 2:
Even closer to the final result. Now border is present, only the shadow is missing:

layout.xml:

<LinearLayout xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@drawable/buttonshape15" >

    <android.support.v7.widget.CardView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        card_view:cardCornerRadius="15dp"
        card_view:cardElevation="0dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <ImageView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:scaleType="fitXY"
                android:background="@drawable/parking" />

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="6"
                android:orientation="vertical"
                android:paddingStart="16dp">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:fontFamily="sans-serif"
                    android:paddingTop="6dp"
                    android:text="Parking"
                    android:textColor="@color/colorPrimary"
                    android:textSize="22sp" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:paddingTop="3dp"
                    android:text="Pay without coins"
                    android:textSize="12sp" />
            </LinearLayout>
        </LinearLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>

To solve the shadow problem I have tried to use layer-list in the background.xml but it gives ugly shadows. Wrapping everything again inside a CardView and set the elevation gives better result but not as perfect as the reference layout has.

Body:
I would use a CardView as parent view with card_view:cornerRadius=5dp and then in that a LinearLayout so it would look something like this .

<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="@color/black"
android:id="@+id/root_layout"
android:theme="@style/light_list_item"
card_view:cornerRadius=5dp>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp" >
<ImageView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.5"
    android:background="@mipmap/ic_launcher"/>
<LinearLayout
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="name"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="cost"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="benefit"/>
</LinearLayout>
</android.support.v7.widget.CardView>

note that I think you should use background for ImageView.

edit for shadow issue please place a parent for cardView that should be either LinearLayout or RelativeLayout . I haven't test it my self but I am quite sure that it would work.

hope this helps please comment if there is something wrong with this.


来源: stackexchange

问:
CURLOPT_PUT vs CURLOPT_POSTFIELDS
When I sent the PUT request API via curl to the REST, I found strange behavior. If you set the parameter curl_setopt($curl, CURLOPT_PUT, true), then queries, in which CURLOPT_POSTFIELDS is not empty, then the query execution lasts 1.5 minutes (as if it depends on some timeout). And if the same request is sent with the parameter curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"), then the query execution lasts about 1 second, as it should be. Can someone explain the fundamental difference between these parameters?

Example code:

```<code>$data = http_build_query(array("enable"=> 1));

if( $curl = curl_init() ) {
    curl_setopt($curl, CURLOPT_URL, BASE_URL .'users/2');
    curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
    curl_setopt($curl, CURLOPT_PUT, true); // execution time 1.5 min
    //curl_setopt ($ curl, CURLOPT_CUSTOMREQUEST, "PUT"); - execution time 1 sec
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    $out = json_decode(curl_exec($curl));
    curl_close($curl);
}
</code>```

答:
If you look at the documentation, It says that when you set CURLOPT_PUT to truethen the file to PUT must be set with CURLOPT_INFILE and CURLOPT_INFILESIZE (In your case you are not setting the file).

Setting CURLOPT_CUSTOMREQUEST to PUT method is not expecting the file which is the main difference between CURLOPT_CUSTOMREQUEST and CURLOPT_PUT.

ContentLicense: CC BY-SA 3.0

Title: CURLOPT_PUT vs CURLOPT_POSTFIELDS

Body:
When I sent the PUT request API via curl to the REST, I found strange behavior. If you set the parameter curl_setopt($curl, CURLOPT_PUT, true), then queries, in which CURLOPT_POSTFIELDS is not empty, then the query execution lasts 1.5 minutes (as if it depends on some timeout). And if the same request is sent with the parameter curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"), then the query execution lasts about 1 second, as it should be. Can someone explain the fundamental difference between these parameters?

Example code:

$data = http_build_query(array("enable"=> 1));

if( $curl = curl_init() ) {
    curl_setopt($curl, CURLOPT_URL, BASE_URL .'users/2');
    curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
    curl_setopt($curl, CURLOPT_PUT, true); // execution time 1.5 min
    //curl_setopt ($ curl, CURLOPT_CUSTOMREQUEST, "PUT"); - execution time 1 sec
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    $out = json_decode(curl_exec($curl));
    curl_close($curl);
}


问:
How to solve saying "designed for phones" in playstore
I am particularly design for tablet.How to avoid this.

My code snippet for support tag's

```<code> <supports-screens
        android:anyDensity="true"
        android:largeScreens="true"
        android:normalScreens="false"
        android:requiresSmallestWidthDp="600"
        android:smallScreens="false"
        android:xlargeScreens="true" />
</code>```

in playstore  i have given screenshot 7 & 10 inches of tablet.

How to solve this???

答:
Are u following design for tablet then use xml folder layout-large as inside res folder then should avoid design for phones.

I'm apply to app for design to tablet to play console this article https://support.google.com/googleplay/android-developer/contact/tabletq.

I got from here

And also ur drawbles using ldpi,xhdpi,xxhdpi uses and other information need then Optimization tips in play store from get it.

User Acquistion----->Optimation Tips from details get ur app.

Body:
I am particularly design for tablet.How to avoid this.

My code snippet for support tag's

 <supports-screens
        android:anyDensity="true"
        android:largeScreens="true"
        android:normalScreens="false"
        android:requiresSmallestWidthDp="600"
        android:smallScreens="false"
        android:xlargeScreens="true" />

in playstore  i have given screenshot 7 & 10 inches of tablet.

How to solve this???


问:
Backtracking solution for palindrome partitioning issue with displacement of sub-string in the output
I am solving the question of palindrome partitioning on Leetcode.

I have written a recursive solution which prints the correct Lists of substrings but for one of the test cases, the order in the list does not match the expected output.

Input:

cbbbcc

Output:

[["c","b","b","b","c","c"],["b","b","b","c","cc"],["b","c","bb","c","c"],["b","bb","c","cc"],["c","bb","b","c","c"],["bb","b","c","cc"],["c","bbb","c","c"],["bbb","c","cc"],["cbbbc","c"]]

Expected:

[["c","b","b","b","c","c"],["c","b","b","b","cc"],["c","b","bb","c","c"],["c","b","bb","cc"],["c","bb","b","c","c"],["c","bb","b","cc"],["c","bbb","c","c"],["c","bbb","cc"],["cbbbc","c"]]

I am not able to figure out why is my recursive call shifting the first element "c" in this example.

```<code>public class Solution {

public List<List<String>> partition(String s) {

    List<List<String>> result = new ArrayList<>();
    backTrack(result, new ArrayList<String>(), s);

    return result;
}

private void backTrack(List<List<String>> result, List<String> cur, String s){

    if(s.length() == 0)
        result.add(new ArrayList<>(cur));

    /* length = i+1 */
    for(int i = 0; i < s.length(); i++){
        if(isPalindrome(s.substring(0, i+1))){
            cur.add(s.substring(0, i+1));
            backTrack(result, cur, s.substring(i+1, s.length()));
            cur.remove(s.substring(0, i+1));
        }
    }

}

private boolean isPalindrome(String s){
    int start = 0, end = s.length() - 1;
    char[] schars = s.toCharArray();

    while(start < end){
        if(schars[start] != schars[end])
            return false;
        start++;
        end--;
    }
    return true;
}
}
</code>```

I did go through an example and as per my logic, I do not see any reason that "c" should be displaced as in the output.

答:
Yes, seems like you were removing the leftmost element instead of the rightmost element.The following should suffice:

```<code>import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class OneSolution {

private List<List<String>> partition(String s) {

    List<List<String>> result = new ArrayList<>();
    backTrack(result, new ArrayList<String>(), s);

    return result;
}

private void backTrack(List<List<String>> result, List<String> cur, String s) {
    if (s.length() == 0)
        result.add(new ArrayList<>(cur));

    for (int i = 0; i < s.length() && s.length() > 0; i++) {
        if (isPalindrome(s.substring(0, i + 1))) {
            cur.add(s.substring(0, i + 1));
            backTrack(result, cur, s.substring(i + 1, s.length()));
            Collections.reverse(cur);  //Reverse String remove 1st element
            cur.remove(s.substring(0, i + 1));
            Collections.reverse(cur);  //Reverse back to original
        }
    }

}

private boolean isPalindrome(String s) {
    StringBuilder stringBuilder = new StringBuilder(s);
    String rev = stringBuilder.reverse().toString();
    return rev.equals(s);
}

public static void main(String[] args) {
    OneSolution os = new OneSolution();
    System.out.println(os.partition("cbbbcc"));
    System.out.println(os.partition("bab"));
}

}
</code>```

Verify

Body:
I am solving the question of palindrome partitioning on Leetcode.

I have written a recursive solution which prints the correct Lists of substrings but for one of the test cases, the order in the list does not match the expected output.

Input:

cbbbcc

Output:

[["c","b","b","b","c","c"],["b","b","b","c","cc"],["b","c","bb","c","c"],["b","bb","c","cc"],["c","bb","b","c","c"],["bb","b","c","cc"],["c","bbb","c","c"],["bbb","c","cc"],["cbbbc","c"]]

Expected:

[["c","b","b","b","c","c"],["c","b","b","b","cc"],["c","b","bb","c","c"],["c","b","bb","cc"],["c","bb","b","c","c"],["c","bb","b","cc"],["c","bbb","c","c"],["c","bbb","cc"],["cbbbc","c"]]

I am not able to figure out why is my recursive call shifting the first element "c" in this example.

public class Solution {

public List<List<String>> partition(String s) {

    List<List<String>> result = new ArrayList<>();
    backTrack(result, new ArrayList<String>(), s);

    return result;
}

private void backTrack(List<List<String>> result, List<String> cur, String s){

    if(s.length() == 0)
        result.add(new ArrayList<>(cur));

    /* length = i+1 */
    for(int i = 0; i < s.length(); i++){
        if(isPalindrome(s.substring(0, i+1))){
            cur.add(s.substring(0, i+1));
            backTrack(result, cur, s.substring(i+1, s.length()));
            cur.remove(s.substring(0, i+1));
        }
    }

}

private boolean isPalindrome(String s){
    int start = 0, end = s.length() - 1;
    char[] schars = s.toCharArray();

    while(start < end){
        if(schars[start] != schars[end])
            return false;
        start++;
        end--;
    }
    return true;
}
}

I did go through an example and as per my logic, I do not see any reason that "c" should be displaced as in the output.

Body:
Yes, seems like you were removing the leftmost element instead of the rightmost element.The following should suffice:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class OneSolution {

private List<List<String>> partition(String s) {

    List<List<String>> result = new ArrayList<>();
    backTrack(result, new ArrayList<String>(), s);

    return result;
}

private void backTrack(List<List<String>> result, List<String> cur, String s) {
    if (s.length() == 0)
        result.add(new ArrayList<>(cur));

    for (int i = 0; i < s.length() && s.length() > 0; i++) {
        if (isPalindrome(s.substring(0, i + 1))) {
            cur.add(s.substring(0, i + 1));
            backTrack(result, cur, s.substring(i + 1, s.length()));
            Collections.reverse(cur);  //Reverse String remove 1st element
            cur.remove(s.substring(0, i + 1));
            Collections.reverse(cur);  //Reverse back to original
        }
    }

}

private boolean isPalindrome(String s) {
    StringBuilder stringBuilder = new StringBuilder(s);
    String rev = stringBuilder.reverse().toString();
    return rev.equals(s);
}

public static void main(String[] args) {
    OneSolution os = new OneSolution();
    System.out.println(os.partition("cbbbcc"));
    System.out.println(os.partition("bab"));
}

}

Verify


问:
java.io.Console support in Eclipse IDE
I use the Eclipse IDE to develop, compile, and run my Java projects. Today, I'm trying to use the java.io.Console class to manage output and, more importantly, user input.

The problem is that System.console() returns null when an application is run "through" Eclipse. Eclipse run the program on a background process, rather than a top-level process with the console window we're familiar with.

Is there a way to force Eclipse to run the program as a top level process, or at least create a Console that the JVM will recognize? Otherwise, I'm forced to jar the project up and run on a command-line environment external to Eclipse.

答:
The workaround that I use is to just use System.in/System.out instead of Console when using Eclipse.  For example, instead of:

```<code>String line = System.console().readLine();
</code>```

You can use:

```<code>BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String line = bufferedReader.readLine();
</code>```

OwnerDisplayName: Ross

Title: java.io.Console support in Eclipse IDE

LastEditorDisplayName: Ross

Body:
The workaround that I use is to just use System.in/System.out instead of Console when using Eclipse.  For example, instead of:

String line = System.console().readLine();

You can use:

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String line = bufferedReader.readLine();

ContentLicense: CC BY-SA 2.5


问:
Multiple flexible height items - how to set the autolayout priorities?
Say you have (for example) a table cell layout with more than one dynamic flexible-height items,

They are linked vertically one to the other in the obvious way.

It seems very difficult to make this work, and very undocumented.

You'd expect that: you set the compression resistance of all the expandable items to 751. But that doesn't work.

After random experimentation, it seems to me that surprisingly you have to do something like this:

have the compression/hugging of the overall view on 250 and 750,

then strangely enough, for the three text views in the example, the priorities have to

...sequentially increase...

And, I think you have to make one of them "one lower" than the overall view - in the example one of them would be 749.

It's difficult/impossible to find the exact "formula" to make it work consistently.

What the heck is the logic of this?  Is it just a pure bug in iOS?

Has anyone found the "correct formula" for making a number of expandables work in a cell?

priorities for the three text views

priorities for the overall holder view

cheers

答:
When I am playing with cells that have a variable height I use:

```<code>tableView.estimatedRowHeight = 20.0
tableView.rowHieght = UITableViewAutomaticDimension
</code>```

These two cause the table view render its cells with the appropriate height. In order for the height to be computed though you should set the cell's data in tableView(cellForRowAt)

Body:
When I am playing with cells that have a variable height I use:

tableView.estimatedRowHeight = 20.0
tableView.rowHieght = UITableViewAutomaticDimension

These two cause the table view render its cells with the appropriate height. In order for the height to be computed though you should set the cell's data in tableView(cellForRowAt)


问:
get first occurrence of a space after last occurrence of parenthesis
I'm trying to dice up a dictionary text file (using Sublime text editor) and need to get the first occurrence of a space after the last ) because I need to replace it with a delimiter I can import into Google sheets.

E.g., The following:

```<code>abierto (masculine) open

abjaso (masculine); abjasio (masculine) Abkhaz

abogado (masculine); abogada (feminine); notario (masculine)    lawyer
</code>```

Should be (note the _ delimiter):

```<code>abierto (masculine)_    open

abjaso (masculine); abjasio (masculine)_    Abkhaz

abogado (masculine); abogada (feminine); notario (masculine)_   lawyer
</code>```

How can I accomplish this?

EDIT: I've tried /\)[^\)]+$/g - to get a ) followed by one or more non-) characters, at the end of the string, greedy... but it only finds one result.

答:
You can use

```<code>\)(?!.*\))
</code>```

to find last occurrences of ), then replace that with )_, which gives you the desired result. Here is a result from ST3

Explanation:

```<code>\)   # find ")"
(    # OPEN capturing group 1
  ?!    # negative lookahead, aka "do not match"
  .*    # anything until
  \)    # character ")"
)    # CLOSE capturing group 1
</code>```

So if you have eg regex a(?!b)and test it on "ab", "ac" and "ad", it will match only the "a" if it precedes something that "does not match" b. So the "a" in "ac" and "ad" is being matched here. But not in "ab". Here, the ) is selected on everything until )

From comment:

Can you help explain this? Also, can you explain why this doesn't work in Regex101? regex101.com/r/GFwrn5/1

That is because you have not enabled the global /g flag there. If you enable it, it will do the job.

Body:
I'm trying to dice up a dictionary text file (using Sublime text editor) and need to get the first occurrence of a space after the last ) because I need to replace it with a delimiter I can import into Google sheets.

E.g., The following:

abierto (masculine) open

abjaso (masculine); abjasio (masculine) Abkhaz

abogado (masculine); abogada (feminine); notario (masculine)    lawyer

Should be (note the _ delimiter):

abierto (masculine)_    open

abjaso (masculine); abjasio (masculine)_    Abkhaz

abogado (masculine); abogada (feminine); notario (masculine)_   lawyer

How can I accomplish this?

EDIT: I've tried /\)[^\)]+$/g - to get a ) followed by one or more non-) characters, at the end of the string, greedy... but it only finds one result.

Body:
You can use

\)(?!.*\))

to find last occurrences of ), then replace that with )_, which gives you the desired result. Here is a result from ST3

Explanation:

\)   # find ")"
(    # OPEN capturing group 1
  ?!    # negative lookahead, aka "do not match"
  .*    # anything until
  \)    # character ")"
)    # CLOSE capturing group 1

So if you have eg regex a(?!b)and test it on "ab", "ac" and "ad", it will match only the "a" if it precedes something that "does not match" b. So the "a" in "ac" and "ad" is being matched here. But not in "ab". Here, the ) is selected on everything until )

From comment:

Can you help explain this? Also, can you explain why this doesn't work in Regex101? regex101.com/r/GFwrn5/1

That is because you have not enabled the global /g flag there. If you enable it, it will do the job.


问:
SQL Server - join rows into comma separated list
Let's suppose I have a temporary table which looks like this:

```<code>+----+------+
| Id | Value|
+----+------+
| 1  |   1  |
| 1  |   2  |
| 1  |   3  |
| 2  |   1  |
| 2  |   2  |
+----+------+
</code>```

And I want my table to be like this:

```<code>    +----+----------+
    | Id | ValueList|
    +----+----------+
    | 1  |   1,2,3  |
    | 2  |   1,2    |
    +----+----------+
</code>```

So basically I need to group my values as a comma separated list.
I already tried the following:

```<code>SELECT Id, STUFF((SELECT ',' + CAST(VALUE AS varchar) FROM @MyTable FOR XML PATH('')), 1 ,1, '') AS ValueList
FROM @MyTable
GROUP BY Id
</code>```

But I get something like:

```<code>        +----+---------------------+
        | Id |      ValueList      |
        +----+---------------------+
        | 1  |   1,1,1,1,1,1,...   |
        +----+---------------------+
</code>```

I cant find what I am doing wrong. Could someone help with this query? Or point me to a right direction?
Thank you.

答:
You are missing the condition inside the sub query.

```<code>SELECT t2.Id, STUFF((SELECT ',' + CAST(VALUE AS varchar) FROM @MyTable t1  where t1.Id =t2.ID FOR XML PATH('')), 1 ,1, '') AS ValueList
FROM @MyTable t2
GROUP BY t2.Id
</code>```

Demo

Body:
Let's suppose I have a temporary table which looks like this:

+----+------+
| Id | Value|
+----+------+
| 1  |   1  |
| 1  |   2  |
| 1  |   3  |
| 2  |   1  |
| 2  |   2  |
+----+------+

And I want my table to be like this:

    +----+----------+
    | Id | ValueList|
    +----+----------+
    | 1  |   1,2,3  |
    | 2  |   1,2    |
    +----+----------+

So basically I need to group my values as a comma separated list.
I already tried the following:

SELECT Id, STUFF((SELECT ',' + CAST(VALUE AS varchar) FROM @MyTable FOR XML PATH('')), 1 ,1, '') AS ValueList
FROM @MyTable
GROUP BY Id

But I get something like:

        +----+---------------------+
        | Id |      ValueList      |
        +----+---------------------+
        | 1  |   1,1,1,1,1,1,...   |
        +----+---------------------+

I cant find what I am doing wrong. Could someone help with this query? Or point me to a right direction?
Thank you.

Body:
You are missing the condition inside the sub query.

SELECT t2.Id, STUFF((SELECT ',' + CAST(VALUE AS varchar) FROM @MyTable t1  where t1.Id =t2.ID FOR XML PATH('')), 1 ,1, '') AS ValueList
FROM @MyTable t2
GROUP BY t2.Id

Demo


问:
No route matches [GET] "/place/new"
I can't catch where a problem is.

I run on server

```<code>rails generate scaffold Place name:string lat:numeric lng:numeric
</code>```

Next, I run

```<code>rake db:migrate
</code>```

So, I try to create new Place on web browser and go to

```<code>/places/new
</code>```

But receive:

```<code>ActionController::RoutingError (No route matches [GET] "/place/new"):
</code>```

I confused because everything works fine on my local machine. What's wrong with me?

btw, routes.rb looks like:

```<code>Rails.application.routes.draw do
    resources :places
end
</code>```

答:
numeric is not a datatype. You have to use float or integer for lat/long instead of numeric.

Corrected command:

```<code>rails generate scaffold Place name:string lat:integer lng:integer
</code>```

Title: No route matches [GET] "/place/new"

Body:
I can't catch where a problem is.

I run on server

rails generate scaffold Place name:string lat:numeric lng:numeric

Next, I run

rake db:migrate

So, I try to create new Place on web browser and go to

/places/new

But receive:

ActionController::RoutingError (No route matches [GET] "/place/new"):

I confused because everything works fine on my local machine. What's wrong with me?

btw, routes.rb looks like:

Rails.application.routes.draw do
    resources :places
end

Body:
numeric is not a datatype. You have to use float or integer for lat/long instead of numeric.

Corrected command:

rails generate scaffold Place name:string lat:integer lng:integer


答:
One alternative to using GROUP BY on the Id would be to use select distinct:

```<code>SELECT DISTINCT
    Id,
    STUFF((SELECT ',' + CAST(t2.VALUE AS varchar)
           FROM @MyTable t2
           WHERE t2.Id = t1.Id
           FOR XML PATH('')), 1 ,1, '') AS ValueList
FROM @MyTable t1
</code>```

Demo

Title: SQL Server - join rows into comma separated list

Body:
One alternative to using GROUP BY on the Id would be to use select distinct:

SELECT DISTINCT
    Id,
    STUFF((SELECT ',' + CAST(t2.VALUE AS varchar)
           FROM @MyTable t2
           WHERE t2.Id = t1.Id
           FOR XML PATH('')), 1 ,1, '') AS ValueList
FROM @MyTable t1

Demo


问:
How to make an object jump automatically in unity 5.6?
I'm developing a game which has the thematic Cubes. I make that game in Unity3D and c#. I want to make a cube(obstacle) jump automatically infinite times, without ever stopping.

How can I do this?

答:
Just add a physics material to your object with 0 friction and 1 bounciness.

For more about physics materials, check this document: https://docs.unity3d.com/Manual/class-PhysicMaterial.html

There is also a tutorial for the subject: https://unity3d.com/learn/tutorials/topics/physics/physics-materials

ContentLicense: CC BY-SA 4.0


问:
Dynamically creating Buttons and setting onClickListener
I have problem with handling dynamically created Buttons on Android. I'm creating N buttons and I have to do the same method when button is clicked but I have to know which button is clicked.

```<code>for (int i = 0; i < NO_BUTTONS; i++){
        Button btn = new Button(this);
        btn.setId(2000+i);

        ...

        btn.setOnClickListener((OnClickListener) this);
        buttonList.addView(btn);
        list.add(btn);
</code>```

Cucurrently I'm adding ID to every button and I'm using the method below to see which button was clicked. (line btn.setId(2000+i); and btn.setOnClickListener((OnClickListener) this);). This method is also implemented in the activity.

```<code>@Override
public void onClick(View v) {
    switch (v.getId()){
        case 2000: selectButton(0);
        break;

        ...

        case 2007: selectButton(7);
        break;
    }
 }
</code>```

This doesn't look good to me so i'm asking is there some better way to do this? or how to send some information to onclick event? any suggestions?

答:
View IDs should not be used for these purposes as View Ids are generated on compilation time depending on IDs defined in xml layout files.

Just place your own IDs in the setTag() method which is available at the View level (so Buttons inherit them). This "tag" can be anything that allow you to recognize a View from others. You retrieve its value with getTag().

Body:
I have problem with handling dynamically created Buttons on Android. I'm creating N buttons and I have to do the same method when button is clicked but I have to know which button is clicked.

for (int i = 0; i < NO_BUTTONS; i++){
        Button btn = new Button(this);
        btn.setId(2000+i);

        ...

        btn.setOnClickListener((OnClickListener) this);
        buttonList.addView(btn);
        list.add(btn);

Cucurrently I'm adding ID to every button and I'm using the method below to see which button was clicked. (line btn.setId(2000+i); and btn.setOnClickListener((OnClickListener) this);). This method is also implemented in the activity.

@Override
public void onClick(View v) {
    switch (v.getId()){
        case 2000: selectButton(0);
        break;

        ...

        case 2007: selectButton(7);
        break;
    }
 }

This doesn't look good to me so i'm asking is there some better way to do this? or how to send some information to onclick event? any suggestions?


问:
Match JSON String to new POJO Object
I am using Spring RestTemplate to communicate with an provided REST service that delivers JSON. To Map the response I am using Jaxon, but I will gladly switch to anything else that works.

I would like to create an POJO that contains sub-content of the delivered data but in a different Structure.

It boils down to this:

Source: { "a": "val_a", "b" : {"c" : "val_c", "d": "val_d"}}

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
class Foo {
   // should contains the content of `"a": "val_a"`
   // but contains null
   private Baa;

   // getter and setter
}

@JsonIgnoreProperties(ignoreUnknown = true)
class Baa {
  private String a;

  // getter and setter
}

// This should be the operation that is done internally by Spring when calling
// ResponseEntity<Foo>response = restTemplate.exchange(url, HttpMethod.GET, entity, Foo.class);
// response.getBody();
private Foo read(String s) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    return mapper.readValue(s, Foo.class);
}
</code>```

The result of the deserialization is an empty Baa object. The actual JSON and POJO Object structure is more complex but this sums it up.

Any Technology that achieves this would be welcome.
The only possibility I came up with is deserializing the JSON in the provided structure and write a Converter class that generates the desired Object but I was hoping to avoid this.

----- Update/clarification ------
The problem is, that the property a should be mapped within class Baa, which lies within Foo but is provided in the root path (is this the right term?) of the provided JSON objekt

答:
```<code>public class Foo {

  private String a;
  private B b;

  // getters setters

}

public class B {

  private String c;
  private String d;

  // getters setters

}
</code>```

Should map with no additional annotations with your code. If you're having a particular code with a non trivial example then post your actual code in whole.

Update on your clarification: no you can't do that with annotations as I said in my comment. You will have to write the custom deserialiser. Check out this answer: Jackson: is it possible to include property of parent object into nested object?

Title: Match JSON String to new POJO Object

Body:
I am using Spring RestTemplate to communicate with an provided REST service that delivers JSON. To Map the response I am using Jaxon, but I will gladly switch to anything else that works.

I would like to create an POJO that contains sub-content of the delivered data but in a different Structure.

It boils down to this:

Source: { "a": "val_a", "b" : {"c" : "val_c", "d": "val_d"}}

@JsonIgnoreProperties(ignoreUnknown = true)
class Foo {
   // should contains the content of `"a": "val_a"`
   // but contains null
   private Baa;

   // getter and setter
}

@JsonIgnoreProperties(ignoreUnknown = true)
class Baa {
  private String a;

  // getter and setter
}

// This should be the operation that is done internally by Spring when calling
// ResponseEntity<Foo>response = restTemplate.exchange(url, HttpMethod.GET, entity, Foo.class);
// response.getBody();
private Foo read(String s) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    return mapper.readValue(s, Foo.class);
}

The result of the deserialization is an empty Baa object. The actual JSON and POJO Object structure is more complex but this sums it up.

Any Technology that achieves this would be welcome.
The only possibility I came up with is deserializing the JSON in the provided structure and write a Converter class that generates the desired Object but I was hoping to avoid this.

----- Update/clarification ------
The problem is, that the property a should be mapped within class Baa, which lies within Foo but is provided in the root path (is this the right term?) of the provided JSON objekt

Body:
public class Foo {

  private String a;
  private B b;

  // getters setters

}

public class B {

  private String c;
  private String d;

  // getters setters

}

Should map with no additional annotations with your code. If you're having a particular code with a non trivial example then post your actual code in whole.

Update on your clarification: no you can't do that with annotations as I said in my comment. You will have to write the custom deserialiser. Check out this answer: Jackson: is it possible to include property of parent object into nested object?


问:
Image not acting "responsive" using flexbox?
I am pretty new to HTML/CSS and have begun trying to learn CSS flexbox layout. Just working on a simple site recreation from scratch using flexbox.

In full screen, the image positioning on the logo looks good. However, when shifting around the screen size, my nav bar on the right side responds but the logo image on the left does not. I believe I have set it up correctly though.

```<code>.header-container {
 display: flex;
 width: 100%;
 height: 150px;
 align-items: center;
 justify-content: space-between;
 }

.header-container .logo .sb{
 display: flex;
 justify-content: flex-start;
 width: 60%;
 position: relative;
 left: 50px;
 padding: 20px;
 }
</code>```

Here's a link to my work as well: https://codepen.io/gkunthara/pen/VWdrYj

What exactly am I doing wrong? Any tips on the type of positioning I'm doing with flexbox or with flexbox, in general, are appreciated!

答:
Remove Position</p>

```<code>.header-container .nav-bar-container {
    display: flex;
    /*position: absolute;*/
    /*right: 100px;*/
}
</code>```

Body:
I am pretty new to HTML/CSS and have begun trying to learn CSS flexbox layout. Just working on a simple site recreation from scratch using flexbox.

In full screen, the image positioning on the logo looks good. However, when shifting around the screen size, my nav bar on the right side responds but the logo image on the left does not. I believe I have set it up correctly though.

.header-container {
 display: flex;
 width: 100%;
 height: 150px;
 align-items: center;
 justify-content: space-between;
 }

.header-container .logo .sb{
 display: flex;
 justify-content: flex-start;
 width: 60%;
 position: relative;
 left: 50px;
 padding: 20px;
 }

Here's a link to my work as well: https://codepen.io/gkunthara/pen/VWdrYj

What exactly am I doing wrong? Any tips on the type of positioning I'm doing with flexbox or with flexbox, in general, are appreciated!

Body:
Remove Position

.header-container .nav-bar-container {
    display: flex;
    /*position: absolute;*/
    /*right: 100px;*/
}


问:
First row Horizontal Recyclerview with Vertical RecyclerView in android
I want to use horizontal recycler with vertical recycler together like google play store but in my app only the first row like image below. I used scrollview but it not correct like I want when we have a lot of data and pagination. And it also has header section for horizontal and vertical recycler and the horizontal recycler header section will change when vertical header section scroll to it the same to TitleSection of UiTableView in iOS.
Thank you!

答:
Use NestedScrollView as container of RecyclerViews.

Set LinearLayoutManager to recycler_view_horizontal with Horizontal orientation.

set LinearLayoutManager to recycler_view_vertical with Vertical orientation.

Use RecyclerView.setNestedScrollingEnabled(false) to RecyclerView for smooth scrolling.

Design your layout structure as below:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/layout_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            android:minHeight="?attr/actionBarSize"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            android:theme="@style/ThemeOverlay.AppCompat.Dark"
            app:titleTextColor="@android:color/white"
            app:contentInsetStartWithNavigation="0dp">
        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/layout_scorll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

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

            <TextView
                android:id="@+id/header1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="12dp"
                android:paddingBottom="8dp"
                android:paddingTop="8dp"
                android:text="Horizontal Recycler Header"
                android:textSize="16sp" />

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recycler_view_horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:nestedScrollingEnabled="false" />

            <TextView
                android:id="@+id/header2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="12dp"
                android:paddingBottom="8dp"
                android:paddingTop="8dp"
                android:text="Vertical Recycler Header"
                android:textSize="16sp" />

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recycler_view_vertical"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:nestedScrollingEnabled="false" />

        </LinearLayout>
    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
</code>```

In your Activtiy:

```<code>mRecyclerViewHorizontal.setNestedScrollingEnabled(false);
mRecyclerViewVertical.setNestedScrollingEnabled(false);

mRecyclerViewHorizontal.setHasFixedSize(false);
mRecyclerViewVertical.setHasFixedSize(false);
</code>```

Hope it helps!

Body:
Use NestedScrollView as container of RecyclerViews.

Set LinearLayoutManager to recycler_view_horizontal with Horizontal orientation.

set LinearLayoutManager to recycler_view_vertical with Vertical orientation.

Use RecyclerView.setNestedScrollingEnabled(false) to RecyclerView for smooth scrolling.

Design your layout structure as below:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/layout_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            android:minHeight="?attr/actionBarSize"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            android:theme="@style/ThemeOverlay.AppCompat.Dark"
            app:titleTextColor="@android:color/white"
            app:contentInsetStartWithNavigation="0dp">
        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/layout_scorll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

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

            <TextView
                android:id="@+id/header1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="12dp"
                android:paddingBottom="8dp"
                android:paddingTop="8dp"
                android:text="Horizontal Recycler Header"
                android:textSize="16sp" />

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recycler_view_horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:nestedScrollingEnabled="false" />

            <TextView
                android:id="@+id/header2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="12dp"
                android:paddingBottom="8dp"
                android:paddingTop="8dp"
                android:text="Vertical Recycler Header"
                android:textSize="16sp" />

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recycler_view_vertical"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:nestedScrollingEnabled="false" />

        </LinearLayout>
    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>

In your Activtiy:

mRecyclerViewHorizontal.setNestedScrollingEnabled(false);
mRecyclerViewVertical.setNestedScrollingEnabled(false);

mRecyclerViewHorizontal.setHasFixedSize(false);
mRecyclerViewVertical.setHasFixedSize(false);

Hope it helps!


问:
Xcode building while device is connected but not archiving
I am trying to build the project using this as basis :
GitHub code

but it is giving me error when i am trying to archive the project, while running it directly on device is okay. If i turn bitcode to off it makes the build but exit with some error on the iphone because dlib library is not being added needed for detection.

```<code>ld: bitcode bundle could not be generated because 'path/lib/libdlib.a(threads_kernel_shared.o)' was built without full bitcode. All object files and libraries for bitcode must be generated from Xcode Archive or Install build for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

I can see there is some problem in generation of dlib library but have no idea how to solve it up.
If anyone can guide me through it, i will be really thankful for the guidance. Thank you.

答: Select Generic iOS Device while archiving

Body:
I am trying to build the project using this as basis :
GitHub code

but it is giving me error when i am trying to archive the project, while running it directly on device is okay. If i turn bitcode to off it makes the build but exit with some error on the iphone because dlib library is not being added needed for detection.

ld: bitcode bundle could not be generated because 'path/lib/libdlib.a(threads_kernel_shared.o)' was built without full bitcode. All object files and libraries for bitcode must be generated from Xcode Archive or Install build for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I can see there is some problem in generation of dlib library but have no idea how to solve it up.
If anyone can guide me through it, i will be really thankful for the guidance. Thank you.


问:
Deleting a many-to-many relationship object in Entity Framework
I have a web server where I serve User objects through a REST API.

Recently I've added the option for users to create Groups. Groups have a Name, a Color (represented as an int), an Owner (User object reference), and Members.

The Members property is a many-to-many relationship. One User can be member of multiple Groups, and one Group may have multiple members.

However I'm having problems with the removal of Groups. I want to give the Owner user the option to delete a Group - thus, removing all members, and removing the reference to the Group itself.

However I'm getting the following error upon trying to delete it:

```<code>The DELETE statement conflicted with the REFERENCE constraint \"FK_GroupUser_Group\". The conflict occurred in database \"database\", table \"dbo.GroupUser\", column 'Groups_Id'.\r\nThe statement has been terminated.
</code>```

I'm using the following code to remove the Group:

```<code>using (var db = new DBContext())
{
    group.Owner.OwnedGroups.Remove(group);
    group.Owner = null;
    db.Groups.Remove(group);
    db.SaveChanges();
}
</code>```

Is there something I'm missing here?

答:
use .WillCascadeOnDelete(true) or Include

WillCascadeOnDelete:

```<code>modelBuilder.Entity<Parent>()
  .HasMany<Child>(c => c.Children)
  .WithOptional(x => x.Parent)
  .WillCascadeOnDelete(true);
</code>```

use Include

```<code>  var adv = db.Adv.Include(b => b.Features)
                  .Include(b => b.AdvDetails)
                  .Include(b => b.AdvGallery)
                  .FirstOrDefault(b => b.Id == id);
  db.Adv.Remove(adv);
</code>```

for .HasMany(...).WithMany(...) Include is ok

Body:
I have a web server where I serve User objects through a REST API.

Recently I've added the option for users to create Groups. Groups have a Name, a Color (represented as an int), an Owner (User object reference), and Members.

The Members property is a many-to-many relationship. One User can be member of multiple Groups, and one Group may have multiple members.

However I'm having problems with the removal of Groups. I want to give the Owner user the option to delete a Group - thus, removing all members, and removing the reference to the Group itself.

However I'm getting the following error upon trying to delete it:

The DELETE statement conflicted with the REFERENCE constraint \"FK_GroupUser_Group\". The conflict occurred in database \"database\", table \"dbo.GroupUser\", column 'Groups_Id'.\r\nThe statement has been terminated.

I'm using the following code to remove the Group:

using (var db = new DBContext())
{
    group.Owner.OwnedGroups.Remove(group);
    group.Owner = null;
    db.Groups.Remove(group);
    db.SaveChanges();
}

Is there something I'm missing here?

Body:
use .WillCascadeOnDelete(true) or Include

WillCascadeOnDelete:

modelBuilder.Entity<Parent>()
  .HasMany<Child>(c => c.Children)
  .WithOptional(x => x.Parent)
  .WillCascadeOnDelete(true);

use Include

  var adv = db.Adv.Include(b => b.Features)
                  .Include(b => b.AdvDetails)
                  .Include(b => b.AdvGallery)
                  .FirstOrDefault(b => b.Id == id);
  db.Adv.Remove(adv);

for .HasMany(...).WithMany(...) Include is ok


问:
Can a module be reloaded from a different location, from within the module?
I have an API A::B that's "use"d by others in their scripts like so:

```<code>use A::B;
my $out = A::B->new(dir => $dir);
...
</code>```

Now, I want a different version of A::B to be used depending on some parameter of the attribute $dir passed to the constructor.  The user of this module has no need to know this - all he has to do is

use A::B

in his code, and expect that the module is picked up from the right location.  Is it possible to do this?

答:
You can't have different versions of a module with the same name.

What I would do instead is having different subclasses of A::B, and a Factory class that instantiates objects of the appropriate class, choosing and loading it based on the factory invocation parameters.

For example:

```<code>my $out = A::B::Factory->create( dir => $dir );
# $out is a A::B::Foo or A::B::Bar depending on $dir
</code>```

In the factory class:

```<code>package A::B::Factory;
use UNIVERSAL::require;

sub create {
  my (undef, %params) = @_;

  my $dir = $params{ dir };

  # some strategy to decide which class has to be used.
  # $class will be a string like "A::B::Foo" or "A::B::Bar"
  # or in general the same of an existing class in your system.
  my $class = ...;

  $class->use;
  return $class->new();
}
</code>```

Body:
I have an API A::B that's "use"d by others in their scripts like so:

use A::B;
my $out = A::B->new(dir => $dir);
...

Now, I want a different version of A::B to be used depending on some parameter of the attribute $dir passed to the constructor.  The user of this module has no need to know this - all he has to do is

use A::B

in his code, and expect that the module is picked up from the right location.  Is it possible to do this?

Body:
You can't have different versions of a module with the same name.

What I would do instead is having different subclasses of A::B, and a Factory class that instantiates objects of the appropriate class, choosing and loading it based on the factory invocation parameters.

For example:

my $out = A::B::Factory->create( dir => $dir );
# $out is a A::B::Foo or A::B::Bar depending on $dir

In the factory class:

package A::B::Factory;
use UNIVERSAL::require;

sub create {
  my (undef, %params) = @_;

  my $dir = $params{ dir };

  # some strategy to decide which class has to be used.
  # $class will be a string like "A::B::Foo" or "A::B::Bar"
  # or in general the same of an existing class in your system.
  my $class = ...;

  $class->use;
  return $class->new();
}


问:
Why do we need an Object Relational Mapper?
I bought a book on Hibernate.  I wanted to learn on what Hibernate is and what is Object Relational Mapping in general.

Harnessing Hibernate has good topics on Hibernate and I do think that I am able to write simple mapping classes now. My problem is, I think I am way ahead on the Hibernate but I really don't know why we need one.

The book explains Hibernate clearly but I think I am at lost because it does not discuss why we need Hibernate and an ORM.

答: Check this !  hibernate-interview-questions-faqs</p>


问:
Flashing nav when hitting the top
I was wondering how I can make the nav-bar flash while hitting the top.

I'm using bootstrap navbar and a jquery script to make it stick to the top while scrolling down but I can't make it flash without jquery looping their 'fadein/out' feature.

Any other options I can use?

```<code>$(function(){

    var advancedNav = $('#custom-bootstrap-menu').offset().top;

    $(window).scroll(function(){
        if( $(window).scrollTop() > advancedNav ) {
                $('#custom-bootstrap-menu').css({position: 'fixed', top: '0px'});
                $('#custom-bootstrap-menu').css('display', 'block');
                $('#custom-bootstrap-menu').css('width', "100%");
        } else {
                $('#custom-bootstrap-menu').css({position: 'static', top: '0px'});
                $('#custom-bootstrap-menu').css('display', 'block');
        }
    });
</code>```

答:
It probably is because when you set the position to "fixed" you are removing the element from the layout, thus the window scroll changes... what you need to account for is the height of the menu by making it wrapped inside a fixed height div. Try this...</p>

```<code><div style="height: 400px">
 <nav id="custom-bootstrap-menu">...</nav>
</div>
</code>```

Title: Flashing nav when hitting the top

Body:
I was wondering how I can make the nav-bar flash while hitting the top.

I'm using bootstrap navbar and a jquery script to make it stick to the top while scrolling down but I can't make it flash without jquery looping their 'fadein/out' feature.

Any other options I can use?

$(function(){

    var advancedNav = $('#custom-bootstrap-menu').offset().top;

    $(window).scroll(function(){
        if( $(window).scrollTop() > advancedNav ) {
                $('#custom-bootstrap-menu').css({position: 'fixed', top: '0px'});
                $('#custom-bootstrap-menu').css('display', 'block');
                $('#custom-bootstrap-menu').css('width', "100%");
        } else {
                $('#custom-bootstrap-menu').css({position: 'static', top: '0px'});
                $('#custom-bootstrap-menu').css('display', 'block');
        }
    });

Body:
It probably is because when you set the position to "fixed" you are removing the element from the layout, thus the window scroll changes... what you need to account for is the height of the menu by making it wrapped inside a fixed height div. Try this...

<div style="height: 400px">
 <nav id="custom-bootstrap-menu">...</nav>
</div>


问:
Testing Android app release build variant
I have written many unit and instrumented tests for my Android app. So far, I only run these against the debug build variant. Is it necessary to run tests against the release build variant? What difference can there be that might give different results from testing? The main one that I can think of is when ProGuard is enabled, which I haven't done. What will ProGuard do that makes it necessary to run my test suite? What other issues should I be aware of that require testing the release build variant?</p>

答:
Is it necessary to run tests against the release build variant?

I think you should.

What difference can there be that might give different results from testing?

A couple of examples:

You might have code that uses fields of the BuildConfig class to enable/disable certain workflows. Some libraries might also use that, especially BuildConfig.BUILD_TYPE. It's common to do things like:

```<code>if (BuildConfig.BUILD_TYPE.equals("debug") {
   ACRA.init(...);
   Stetho.init(...);
   ...
}
</code>```

but have code fail in release builds due to trying to use components/libraries that were not initialized correctly.

As you mentioned, ProGuard might throw away some of your classes unless it's properly configured (e.g. imagine you forgot to add rules for some 3rd party library). Running your tests against the release variant ensures that the ProGuard configuration is correct.

What will ProGuard do that makes it necessary to run my test suite?

ProGuard might remove classes/methods/fields that are, for example, loaded via reflection unless you add the @Keep annotation to them. It might also rename classes used by libraries like Realm, Retrofit, Gson or Volley resulting in all unit and integration tests passing on debug builds (where ProGuard isn't enabled) but failing on release builds. You definitely want to test these before shipping our a new APK.

What other issues should I be aware of that require testing the release build variant?

The release build might also apply PNG crunching, specify different parameters via the buildConfigField method in Gradle, apply splits by ABI or density or enable/disable multidex and others. All of these can have implications in the way that your app works, so why not be on the safe side and test them too.

Another frequent problem that you can catch using these is ensure that you've not accidentally put code in the wrong location (e.g. /src/debug/java/) that happens to be loaded in debug builds but not in other variants.

Body:
Is it necessary to run tests against the release build variant?

I think you should.

What difference can there be that might give different results from testing?

A couple of examples:

You might have code that uses fields of the BuildConfig class to enable/disable certain workflows. Some libraries might also use that, especially BuildConfig.BUILD_TYPE. It's common to do things like:

if (BuildConfig.BUILD_TYPE.equals("debug") {
   ACRA.init(...);
   Stetho.init(...);
   ...
}

but have code fail in release builds due to trying to use components/libraries that were not initialized correctly.

As you mentioned, ProGuard might throw away some of your classes unless it's properly configured (e.g. imagine you forgot to add rules for some 3rd party library). Running your tests against the release variant ensures that the ProGuard configuration is correct.

What will ProGuard do that makes it necessary to run my test suite?

ProGuard might remove classes/methods/fields that are, for example, loaded via reflection unless you add the @Keep annotation to them. It might also rename classes used by libraries like Realm, Retrofit, Gson or Volley resulting in all unit and integration tests passing on debug builds (where ProGuard isn't enabled) but failing on release builds. You definitely want to test these before shipping our a new APK.

What other issues should I be aware of that require testing the release build variant?

The release build might also apply PNG crunching, specify different parameters via the buildConfigField method in Gradle, apply splits by ABI or density or enable/disable multidex and others. All of these can have implications in the way that your app works, so why not be on the safe side and test them too.

Another frequent problem that you can catch using these is ensure that you've not accidentally put code in the wrong location (e.g. /src/debug/java/) that happens to be loaded in debug builds but not in other variants.


问:
Converting binary characters to something jQuery can use
I’m using the BinaryWrite method of the HttpResponse class to fetch a web page.

Something similar to the example…

```<code>FileStream MyFileStream;
long FileSize;

MyFileStream = new FileStream("APage.html", FileMode.Open);
FileSize = MyFileStream.Length;

byte[] Buffer = new byte[(int)FileSize];
MyFileStream.Read(Buffer, 0, (int)FileSize);
MyFileStream.Close();

Response.BinaryWrite(Buffer);
</code>```

I’m then using the jQuery ajax method to get that response. But I’m having trouble doing anything with it - so if I had…

```<code>$.ajax({
    type: "GET",
    url: "GetUrl.Proxy",
    data: { url: 'http://www.example.org/test.html' },
    success: function(data) {
        $('iframe').contents().find('html body').html(data.toString());
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    alert(errorThrown);
    }
 });
</code>```

This returns a stream of binary characters, what I want is something that jQuery can use to set a html element.

答:
Set the content-type first:

```<code>Response.Clear();
Response.ContentType = "text/html";
...
</code>```

In response to the question of finding the content type of the file:

```<code>string mt = "application/unknown";
string ext = Path.GetExtension(filename).ToLower();
var regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null) {
  var tempMt = regKey.GetValue("Content Type");
  if (tempMt != null) {
    tempMt = regKey.GetValue("Content Type").ToString();
  }
}
</code>```

Personally, I'd probably just do a switch statement with the likely extensions and types...

Body:
I’m using the BinaryWrite method of the HttpResponse class to fetch a web page.

Something similar to the example…

FileStream MyFileStream;
long FileSize;

MyFileStream = new FileStream("APage.html", FileMode.Open);
FileSize = MyFileStream.Length;

byte[] Buffer = new byte[(int)FileSize];
MyFileStream.Read(Buffer, 0, (int)FileSize);
MyFileStream.Close();

Response.BinaryWrite(Buffer);

I’m then using the jQuery ajax method to get that response. But I’m having trouble doing anything with it - so if I had…

$.ajax({
    type: "GET",
    url: "GetUrl.Proxy",
    data: { url: 'http://www.example.org/test.html' },
    success: function(data) {
        $('iframe').contents().find('html body').html(data.toString());
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    alert(errorThrown);
    }
 });

This returns a stream of binary characters, what I want is something that jQuery can use to set a html element.

Body:
Set the content-type first:

Response.Clear();
Response.ContentType = "text/html";
...

In response to the question of finding the content type of the file:

string mt = "application/unknown";
string ext = Path.GetExtension(filename).ToLower();
var regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null) {
  var tempMt = regKey.GetValue("Content Type");
  if (tempMt != null) {
    tempMt = regKey.GetValue("Content Type").ToString();
  }
}

Personally, I'd probably just do a switch statement with the likely extensions and types...


问:
CORS error on Chrome but works in IE
I have created a form that would enable users to raise JIRA tickets from an html form. i have asked the admin to add the origin (sharepoint online site, the form is hosted) to the whitelist of JIRA as a wildard expression with format https://xxxx.sharepoint.com/*.

it now works in IE but i still get errors in chroe:

jquery-3.1.0.min.js:4 XMLHttpRequest cannot load
  https://jira.xxx.xx/rest/api/2/issue/. Response to preflight request
  doesn't pass access control check: No 'Access-Control-Allow-Origin'
  header is present on the requested resource. Origin
  'https://xxxx.sharepoint.com' is therefore not allowed access. The
  response had HTTP status code 403.

in Edge i get this error:

HTTP403: FORBIDDEN - The server understood the request, but is
  refusing to fulfill it.

One thing i have noticed is that when i run it on IE, after clicking submit. i am presented with a pop screen to log onto my JIRA credentials. this doesnt happen to Chrome or Edge. can you please let me know what i am missing here?

This is my ajax call:

```<code>return $.ajax({
    url: 'https://jira.xxxx.com/rest/api/2/issue/',
    type: "POST",
    data: parameters,
    contentType: 'application/json',
    dataType: 'JSON',
    async: false,
    processData: false,
    beforeSend: function (xhr) {
        xhr.setRequestHeader('Authorization', 'basic: '+make_base_auth(username, password));
        xhr.setRequestHeader( 'Access-Control-Allow-Origin', 'https://jira.xxxx.com');
        xhr.setRequestHeader( 'X-Atlassian-Token', 'nocheck');
        xhr.setRequestHeader( 'Access-Control-Allow-Credentials', 'true');
        xhr.setRequestHeader( 'Access-Control-Allow-Methods', 'ACL, CANCELUPLOAD, CHECKIN, CHECKOUT, COPY, DELETE, GET, HEAD, LOCK, MKCALENDAR, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, REPORT, SEARCH, UNCHECKOUT, UNLOCK, UPDATE, VERSION-CONTROL');
        xhr.setRequestHeader( 'Access-Control-Allow-Headers', 'Overwrite, Destination, Content-Type, Depth, User-Agent, Translate, Range, Content-Range, Timeout, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control, Location, Lock-Token, If');
        xhr.setRequestHeader( 'Access-Control-Expose-Headers', 'DAV, content-length, Allow');
    },
    error: function (errmsg) {
        console.log('error ocured:' + errmsg.statusText);
    },
    success: function (text) {
        console.log(text);
    },
});
</code>```

答:
All of the Access-Control headers you are adding are response headers.  Sending them in the request is meaningless.  CORS does have a couple request headers, but they are sent by the browser.  Your requests shouldn't send them.  If the server is properly configured for cross-origin requests, it will set these headers when appropriate in the responses it returns.

Chrome is telling you that the CORS preflight request doesn't have an Access-Control-Allow-Origin header.  The preflight request is an OPTIONS request that is sent to ask the server if it will be allowed to make a request.  If the server sends back the right headers (currently it isn't) then the browser knows it can make the actual POST request.  You aren't getting past the preflight request.

There is nothing wrong with your request for a cross-origin perspective (other than the extraneous headers already mentioned).  Assuming everything else is correct, the problem is with the server running the API.  Whoever controls that server will need to configure it to properly respond to CORS preflight requests.

My best guess is that the API is configured to respond to actual requests, but not preflight requests.  And, I'm guessing that IE incorrectly treats the request as a "simple request" which doesn't require a preflight request.  That could explain why it works in IE, but not Chrome.  But, I can only guess without more information.

Title: CORS error on Chrome but works in IE

Body:
I have created a form that would enable users to raise JIRA tickets from an html form. i have asked the admin to add the origin (sharepoint online site, the form is hosted) to the whitelist of JIRA as a wildard expression with format https://xxxx.sharepoint.com/*.

it now works in IE but i still get errors in chroe:

jquery-3.1.0.min.js:4 XMLHttpRequest cannot load
  https://jira.xxx.xx/rest/api/2/issue/. Response to preflight request
  doesn't pass access control check: No 'Access-Control-Allow-Origin'
  header is present on the requested resource. Origin
  'https://xxxx.sharepoint.com' is therefore not allowed access. The
  response had HTTP status code 403.

in Edge i get this error:

HTTP403: FORBIDDEN - The server understood the request, but is
  refusing to fulfill it.

One thing i have noticed is that when i run it on IE, after clicking submit. i am presented with a pop screen to log onto my JIRA credentials. this doesnt happen to Chrome or Edge. can you please let me know what i am missing here?

This is my ajax call:

return $.ajax({
    url: 'https://jira.xxxx.com/rest/api/2/issue/',
    type: "POST",
    data: parameters,
    contentType: 'application/json',
    dataType: 'JSON',
    async: false,
    processData: false,
    beforeSend: function (xhr) {
        xhr.setRequestHeader('Authorization', 'basic: '+make_base_auth(username, password));
        xhr.setRequestHeader( 'Access-Control-Allow-Origin', 'https://jira.xxxx.com');
        xhr.setRequestHeader( 'X-Atlassian-Token', 'nocheck');
        xhr.setRequestHeader( 'Access-Control-Allow-Credentials', 'true');
        xhr.setRequestHeader( 'Access-Control-Allow-Methods', 'ACL, CANCELUPLOAD, CHECKIN, CHECKOUT, COPY, DELETE, GET, HEAD, LOCK, MKCALENDAR, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, REPORT, SEARCH, UNCHECKOUT, UNLOCK, UPDATE, VERSION-CONTROL');
        xhr.setRequestHeader( 'Access-Control-Allow-Headers', 'Overwrite, Destination, Content-Type, Depth, User-Agent, Translate, Range, Content-Range, Timeout, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control, Location, Lock-Token, If');
        xhr.setRequestHeader( 'Access-Control-Expose-Headers', 'DAV, content-length, Allow');
    },
    error: function (errmsg) {
        console.log('error ocured:' + errmsg.statusText);
    },
    success: function (text) {
        console.log(text);
    },
});


问:
Can't display the proper value
I have these classes:

```<code>interface Shape
{
    public double getPerimeter();
    public double getArea();
    public void getDetails();
}
</code>```

and

```<code>class Circle implements Shape
{
    private double PI = 3.14;
    private int radius;
    double perimeter, area;

    //constructor
    public Circle(int radius)
    {
        perimeter = 2.0 * (PI * radius);
        area = PI * (radius * radius);
    }

    public int getRadius()
    {
        return radius;
    }

    public double getPerimeter()
    {
        return perimeter;
    }

    public double getArea()
    {
        return area;
    }

    public void getDetails()
    {
        System.out.println("Shape Type: Circle " + "\n"
                         + "Radius: " + getRadius() + "\n"
                         + "Perimeter: " + getPerimeter() + "\n"
                         + "Area: "  + getArea() + "\n"         );
    }
}
</code>```

and finally

```<code>public class TestShape
{
    public static void main(String args[])
    {

        for(int i = 0; i < args.length; i++)
        {
            try
            {
                Integer.parseInt(args[i]);
            }

            catch(NumberFormatException nfe)
            {
                System.err.print("wrong");
            }

            catch(IllegalArgumentException iae)
            {
                System.err.print("wrong");
            }

            if(args.length==1)
            {
                i = Integer.parseInt(args[0]);
                Circle r1 = new Circle(i);
                r1.getDetails();
            }
        }

    }

}
</code>```

We were assigned to input 1,2 or 3 numbers on the command line of the terminal and the output would display what kind of shape it is depending on the array size. I managed to get the proper parameter and area when I input a number but the radius keeps displaying 0 instead of the actual number I inputted.

This is what the output looks like

So what do you guys think?

答:
You are not assigning the radius in the constructor of Circle...

```<code>public Circle(int radius)
{
    perimeter = 2.0 * (PI * radius);
    area = PI * (radius * radius);
    this.radius = radius // this statement is missing
}
</code>```

Therefore, circle.getRadius() always returns the uninitialized default int value 0.

Title: Can't display the proper value

Body:
I have these classes:

interface Shape
{
    public double getPerimeter();
    public double getArea();
    public void getDetails();
}

and

class Circle implements Shape
{
    private double PI = 3.14;
    private int radius;
    double perimeter, area;

    //constructor
    public Circle(int radius)
    {
        perimeter = 2.0 * (PI * radius);
        area = PI * (radius * radius);
    }

    public int getRadius()
    {
        return radius;
    }

    public double getPerimeter()
    {
        return perimeter;
    }

    public double getArea()
    {
        return area;
    }

    public void getDetails()
    {
        System.out.println("Shape Type: Circle " + "\n"
                         + "Radius: " + getRadius() + "\n"
                         + "Perimeter: " + getPerimeter() + "\n"
                         + "Area: "  + getArea() + "\n"         );
    }
}

and finally

public class TestShape
{
    public static void main(String args[])
    {

        for(int i = 0; i < args.length; i++)
        {
            try
            {
                Integer.parseInt(args[i]);
            }

            catch(NumberFormatException nfe)
            {
                System.err.print("wrong");
            }

            catch(IllegalArgumentException iae)
            {
                System.err.print("wrong");
            }

            if(args.length==1)
            {
                i = Integer.parseInt(args[0]);
                Circle r1 = new Circle(i);
                r1.getDetails();
            }
        }

    }

}

We were assigned to input 1,2 or 3 numbers on the command line of the terminal and the output would display what kind of shape it is depending on the array size. I managed to get the proper parameter and area when I input a number but the radius keeps displaying 0 instead of the actual number I inputted.

This is what the output looks like

So what do you guys think?

Body:
You are not assigning the radius in the constructor of Circle...

public Circle(int radius)
{
    perimeter = 2.0 * (PI * radius);
    area = PI * (radius * radius);
    this.radius = radius // this statement is missing
}

Therefore, circle.getRadius() always returns the uninitialized default int value 0.


问:
RecyclerView java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position when resume from added fragment
Can you guys help me on this

here is my code to add fragment

```<code>mRecyclerView.addOnItemTouchListener(
    new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            if (!IsScrolling) {
                Fragment fragment = new ProductInfoFragment();
                    Bundle bundle = new Bundle();
                    bundle.putString("prodID", mItems.get(position).getproductID());
                    bundle.putString("catName", catName);
                    fragment.setArguments(bundle);
                    FragmentManager fragmentManager = getActivity().getFragmentManager();
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                                        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                                        fragmentTransaction.add(R.id.fragmentContainer, fragment, "ProuctInfoFragment");
                                        fragmentTransaction.addToBackStack(null);
                                        fragmentTransaction.commit();
                                        mItems.clear();
                                    }

                                }

                            })
                    );
</code>```

But when i press back from the added fragment i got this error and my app crash.

```<code>FATAL EXCEPTION: main Process: com.tiseno.poplook, PID: 2617
 java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 5(offset:5).state:9
      at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4401)
      at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4359)
      at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1961)
      at android.support.v7.widget.GridLayoutManager.layoutChunk(GridLayoutManager.java:438)
      at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1333)
      at android.support.v7.widget.LinearLayoutManager.scrollBy(LinearLayoutManager.java:1161)
      at android.support.v7.widget.LinearLayoutManager.scrollVerticallyBy(LinearLayoutManager.java:1018)
      at android.support.v7.widget.RecyclerView$ViewFlinger.run(RecyclerView.java:3807)
      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
      at android.view.Choreographer.doCallbacks(Choreographer.java:670)
      at android.view.Choreographer.doFrame(Choreographer.java:603)
      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
      at android.os.Handler.handleCallback(Handler.java:739)
      at android.os.Handler.dispatchMessage(Handler.java:95)
      at android.os.Looper.loop(Looper.java:224)
      at android.app.ActivityThread.main(ActivityThread.java:5514)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

why is this happening? please help. im using two fragment. the product list fragent and product details fragment

答:
Try this

i was facing the same issue ,when you are clearing your list you have to notify the adapter because everytime you are changing the list and the adapter is containing old list so you have to notify the adapter after clearing the list before adding new items in adapter

make instance of data members in starting oof your class

```<code>ArrayList<HashMap<String,String>> yourarraylist =new ArrayList<>();
Youradaptername instance;
</code>```

after clearing your list notify the adapter

```<code> yourarraylist .clear();
 instance.notifyDataSetChanged();
</code>```

Body:
Can you guys help me on this

here is my code to add fragment

mRecyclerView.addOnItemTouchListener(
    new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            if (!IsScrolling) {
                Fragment fragment = new ProductInfoFragment();
                    Bundle bundle = new Bundle();
                    bundle.putString("prodID", mItems.get(position).getproductID());
                    bundle.putString("catName", catName);
                    fragment.setArguments(bundle);
                    FragmentManager fragmentManager = getActivity().getFragmentManager();
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                                        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                                        fragmentTransaction.add(R.id.fragmentContainer, fragment, "ProuctInfoFragment");
                                        fragmentTransaction.addToBackStack(null);
                                        fragmentTransaction.commit();
                                        mItems.clear();
                                    }

                                }

                            })
                    );

But when i press back from the added fragment i got this error and my app crash.

FATAL EXCEPTION: main Process: com.tiseno.poplook, PID: 2617
 java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 5(offset:5).state:9
      at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4401)
      at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4359)
      at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1961)
      at android.support.v7.widget.GridLayoutManager.layoutChunk(GridLayoutManager.java:438)
      at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1333)
      at android.support.v7.widget.LinearLayoutManager.scrollBy(LinearLayoutManager.java:1161)
      at android.support.v7.widget.LinearLayoutManager.scrollVerticallyBy(LinearLayoutManager.java:1018)
      at android.support.v7.widget.RecyclerView$ViewFlinger.run(RecyclerView.java:3807)
      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
      at android.view.Choreographer.doCallbacks(Choreographer.java:670)
      at android.view.Choreographer.doFrame(Choreographer.java:603)
      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
      at android.os.Handler.handleCallback(Handler.java:739)
      at android.os.Handler.dispatchMessage(Handler.java:95)
      at android.os.Looper.loop(Looper.java:224)
      at android.app.ActivityThread.main(ActivityThread.java:5514)
      at java.lang.reflect.Method.invoke(Native Method)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

why is this happening? please help. im using two fragment. the product list fragent and product details fragment

Body:
Try this

i was facing the same issue ,when you are clearing your list you have to notify the adapter because everytime you are changing the list and the adapter is containing old list so you have to notify the adapter after clearing the list before adding new items in adapter

make instance of data members in starting oof your class

ArrayList<HashMap<String,String>> yourarraylist =new ArrayList<>();
Youradaptername instance;

after clearing your list notify the adapter

 yourarraylist .clear();
 instance.notifyDataSetChanged();


问:
Powershell Inkove-expression
Yesterday I read about the invoke-expression
from
http://technet.microsoft.com/en-us/library/dd347550.aspx

```<code>invoke-expression -command "c:\batfile.bat"
</code>```

It works very well, but how can I get the results and also , how to add args for .bat file?

答:
Invoke-Expression is to Call up the EXpression,And '.Bat' is not an expression.

So if you want to call .Bat File Justc:\batfile.bat Could Do the trick.

Or if you want to explore on the invoke-expression Copy the commands in Batch file into a variable to see the code being executed.

There was similar instance where I had to do something similar,And I had used it as

```<code>$prog="cmd.exe"
$TARGETDIR = 'd:\temp'
$x='C:\Users\v-chetak\Desktop\1.bat'
$params=@("/C";"$x";" >d:\temp\result17.txt")
Start-Process -Verb runas $prog +$params
</code>```

The  $params Will Hold all the arguments you want to pass.

Title: Powershell Inkove-expression

Body:
Yesterday I read about the invoke-expression
from
http://technet.microsoft.com/en-us/library/dd347550.aspx

invoke-expression -command "c:\batfile.bat"

It works very well, but how can I get the results and also , how to add args for .bat file?

Body:
Invoke-Expression is to Call up the EXpression,And '.Bat' is not an expression.

So if you want to call .Bat File Justc:\batfile.bat Could Do the trick.

Or if you want to explore on the invoke-expression Copy the commands in Batch file into a variable to see the code being executed.

There was similar instance where I had to do something similar,And I had used it as

$prog="cmd.exe"
$TARGETDIR = 'd:\temp'
$x='C:\Users\v-chetak\Desktop\1.bat'
$params=@("/C";"$x";" >d:\temp\result17.txt")
Start-Process -Verb runas $prog +$params

The  $params Will Hold all the arguments you want to pass.


问:
how to reduce number of condition checks when I select one/two/three/four/five/six from the 6 select options?
Example: When I have only two select options

```<code>input_one = 'one';
input_two = 'two';
</code>```

when I select only input_one

```<code>if((isset($_POST['input_one']) && (!isset($_POST['input_two']) {
    //query
}
</code>```

When I select only input_two

```<code>elseif((!isset($_POST['input_one']) && (isset($_POST['input_two'])) {
    //query
}
</code>```

When I don't select any of those

```<code>elseif((!isset($_POST['input_one']) && (!isset($_POST['input_two'])) {
    //query
}
</code>```

When I select both of them

```<code>elsif((isset($_POST['input_one']) && (!isset($_POST['input_two'])) {
    //query
}
</code>```

but when I have 6 input options then I need to write a number of conditions. How do I reduce those, if there is any alternate method?

答:
```<code>$query = "some query";
foreach($_POST as $key => $post){
  switch($key){
    case 1:
     $query .= " AND some condition";
    break;
    case 2:
     $query .= " AND some condition";
    break;
  }
}
mysqli_query($sql,$query);
</code>```

Body:
Example: When I have only two select options

input_one = 'one';
input_two = 'two';

when I select only input_one

if((isset($_POST['input_one']) && (!isset($_POST['input_two']) {
    //query
}

When I select only input_two

elseif((!isset($_POST['input_one']) && (isset($_POST['input_two'])) {
    //query
}

When I don't select any of those

elseif((!isset($_POST['input_one']) && (!isset($_POST['input_two'])) {
    //query
}

When I select both of them

elsif((isset($_POST['input_one']) && (!isset($_POST['input_two'])) {
    //query
}

but when I have 6 input options then I need to write a number of conditions. How do I reduce those, if there is any alternate method?


问:
SQL Server - join rows into comma separated list
Let's suppose I have a temporary table which looks like this:

```<code>+----+------+
| Id | Value|
+----+------+
| 1  |   1  |
| 1  |   2  |
| 1  |   3  |
| 2  |   1  |
| 2  |   2  |
+----+------+
</code>```

And I want my table to be like this:

```<code>    +----+----------+
    | Id | ValueList|
    +----+----------+
    | 1  |   1,2,3  |
    | 2  |   1,2    |
    +----+----------+
</code>```

So basically I need to group my values as a comma separated list.
I already tried the following:

```<code>SELECT Id, STUFF((SELECT ',' + CAST(VALUE AS varchar) FROM @MyTable FOR XML PATH('')), 1 ,1, '') AS ValueList
FROM @MyTable
GROUP BY Id
</code>```

But I get something like:

```<code>        +----+---------------------+
        | Id |      ValueList      |
        +----+---------------------+
        | 1  |   1,1,1,1,1,1,...   |
        +----+---------------------+
</code>```

I cant find what I am doing wrong. Could someone help with this query? Or point me to a right direction?
Thank you.

答:
Try this :

```<code>create table #t(id int, value int)
insert into #t values
(1,1),
(1,2),
(1,3),
(2,1),
(2,2)

SELECT t2.Id,
STUFF((SELECT ',' + CAST(VALUE AS varchar) FROM #t t1  where t1.Id =t2.ID FOR XML PATH('')), 1 ,1, '') AS list
FROM #t t2
GROUP BY t2.Id
</code>```

output :

```<code>Id          list
---        -------
1           1,2,3
2           1,2
</code>```

Body:
Let's suppose I have a temporary table which looks like this:

+----+------+
| Id | Value|
+----+------+
| 1  |   1  |
| 1  |   2  |
| 1  |   3  |
| 2  |   1  |
| 2  |   2  |
+----+------+

And I want my table to be like this:

    +----+----------+
    | Id | ValueList|
    +----+----------+
    | 1  |   1,2,3  |
    | 2  |   1,2    |
    +----+----------+

So basically I need to group my values as a comma separated list.
I already tried the following:

SELECT Id, STUFF((SELECT ',' + CAST(VALUE AS varchar) FROM @MyTable FOR XML PATH('')), 1 ,1, '') AS ValueList
FROM @MyTable
GROUP BY Id

But I get something like:

        +----+---------------------+
        | Id |      ValueList      |
        +----+---------------------+
        | 1  |   1,1,1,1,1,1,...   |
        +----+---------------------+

I cant find what I am doing wrong. Could someone help with this query? Or point me to a right direction?
Thank you.

Body:
Try this :

create table #t(id int, value int)
insert into #t values
(1,1),
(1,2),
(1,3),
(2,1),
(2,2)

SELECT t2.Id,
STUFF((SELECT ',' + CAST(VALUE AS varchar) FROM #t t1  where t1.Id =t2.ID FOR XML PATH('')), 1 ,1, '') AS list
FROM #t t2
GROUP BY t2.Id

output :

Id          list
---        -------
1           1,2,3
2           1,2