问:
Get thumbnail image of video from video url
Is it possible to get the thumbnail image from a video Url? I need to thumbnails of videos in a list view.</p>

答:
It is working in my case </p>

```<code>Uri videoUri = data.getData();
                String selectedPathVideo="";
                selectedPathVideo = ImageFilePath.getPath(getApplicationContext(), videoUri);
                Log.i("Image File Path", ""+selectedPathVideo);

                try {
                    Bitmap thumb = ThumbnailUtils.createVideoThumbnail(selectedPathVideo, MediaStore.Video.Thumbnails.MICRO_KIND);

                    imgFarmerVideo.setImageBitmap(thumb);

                } catch (Exception e) {
                    e.printStackTrace();
                }
</code>```

<p>The Support File </p>

```<code>public class ImageFilePath {
    /**
     * Method for return file path of Gallery image
     *
     * @param context
     * @param uri
     * @return path of the selected image file from gallery
     */
    public static String getPath(final Context context, final Uri uri)
    {

        //check here to KITKAT or new version
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {

            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] {
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}
</code>```

Body:
It is working in my case

Uri videoUri = data.getData();
                String selectedPathVideo="";
                selectedPathVideo = ImageFilePath.getPath(getApplicationContext(), videoUri);
                Log.i("Image File Path", ""+selectedPathVideo);

                try {
                    Bitmap thumb = ThumbnailUtils.createVideoThumbnail(selectedPathVideo, MediaStore.Video.Thumbnails.MICRO_KIND);

                    imgFarmerVideo.setImageBitmap(thumb);

                } catch (Exception e) {
                    e.printStackTrace();
                }

The Support File

public class ImageFilePath {
    /**
     * Method for return file path of Gallery image
     *
     * @param context
     * @param uri
     * @return path of the selected image file from gallery
     */
    public static String getPath(final Context context, final Uri uri)
    {

        //check here to KITKAT or new version
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {

            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] {
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }
}


来源: stackexchange

问:
Android: Implementing expandable Listview along with Linearlayout Having Images and details
I have Implemented expandable Listview using following links.
    http://www.androidhive.info/2013/07/android-expandable-list-view-tutorial

while using expandable Listview,on expand and collapse of the list, list is hidden under the Textview.

Here is my layout

fragment_main.xml

```<code><android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

<android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true">

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

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="@dimen/profile_detail_image"
                android:scaleType="fitXY"/>

                <include layout="@layout/fragment_detail" />

            </LinearLayout>

        </android.support.v4.widget.NestedScrollView>
     </RelativeLayout>
</android.support.v4.widget.SwipeRefreshLayout>
</code>```

fragment_detail.xml

```<code><RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.CardView
        android:id="@+id/cardview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardElevation="5dp"
        app:contentPadding="5dp">

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

            <TableLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:stretchColumns="*">

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

         <LinearLayout android:orientation="vertical">

                <TextView
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:textSize="24sp" />

              <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="18sp" />

            <TextView
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:textSize="18sp" />
        </LinearLayout>
        </LinearLayout>
    </android.support.v7.widget.CardView>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Description"
        android:layout_below="@+id/cardview"
        style="@style/Base.TextAppearance.AppCompat.Title" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:textSize="18sp"
        android:padding="10dp"
        android:fontFamily="sans-serif-light"
        android:layout_below="@+id/description_text"/>

    <ExpandableListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layoutDirection="rtl"/>

    <Button
        style="@style/TextAppearance.AppCompat.Widget.Button.Colored"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:layout_alignParentBottom="true"
        android:text="Order" />
</RelativeLayout>
</code>```

答:
Anyone Looking for answer. I found a Solution.

first create a class

```<code>public class Utility{
    public static void getExpandableListViewSize(ExpandableListView myListView) {
        ListAdapter myListAdapter = myListView.getAdapter();
        if (myListAdapter == null) {
            //do nothing return null
            return;
        }
        //set listAdapter in loop for getting final size
        int totalHeight = 0;
        for (int size = 0; size < myListAdapter.getCount(); size++) {
            View listItem = myListAdapter.getView(size,null, myListView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        //setting listview item in adapter
        ViewGroup.LayoutParams params = myListView.getLayoutParams();
        params.height = totalHeight + (myListView.getDividerHeight() * (myListAdapter.getCount() - 1));
        myListView.setLayoutParams(params);
        // print height of adapter on log
        Log.i("height of listItem:", String.valueOf(totalHeight));
    }
}
</code>```

just call the method in activity Like

```<code>expListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
                @Override
                public void onGroupExpand(int groupPosition) {
                    Utility.getExpandableListViewSize(expListView);
                }
            });
</code>```

for decreasing the Height

```<code>expListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
            @Override
            public void onGroupCollapse(int groupPosition) {
                Utility.getExpandableListViewSize(expListView);
            }
        });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have Implemented expandable Listview using following links.
    http://www.androidhive.info/2013/07/android-expandable-list-view-tutorial

while using expandable Listview,on expand and collapse of the list, list is hidden under the Textview.

Here is my layout

fragment_main.xml

<android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

<android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true">

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

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="@dimen/profile_detail_image"
                android:scaleType="fitXY"/>

                <include layout="@layout/fragment_detail" />

            </LinearLayout>

        </android.support.v4.widget.NestedScrollView>
     </RelativeLayout>
</android.support.v4.widget.SwipeRefreshLayout>

fragment_detail.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.CardView
        android:id="@+id/cardview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardElevation="5dp"
        app:contentPadding="5dp">

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

            <TableLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:stretchColumns="*">

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

         <LinearLayout android:orientation="vertical">

                <TextView
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:textSize="24sp" />

              <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="18sp" />

            <TextView
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:textSize="18sp" />
        </LinearLayout>
        </LinearLayout>
    </android.support.v7.widget.CardView>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Description"
        android:layout_below="@+id/cardview"
        style="@style/Base.TextAppearance.AppCompat.Title" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:textSize="18sp"
        android:padding="10dp"
        android:fontFamily="sans-serif-light"
        android:layout_below="@+id/description_text"/>

    <ExpandableListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layoutDirection="rtl"/>

    <Button
        style="@style/TextAppearance.AppCompat.Widget.Button.Colored"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:layout_alignParentBottom="true"
        android:text="Order" />
</RelativeLayout>

Body:
Anyone Looking for answer. I found a Solution.

first create a class

public class Utility{
    public static void getExpandableListViewSize(ExpandableListView myListView) {
        ListAdapter myListAdapter = myListView.getAdapter();
        if (myListAdapter == null) {
            //do nothing return null
            return;
        }
        //set listAdapter in loop for getting final size
        int totalHeight = 0;
        for (int size = 0; size < myListAdapter.getCount(); size++) {
            View listItem = myListAdapter.getView(size,null, myListView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        //setting listview item in adapter
        ViewGroup.LayoutParams params = myListView.getLayoutParams();
        params.height = totalHeight + (myListView.getDividerHeight() * (myListAdapter.getCount() - 1));
        myListView.setLayoutParams(params);
        // print height of adapter on log
        Log.i("height of listItem:", String.valueOf(totalHeight));
    }
}

just call the method in activity Like

expListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
                @Override
                public void onGroupExpand(int groupPosition) {
                    Utility.getExpandableListViewSize(expListView);
                }
            });

for decreasing the Height

expListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
            @Override
            public void onGroupCollapse(int groupPosition) {
                Utility.getExpandableListViewSize(expListView);
            }
        });


问:
Chrome blocking my paypal button
Installed a paypal button on my landing page but Chrome's seeing a popup and blocking it. Not ideal for people who actually want to pay.

You can reproduce the problem here: https://snapstories.leadpages.co/paypal-button-test/

Any way around this?

答:
Ideally if you want a popup based experience with paypal, you should use the checkout.js javascript integration:

https://developer.paypal.com/demo/checkout/

https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/add-paypal-button/

Title: Chrome blocking my paypal button


问:
Get woocommerce sale price instead of regular price?
I am attempting to grab the sale price of a woocommerce product and than display the price 20% off.

The code I have right now is sort of working. Its grabbing the "regular" price and displaying that as 20% off. But I would like it to grab the sale price.

How is this done in woocommerce?

Here is my PHP

```<code><?php
if($product->product_type=='variable') {
    global $product;
    $sales_price = esc_attr( $product->get_display_price() );
    $discount = 20;
    $currency = esc_attr( get_woocommerce_currency() );
    $new_price = ($sales_price * $discount) / 20;

    echo 'Get this product for '.$new_price.$currency.' with (Promo code)';
}
?>
</code>```

答: You need to get sale price something like this $_product->get_sale_price(); instead of esc_attr( $product->get_display_price()

Body:
I am attempting to grab the sale price of a woocommerce product and than display the price 20% off.

The code I have right now is sort of working. Its grabbing the "regular" price and displaying that as 20% off. But I would like it to grab the sale price.

How is this done in woocommerce?

Here is my PHP

<?php
if($product->product_type=='variable') {
    global $product;
    $sales_price = esc_attr( $product->get_display_price() );
    $discount = 20;
    $currency = esc_attr( get_woocommerce_currency() );
    $new_price = ($sales_price * $discount) / 20;

    echo 'Get this product for '.$new_price.$currency.' with (Promo code)';
}
?>


问:
How to get data for the last week data?
I am trying to write a report whereby the report will have the contract updated records for the past week using ms sql script. Every Monday the report will be sent for the last Mon-sun. I tried the below query. it doesnt seems to work. Any idea how to achieve this?

```<code>SET DATEFIRST 1

select distinct [...]
where CONTRACT_UPDATE_DATE>= dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
AND CONTRACT_UPDATE_DATE<  dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))
</code>```

Thanks.

答:
```<code>select * from table_abc WHERE
CAST(CONTRACT_UPDATE_DATE as date) between
CAST(DATEADD(dd, -7, GETDATE()) as date) and
CAST(GETDATE() AS DATE)
</code>```

use dateadd to get 1 week before current date.

You can remove the cast as date if you need to validate by timestamp also.

Title: How to get data for the last week data?

Body:
I am trying to write a report whereby the report will have the contract updated records for the past week using ms sql script. Every Monday the report will be sent for the last Mon-sun. I tried the below query. it doesnt seems to work. Any idea how to achieve this?

SET DATEFIRST 1

select distinct [...]
where CONTRACT_UPDATE_DATE>= dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
AND CONTRACT_UPDATE_DATE<  dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))

Thanks.

Body:
select * from table_abc WHERE
CAST(CONTRACT_UPDATE_DATE as date) between
CAST(DATEADD(dd, -7, GETDATE()) as date) and
CAST(GETDATE() AS DATE)

use dateadd to get 1 week before current date.

You can remove the cast as date if you need to validate by timestamp also.


问:
Compilation errors in simple Java program with Scanner
```<code>import java.util.*;
public class strings {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.next();
        System.out.print("Type your seconds integer : ");
        int second = keyboard.next();
        System.out.print("The sum of your two integers are:");
    }
}
</code>```

<p>I dont know why im getting 2 errors on strings cannot converted to int. </p>

答:
I have three solutions for this problem :

First

In your code you are using keyboard.next() which will return a string that you have to convert it into Integer. For that you can use keyboard.nextInt(), it will directly convert the string into integer.

```<code>import java.util.Scanner;

public class strings {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.nextInt();
        System.out.print("Type your seconds integer : ");
        int second = keyboard.nextInt();
        System.out.print("The sum of your two integers are:"+(first+second));
    }
}
</code>```

Second

or you can convert the string into Integer by using  Integer.parseInt(**String to be converted to Integer**), this will convert the string into Integer.

```<code>import java.util.Scanner;

public class strings {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = Integer.parseInt(keyboard.next());
        System.out.print("Type your seconds integer : ");
        int second = Integer.parseInt(keyboard.next());
        System.out.print("The sum of your two integers are:"+(first+second));
    }
}
</code>```

Third

or you can convert the string into Integer by using  Integer.valueOf(**String to be converted to Integer**), this will convert the string into Integer.

```<code>import java.util.Scanner;

public class strings {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = Integer.valueOf(keyboard.next());
        System.out.print("Type your seconds integer : ");
        int second = Integer.valueOf(keyboard.next());
        System.out.print("The sum of your two integers are:"+(first+second));
    }
}
</code>```

Body:
import java.util.*;
public class strings {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.next();
        System.out.print("Type your seconds integer : ");
        int second = keyboard.next();
        System.out.print("The sum of your two integers are:");
    }
}

I dont know why im getting 2 errors on strings cannot converted to int.

Body:
I have three solutions for this problem :

First

In your code you are using keyboard.next() which will return a string that you have to convert it into Integer. For that you can use keyboard.nextInt(), it will directly convert the string into integer.

import java.util.Scanner;

public class strings {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.nextInt();
        System.out.print("Type your seconds integer : ");
        int second = keyboard.nextInt();
        System.out.print("The sum of your two integers are:"+(first+second));
    }
}

Second

or you can convert the string into Integer by using  Integer.parseInt(**String to be converted to Integer**), this will convert the string into Integer.

import java.util.Scanner;

public class strings {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = Integer.parseInt(keyboard.next());
        System.out.print("Type your seconds integer : ");
        int second = Integer.parseInt(keyboard.next());
        System.out.print("The sum of your two integers are:"+(first+second));
    }
}

Third

or you can convert the string into Integer by using  Integer.valueOf(**String to be converted to Integer**), this will convert the string into Integer.

import java.util.Scanner;

public class strings {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = Integer.valueOf(keyboard.next());
        System.out.print("Type your seconds integer : ");
        int second = Integer.valueOf(keyboard.next());
        System.out.print("The sum of your two integers are:"+(first+second));
    }
}


问:
How to subtract or add date from a variable?
I have a date in the variable x=20170402, getting this value from another file.

I want to modify this by adding/subtracting and save to new variable. How can i do this?

ex: if i subtract one day, y=20170401; two days, y=20170331

and it is GNU based.

答:
With GNU date it can be done quite easily with its -d switch.

```<code>x=20170402
date -d "$x -1 days" "+%Y%m%d"
20170401
</code>```

and for 2 days

```<code>date -d "$x - 2 days" "+%Y%m%d"
20170331
</code>```

Body:
With GNU date it can be done quite easily with its -d switch.

x=20170402
date -d "$x -1 days" "+%Y%m%d"
20170401

and for 2 days

date -d "$x - 2 days" "+%Y%m%d"
20170331


问:
Mach-O Linker Error on Xcode 4.6
I have an iOS app on Xcode 4.6 and when I recently tried to build and run in the iPhone 6.1 simulator I got a "Mach-O Linker Error." It continued to say:

ld: 17 duplicate symbols for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Does anyone know how to solve this?

Thanks so much!

答:
In my case it was constants.

```<code>NSString *const cellID = @"cellID";
</code>```

This line was written in two .m files. After appending static keyword at the start the problem was resolved.

This issue can be recreated in a new project too. You would think that defining constants in the different .m files won't have any effect as they are private. But I don't know how the compiler is handling stuffs behind the scene. On top of that when you tap the issue from issue navigator it doesn't open up a page in the editor like it does for any other issue. Really frustrating.

Title: Mach-O Linker Error on Xcode 4.6

Body:
In my case it was constants.

NSString *const cellID = @"cellID";

This line was written in two .m files. After appending static keyword at the start the problem was resolved.

This issue can be recreated in a new project too. You would think that defining constants in the different .m files won't have any effect as they are private. But I don't know how the compiler is handling stuffs behind the scene. On top of that when you tap the issue from issue navigator it doesn't open up a page in the editor like it does for any other issue. Really frustrating.


问:
Expression function: Generic type T predicate
Is it possible to parse generic type T from predicate expression and convert it back to another type and then create new expression by using converted type?

I'm doing the conversion from T to DTO.Company and after that I should do the mapping from DTO.Company to DAL.Company. In below code example I'm trying to do conversion but first I need to know that is it even possible and secondly I need to know how to convert DTO.Company to DAL.Company inside the predicate parameters before setting the bar variable.

```<code>    // This works!!!! But I want to make it generic as possible!
    public T Fetch<T>(Expression<Func<DAL.Company, bool>> predicate) where T : class
    {
        var typeOfT = typeof(T);
        if (typeOfT != typeof(DTO.Company))
        {
            return null;
        }
        var companies = _dbContext.Companies.Where(predicate);

        var ret = new Collection<DTO.Company>();
        foreach (var company in companies)
        {
            ret.Add(company.ConvertToDataTransferObject());
        }
        return (T)Convert.ChangeType(ret, typeof(T));
    }

    // This does not work!!!
    public T Fetch<T>(Expression<Func<T, bool>> predicate) where T : class
    {
        var typeOfT = typeof(T);
        if (typeOfT != typeof(DTO.Company))
        {
            return null;
        }
        var foo = Expression.Convert(predicate.Body, typeof(bool));

    //Below I'm getting Exception thrown: 'System.ArgumentException' in System.Core.dll
    //Additional information: ParameterExpression of type 'DTO.Company' cannot be used for delegate parameter of type 'DAL.Company'

        var bar = Expression.Lambda<Func<DAL.Company, bool>>(foo, predicate.Parameters);
        var companies = _dbContext.Companies.Where(bar);

        var ret = new Collection<DTO.Company>();
        foreach (var company in companies)
        {
            ret.Add(company.ConvertToDataTransferObject());
        }
        return (T)Convert.ChangeType(ret, typeof(T));
    }
</code>```

答:
Ok, I changed logic a little bit.

First logic was:

Service layer takes only DTO parameters and returns only DTO objects.

Repository layer takes only DTO parameters and predicate parameters are only DTO and returns only DTO pbjects.

Now it's:

Service layer takes only DTO parameters and returns only DTO objects.

Repository layer takes only DTO paramaters and predicate parameters are only DAL and returns only DTO objects.

Body:
Is it possible to parse generic type T from predicate expression and convert it back to another type and then create new expression by using converted type?

I'm doing the conversion from T to DTO.Company and after that I should do the mapping from DTO.Company to DAL.Company. In below code example I'm trying to do conversion but first I need to know that is it even possible and secondly I need to know how to convert DTO.Company to DAL.Company inside the predicate parameters before setting the bar variable.

    // This works!!!! But I want to make it generic as possible!
    public T Fetch<T>(Expression<Func<DAL.Company, bool>> predicate) where T : class
    {
        var typeOfT = typeof(T);
        if (typeOfT != typeof(DTO.Company))
        {
            return null;
        }
        var companies = _dbContext.Companies.Where(predicate);

        var ret = new Collection<DTO.Company>();
        foreach (var company in companies)
        {
            ret.Add(company.ConvertToDataTransferObject());
        }
        return (T)Convert.ChangeType(ret, typeof(T));
    }

    // This does not work!!!
    public T Fetch<T>(Expression<Func<T, bool>> predicate) where T : class
    {
        var typeOfT = typeof(T);
        if (typeOfT != typeof(DTO.Company))
        {
            return null;
        }
        var foo = Expression.Convert(predicate.Body, typeof(bool));

    //Below I'm getting Exception thrown: 'System.ArgumentException' in System.Core.dll
    //Additional information: ParameterExpression of type 'DTO.Company' cannot be used for delegate parameter of type 'DAL.Company'

        var bar = Expression.Lambda<Func<DAL.Company, bool>>(foo, predicate.Parameters);
        var companies = _dbContext.Companies.Where(bar);

        var ret = new Collection<DTO.Company>();
        foreach (var company in companies)
        {
            ret.Add(company.ConvertToDataTransferObject());
        }
        return (T)Convert.ChangeType(ret, typeof(T));
    }


问:
Excluding a file from a gulp task not working
I have a gulp task I've put together where I need to exclude a single file. The task is below. I've tried a few variations of exclusion like: !+source... and source + '!sass/**/navigation-offcanvas.scss'. Obviously my syntax is off. I looked at this article: https://discourse.roots.io/t/exclude-file-types-in-fonts-task/5356 and this: https://medium.com/@jack.yin/exclude-directory-pattern-in-gulp-with-glob-in-gulp-src-9cc981f32116 and still not quite there.

```<code>gulp.task('styles', function() {
return gulp.src([
  source + 'sass/**/*.scss',
  !source + 'sass/**/navigation-offcanvas.scss'
])
</code>```

答:
The not <code>!</code> operator shall be within the string, in this way (the way you have it in the question), it is evaluating as a javascript call and not being evaluted within gulp. </p>

```<code> gulp.task('styles', function() {
    return gulp.src([
      source + 'sass/**/*.scss',
      '!' + source + 'sass/**/navigation-offcanvas.scss'
    ])
</code>```

OwnerDisplayName: yannibmbr

Body:
I have a gulp task I've put together where I need to exclude a single file. The task is below. I've tried a few variations of exclusion like: !+source... and source + '!sass/**/navigation-offcanvas.scss'. Obviously my syntax is off. I looked at this article: https://discourse.roots.io/t/exclude-file-types-in-fonts-task/5356 and this: https://medium.com/@jack.yin/exclude-directory-pattern-in-gulp-with-glob-in-gulp-src-9cc981f32116 and still not quite there.

gulp.task('styles', function() {
return gulp.src([
  source + 'sass/**/*.scss',
  !source + 'sass/**/navigation-offcanvas.scss'
])

Body:
The not ! operator shall be within the string, in this way (the way you have it in the question), it is evaluating as a javascript call and not being evaluted within gulp.

 gulp.task('styles', function() {
    return gulp.src([
      source + 'sass/**/*.scss',
      '!' + source + 'sass/**/navigation-offcanvas.scss'
    ])


问:
Error with file reader
I'm getting an error with

```<code>PersonsInfoData[i] = PersonsInfoin.setPersonsInfo(temp[0],temp[1],temp[2],temp[3],temp[4]);
</code>```

"Incompatible types: void cannot be coverted to PersonsInfo"

```<code>public void readFile(String fileName)
{
    // Try to read in the data and if an exception occurs go to the Catch section
    try
    {
        FileInputStream fstream = new FileInputStream(fileName);
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        int i = 0;    // i is used as the line counter
        String line;  // line is used to temporarily store the line read in from the data file

        // Read a line from the data file into the buffer and then check whether
        //      it is null.  The while loop continues until a line read in is null.
        while ((line = br.readLine()) != null)
        {
            // Split the line of data (from the text file) and put each entry into the
    //                                             temporary array - temp[]
            String[] temp = line.split(",");
            // Save each entry into its respective PCDataRecord object.
            PersonsInfoData[i] = PersonsInfoin.setPersonsInfo(temp[0],temp[1],temp[2],temp[3],temp[4]);
            i++;  // Increment i so we can keep a count of how many entries have been read in.
        }
        numberOfEntries = i;   // Set numberOfEntries equal to i, to remember how many entries are now in the array
        br.close();            // Close the BufferedReader
        in.close();            // Close the DataInputStream
        fstream.close();       // Close the FileInputStream
    }
    catch (Exception e)
    {
        System.err.println("Error Reading File: " + e.getMessage());
    }
}
</code>```

答:
this is a setter statement:

```<code>PersonsInfoin.setPersonsInfo(temp[0],temp[1],temp[2],temp[3],temp[4]);
</code>```

so, not all setters return objects, in your case that method returns returns nothing (void) making your statement equivalent to doing:

```<code>PersonsInfoData[i] = void
</code>```

which is invalid...

Title: Error with file reader

Body:
I'm getting an error with

PersonsInfoData[i] = PersonsInfoin.setPersonsInfo(temp[0],temp[1],temp[2],temp[3],temp[4]);

"Incompatible types: void cannot be coverted to PersonsInfo"

public void readFile(String fileName)
{
    // Try to read in the data and if an exception occurs go to the Catch section
    try
    {
        FileInputStream fstream = new FileInputStream(fileName);
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        int i = 0;    // i is used as the line counter
        String line;  // line is used to temporarily store the line read in from the data file

        // Read a line from the data file into the buffer and then check whether
        //      it is null.  The while loop continues until a line read in is null.
        while ((line = br.readLine()) != null)
        {
            // Split the line of data (from the text file) and put each entry into the
    //                                             temporary array - temp[]
            String[] temp = line.split(",");
            // Save each entry into its respective PCDataRecord object.
            PersonsInfoData[i] = PersonsInfoin.setPersonsInfo(temp[0],temp[1],temp[2],temp[3],temp[4]);
            i++;  // Increment i so we can keep a count of how many entries have been read in.
        }
        numberOfEntries = i;   // Set numberOfEntries equal to i, to remember how many entries are now in the array
        br.close();            // Close the BufferedReader
        in.close();            // Close the DataInputStream
        fstream.close();       // Close the FileInputStream
    }
    catch (Exception e)
    {
        System.err.println("Error Reading File: " + e.getMessage());
    }
}

Body:
this is a setter statement:

PersonsInfoin.setPersonsInfo(temp[0],temp[1],temp[2],temp[3],temp[4]);

so, not all setters return objects, in your case that method returns returns nothing (void) making your statement equivalent to doing:

PersonsInfoData[i] = void

which is invalid...


答:
The command date should be enough.</p>

```<code>$ x=20170402;
$ date -d "$x 1 day ago" +'%Y%m%d'
20170401

$ date -d "$x 2 day ago" +'%Y%m%d'
20170331
</code>```

Title: How to subtract or add date from a variable?

Body:
I have a date in the variable x=20170402, getting this value from another file.

I want to modify this by adding/subtracting and save to new variable. How can i do this?

ex: if i subtract one day, y=20170401; two days, y=20170331

and it is GNU based.

Body:
The command date should be enough.

$ x=20170402;
$ date -d "$x 1 day ago" +'%Y%m%d'
20170401

$ date -d "$x 2 day ago" +'%Y%m%d'
20170331


答:
I suggest this solution: </p>

```<code> select * from DB where Datediff(day, CONVERT(DATE, Sysdatetime()),
                                 CONVERT(DATE, CONTRACT_UPDATE_DATE))<=7 and  Datediff(day, CONVERT(DATE, Sysdatetime()),
                                 CONVERT(DATE, CONTRACT_UPDATE_DATE))>0
</code>```

Title: How to get data for the last week data?

Body:
I suggest this solution:

 select * from DB where Datediff(day, CONVERT(DATE, Sysdatetime()),
                                 CONVERT(DATE, CONTRACT_UPDATE_DATE))<=7 and  Datediff(day, CONVERT(DATE, Sysdatetime()),
                                 CONVERT(DATE, CONTRACT_UPDATE_DATE))>0


问:
Connect AndroidThings to adb via ethernet cable
Quick question. It is possible to get adb via ethernet cable connected to my laptop instead of connecting to router?</p>

答:
This is possible, though it's a bit more work. Here are a couple of options:

Run a DHCP service on your laptop to assign the board an IP address.

Connect to the board over serial and assign a static IP address.

If the ethernet port in your laptop doesn't autocross, you may need to connect the devices using a crossover cable instead of a patch cable.

DHCP Service

Ubuntu: Use a local service like avahi-daemon.

Mac OS: Enable internet sharing on the Ethernet port.

Windows: I have never tried, but others have used DHCP Server for Windows for this purpose.

Static IP

Use the serial debug console instructions to connect a serial cable and access the shell.

Connect the Ethernet cable between the board and your computer.

Run the following command as root (replace x.x.x.x with a real IP address):

ip addr add x.x.x.x dev eth0

Verify that the IP address was set properly with ifconfig

Run adb connect x.x.x.x or adb connect Android.local

The static IP address will only stick as long as the Ethernet link is active. If the device reboots or ethernet is unplugged, you'll have to run this procedure again.


答:
The prediction() function is available in both neuralnet and ROCR package in R. So do not load both packages together. First load neuralnet, train your model and then detach it using detach() and then load ROCR package. Try following code:

```<code>#load packages
require(neuralnet)

#create data set
train<-read.table(file="train.txt",header=TRUE,sep=",")
test<- read.table(file="test.txt",header=TRUE,sep=",")

#build model and make predictions
nn.sag <- neuralnet(Type ~ Area+Perimeter+Compactness+Length+Width+Asymmetry+Groove, data = train, hidden = 5, algorithm = "sag", err.fct = "sse", linear.output = FALSE)

prob = compute(nn.sag, test[, -ncol(test)] )
prob.result <- prob$net.result

detach(package:neuralnet,unload = T)

library(ROCR)
nn.pred = prediction(prob.result, test$Type)
pref <- performance(nn.pred, "tpr", "fpr")
plot(pref)
</code>```

Title: Plot a Neural Net Curve Using neuralnet and ROCR package

Body:
Here I have a classification task and I need to use neuralnet and ROCR packages. The problem is that I got the error messages when I use prediction function.

Here is my code:

#load packages
require(neuralnet)
library(ROCR)

#create data set
train<-read.table(file="train.txt",header=TRUE,sep=",")
test<- read.table(file="test.txt",header=TRUE,sep=",")

#build model and make predictions
nn.sag <- neuralnet(Type ~ Area+Perimeter+Compactness+Length+Width+Asymmetry+Groove, data = train, hidden = 5, algorithm = "sag", err.fct = "sse", linear.output = FALSE)

prob = compute(nn.sag, test[, -ncol(test)] )
prob.result <- prob$net.result

nn.pred = prediction(prob.result, test$Type)
pref <- performance(nn.pred, "tpr", "fpr")
plot(pref)

And here I got the error message for the 'prediction' function:
'$ operator is invalid for atomic vectors'

The dataset looks like (only training dataset here):

Area,Perimeter,Compactness,Length,Width,Asymmetry,Groove,Type
14.8,14.52,0.8823,5.656,3.288,3.112,5.309,1
14.79,14.52,0.8819,5.545,3.291,2.704,5.111,1
14.99,14.56,0.8883,5.57,3.377,2.958,5.175,1
19.14,16.61,0.8722,6.259,3.737,6.682,6.053,0
15.69,14.75,0.9058,5.527,3.514,1.599,5.046,1
14.11,14.26,0.8722,5.52,3.168,2.688,5.219,1
13.16,13.55,0.9009,5.138,3.201,2.461,4.783,1
16.16,15.33,0.8644,5.845,3.395,4.266,5.795,0
15.01,14.76,0.8657,5.789,3.245,1.791,5.001,1
14.11,14.1,0.8911,5.42,3.302,2.7,5,1
17.98,15.85,0.8993,5.979,3.687,2.257,5.919,0
21.18,17.21,0.8989,6.573,4.033,5.78,6.231,0
14.29,14.09,0.905,5.291,3.337,2.699,4.825,1
14.59,14.28,0.8993,5.351,3.333,4.185,4.781,1
11.42,12.86,0.8683,5.008,2.85,2.7,4.607,1
12.11,13.47,0.8392,5.159,3.032,1.502,4.519,1
15.6,15.11,0.858,5.832,3.286,2.725,5.752,0
15.38,14.66,0.899,5.477,3.465,3.6,5.439,0
18.94,16.49,0.875,6.445,3.639,5.064,6.362,0
12.36,13.19,0.8923,5.076,3.042,3.22,4.605,1
14.01,14.29,0.8625,5.609,3.158,2.217,5.132,1
17.12,15.55,0.8892,5.85,3.566,2.858,5.746,0
15.78,14.91,0.8923,5.674,3.434,5.593,5.136,1
16.19,15.16,0.8849,5.833,3.421,0.903,5.307,1
14.43,14.4,0.8751,5.585,3.272,3.975,5.144,1
13.8,14.04,0.8794,5.376,3.155,1.56,4.961,1
14.46,14.35,0.8818,5.388,3.377,2.802,5.044,1
18.59,16.05,0.9066,6.037,3.86,6.001,5.877,0
18.75,16.18,0.8999,6.111,3.869,4.188,5.992,0
15.49,14.94,0.8724,5.757,3.371,3.412,5.228,1
12.73,13.75,0.8458,5.412,2.882,3.533,5.067,1
13.5,13.85,0.8852,5.351,3.158,2.249,5.176,1
14.38,14.21,0.8951,5.386,3.312,2.462,4.956,1
14.86,14.67,0.8676,5.678,3.258,2.129,5.351,1
18.45,16.12,0.8921,6.107,3.769,2.235,5.794,0
17.32,15.91,0.8599,6.064,3.403,3.824,5.922,0
20.2,16.89,0.8894,6.285,3.864,5.173,6.187,0
20.03,16.9,0.8811,6.493,3.857,3.063,6.32,0
18.14,16.12,0.8772,6.059,3.563,3.619,6.011,0
13.99,13.83,0.9183,5.119,3.383,5.234,4.781,1
15.57,15.15,0.8527,5.92,3.231,2.64,5.879,0
16.2,15.27,0.8734,5.826,3.464,2.823,5.527,1
20.97,17.25,0.8859,6.563,3.991,4.677,6.316,0
14.16,14.4,0.8584,5.658,3.129,3.072,5.176,1
13.45,14.02,0.8604,5.516,3.065,3.531,5.097,1
15.5,14.86,0.882,5.877,3.396,4.711,5.528,1
16.77,15.62,0.8638,5.927,3.438,4.92,5.795,0
12.74,13.67,0.8564,5.395,2.956,2.504,4.869,1
14.88,14.57,0.8811,5.554,3.333,1.018,4.956,1
14.28,14.17,0.8944,5.397,3.298,6.685,5.001,1
14.34,14.37,0.8726,5.63,3.19,1.313,5.15,1
14.03,14.16,0.8796,5.438,3.201,1.717,5.001,1
19.11,16.26,0.9081,6.154,3.93,2.936,6.079,0
14.52,14.6,0.8557,5.741,3.113,1.481,5.487,1
18.43,15.97,0.9077,5.98,3.771,2.984,5.905,0
18.81,16.29,0.8906,6.272,3.693,3.237,6.053,0
13.78,14.06,0.8759,5.479,3.156,3.136,4.872,1
14.69,14.49,0.8799,5.563,3.259,3.586,5.219,1
18.85,16.17,0.9056,6.152,3.806,2.843,6.2,0
12.88,13.5,0.8879,5.139,3.119,2.352,4.607,1
12.78,13.57,0.8716,5.262,3.026,1.176,4.782,1
14.33,14.28,0.8831,5.504,3.199,3.328,5.224,1
19.46,16.5,0.8985,6.113,3.892,4.308,6.009,0
19.38,16.72,0.8716,6.303,3.791,3.678,5.965,0
15.26,14.85,0.8696,5.714,3.242,4.543,5.314,1
20.24,16.91,0.8897,6.315,3.962,5.901,6.188,0
19.94,16.92,0.8752,6.675,3.763,3.252,6.55,0
20.71,17.23,0.8763,6.579,3.814,4.451,6.451,0
16.17,15.38,0.8588,5.762,3.387,4.286,5.703,0
13.02,13.76,0.8641,5.395,3.026,3.373,4.825,1
16.53,15.34,0.8823,5.875,3.467,5.532,5.88,0
13.89,14.02,0.888,5.439,3.199,3.986,4.738,1
18.98,16.57,0.8687,6.449,3.552,2.144,6.453,0
17.08,15.38,0.9079,5.832,3.683,2.956,5.484,1
15.03,14.77,0.8658,5.702,3.212,1.933,5.439,1
16.14,14.99,0.9034,5.658,3.562,1.355,5.175,1
18.65,16.41,0.8698,6.285,3.594,4.391,6.102,0
20.1,16.99,0.8746,6.581,3.785,1.955,6.449,0
17.99,15.86,0.8992,5.89,3.694,2.068,5.837,0
15.88,14.9,0.8988,5.618,3.507,0.7651,5.091,1
13.22,13.84,0.868,5.395,3.07,4.157,5.088,1
18.3,15.89,0.9108,5.979,3.755,2.837,5.962,0
19.51,16.71,0.878,6.366,3.801,2.962,6.185,0

Body:
The prediction() function is available in both neuralnet and ROCR package in R. So do not load both packages together. First load neuralnet, train your model and then detach it using detach() and then load ROCR package. Try following code:

#load packages
require(neuralnet)

#create data set
train<-read.table(file="train.txt",header=TRUE,sep=",")
test<- read.table(file="test.txt",header=TRUE,sep=",")

#build model and make predictions
nn.sag <- neuralnet(Type ~ Area+Perimeter+Compactness+Length+Width+Asymmetry+Groove, data = train, hidden = 5, algorithm = "sag", err.fct = "sse", linear.output = FALSE)

prob = compute(nn.sag, test[, -ncol(test)] )
prob.result <- prob$net.result

detach(package:neuralnet,unload = T)

library(ROCR)
nn.pred = prediction(prob.result, test$Type)
pref <- performance(nn.pred, "tpr", "fpr")
plot(pref)


问:
batch script copying file from only the last line of given text file
I am trying to copy different file in given folder from a text file (line by line) and by using some specific keywords in lines but it is copying file from the last line. I am new in batch scripting so I don't know too much about syntax of batch script my code is

```<code>@echo off
setlocal disableDelayedExpansion
mkdir events_sorted
for /f "tokens=3-7" %%a in (input.txt) do set id=%%a-%%b-%%c-%%d%%e

for /r /d %%i in (.) do (
    cd %%i
    copy "%id%-00S.*" "%CD%/events_sorted/"
 )

pause
</code>```

Thanx

答:
You need to nest the for /R loop into your for /F loop by placing ( after do and putting ) at the end before pause. In addition, do not store the line string in variable id, simply use the line string directly within the copy command line. Furthermore, do not use cd %%i, but use %%i immediately rather than %CD%. Here is the fixed code:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

mkdir "events_sorted"
for /F "usebackq tokens=3-7" %%a in ("input.txt") do (
    for /R /D %%i in (.) do (
        copy "%%a-%%b-%%c-%%d%%e-00S.*" "%%~i/events_sorted/"
    )
)
pause

endlocal
exit /B
```

Body:
I am trying to copy different file in given folder from a text file (line by line) and by using some specific keywords in lines but it is copying file from the last line. I am new in batch scripting so I don't know too much about syntax of batch script my code is

@echo off
setlocal disableDelayedExpansion
mkdir events_sorted
for /f "tokens=3-7" %%a in (input.txt) do set id=%%a-%%b-%%c-%%d%%e

for /r /d %%i in (.) do (
    cd %%i
    copy "%id%-00S.*" "%CD%/events_sorted/"
 )

pause

Thanx


问:
Creating polymer element

<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width">

 <link rel="import" href="bower_components/polymer/polymer-mini.html">

<polymer-element name="x-foo" noscript>
 <template>
  Hello x-foo
 </template>
</polymer-element>
<x-foo></x-foo>

```

Hello Guys, i'm actually new to polymer and i have been trying to run my first stuff on it but its not forth coming and its a bit frustrating you know .
the above code is not showing me anything on my browser and i don't know what i'm doing wrong because there is nothing i can see as the output on my browser after serving and i'm using google chrome.

答: The code above is for Polymer 0.x and not Polymer 1.x. If you want to work with 1.x version you should have a look at Polymer's own documentation for same for other topics related to 1.x.

Title: Creating polymer element

Body:
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width">

 <link rel="import" href="bower_components/polymer/polymer-mini.html">

<polymer-element name="x-foo" noscript>
 <template>
  Hello x-foo
 </template>
</polymer-element>
<x-foo></x-foo>

Hello Guys, i'm actually new to polymer and i have been trying to run my first stuff on it but its not forth coming and its a bit frustrating you know .
the above code is not showing me anything on my browser and i don't know what i'm doing wrong because there is nothing i can see as the output on my browser after serving and i'm using google chrome.


问:
How to remove the selected tab indicator from the FragmentTabhost?
I have tried several links for remove the selected tab in FragmentTabHost but does not work for me .

First link

Second link

I have tried this also in my Xml but it is not working

```<code>android:tabStripEnabled="false"
</code>```

And it is my layout for the fragmenttabhost.

```<code><FrameLayout

    android:id="@+id/realtabcontent"
    android:layout_width="match_parent"
    android:layout_weight="1"
    android:layout_height="0dp"
     />
    <android.support.v4.app.FragmentTabHost
      android:id="@android:id/tabhost"
      android:layout_width="match_parent"
      android:layout_alignParentBottom="true"
      android:background="@drawable/top_bg"
      app:tabIndicatorColor="#000"
      android:tabStripEnabled="false"
      app:tabIndicatorHeight="0dp"
      android:layout_height="60dp"
      >

    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0" />

    <LinearLayout
        android:id="@+id/tab_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:showDividers="none"
        android:orientation="horizontal"
        android:weightSum="5" >

        <ImageView
            android:id="@+id/genralTabBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"
            android:padding="15dp"
            android:background="@drawable/button_1_off" />

        <ImageView
            android:id="@+id/treandingTabBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"
            android:padding="12dp"
            android:background="@drawable/button_2_off" />

        <ImageView
            android:id="@+id/profileTabBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"
            android:padding="12dp"
            android:background="@drawable/button_3_off" />

</android.support.v4.app.FragmentTabHost>
</code>```

And in my devices selected tab look like (Plz check images)

Moto E device

HTC device

答:
Sorry For Late Reply
I am also getting this issue and I tried many things on it and finally I get success.

Try This Below code.

```<code> fragmentTabHost.addTab(fragmentTabHost.newTabSpec("tab1").setIndicator("", getResources().getDrawable(R.drawable.tab1)),
            HomeFragment.class, null);

    fragmentTabHost.getTabWidget().getChildAt(0).setBackground(null);//set child background as null
    fragmentTabHost.addTab(fragmentTabHost.newTabSpec("tab2").setIndicator("", getResources().getDrawable(R.drawable.tab2)),
            CartFragment.class, null);
    fragmentTabHost.getTabWidget().getChildAt(1).setBackground(null););//set child background as null

    fragmentTabHost.addTab(fragmentTabHost.newTabSpec("tab3").setIndicator("", getResources().getDrawable(R.drawable.tab3)),
            MoreStuffFragment.class, null);
    fragmentTabHost.getTabWidget().getChildAt(2).setBackground(null); );//set child background as null
</code>```

fragmentTabHost.getTabWidget().getChildAt("Your tab position").setBackground(null);

Simply you have to get child and set it's background as null and you have done

Body:
I have tried several links for remove the selected tab in FragmentTabHost but does not work for me .

First link

Second link

I have tried this also in my Xml but it is not working

android:tabStripEnabled="false"

And it is my layout for the fragmenttabhost.

<FrameLayout

    android:id="@+id/realtabcontent"
    android:layout_width="match_parent"
    android:layout_weight="1"
    android:layout_height="0dp"
     />
    <android.support.v4.app.FragmentTabHost
      android:id="@android:id/tabhost"
      android:layout_width="match_parent"
      android:layout_alignParentBottom="true"
      android:background="@drawable/top_bg"
      app:tabIndicatorColor="#000"
      android:tabStripEnabled="false"
      app:tabIndicatorHeight="0dp"
      android:layout_height="60dp"
      >

    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0" />

    <LinearLayout
        android:id="@+id/tab_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:showDividers="none"
        android:orientation="horizontal"
        android:weightSum="5" >

        <ImageView
            android:id="@+id/genralTabBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"
            android:padding="15dp"
            android:background="@drawable/button_1_off" />

        <ImageView
            android:id="@+id/treandingTabBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"
            android:padding="12dp"
            android:background="@drawable/button_2_off" />

        <ImageView
            android:id="@+id/profileTabBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"
            android:padding="12dp"
            android:background="@drawable/button_3_off" />

</android.support.v4.app.FragmentTabHost>

And in my devices selected tab look like (Plz check images)

Moto E device

HTC device

Body:
Sorry For Late Reply
I am also getting this issue and I tried many things on it and finally I get success.

Try This Below code.

 fragmentTabHost.addTab(fragmentTabHost.newTabSpec("tab1").setIndicator("", getResources().getDrawable(R.drawable.tab1)),
            HomeFragment.class, null);

    fragmentTabHost.getTabWidget().getChildAt(0).setBackground(null);//set child background as null
    fragmentTabHost.addTab(fragmentTabHost.newTabSpec("tab2").setIndicator("", getResources().getDrawable(R.drawable.tab2)),
            CartFragment.class, null);
    fragmentTabHost.getTabWidget().getChildAt(1).setBackground(null););//set child background as null

    fragmentTabHost.addTab(fragmentTabHost.newTabSpec("tab3").setIndicator("", getResources().getDrawable(R.drawable.tab3)),
            MoreStuffFragment.class, null);
    fragmentTabHost.getTabWidget().getChildAt(2).setBackground(null); );//set child background as null

fragmentTabHost.getTabWidget().getChildAt("Your tab position").setBackground(null);

Simply you have to get child and set it's background as null and you have done


问:
Gulp does not produce intended Css and Html folder
gulp build command in command prompt creates a folder js and also a file scripts.js in dist folder. But the same does not get created for Css and Html. My css and Html folder have atlest one file and are not empty.

```<code>const gulp = require('gulp');
const concat = require('gulp-concat');
const browserSync = require('browser-sync').create();

const scripts = require('./scripts');
const styles = require('./styles');

var devMode = false;

gulp.task('css',function(){
    gulp.src(styles)
        .pipe(concat('main.css'))
        .pipe(gulp.dest('./dist/css'))
        .pipe(browserSync.reload({
            stream : true
    }))
});

gulp.task('js',function(){
    gulp.src(scripts)
        .pipe(concat('scripts.js'))
        .pipe(gulp.dest('./dist/js'))
        .pipe(browserSync.reload({
            stream : true
    }))
});

gulp.task('html',function(){
    gulp.src('./src/templates/**/*.html')
        .pipe(gulp.dest('./dist/html'))
        .pipe(browserSync.reload({
            stream : true
    }))
});

gulp.task('build',function(){
    gulp.start(['css','js','html'])
});

gulp.task('browser-sync',function(){
    browserSync.init(null,{
        open : false,
        server : {
            baseDir : 'dist'
        }
    })
});

gulp.task('start',function(){
    devMode = true;
    gulp.start(['build','browser-sync']);
    gulp.watch(['./src/css/**/*.css'],['css']);
    gulp.watch(['./src/js/**/*.js'],['js']);
    gulp.watch(['./src/templates/**/*.html'],['html']);
});
</code>```

Following is the output

The project structure

答:
I would suggest you use yeoman with a generator like Fountain so that you dont have to spend your time on building the gulp tasks . Fountain has a very good gulp setup which you could customize according to your need.

While loading the files with gulp.src you need to pass the path to the files , Here you have mentioned only gulp.src(require(./styles)) which I am not sure would work . Instead pass , gulp.src('**/*.css') which would scan through all the folders and take all the .css files.

Body:
gulp build command in command prompt creates a folder js and also a file scripts.js in dist folder. But the same does not get created for Css and Html. My css and Html folder have atlest one file and are not empty.

const gulp = require('gulp');
const concat = require('gulp-concat');
const browserSync = require('browser-sync').create();

const scripts = require('./scripts');
const styles = require('./styles');

var devMode = false;

gulp.task('css',function(){
    gulp.src(styles)
        .pipe(concat('main.css'))
        .pipe(gulp.dest('./dist/css'))
        .pipe(browserSync.reload({
            stream : true
    }))
});

gulp.task('js',function(){
    gulp.src(scripts)
        .pipe(concat('scripts.js'))
        .pipe(gulp.dest('./dist/js'))
        .pipe(browserSync.reload({
            stream : true
    }))
});

gulp.task('html',function(){
    gulp.src('./src/templates/**/*.html')
        .pipe(gulp.dest('./dist/html'))
        .pipe(browserSync.reload({
            stream : true
    }))
});

gulp.task('build',function(){
    gulp.start(['css','js','html'])
});

gulp.task('browser-sync',function(){
    browserSync.init(null,{
        open : false,
        server : {
            baseDir : 'dist'
        }
    })
});

gulp.task('start',function(){
    devMode = true;
    gulp.start(['build','browser-sync']);
    gulp.watch(['./src/css/**/*.css'],['css']);
    gulp.watch(['./src/js/**/*.js'],['js']);
    gulp.watch(['./src/templates/**/*.html'],['html']);
});

Following is the output

The project structure


问:
Lombok does not work for Eclipse Neon
I downloaded lombok.jar (lombok-1.16.14.jar) put it into my Downloads. Then I clicked on this jar, the execution correctly identifies the Eclipse instances on my MacOS and then I selected the instance I want.  Lombok is also specified in the pom.xml

      org.projectlombok
      lombok
       1.16.14
       provided

In eclipse.ini I got the addition:
-javaagent:../Eclipse/lombok.jar

lombok.jar was added to the same directory as eclise.ini
/Applications/Eclipse.app/Contents/Eclipse

I am still getting setter/getter errors in Eclipse Problems despite that my mvn build works fine.

The code for a User:

```<code>@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@EntityListeners(UserListener.class)
public class User implements Serializable, UserDetails {
...
</code>```

The error:

```<code>The method getRole() is undefined for the type User
</code>```

答: For me, downloading the latest Eclipse Neon, i.e. Neon 3, fixed the problem</p>

Title: Lombok does not work for Eclipse Neon

Body:
I downloaded lombok.jar (lombok-1.16.14.jar) put it into my Downloads. Then I clicked on this jar, the execution correctly identifies the Eclipse instances on my MacOS and then I selected the instance I want.  Lombok is also specified in the pom.xml

      org.projectlombok
      lombok
       1.16.14
       provided

In eclipse.ini I got the addition:
-javaagent:../Eclipse/lombok.jar

lombok.jar was added to the same directory as eclise.ini
/Applications/Eclipse.app/Contents/Eclipse

I am still getting setter/getter errors in Eclipse Problems despite that my mvn build works fine.

The code for a User:

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@EntityListeners(UserListener.class)
public class User implements Serializable, UserDetails {
...

The error:

The method getRole() is undefined for the type User


问:
How to use Scala's singleton-object types?
I'm writing a class which serves as base class for a series of singleton objects. In each singleton objects, there will be vals representing certain properties, and I want to write a method which, for each singleton object, only accepts objects created by it.

So I have the following:

```<code>class Obj[M <: Maker]

class Maker {
  implicit val me: this.type = this
  def make[M <: Maker](implicit maker: M) = new Obj[M]
  def accept(obj: Obj[this.type]) = {...}
}
</code>```

So far, so good. Then I want to declare one of these singleton objects:

```<code>object M extends Maker {
  val a = make
}
</code>```

But then, if I try this:

```<code>M.accept(M.a)
</code>```

then I get a compile-time error:

```<code>type mismatch; found : com.test.Obj[object com.test.M] required: com.test.Obj[com.test.M.type]
</code>```

My questions:

What's the type object com.test.M, and how is it different from com.test.M.type?

How can I do this in a smarter way?

答:
Use this.type instead of M. This simplified example should work:

```<code>class Obj[M <: Maker]

class Maker {
  def make() = new Obj[this.type]
  def accept(obj: Obj[this.type]) = println(obj)
}

object M extends Maker

object N extends Maker

M.accept(M.make()) //works!
M.accept(N.make()) //error! type mismatch!
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm writing a class which serves as base class for a series of singleton objects. In each singleton objects, there will be vals representing certain properties, and I want to write a method which, for each singleton object, only accepts objects created by it.

So I have the following:

class Obj[M <: Maker]

class Maker {
  implicit val me: this.type = this
  def make[M <: Maker](implicit maker: M) = new Obj[M]
  def accept(obj: Obj[this.type]) = {...}
}

So far, so good. Then I want to declare one of these singleton objects:

object M extends Maker {
  val a = make
}

But then, if I try this:

M.accept(M.a)

then I get a compile-time error:

type mismatch; found : com.test.Obj[object com.test.M] required: com.test.Obj[com.test.M.type]

My questions:

What's the type object com.test.M, and how is it different from com.test.M.type?

How can I do this in a smarter way?

Body:
Use this.type instead of M. This simplified example should work:

class Obj[M <: Maker]

class Maker {
  def make() = new Obj[this.type]
  def accept(obj: Obj[this.type]) = println(obj)
}

object M extends Maker

object N extends Maker

M.accept(M.make()) //works!
M.accept(N.make()) //error! type mismatch!


问:
Python: List of lists - presence of an element
I am trying to check the presence of an element in a list of lists and, if so, do something at this particular list (within the list of list):

```<code>transac1 = ['John','6', '20/10/2016']
transac2 = ['Emma','6', '20/10/2016']
transactions = [['Marie',2],['Emma',9]]
</code>```

I would like to do the following:

```<code>## non-Python code
if ['John',x] exists in transactions:
     ## I need to have the index where [John,x] is at that point
     then transactions[index][1] += transac1[1]
else:
     transactions.append(['John',6])
</code>```

So executing this loop with transac1 would make:

```<code>transactions = [['Marie',2],['Emma',9],['John',6]]
</code>```

And executing this loop with transac2 would make:

```<code>transactions = [['Marie',2],['Emma',15],['John',6]]
</code>```

The problem I face with a "classic double loop" is that, each time it does not find ['John',x] it will append to the list, where I need to know that for the entire list before doing something (plus, I have the assurance that if 'John' is in the list, it is only once).

My constraint is I cannot use Dictionaries. Thanks a lot.

答:
To loop over the list of list and get the indexes:</p>

```<code>for idx, item in enumerate(transactions):
    if item[0] == 'John' and item[1] == x:
        pass
    else:
        transactions.append(['John',6])
</code>```

Body:
I am trying to check the presence of an element in a list of lists and, if so, do something at this particular list (within the list of list):

transac1 = ['John','6', '20/10/2016']
transac2 = ['Emma','6', '20/10/2016']
transactions = [['Marie',2],['Emma',9]]

I would like to do the following:

## non-Python code
if ['John',x] exists in transactions:
     ## I need to have the index where [John,x] is at that point
     then transactions[index][1] += transac1[1]
else:
     transactions.append(['John',6])

So executing this loop with transac1 would make:

transactions = [['Marie',2],['Emma',9],['John',6]]

And executing this loop with transac2 would make:

transactions = [['Marie',2],['Emma',15],['John',6]]

The problem I face with a "classic double loop" is that, each time it does not find ['John',x] it will append to the list, where I need to know that for the entire list before doing something (plus, I have the assurance that if 'John' is in the list, it is only once).

My constraint is I cannot use Dictionaries. Thanks a lot.

Body:
To loop over the list of list and get the indexes:

for idx, item in enumerate(transactions):
    if item[0] == 'John' and item[1] == x:
        pass
    else:
        transactions.append(['John',6])


问:
Python: Extract single line from file
Very new, please be nice and explain slowly and clearly. Thanks :)

I've tried searching how to extract a single line in python, but all the responses seem much more complicated (and confusing) than what I'm looking for. I have a file, it has a lot of lines, I want to pull out just the line that starts with #.

My file.txt:

```<code>"##STUFF"
"##STUFF"
#DATA 01 02 03 04 05
More lines here
More lines here
More lines here
</code>```

My attempt at a script:

```<code>file = open("file.txt", "r")

splitdata = []

for line in file:
    if line.startswith['#'] = data
    splitdata = data.split()
    print splitdata

#expected output:
#splitdata = [#DATA, 1, 2, 3, 4, 5]
</code>```

The error I get:

line.startswith['#'] = data

TypeError: 'builtin_function_or_method' object does not support item assignment

That seems to mean it doesn't like my "= data", but I'm not sure how to tell it that I want to take the line that starts with # and save it separately.

答:
That's an if condition that expects predicate statement not the assignment.

```<code>if line.startswith('#'):
</code>```

startswith(...)
      S.startswith(prefix[, start[, end]]) -> bool

```<code>Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.
</code>```

Title: Python: Extract single line from file

Body:
Very new, please be nice and explain slowly and clearly. Thanks :)

I've tried searching how to extract a single line in python, but all the responses seem much more complicated (and confusing) than what I'm looking for. I have a file, it has a lot of lines, I want to pull out just the line that starts with #.

My file.txt:

"##STUFF"
"##STUFF"
#DATA 01 02 03 04 05
More lines here
More lines here
More lines here

My attempt at a script:

file = open("file.txt", "r")

splitdata = []

for line in file:
    if line.startswith['#'] = data
    splitdata = data.split()
    print splitdata

#expected output:
#splitdata = [#DATA, 1, 2, 3, 4, 5]

The error I get:

line.startswith['#'] = data

TypeError: 'builtin_function_or_method' object does not support item assignment

That seems to mean it doesn't like my "= data", but I'm not sure how to tell it that I want to take the line that starts with # and save it separately.

Body:
That's an if condition that expects predicate statement not the assignment.

if line.startswith('#'):

startswith(...)
      S.startswith(prefix[, start[, end]]) -> bool

Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.


问:
Microsoft.dotnet.props was not found - Confirm that path in <import> declaration is correct
I am trying to run dotnet core project I get error: Microsoft.dotnet.props was not found.

I have installed the dotnet core please check below screenshot.

I have seen other threads below but they are not working for me.

Microsoft.DotNet.Props was not found

ASP.Net Core Web API Build Error - MSB4019 The imported project Microsoft.DotNet.Props was not found. Confirm that the path in the <Import>

I am new to this; I have tried and read lots of issues on SO and git but I am not able to sort issue. Any help will be great.

Let me know if I need to add more details.

答: I am wondering why you try to work with 1.0.1. There is 1.1 available now. I think theres a problem with the global.json File, where dotnetcore get the Properties by IOC for the solution.. Youve got this file? Try to download 1.1 .. https://www.microsoft.com/net/download/core</p>


问:
How to configure windows 10 not to open link in Edge?
I use Google Chrome as my default browser in Windows 10, but when I click a link in external programs (for instance Skype, Teamcity) Microsoft Edge is launched and open the link instead of Google Chrome. How can I fix it?</p>

答:
For Me - The following worked

Create the GodMode folder.

Create a new folder and rename it to the following -> GodMode.{ED7BA470-8E54-465E-825C-99712043E01C}

Open the "GodMode" folder and find "Set Your Default Programs"

Open it and you will be able to select the program from the left panel and click "set this program as default"


问:
C++ using a priority queue of objects
I want to make a priority queue of objects, Specifically pair of (int, int). The queue should contain pairs with a priority assigned to them.

```<code>#include <iostream>
#include <queue>

using namespace std;

class saPair{
public:
    int s;
    int a;
    double priority;
    saPair(int s, int a, double priority){
        this->s = s;
        this->a = a;
        this->priority = priority;
    }
};

// the priority menmber variable determines the priority in the queue
// highest priority pair of (int, int) stays on the top
bool operator< (const saPair& x, const saPair& y) {
    return x.priority < y.priority;
}

int main()
{
    priority_queue<saPair> pq;
    pq.push(saPair(0,0, 0.3));
    pq.push(saPair(0,1, 0.1));
    pq.push(saPair(0,3, 0.5));
    pq.push(saPair(0,3, 5));

    cout << pq.top().a << endl;
    pq.pop();
    cout << pq.top().a << endl;
    pq.pop();
    cout << pq.top().a << endl;

}
</code>```

As you can see, the pair (0,3) has highest priority so it stays on the top. But the problem with my implementation is that, if I add (0,3) pair again with different priority, I add a new element to the queue, instead of replacing the priority of the already existing (0,3) pair.

I feel like I choose the wrong data structure for my requirement. I tried map taking key value, by defining a new saPair(int, int) class with operating overload for < operator. But even that doesn't seem to work properly..

Any suggestions on how to proceed? or modify

答:
It seems like you need a multi-key access to your container: you want to sort it by priority (or at least have a binary heap by priority as in priority_queue), and you want the pair values to be unique, so you'll need a pair value lookup too.

There is no default solution for that in standard library, but it shouldn't be too hard to craft your own.

I'd suggest simply storing an additional std::set<saPair> to check if the pair is already in your container. This way you can keep your priority_queue the way it is, and it won't take too much effort to implement.

Don't forget to add operator< to saPair though (or replace it by std::pair), otherwise std::set would not be able to work with it.

Another option is just manually check your priority_queue for a pair every time you add it. While asymptotically worse than std::set solution, this might very well be faster in practice, and it will save you some space. However I think the code would be much cleaner if you go with std::set.

Yet another solution is boost::multi_index, which allows you to easily construct any multi-indexed container you want. However I don't think it'll let you capitalize on the fact that you don't need a strong ordering by priority, so it won't have a linear contiguous layout like priority_queue does.

Title: C++ using a priority queue of objects

Body:
I want to make a priority queue of objects, Specifically pair of (int, int). The queue should contain pairs with a priority assigned to them.

#include <iostream>
#include <queue>

using namespace std;

class saPair{
public:
    int s;
    int a;
    double priority;
    saPair(int s, int a, double priority){
        this->s = s;
        this->a = a;
        this->priority = priority;
    }
};

// the priority menmber variable determines the priority in the queue
// highest priority pair of (int, int) stays on the top
bool operator< (const saPair& x, const saPair& y) {
    return x.priority < y.priority;
}

int main()
{
    priority_queue<saPair> pq;
    pq.push(saPair(0,0, 0.3));
    pq.push(saPair(0,1, 0.1));
    pq.push(saPair(0,3, 0.5));
    pq.push(saPair(0,3, 5));

    cout << pq.top().a << endl;
    pq.pop();
    cout << pq.top().a << endl;
    pq.pop();
    cout << pq.top().a << endl;

}

As you can see, the pair (0,3) has highest priority so it stays on the top. But the problem with my implementation is that, if I add (0,3) pair again with different priority, I add a new element to the queue, instead of replacing the priority of the already existing (0,3) pair.

I feel like I choose the wrong data structure for my requirement. I tried map taking key value, by defining a new saPair(int, int) class with operating overload for < operator. But even that doesn't seem to work properly..

Any suggestions on how to proceed? or modify


问:
Read json payload from gitlab webhook in Jenkins
I followed this tutorial to setup a Jenkins job to run whenever a push is made to the gitlab repository. I tested the webhook and I can see that the job is triggered. However, I don't see anything in the payload.

Just wondering, if anyone has ever tried to read the payload received from gitlab webhook?

答:
Jenkins Gitlab Plugin sends these POST parameters to Jenkins whenever any event occurs in the Gitlab repo.

You can add env in the Jenkins console to get what all Gitlab parameters are exported to the Jenkins environment. Then you can print or use the required variables.

e.g

```<code>echo $gitlabSourceRepoURL
echo $gitlabAfter
echo $gitlabTargetBranch
echo $gitlabSourceRepoHttpUrl
echo $gitlabMergeRequestLastCommit
echo $gitlabSourceRepoSshUrl
echo $gitlabSourceRepoHomepage
echo $gitlabBranch
echo $gitlabSourceBranch
echo $gitlabUserEmail
echo $gitlabBefore
echo $gitlabSourceRepoName
echo $gitlabSourceNamespace
echo $gitlabUserName
</code>```

Body:
Jenkins Gitlab Plugin sends these POST parameters to Jenkins whenever any event occurs in the Gitlab repo.

You can add env in the Jenkins console to get what all Gitlab parameters are exported to the Jenkins environment. Then you can print or use the required variables.

e.g

echo $gitlabSourceRepoURL
echo $gitlabAfter
echo $gitlabTargetBranch
echo $gitlabSourceRepoHttpUrl
echo $gitlabMergeRequestLastCommit
echo $gitlabSourceRepoSshUrl
echo $gitlabSourceRepoHomepage
echo $gitlabBranch
echo $gitlabSourceBranch
echo $gitlabUserEmail
echo $gitlabBefore
echo $gitlabSourceRepoName
echo $gitlabSourceNamespace
echo $gitlabUserName


问:
Why does this shell script exit without reading `case`?
I am writing a bash shell script for practice, but can't seem to fix its behavior. The script copies an array of files and directories into a given backup directory, $path, and compresses it to a .tar.gz file.

The iteration I'm working on should check if said .tar.gz file already exists using the naming pattern for backup directory ($date_value.tar.gz), and has specific cases depending on the answer. The script is expected to be ran from main project directory for now.

The following code is the part that goes wrong.

```<code>if [ -f "$path/$date_value.tar.gz" ] ; then

  echo "A $date_value.tar.gz directory already exists."

  read -p "Do you wish to update directory ? (Y/N)"

  echo # Moves to new line; for user experience purpose only

  case $REPLY in

        # Case when user wrote "Y" or "y" as in Yes
        " [[ $REPLY =~ ^[Yy]$ ]] " )

            # Extract archive
            tar xf "$path/$date_value.tar.gz"

            # Synchronise directories
            rsync --update -raz --progress \
                  --include="$current_path${files_array[@]}" "$path/$date_value" \
                  --exclude="*"

   exit 0;
;;

        # Case when user wrote anything else
        " [[ $REPLY =~ ^[*]$ ]] " )

            echo "Script didn't make any change and stopped itself."

    exit 1;
esac

# Else if backup directory doesn't exist yet
else

    # Make a directory using the date
    mkdir "$path/$date_value"

    # Loops over the whole array and copies files/directories
    # recursively to given directory with current rights
    for i in ${files_array[@]}; do
            cp -ar ${i} /home/robin/backup/by_date/"$date_value"/
    done

    # Goes to backup directory
    cd "$path"

    # Compress backup directory into tarball AND(=&&) removes it if successfull
    tar cfM "$date_value.tar.gz" "$date_value" && rm -Rf "$date_value"

fi
</code>```

When run in bash -x mode, I see that it proceeds as expected until the case $REPLY in line, then suddenly stops without running through the case. I put an exit 1 as a test after the last closing fi and can confirm the script simply jumps past case and stops, since there are no further instructions.

What is going wrong in there, and why is it ditching the case?

Documentation used to write this code:

Flow control : http://linuxcommand.org/wss0120.php

Check if a directory exists in a shell script

Test building : http://tldp.org/LDP/abs/html/testconstructs.html#DBLBRACKETS

Test building using [[ ]] specific operators : Bash regex =~ operator

Run on Debian, with bash as terminal.

答:
Incorrect:

```<code>" [[ $REPLY =~ ^[Yy]$ ]] " )
</code>```

Correct:

```<code>[Yy])
</code>```

There are other errors in the OP code, but start with that...

Body:
I am writing a bash shell script for practice, but can't seem to fix its behavior. The script copies an array of files and directories into a given backup directory, $path, and compresses it to a .tar.gz file.

The iteration I'm working on should check if said .tar.gz file already exists using the naming pattern for backup directory ($date_value.tar.gz), and has specific cases depending on the answer. The script is expected to be ran from main project directory for now.

The following code is the part that goes wrong.

if [ -f "$path/$date_value.tar.gz" ] ; then

  echo "A $date_value.tar.gz directory already exists."

  read -p "Do you wish to update directory ? (Y/N)"

  echo # Moves to new line; for user experience purpose only

  case $REPLY in

        # Case when user wrote "Y" or "y" as in Yes
        " [[ $REPLY =~ ^[Yy]$ ]] " )

            # Extract archive
            tar xf "$path/$date_value.tar.gz"

            # Synchronise directories
            rsync --update -raz --progress \
                  --include="$current_path${files_array[@]}" "$path/$date_value" \
                  --exclude="*"

   exit 0;
;;

        # Case when user wrote anything else
        " [[ $REPLY =~ ^[*]$ ]] " )

            echo "Script didn't make any change and stopped itself."

    exit 1;
esac

# Else if backup directory doesn't exist yet
else

    # Make a directory using the date
    mkdir "$path/$date_value"

    # Loops over the whole array and copies files/directories
    # recursively to given directory with current rights
    for i in ${files_array[@]}; do
            cp -ar ${i} /home/robin/backup/by_date/"$date_value"/
    done

    # Goes to backup directory
    cd "$path"

    # Compress backup directory into tarball AND(=&&) removes it if successfull
    tar cfM "$date_value.tar.gz" "$date_value" && rm -Rf "$date_value"

fi

When run in bash -x mode, I see that it proceeds as expected until the case $REPLY in line, then suddenly stops without running through the case. I put an exit 1 as a test after the last closing fi and can confirm the script simply jumps past case and stops, since there are no further instructions.

What is going wrong in there, and why is it ditching the case?

Documentation used to write this code:

Flow control : http://linuxcommand.org/wss0120.php

Check if a directory exists in a shell script

Test building : http://tldp.org/LDP/abs/html/testconstructs.html#DBLBRACKETS

Test building using [[ ]] specific operators : Bash regex =~ operator

Run on Debian, with bash as terminal.

Body:
Incorrect:

" [[ $REPLY =~ ^[Yy]$ ]] " )

Correct:

[Yy])

There are other errors in the OP code, but start with that...


问:
How to get data for the last week data?
I am trying to write a report whereby the report will have the contract updated records for the past week using ms sql script. Every Monday the report will be sent for the last Mon-sun. I tried the below query. it doesnt seems to work. Any idea how to achieve this?

```<code>SET DATEFIRST 1

select distinct [...]
where CONTRACT_UPDATE_DATE>= dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
AND CONTRACT_UPDATE_DATE<  dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))
</code>```

Thanks.

答:
You can try this,</p>

```<code>SELECT Created_Date
FROM sample1
WHERE Created_Date >= DATEADD(day,-11117, GETDATE())
</code>```

Title: How to get data for the last week data?

Body:
I am trying to write a report whereby the report will have the contract updated records for the past week using ms sql script. Every Monday the report will be sent for the last Mon-sun. I tried the below query. it doesnt seems to work. Any idea how to achieve this?

SET DATEFIRST 1

select distinct [...]
where CONTRACT_UPDATE_DATE>= dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate()))
AND CONTRACT_UPDATE_DATE<  dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))

Thanks.

Body:
You can try this,

SELECT Created_Date
FROM sample1
WHERE Created_Date >= DATEADD(day,-11117, GETDATE())


问:
how to upload the file in react-native for android
I tried for the uploading the image using react-native-file-transfer-android.
  But it not uploading, It gives response  like this

object reference not set to an instance of an object
  Here is my code:

```<code>var FileTransfer = require('react-native-file-transfer-android');
selectPhotoTapped() {
    const options = {
      quality: 1.0,
      maxWidth: 500,
      maxHeight: 500,
      storageOptions: {
        skipBackup: true
      }
    };

    ImagePicker.showImagePicker(options, (response) => {
      console.log('Response = ', response);

      if (response.didCancel) {
        console.log('User cancelled photo picker');
      }
      else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      }
      else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
      }
      else {
        let source = { uri: response.uri };
        FileTransfer.upload({
          uri: source.uri,
          uploadUrl: 'http://52.34.32.119/FileUploadHandler.ashx?upload=start',
          fileName: 'temp.jpg',
          mimeType: 'image/jpg',
          headers: {
            'Accept': 'application/json'
          },
          data: {

          }
        }, (err, res) => {
          if(err) {
            alert("error:"+JSON.stringify(err))
            console.error(err);
          } else {
            alert("res:"+JSON.stringify(res))
            console.log(res);
          }
        });
this.setState({
          avatarSource: source
        });
      }
    });
  }
</code>```

Can any one give me some suggestions that is there any wrong in my code. Or give me suggestions that how to upload the file. Any help much appreciated.

答: You are passing in an 'options' object into a your showImagePicker() call but this doesn't appear to be defined? </p>

Body:
I tried for the uploading the image using react-native-file-transfer-android.
  But it not uploading, It gives response  like this

object reference not set to an instance of an object
  Here is my code:

var FileTransfer = require('react-native-file-transfer-android');
selectPhotoTapped() {
    const options = {
      quality: 1.0,
      maxWidth: 500,
      maxHeight: 500,
      storageOptions: {
        skipBackup: true
      }
    };

    ImagePicker.showImagePicker(options, (response) => {
      console.log('Response = ', response);

      if (response.didCancel) {
        console.log('User cancelled photo picker');
      }
      else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      }
      else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
      }
      else {
        let source = { uri: response.uri };
        FileTransfer.upload({
          uri: source.uri,
          uploadUrl: 'http://52.34.32.119/FileUploadHandler.ashx?upload=start',
          fileName: 'temp.jpg',
          mimeType: 'image/jpg',
          headers: {
            'Accept': 'application/json'
          },
          data: {

          }
        }, (err, res) => {
          if(err) {
            alert("error:"+JSON.stringify(err))
            console.error(err);
          } else {
            alert("res:"+JSON.stringify(res))
            console.log(res);
          }
        });
this.setState({
          avatarSource: source
        });
      }
    });
  }

Can any one give me some suggestions that is there any wrong in my code. Or give me suggestions that how to upload the file. Any help much appreciated.


问:
Receive two json objects at once in ajax method jquery
I am trying to return two json objects.But i am able to receive only one. Am i doing wrong? Success is just showing 'success' as string when i try to alert this but otherwise in firebug it has value=true
.So, it must show true which is its value and not the variable instead.

I am returning below in which data is receiving but success is not
showing its value. How should i extract the value of success in
my $.ajax funtion..

```<code> return Json(new { data = obj, success = isSuccess });

$.ajax({
            type: "POST",
            url: "controller/Action",
            data: "",
            success: function (data, success) {
                debugger;
                alert(success);

            },
</code>```

答:
you are sending both obj and isSuccess flag in one object as JSON

```<code>Json(new { data = obj, success = isSuccess });
</code>```

so finally in ajax call success event you will get that wrapper object only, which will have two properties data and success.

```<code>$.ajax({
    type: "POST",
    url: "controller/Action",
    data: "",
    success: function (wrapperObj) {
        console.log(wrapperObj.success); // this will be your isSuccess flag.
        if(wrapperObj.success)
        {
            console.log(wrapperObj.data); // this will be your obj.
        }
    }
})
</code>```

Body:
I am trying to return two json objects.But i am able to receive only one. Am i doing wrong? Success is just showing 'success' as string when i try to alert this but otherwise in firebug it has value=true
.So, it must show true which is its value and not the variable instead.

I am returning below in which data is receiving but success is not
showing its value. How should i extract the value of success in
my $.ajax funtion..

 return Json(new { data = obj, success = isSuccess });

$.ajax({
            type: "POST",
            url: "controller/Action",
            data: "",
            success: function (data, success) {
                debugger;
                alert(success);

            },

Body:
you are sending both obj and isSuccess flag in one object as JSON

Json(new { data = obj, success = isSuccess });

so finally in ajax call success event you will get that wrapper object only, which will have two properties data and success.

$.ajax({
    type: "POST",
    url: "controller/Action",
    data: "",
    success: function (wrapperObj) {
        console.log(wrapperObj.success); // this will be your isSuccess flag.
        if(wrapperObj.success)
        {
            console.log(wrapperObj.data); // this will be your obj.
        }
    }
})