问:
Video loop plays in localhost not in server
I have a video in my page and I called it like

```<code><video width="100%" autoplay='true' loop>
  <source src="img/Jolly.mp4" type="video/mp4">
  <source src="img/Jolly.ogg" type="video/ogg">
      Your browser does not support HTML5 video.
</video>
</code>```

It is not working recently.
In Chrome Browser console it shows that

```<code>"Failed to load resource: net::ERR_CONNECTION_RESET"
</code>```

In mozilla console it shows

```<code>All candidate resources failed to load. Media load paused.
</code>```

But when I downloaded the code and tested in localhost it works fine. I already checked the answer regarding this error but it doesn't helps.So what should I do?

答:
It might be  IIS5 issue
I think it is required to add new MIME type to IIS server during site setup.

IIS

MIME Types

Confirm there is no entry for the video file type
then add

List item

"mp4"/"video/m4".

If this is not case, you might need to add on .htaccess. Do something like below

```<code>AddType video/mp4 .mp4
</code>```

Body:
I have a video in my page and I called it like

<video width="100%" autoplay='true' loop>
  <source src="img/Jolly.mp4" type="video/mp4">
  <source src="img/Jolly.ogg" type="video/ogg">
      Your browser does not support HTML5 video.
</video>

It is not working recently.
In Chrome Browser console it shows that

"Failed to load resource: net::ERR_CONNECTION_RESET"

In mozilla console it shows

All candidate resources failed to load. Media load paused.

But when I downloaded the code and tested in localhost it works fine. I already checked the answer regarding this error but it doesn't helps.So what should I do?

Body:
It might be  IIS5 issue
I think it is required to add new MIME type to IIS server during site setup.

IIS

MIME Types

Confirm there is no entry for the video file type
then add

List item

"mp4"/"video/m4".

If this is not case, you might need to add on .htaccess. Do something like below

AddType video/mp4 .mp4


来源: stackexchange

问:
Different resource folders for separate tablet & mobile APKs
I am building an app that has two APKs: one for tablets and the other for mobiles.

The tablet version won't use the drawable of the mobile APK and vice versa.

I want to do this because of APK size.

Can anyone give me pointers how to achieve this?

I tried to use flavors for this but it can make the two APK.

答:
You can achieve this, as Google play store providing support for multiple apks.
You can check here for more details-
Creating Multiple APKs for Different Screen Sizes</p>

ContentLicense: CC BY-SA 3.0


问:
How to stop updating the field or variable in object while copyToRealmOrUpdate in realm
```<code>Pojo Class:

public class ChannelResponse extends RealmObject{
   private RealmList<TvChannel> tv_channel;
}

public class TvChannel extends RealmObject{
@PrimaryKey
private String id;
private String stream_display_name;
private String stream_icon;
private String streaming_url;
private int isFavorite;
}
</code>```

here isFavorite is int which should not get updated while updation of other fields when i get from API channelResponse and in api json object TvChannel dosent have isFavorite feild.

i am updating like this:

```<code>Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.copyToRealmOrUpdate(channelResponse);
realm.commitTransaction();
realm.close();
</code>```

答: Have you apply @Ignore to the isFavorite field before ?</p>

Body:
Pojo Class:

public class ChannelResponse extends RealmObject{
   private RealmList<TvChannel> tv_channel;
}

public class TvChannel extends RealmObject{
@PrimaryKey
private String id;
private String stream_display_name;
private String stream_icon;
private String streaming_url;
private int isFavorite;
}

here isFavorite is int which should not get updated while updation of other fields when i get from API channelResponse and in api json object TvChannel dosent have isFavorite feild.

i am updating like this:

Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.copyToRealmOrUpdate(channelResponse);
realm.commitTransaction();
realm.close();


问:
Java mapper recursively with lists
I have a mapper method which takes list of entities called Claim iterates over them and maps to CompensationDTO and adds to list, but entity can contain lists of children entities which type is also Claim and those children can also contain list of Claims, so to iterate over them all is best to use recursion but i'm not sure how it should be written

```<code>    private List<CompensationDTO> mapToDTO(List<Claims> claims) {
    List<CompensationsDTO> compensations = new ArrayList<>();
    if (claims.isEmpty()) {
        return new ArrayList<>();
    }
    for (Claim claim : claims) {
        CompensationDTO compensationDTO = new CompensationDTO();
        compensationDTO.setId(claim.getId());
        compensationDTO.setAmount(claim.getAmount());
        compensationDTO.setType(claim.getType());
        compensations.add(compensationDTO);
        mapToDTO(claim.getChildrenClaims());
    }
    return compensations;
}
</code>```

I understand that the base case should return empty list but i don't know where to put the recursive function call mapToDTO(claim.getChildrenClaims());

答:
mapToDTO returns List<CompensationDTO> and you need to add these elements to your local list.

```<code>List<CompensationDTO> rec = mapToDTO(claim.getChildrenClaims());
compensations.addAll(rec);
</code>```

Title: Java mapper recursively with lists

Body:
I have a mapper method which takes list of entities called Claim iterates over them and maps to CompensationDTO and adds to list, but entity can contain lists of children entities which type is also Claim and those children can also contain list of Claims, so to iterate over them all is best to use recursion but i'm not sure how it should be written

    private List<CompensationDTO> mapToDTO(List<Claims> claims) {
    List<CompensationsDTO> compensations = new ArrayList<>();
    if (claims.isEmpty()) {
        return new ArrayList<>();
    }
    for (Claim claim : claims) {
        CompensationDTO compensationDTO = new CompensationDTO();
        compensationDTO.setId(claim.getId());
        compensationDTO.setAmount(claim.getAmount());
        compensationDTO.setType(claim.getType());
        compensations.add(compensationDTO);
        mapToDTO(claim.getChildrenClaims());
    }
    return compensations;
}

I understand that the base case should return empty list but i don't know where to put the recursive function call mapToDTO(claim.getChildrenClaims());

Body:
mapToDTO returns List<CompensationDTO> and you need to add these elements to your local list.

List<CompensationDTO> rec = mapToDTO(claim.getChildrenClaims());
compensations.addAll(rec);


问:
centos cpu usage is very high, but I cannot find the process
I use the command top/htop to find the process, but i failed.
The cpu pecentage of every process is only 0.x%.
How can i find the exactly one process that cause the hight cpu usage?</p>

答:
If nothing is showing up as using CPU time, it could be something like disk access time causing the perception of slow CPU.

You mentioned htop.
In htop, try hitting F2 for setup, arrow down in the 'Setup' column to select 'Columns'.  Arrow to the right twice, and arrow down until you see 'IO_RATE' selected.  Press 'enter' to add it to the active columns list.

You can adjust it's position by highlighting it and pressing F7 and F8 to move it up or down respectively.

With IO_RATE added to your output, look for processes that appear to be constantly writing to disk.

Along the same vein, check the process states as well, and look for "D" (uninterruptible sleep, usually I/O).  PS info reference


问:
Angular2 : how to call main component function from a child component
How to call main component function from a child component when I have deep nested hierarchy?

I have 3 components, button component I'm including inside browser component and browser component I'm including inside main component.

On click of button I need to call a function which is inside main component.

Button Component

```<code>@Component({
    selector: 'cb-button',
    templateUrl: 'cb-button.component.html',
    styleUrls: ['cb-button.component.scss']
})

export class CbButtonComponent {

     @Output() onClick: EventEmitter<any> = new EventEmitter();

     onBtnClick(): void {
        this.onClick.emit();
    }
}
</code>```

button component html

```<code><div (click)="onBtnClick()">
    <button>btn</button>
</div>
</code>```

browser component

```<code>@Component({
    selector: 'topology-browser',
    templateUrl: 'topology-browser.component.html',
    styleUrls: ['topology-browser.component.scss']
})

export class TopologyBrowserComponent {

   @Input('campus') campus: Campus;
}
</code>```

browser component html

```<code><div>
<h1>browser title</h1>
<cb-button (click)="editCampus()"></cb-button>
</div>
</code>```

and finally in main component i'm including browser component

main-component.ts

```<code>editCampus() {
  alert('clicked');
}
</code>```

html

```<code><topology-browser [campus]="campus"></topology-browser>
</code>```

when I click button I'm getting below error

Errorself.parentView.context.editCampus is not a function

答:
If you know what type the root component is, you can use Pengyy's method.

If you don't know what type in advance but you can customize the root component to your needs, a shared service is a good way.

A more generic way is to get the root component by injecting ApplicationRef (not actually tested myself):

constructor(app:ApplicationRef, injector: Injector) {
  app.components[0].someMethodOnMainComponent();
}
```

https://angular.io/docs/ts/latest/api/core/index/ApplicationRef-class.html

Body:
How to call main component function from a child component when I have deep nested hierarchy?

I have 3 components, button component I'm including inside browser component and browser component I'm including inside main component.

On click of button I need to call a function which is inside main component.

Button Component

@Component({
    selector: 'cb-button',
    templateUrl: 'cb-button.component.html',
    styleUrls: ['cb-button.component.scss']
})

export class CbButtonComponent {

     @Output() onClick: EventEmitter<any> = new EventEmitter();

     onBtnClick(): void {
        this.onClick.emit();
    }
}

button component html

    <button>btn</button>

browser component

@Component({
    selector: 'topology-browser',
    templateUrl: 'topology-browser.component.html',
    styleUrls: ['topology-browser.component.scss']
})

export class TopologyBrowserComponent {

   @Input('campus') campus: Campus;
}

browser component html

browser title

<cb-button (click)="editCampus()"></cb-button>

and finally in main component i'm including browser component

main-component.ts

editCampus() {
  alert('clicked');
}

html

<topology-browser [campus]="campus"></topology-browser>

when I click button I'm getting below error

Errorself.parentView.context.editCampus is not a function

Body:
If you know what type the root component is, you can use Pengyy's method.

If you don't know what type in advance but you can customize the root component to your needs, a shared service is a good way.

A more generic way is to get the root component by injecting ApplicationRef (not actually tested myself):

constructor(app:ApplicationRef, injector: Injector) {
  app.components[0].someMethodOnMainComponent();
}

https://angular.io/docs/ts/latest/api/core/index/ApplicationRef-class.html


问:
Get Images and Videos from Android Phone into Custom Gallery
I'm trying to create a custom gallery that allows users to pick from all the photos and videos contained on their Android device. I know how to create a gallery of just photos and just videos, but if I want to combine both, how can I do this?

I think the issue comes down to how I create my cursor.  To select all videos, I created the cursor this way:

```<code>String[] videoParams = {MediaStore.Video.Media._ID,
        MediaStore.Video.Media.DATA,
        MediaStore.Video.Media.DATE_TAKEN,
        MediaStore.Video.Thumbnails.DATA};

videocursor = getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoParams, null, null, null);
</code>```

If I want to query all the media files, not just video, what do I do?

This is what I tried, based off of: Custom Gallery with Images and Videos in android to select multiple items

```<code>    String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
    String jpg_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("jpg");
    String png_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("png");
    String mp4_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("mp4");
    String[] selectionArgs = new String[]{jpg_mimeType, png_mimeType, mp4_mimeType};

    mediaCursor = getContentResolver().query(MediaStore.Files.getContentUri("internal"), null, selectionMimeType, selectionArgs, MediaStore.Files.FileColumns.DATE_ADDED);
</code>```

This gives me the error java.lang.IllegalArgumentException: Cannot bind argument at index 3 because the index is out of range.  The statement has 1 parameters at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:167)

Perhaps my approach is completely wrong, but I can't find any examples of custom android galleries using both images and videos, which is bizarre to me as this seems like it would be a common thing to create.

Here's all of my code, in case it's helpful:

```<code>public class GridViewCompatActivity extends Activity {

    GridViewCompat gridView;

    private static final String TAG = "GridViewCompatActivity";

    Cursor videocursor;
    Cursor mediaCursor;

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

        gridView = (GridViewCompat) findViewById(R.id.gridView1);

        // NOTE: We are using setChoiceMode, as I said, its a drop-in replacement
        gridView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        gridView.setAdapter(new ImageAdapter(getApplicationContext()));

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> view, View arg1, int pos, long id) {
                // We need to invalidate all views on 4.x versions
                GridViewCompat gridView = (GridViewCompat) view;
                gridView.invalidateViews();
            }

        });

        findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                SparseBooleanArray checkArray;
                checkArray = gridView.getCheckedItemPositions();

                String selectedPos = "Selected positions: ";
                int count = checkArray.size();
                for (int i = 0; i < count; i++) {
                    if (checkArray.valueAt(i))
                        selectedPos += checkArray.keyAt(i) + ",";
                }

                Intent intent = new Intent();
                intent.putExtra("result", selectedPos);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });
    }

    public class ImageAdapter extends BaseAdapter {
        private Context mContext;

        public ImageAdapter(Context c) {
            mContext = c;
        }

        public int getCount() {
            Log.d(TAG, "number of media: " + Integer.toString(MediaStore.Files.FileColumns.DATA.length()));
            int mediaParams = MediaStore.MediaColumns.DATA.length();
            return mediaParams;
        }

        public Object getItem(int position) {
            return null;
        }

        public long getItemId(int position) {
            return 0;
        }

        // create a new grid view item for each item referenced by the Adapter
        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            CheckBox checkBox;
            if (convertView == null) {
                LayoutInflater layoutInflater = LayoutInflater.from(mContext);
                convertView = layoutInflater.inflate(R.layout.grid_view_item, parent, false);
            }
            imageView = (ImageView) convertView.findViewById(R.id.imageView1);
            checkBox = (CheckBox) convertView.findViewById(R.id.checkBox1);

            GridViewCompat gvc = (GridViewCompat) parent;
            if (gvc.getChoiceMode() == ListView.CHOICE_MODE_MULTIPLE) {
                SparseBooleanArray checkArray;
                checkArray = gvc.getCheckedItemPositions();

                checkBox.setChecked(false);
                if (checkArray != null) {
                    if (checkArray.get(position)) {
                        checkBox.setChecked(true);
                    }
                }

            }
            // imageView.setImageResource(mThumbIds[position]);
            Bitmap bmThumbnail;
            Log.d(TAG, "position: " + position);
            mediaCursor = getContentResolver().query(MediaStore.Files.getContentUri("internal"), null, selectionMimeType, selectionArgs, MediaStore.Files.FileColumns.DATE_ADDED);
            Log.d(TAG, Integer.toString(mediaCursor.getCount()));

            for (int i = 0; i < mediaCursor.getCount(); i++){
                mediaCursor.moveToPosition(i);
                Boolean isVideo = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA)).length() > 0;
                Log.d(TAG, "isVideo: " + isVideo);
                String mediaPath = "";
                if(isVideo){
                    mediaPath = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
                    video_paths.add(mediaPath);
                }else{
                    mediaPath = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    video_paths.add(mediaPath);
                }
                Log.d(TAG, "mediaPath: " +mediaPath);
            }

            mediaCursor.moveToPosition(position);
            String video_path = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
            Log.d(TAG, "video_path: " + video_path);
            imageView.setImageBitmap(ThumbnailUtils.createVideoThumbnail(video_path, Thumbnails.MICRO_KIND));

            return convertView;
        }

        ArrayList<String> video_paths = new ArrayList<String>();

        String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
        String jpg_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("jpg");
        String png_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("png");
        String mp4_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("mp4");
        String[] selectionArgs = new String[]{jpg_mimeType, png_mimeType, mp4_mimeType};

//        String[] videoParams = {MediaStore.Video.Media._ID,
//                MediaStore.Video.Media.DATA,
//                MediaStore.Video.Media.DATE_TAKEN,
//                MediaStore.Video.Thumbnails.DATA};
//        }
}
}
</code>```

答:
Download source code form here (Get all videos from gallery android).</p>

```<code> public void fn_video() {

        int int_position = 0;
        Uri uri;
        Cursor cursor;
        int column_index_data, column_index_folder_name,column_id,thum;

        String absolutePathOfImage = null;
        uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;

        String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Video.Media.BUCKET_DISPLAY_NAME,MediaStore.Video.Media._ID,MediaStore.Video.Thumbnails.DATA};

        final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
        cursor = getApplicationContext().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");

        column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
        column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.BUCKET_DISPLAY_NAME);
        column_id = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
        thum = cursor.getColumnIndexOrThrow(MediaStore.Video.Thumbnails.DATA);

        while (cursor.moveToNext()) {
            absolutePathOfImage = cursor.getString(column_index_data);
            Log.e("Column", absolutePathOfImage);
            Log.e("Folder", cursor.getString(column_index_folder_name));
            Log.e("column_id", cursor.getString(column_id));
            Log.e("thum", cursor.getString(thum));

            Model_Video obj_model = new Model_Video();
            obj_model.setBoolean_selected(false);
            obj_model.setStr_path(absolutePathOfImage);
            obj_model.setStr_thumb(cursor.getString(thum));

            al_video.add(obj_model);

        }

}
</code>```

Body:
I'm trying to create a custom gallery that allows users to pick from all the photos and videos contained on their Android device. I know how to create a gallery of just photos and just videos, but if I want to combine both, how can I do this?

I think the issue comes down to how I create my cursor.  To select all videos, I created the cursor this way:

String[] videoParams = {MediaStore.Video.Media._ID,
        MediaStore.Video.Media.DATA,
        MediaStore.Video.Media.DATE_TAKEN,
        MediaStore.Video.Thumbnails.DATA};

videocursor = getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoParams, null, null, null);

If I want to query all the media files, not just video, what do I do?

This is what I tried, based off of: Custom Gallery with Images and Videos in android to select multiple items

    String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
    String jpg_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("jpg");
    String png_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("png");
    String mp4_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("mp4");
    String[] selectionArgs = new String[]{jpg_mimeType, png_mimeType, mp4_mimeType};

    mediaCursor = getContentResolver().query(MediaStore.Files.getContentUri("internal"), null, selectionMimeType, selectionArgs, MediaStore.Files.FileColumns.DATE_ADDED);

This gives me the error java.lang.IllegalArgumentException: Cannot bind argument at index 3 because the index is out of range.  The statement has 1 parameters at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:167)

Perhaps my approach is completely wrong, but I can't find any examples of custom android galleries using both images and videos, which is bizarre to me as this seems like it would be a common thing to create.

Here's all of my code, in case it's helpful:

public class GridViewCompatActivity extends Activity {

    GridViewCompat gridView;

    private static final String TAG = "GridViewCompatActivity";

    Cursor videocursor;
    Cursor mediaCursor;

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

        gridView = (GridViewCompat) findViewById(R.id.gridView1);

        // NOTE: We are using setChoiceMode, as I said, its a drop-in replacement
        gridView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        gridView.setAdapter(new ImageAdapter(getApplicationContext()));

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> view, View arg1, int pos, long id) {
                // We need to invalidate all views on 4.x versions
                GridViewCompat gridView = (GridViewCompat) view;
                gridView.invalidateViews();
            }

        });

        findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                SparseBooleanArray checkArray;
                checkArray = gridView.getCheckedItemPositions();

                String selectedPos = "Selected positions: ";
                int count = checkArray.size();
                for (int i = 0; i < count; i++) {
                    if (checkArray.valueAt(i))
                        selectedPos += checkArray.keyAt(i) + ",";
                }

                Intent intent = new Intent();
                intent.putExtra("result", selectedPos);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });
    }

    public class ImageAdapter extends BaseAdapter {
        private Context mContext;

        public ImageAdapter(Context c) {
            mContext = c;
        }

        public int getCount() {
            Log.d(TAG, "number of media: " + Integer.toString(MediaStore.Files.FileColumns.DATA.length()));
            int mediaParams = MediaStore.MediaColumns.DATA.length();
            return mediaParams;
        }

        public Object getItem(int position) {
            return null;
        }

        public long getItemId(int position) {
            return 0;
        }

        // create a new grid view item for each item referenced by the Adapter
        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            CheckBox checkBox;
            if (convertView == null) {
                LayoutInflater layoutInflater = LayoutInflater.from(mContext);
                convertView = layoutInflater.inflate(R.layout.grid_view_item, parent, false);
            }
            imageView = (ImageView) convertView.findViewById(R.id.imageView1);
            checkBox = (CheckBox) convertView.findViewById(R.id.checkBox1);

            GridViewCompat gvc = (GridViewCompat) parent;
            if (gvc.getChoiceMode() == ListView.CHOICE_MODE_MULTIPLE) {
                SparseBooleanArray checkArray;
                checkArray = gvc.getCheckedItemPositions();

                checkBox.setChecked(false);
                if (checkArray != null) {
                    if (checkArray.get(position)) {
                        checkBox.setChecked(true);
                    }
                }

            }
            // imageView.setImageResource(mThumbIds[position]);
            Bitmap bmThumbnail;
            Log.d(TAG, "position: " + position);
            mediaCursor = getContentResolver().query(MediaStore.Files.getContentUri("internal"), null, selectionMimeType, selectionArgs, MediaStore.Files.FileColumns.DATE_ADDED);
            Log.d(TAG, Integer.toString(mediaCursor.getCount()));

            for (int i = 0; i < mediaCursor.getCount(); i++){
                mediaCursor.moveToPosition(i);
                Boolean isVideo = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA)).length() > 0;
                Log.d(TAG, "isVideo: " + isVideo);
                String mediaPath = "";
                if(isVideo){
                    mediaPath = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
                    video_paths.add(mediaPath);
                }else{
                    mediaPath = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    video_paths.add(mediaPath);
                }
                Log.d(TAG, "mediaPath: " +mediaPath);
            }

            mediaCursor.moveToPosition(position);
            String video_path = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
            Log.d(TAG, "video_path: " + video_path);
            imageView.setImageBitmap(ThumbnailUtils.createVideoThumbnail(video_path, Thumbnails.MICRO_KIND));

            return convertView;
        }

        ArrayList<String> video_paths = new ArrayList<String>();

        String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
        String jpg_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("jpg");
        String png_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("png");
        String mp4_mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("mp4");
        String[] selectionArgs = new String[]{jpg_mimeType, png_mimeType, mp4_mimeType};

//        String[] videoParams = {MediaStore.Video.Media._ID,
//                MediaStore.Video.Media.DATA,
//                MediaStore.Video.Media.DATE_TAKEN,
//                MediaStore.Video.Thumbnails.DATA};
//        }
}
}

Body:
Download source code form here (Get all videos from gallery android).

 public void fn_video() {

        int int_position = 0;
        Uri uri;
        Cursor cursor;
        int column_index_data, column_index_folder_name,column_id,thum;

        String absolutePathOfImage = null;
        uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;

        String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Video.Media.BUCKET_DISPLAY_NAME,MediaStore.Video.Media._ID,MediaStore.Video.Thumbnails.DATA};

        final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
        cursor = getApplicationContext().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");

        column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
        column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.BUCKET_DISPLAY_NAME);
        column_id = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
        thum = cursor.getColumnIndexOrThrow(MediaStore.Video.Thumbnails.DATA);

        while (cursor.moveToNext()) {
            absolutePathOfImage = cursor.getString(column_index_data);
            Log.e("Column", absolutePathOfImage);
            Log.e("Folder", cursor.getString(column_index_folder_name));
            Log.e("column_id", cursor.getString(column_id));
            Log.e("thum", cursor.getString(thum));

            Model_Video obj_model = new Model_Video();
            obj_model.setBoolean_selected(false);
            obj_model.setStr_path(absolutePathOfImage);
            obj_model.setStr_thumb(cursor.getString(thum));

            al_video.add(obj_model);

        }

}


问:
How to add margins to the grid view through CSS

* {
  box-sizing: border-box;
}

h1 {
  text-align: center;
  font-family: sans-serif;
  font-weight: normal;
  padding-bottom: 20px;
}

#section1{
 margin-right: 10px;
}
#section2{
 margin-right: 10px;
}

div div {
  border: 1px solid;
  width: 90%;
  background-color: #9E9E9E;
  position: relative;
  margin-bottom: 10px;
  margin-left: auto;
  margin-right: auto;
}

div div div {
  text-align: center;
  position: absolute;
  right: 0;
  top: 0;
  margin: 0px;
  font-weight: bold;
}

#Chicken {
  background-color: #EF9A9A;
  width: 25%;
  border: 1px solid;
}

#Beef {
  background-color: #F44336;
  width: 25%;
  border: 1px solid;
  color: white;
  border-color: black;
}

#Sushi {
  background-color: #CDDC39;
  width: 25%;
  border: 1px solid;
}

p {
  padding: 10px;
}

.row {
  width: 100%;
}

@media (min-width: 992px) {
  .col-lg-1,
  .col-lg-2,
  .col-lg-3,
  .col-lg-4,
  .col-lg-5,
  .col-lg-6,
  .col-lg-7,
  .col-lg-8,
  .col-lg-9,
  .col-lg-10,
  .col-lg-11,
  .col-lg-12 {
    float: left;
  }
  .col-lg-1 {
    width: 8.33%;
  }
  .col-lg-2 {
    width: 16.66%;
  }
  .col-lg-3 {
    width: 25%;
  }
  .col-lg-4 {
    width: 33.33%;
  }
  .col-lg-5 {
    width: 41.66%;
  }
  .col-lg-6 {
    width: 50%;
  }
  .col-lg-7 {
    width: 58.33%;
  }
  .col-lg-8 {
    width: 66.66%;
  }
  .col-lg-9 {
    width: 74.99%;
  }
  .col-lg-10 {
    width: 83.33%;
  }
  .col-lg-11 {
    width: 91.66%;
  }
  .col-lg-12 {
    width: 100%;
  }
}

@media (min-width: 767px) and (max-width: 991px) {
  .col-md-1,
  .col-md-2,
  .col-md-3,
  .col-md-4,
  .col-md-5,
  .col-md-6,
  .col-md-7,
  .col-md-8,
  .col-md-9,
  .col-md-10,
  .col-md-11,
  .col-md-12 {
    float: left;
  }
  .col-md-1 {
    width: 8.33%;
  }
  .col-md-2 {
    width: 16.66%;
  }
  .col-md-3 {
    width: 25%;
  }
  .col-md-4 {
    width: 33.33%;
  }
  .col-md-5 {
    width: 41.66%;
  }
  .col-md-6 {
    width: 50%;
  }
  .col-md-7 {
    width: 58.33%;
  }
  .col-md-8 {
    width: 66.66%;
  }
  .col-md-9 {
    width: 74.99%;
  }
  .col-md-10 {
    width: 83.33%;
  }
  .col-md-11 {
    width: 91.66%;
  }
  .col-md-12 {
    width: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Assignment solution for module 2</title>
  <link rel="stylesheet" href="css">
</head>

<body>
  <h1> Our Menu</h1>
  <div class="row">
    <div id="section1" class="col-lg-4 col-md-6 col-xs-12">
      <div id="Chicken">Chicken</div>
      <p> lorem ipsum dolor sit amet, concectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
      </p>
    </div>
    <div id="section2" class="col-lg-4 col-md-6">
      <div id="Beef">Beef</div>
      <p> lorem ipsum dolor sit amet, concectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
      </p>
    </div>
    <div id="section3" class="col-lg-4 col-md-12">
      <div id="Sushi">Sushi</div>
      <p> lorem ipsum dolor sit amet, concectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
      </p>
    </div>
  </div>
</body>

</html></code>```

How do I add margins between the boxes in the large screen view  Can anybody see how can it be done. I have tried to add the margin between boxes in the large screen view but it simply doesn't show, It just breaks the line and shows in the next line.
It must also view correctly like specified in other sizes too.

答:
i got some relavant code from one community for your post,find this below.</p>

```<code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* {
    box-sizing: border-box;
}
.header {
    border: 1px solid red;
    padding: 15px;
}
.menu {
    width: 25%;
    float: left;
    padding: 15px;
    border: 1px solid red;
}
.main {
    width: 75%;
    float: left;
    padding: 15px;
    border: 1px solid red;
}
</style>
</head>
<body>

<div class="header">
  <h1>Chania</h1>
</div>

<div class="menu">
  <ul>
    <li>The Flight</li>
    <li>The City</li>
    <li>The Island</li>
    <li>The Food</li>
  </ul>
</div>

<div class="main">
  <h1>The City</h1>
  <p>Chania is the capital of the Chania region on the island of Crete. The city can be divided in two parts, the old town and the modern city.</p>
  <p>Resize the browser window to see how the content respond to the resizing.</p>
</div>

</body>
</html>
</code>```

Body:
* {
  box-sizing: border-box;
}

h1 {
  text-align: center;
  font-family: sans-serif;
  font-weight: normal;
  padding-bottom: 20px;
}

#section1{
 margin-right: 10px;
}
#section2{
 margin-right: 10px;
}

div div {
  border: 1px solid;
  width: 90%;
  background-color: #9E9E9E;
  position: relative;
  margin-bottom: 10px;
  margin-left: auto;
  margin-right: auto;
}

div div div {
  text-align: center;
  position: absolute;
  right: 0;
  top: 0;
  margin: 0px;
  font-weight: bold;
}

#Chicken {
  background-color: #EF9A9A;
  width: 25%;
  border: 1px solid;
}

#Beef {
  background-color: #F44336;
  width: 25%;
  border: 1px solid;
  color: white;
  border-color: black;
}

#Sushi {
  background-color: #CDDC39;
  width: 25%;
  border: 1px solid;
}

p {
  padding: 10px;
}

.row {
  width: 100%;
}

@media (min-width: 992px) {
  .col-lg-1,
  .col-lg-2,
  .col-lg-3,
  .col-lg-4,
  .col-lg-5,
  .col-lg-6,
  .col-lg-7,
  .col-lg-8,
  .col-lg-9,
  .col-lg-10,
  .col-lg-11,
  .col-lg-12 {
    float: left;
  }
  .col-lg-1 {
    width: 8.33%;
  }
  .col-lg-2 {
    width: 16.66%;
  }
  .col-lg-3 {
    width: 25%;
  }
  .col-lg-4 {
    width: 33.33%;
  }
  .col-lg-5 {
    width: 41.66%;
  }
  .col-lg-6 {
    width: 50%;
  }
  .col-lg-7 {
    width: 58.33%;
  }
  .col-lg-8 {
    width: 66.66%;
  }
  .col-lg-9 {
    width: 74.99%;
  }
  .col-lg-10 {
    width: 83.33%;
  }
  .col-lg-11 {
    width: 91.66%;
  }
  .col-lg-12 {
    width: 100%;
  }
}

@media (min-width: 767px) and (max-width: 991px) {
  .col-md-1,
  .col-md-2,
  .col-md-3,
  .col-md-4,
  .col-md-5,
  .col-md-6,
  .col-md-7,
  .col-md-8,
  .col-md-9,
  .col-md-10,
  .col-md-11,
  .col-md-12 {
    float: left;
  }
  .col-md-1 {
    width: 8.33%;
  }
  .col-md-2 {
    width: 16.66%;
  }
  .col-md-3 {
    width: 25%;
  }
  .col-md-4 {
    width: 33.33%;
  }
  .col-md-5 {
    width: 41.66%;
  }
  .col-md-6 {
    width: 50%;
  }
  .col-md-7 {
    width: 58.33%;
  }
  .col-md-8 {
    width: 66.66%;
  }
  .col-md-9 {
    width: 74.99%;
  }
  .col-md-10 {
    width: 83.33%;
  }
  .col-md-11 {
    width: 91.66%;
  }
  .col-md-12 {
    width: 100%;
  }
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Assignment solution for module 2</title>
  <link rel="stylesheet" href="css">

 Our Menu

Chicken

 lorem ipsum dolor sit amet, concectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad

Beef

 lorem ipsum dolor sit amet, concectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad

Sushi

 lorem ipsum dolor sit amet, concectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad

How do I add margins between the boxes in the large screen view  Can anybody see how can it be done. I have tried to add the margin between boxes in the large screen view but it simply doesn't show, It just breaks the line and shows in the next line.
It must also view correctly like specified in other sizes too.

Body:
i got some relavant code from one community for your post,find this below.

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* {
    box-sizing: border-box;
}
.header {
    border: 1px solid red;
    padding: 15px;
}
.menu {
    width: 25%;
    float: left;
    padding: 15px;
    border: 1px solid red;
}
.main {
    width: 75%;
    float: left;
    padding: 15px;
    border: 1px solid red;
}
</style>
</head>
<body>

<div class="header">
  <h1>Chania</h1>
</div>

<div class="menu">
  <ul>
    <li>The Flight</li>
    <li>The City</li>
    <li>The Island</li>
    <li>The Food</li>
  </ul>
</div>

<div class="main">
  <h1>The City</h1>
  <p>Chania is the capital of the Chania region on the island of Crete. The city can be divided in two parts, the old town and the modern city.</p>
  <p>Resize the browser window to see how the content respond to the resizing.</p>
</div>

</body>
</html>


问:
Like and And Or ISNull using Linq to Entity Entity Framework4? How do you do that?
I have a screen in my project " Enquiry" where I user can perform 2 kinds of search.I cannot figure out how to do a "like" or "And or is null" in Linq to entity.

Simple Search  ( Search in all fields  using "Like" operator)

Advanced Advanced Search (Use "And" Operator)

So lets take these 3 tables and make up a noddy example.

Customer Table  (CustomerID,Name,Surname)

Address(AddressID,Street,City)

CustomerOrder (OrderID,OrderName)

Basic search :
this is how I would do it in Sql

```<code>  SELECT TOP (100) C.Name,C.Surname,CA.Street,CA.City,CO.OrderName
  FROM Customer C
  LEFT JOIN CustomerAddress CA ON C.CustomerID=CA.CustomerID
  LEFT JOIN CustomerOrders CO ON C.CustomerID=CA.CustomerID
  WHERE  (C.CustomerID LIKE '%' + @SearchText + '%'
  OR C.Surname LIKE '%' + @SearchText + '%'
  OR C.Name LIKE '%' + @SearchText + '%'
  OR CA.Street LIKE '%' + @SearchText + '%'
  OR CA.City LIKE '%' + @SearchText + '%'
  OR  CO.OrderName LIKE '%' + @SearchText + '%') )
</code>```

Advanced Search

This my sql where clause

```<code>    WHERE  (C.CustomerID =@CustomerID or @CustomerID ISNULL
    AND C.Surname =@Surname or @Surname ISNULL
    AND C.Name=@Name or @Name ISNULL
    AND CA.Street =@Street or @Street ISNULL
    AND CA.City =@City or @City ISNULL
    AND  CO.OrderName =@OrderName or @OrderName ISNULL)
    AND ((ModifiedDate BETWEEN ISNULL(convert(varchar,@FromDate,101),'01/01/1901')
    AND ISNULL(convert(varchar,@ToDate,101),'12/31/9999'))
</code>```

How do you do Likes or and or is null in entity framework?

thanks a lot!

答:
For LIKE, you can use Contains, StartsWith, or EndsWith.  For IS NULL, use == null.

Example:

```<code>var list = from p in Products
           where (p.Description.Contains("v") && p.Description.StartsWith("C"))
                    || p.MFRCode == "TOYOTA"
                    || p.Universal == null
           select p;
</code>```

will cause EF to generate this SQL:

```<code>SELECT
[Extent1].[MFRCode] AS [MFRCode],
[Extent1].[MFRProductID] AS [MFRProductID],
[Extent1].[Universal] AS [Universal],
[Extent1].[Description] AS [Description]
FROM [dbo].[Products] AS [Extent1]
WHERE (([Extent1].[Description] LIKE N'%v%') AND ([Extent1].[Description] LIKE N'C%')) OR (N'TOYOTA' = [Extent1].[MFRCode]) OR ([Extent1].[Universal] IS NULL)
</code>```

and produce these results:

Edit

I used LINQPad to generate these results.  It's a great tool, free to use (there's an option to purchase an Intellisense feature), and definitely worth a look if you'd like to experiment with different LINQ queries and see the SQL that EF is generating (it's good for general LINQ experimentation and quickly trying out simple code as well).

ContentLicense: CC BY-SA 2.5

Body:
I have a screen in my project " Enquiry" where I user can perform 2 kinds of search.I cannot figure out how to do a "like" or "And or is null" in Linq to entity.

Simple Search  ( Search in all fields  using "Like" operator)

Advanced Advanced Search (Use "And" Operator)

So lets take these 3 tables and make up a noddy example.

Customer Table  (CustomerID,Name,Surname)

Address(AddressID,Street,City)

CustomerOrder (OrderID,OrderName)

Basic search :
this is how I would do it in Sql

  SELECT TOP (100) C.Name,C.Surname,CA.Street,CA.City,CO.OrderName
  FROM Customer C
  LEFT JOIN CustomerAddress CA ON C.CustomerID=CA.CustomerID
  LEFT JOIN CustomerOrders CO ON C.CustomerID=CA.CustomerID
  WHERE  (C.CustomerID LIKE '%' + @SearchText + '%'
  OR C.Surname LIKE '%' + @SearchText + '%'
  OR C.Name LIKE '%' + @SearchText + '%'
  OR CA.Street LIKE '%' + @SearchText + '%'
  OR CA.City LIKE '%' + @SearchText + '%'
  OR  CO.OrderName LIKE '%' + @SearchText + '%') )

Advanced Search

This my sql where clause

    WHERE  (C.CustomerID =@CustomerID or @CustomerID ISNULL
    AND C.Surname =@Surname or @Surname ISNULL
    AND C.Name=@Name or @Name ISNULL
    AND CA.Street =@Street or @Street ISNULL
    AND CA.City =@City or @City ISNULL
    AND  CO.OrderName =@OrderName or @OrderName ISNULL)
    AND ((ModifiedDate BETWEEN ISNULL(convert(varchar,@FromDate,101),'01/01/1901')
    AND ISNULL(convert(varchar,@ToDate,101),'12/31/9999'))

How do you do Likes or and or is null in entity framework?

thanks a lot!

Body:
For LIKE, you can use Contains, StartsWith, or EndsWith.  For IS NULL, use == null.

Example:

var list = from p in Products
           where (p.Description.Contains("v") && p.Description.StartsWith("C"))
                    || p.MFRCode == "TOYOTA"
                    || p.Universal == null
           select p;

will cause EF to generate this SQL:

SELECT
[Extent1].[MFRCode] AS [MFRCode],
[Extent1].[MFRProductID] AS [MFRProductID],
[Extent1].[Universal] AS [Universal],
[Extent1].[Description] AS [Description]
FROM [dbo].[Products] AS [Extent1]
WHERE (([Extent1].[Description] LIKE N'%v%') AND ([Extent1].[Description] LIKE N'C%')) OR (N'TOYOTA' = [Extent1].[MFRCode]) OR ([Extent1].[Universal] IS NULL)

and produce these results:

Edit

I used LINQPad to generate these results.  It's a great tool, free to use (there's an option to purchase an Intellisense feature), and definitely worth a look if you'd like to experiment with different LINQ queries and see the SQL that EF is generating (it's good for general LINQ experimentation and quickly trying out simple code as well).


问:
python list all combiniations without itertools

I just want to make all combination of list(two size)

for example: input= [1, 2, 3] => output = [[1,2], [1,3], [2,3]]

how can i make this code more concise and simple?(one-liner?)

it doesn't mean list compreshension.

my code

```<code>def all_combinations(input_lst):
    return_lst=[]
    for i in range(0, len(input_lst)-1):
        for j in range(i+1, len(input_lst)):
            return_lst.append([input_lst[i], input_lst[j]])
    return return_lst
</code>```

Body:
I just want to make all combination of list(two size)

for example: input= [1, 2, 3] => output = [[1,2], [1,3], [2,3]]

how can i make this code more concise and simple?(one-liner?)

it doesn't mean list compreshension.

my code

def all_combinations(input_lst):
    return_lst=[]
    for i in range(0, len(input_lst)-1):
        for j in range(i+1, len(input_lst)):
            return_lst.append([input_lst[i], input_lst[j]])
    return return_lst

Body:
l = [1,2,3,4,]
=> [(2, 1), (3, 1), (4, 1), (3, 2), (4, 2), (4, 3)]

1. use enumerate

[ (x,y) for (i,y) in enumerate(l)  for x in l[i+1:] ]

2. use index

[ (x,y) for y in l  for x in l[l.index(y)+1:] ]


问:
How to parse json when collectionView is tap
Hello I'm just wondering if there is another way to parse json data when a collection view is click and pass it to another view. This is the API im using. This is how I do it at the moment. This is how my class looks. First I create a closure. Then I created my hero class. Then I have my json parse function.

This is how my collectionView didSelectItemAt func looks. This is where im trying to put my json parse function, or is it better to put it in the hero class. Im new to this so I don't really know.

Not sure if I explained it well. So I'll include my viewcontroller code if needed. Would appreciate any help :)

答:
After perform Segue you need to do following code to pass the Hero object to HeroDetail Controller:

```<code>  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Pass the selected object to the new view controller.
        if segue.identifier == "HeroDetails" {

            let heroDetailVC = segue.destinationViewController as! HeroDetailVC
            heroDetailVC.hero = sender as! Hero

        }
     }
</code>```

Make sure you have created Variable for Hero Object in HeroDetail Controller.

This will help you to pass the data over multiple controller using Segue Method.

Body:
After perform Segue you need to do following code to pass the Hero object to HeroDetail Controller:

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Pass the selected object to the new view controller.
        if segue.identifier == "HeroDetails" {

            let heroDetailVC = segue.destinationViewController as! HeroDetailVC
            heroDetailVC.hero = sender as! Hero

        }
     }

Make sure you have created Variable for Hero Object in HeroDetail Controller.

This will help you to pass the data over multiple controller using Segue Method.


问:
Add labels as threads in a QtWindow
i've been trying to create a program in Python that randomly creates dinamic labels on a window, using threads. But something is wrong, couls someone help me please?

I've tried using a thread to call the "animation" function, but it just don't works.

CODE:

```<code># -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'bt.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui
import sys
import threading
import time

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(473, 700)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
        MainWindow.setSizePolicy(sizePolicy)
        MainWindow.setMinimumSize(QtCore.QSize(473, 700))
        MainWindow.setMaximumSize(QtCore.QSize(473, 700))
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(0, 0, 473, 700))
        self.label.setText(_fromUtf8(""))
        self.label.setPixmap(QtGui.QPixmap(_fromUtf8("images/bg.png")))
        self.label.setObjectName(_fromUtf8("label"))
        self.label_2 = QtGui.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(100, 610, 273, 28))
        self.label_2.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.label_2.setText(_fromUtf8(""))
        self.label_2.setPixmap(QtGui.QPixmap(_fromUtf8("images/click.png")))
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.label_2.mousePressEvent = self.openGame
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "Breaking Thread", None))

    def openGame(self, event):
        GameWindow.show()
        MainWindow.close()
        t1.start()
        t1.join()

class Ui_GameWindow(object):
    def setupUi(self, GameWindow):
        GameWindow.setObjectName(_fromUtf8("GameWindow"))
        GameWindow.resize(473, 700)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(GameWindow.sizePolicy().hasHeightForWidth())
        GameWindow.setSizePolicy(sizePolicy)
        GameWindow.setMinimumSize(QtCore.QSize(473, 700))
        GameWindow.setMaximumSize(QtCore.QSize(473, 700))
        self.centralwidget = QtGui.QWidget(GameWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(0, 0, 473, 700))
        self.label.setText(_fromUtf8(""))
        self.label.setPixmap(QtGui.QPixmap(_fromUtf8("images/bg2.png")))
        self.label.setObjectName(_fromUtf8("label"))
        GameWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(GameWindow)
        QtCore.QMetaObject.connectSlotsByName(GameWindow)

    def retranslateUi(self, GameWindow):
        GameWindow.setWindowTitle(_translate("GameWindow", "Breaking Thread", None))

    def animation(self):
        self.centralwidget = QtGui.QWidget(GameWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.label_3 = QtGui.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(60, 60, 30, 30))
        self.label_3.setText(_fromUtf8(""))
        self.label_3.setPixmap(QtGui.QPixmap(_fromUtf8("images/bg.png")))
        self.label_3.setObjectName(_fromUtf8("label_3"))

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)

    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)

    GameWindow = QtGui.QMainWindow()
    gi = Ui_GameWindow()
    gi.setupUi(GameWindow)

    t1 = threading.Thread(target=gi.animation())

    MainWindow.show()
    sys.exit(app.exec_())
</code>```

答:
You can't do this - GUI operations must happen in the main thread.

If you want to do something in a secondary thread, use signals and slots to communicate with the main thread and do the GUI updates there.

Title: Add labels as threads in a QtWindow

Body:
i've been trying to create a program in Python that randomly creates dinamic labels on a window, using threads. But something is wrong, couls someone help me please?

I've tried using a thread to call the "animation" function, but it just don't works.

CODE:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'bt.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui
import sys
import threading
import time

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(473, 700)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
        MainWindow.setSizePolicy(sizePolicy)
        MainWindow.setMinimumSize(QtCore.QSize(473, 700))
        MainWindow.setMaximumSize(QtCore.QSize(473, 700))
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(0, 0, 473, 700))
        self.label.setText(_fromUtf8(""))
        self.label.setPixmap(QtGui.QPixmap(_fromUtf8("images/bg.png")))
        self.label.setObjectName(_fromUtf8("label"))
        self.label_2 = QtGui.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(100, 610, 273, 28))
        self.label_2.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.label_2.setText(_fromUtf8(""))
        self.label_2.setPixmap(QtGui.QPixmap(_fromUtf8("images/click.png")))
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.label_2.mousePressEvent = self.openGame
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "Breaking Thread", None))

    def openGame(self, event):
        GameWindow.show()
        MainWindow.close()
        t1.start()
        t1.join()

class Ui_GameWindow(object):
    def setupUi(self, GameWindow):
        GameWindow.setObjectName(_fromUtf8("GameWindow"))
        GameWindow.resize(473, 700)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(GameWindow.sizePolicy().hasHeightForWidth())
        GameWindow.setSizePolicy(sizePolicy)
        GameWindow.setMinimumSize(QtCore.QSize(473, 700))
        GameWindow.setMaximumSize(QtCore.QSize(473, 700))
        self.centralwidget = QtGui.QWidget(GameWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(0, 0, 473, 700))
        self.label.setText(_fromUtf8(""))
        self.label.setPixmap(QtGui.QPixmap(_fromUtf8("images/bg2.png")))
        self.label.setObjectName(_fromUtf8("label"))
        GameWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(GameWindow)
        QtCore.QMetaObject.connectSlotsByName(GameWindow)

    def retranslateUi(self, GameWindow):
        GameWindow.setWindowTitle(_translate("GameWindow", "Breaking Thread", None))

    def animation(self):
        self.centralwidget = QtGui.QWidget(GameWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.label_3 = QtGui.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(60, 60, 30, 30))
        self.label_3.setText(_fromUtf8(""))
        self.label_3.setPixmap(QtGui.QPixmap(_fromUtf8("images/bg.png")))
        self.label_3.setObjectName(_fromUtf8("label_3"))

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)

    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)

    GameWindow = QtGui.QMainWindow()
    gi = Ui_GameWindow()
    gi.setupUi(GameWindow)

    t1 = threading.Thread(target=gi.animation())

    MainWindow.show()
    sys.exit(app.exec_())


问:
Print specific part of webpage
I'm trying to print a specific part of my application.

The application has a list of users, displaying their first and last name. When I click a user I get a popup with more detailed information about them.

How would I go about printing just the popup for a user I clicked?
The popup looks like this:

```<code> <div id="user<?=$user->id;?>" class="popup">
      <div class="details">
           User details...
      </div>
      <a href="#print">Print</a>
 </div>
</code>```

The print button isn't working yet though.

答:
Instead of all the complicated JavaScript, you can actually achieve this with simple CSS: just use two CSS files, one for your normal screen display, and another for the display of ONLY the content you wish to print. In this latter file, hide everything you don't want printed, display only the pop up.

Remember to define the media attribute of both CSS files:

```<code><link rel="stylesheet" href="screen-css.css" media="all" />
<link rel="stylesheet" href="print-css.css" media="print" />
</code>```

Title: Print specific part of webpage

Body:
I'm trying to print a specific part of my application.

The application has a list of users, displaying their first and last name. When I click a user I get a popup with more detailed information about them.

How would I go about printing just the popup for a user I clicked?
The popup looks like this:

 <div id="user<?=$user->id;?>" class="popup">

           User details...

      Print

The print button isn't working yet though.

Body:
Instead of all the complicated JavaScript, you can actually achieve this with simple CSS: just use two CSS files, one for your normal screen display, and another for the display of ONLY the content you wish to print. In this latter file, hide everything you don't want printed, display only the pop up.

Remember to define the media attribute of both CSS files:

<link rel="stylesheet" href="screen-css.css" media="all" />
<link rel="stylesheet" href="print-css.css" media="print" />


问:
Simple Math with JS
Hello I need a quick hand, I have this div below

$1500

I need to do some simple math with that amount I need to divide it in half, then divide it by 6 and display the result like below.

Pay as low as $"result here"

I am a graphic designer I need this for a webpage and I know this should be simple but I just can't figure it out I really appreciate any help here.

答:
First get text of div var text = $('.price').text(); // "$1500"

Then parse it as integer var price = text.replace(/[^\d]/, ''); // "$1500" -> 1500

Finally place text to where it belongs: $('.payment').text('Pay as low as $'+(price / 2 / 6));

$(document).ready(function () {
  var text = $('.price').text();
  var price = text.replace(/[^\d]/, '');
  $('.payment span').text(price / 12);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
<span class="payment">Pay as low as $<span></span> </span></code>```

Title: Simple Math with JS

Body:
First get text of div var text = $('.price').text(); // "$1500"

Then parse it as integer var price = text.replace(/[^\d]/, ''); // "$1500" -> 1500

Finally place text to where it belongs: $('.payment').text('Pay as low as $'+(price / 2 / 6));

$(document).ready(function () {
  var text = $('.price').text();
  var price = text.replace(/[^\d]/, '');
  $('.payment span').text(price / 12);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>
<span class="payment">Pay as low as $<span></span> </span>


问:
Operator '!' cannot be applied to operand of type '<null>
I am using MVC 5 ViewBag and trying to do

```<code>@if (!ViewBag.UserLoggedIn) {
   <a onclick="javascript:UserSessionManager.UserLogout()">LogOut</a>
}
</code>```

but getting an error:

```<code>Operator '!' cannot be applied to operand of type '<null>'
</code>```

答: You can only  use ! operator if it is comparable.So make sure that you pass boolean variable.If you dont want to do it,then you may want to do UserLogout() where UserLoggedIn == null.

Body:
I am using MVC 5 ViewBag and trying to do

@if (!ViewBag.UserLoggedIn) {
   LogOut
}

but getting an error:

Operator '!' cannot be applied to operand of type '<null>'


问:
Is there a C# equivalent to access-modifier regions in C++
It's possible to declare variables with the below structure in C++

```<code>private:
public:
protected:
    float bla1;
    float bla2;
    float bla3;
</code>```

Is there an equivalent in C#? It seems rather tedious having to repeat yourself;

```<code>protected float bla1;
protected float bla2;
protected float bla3;
</code>```

答:
No. The access is specified on each declaration.

The benefit of this is that a method's location within the source file has no effect on the behaviour. That means you can move methods and properties around (e.g. to cluster related methods together) with impunity. The same isn't quite true of fields - it's possible to make the declaration order of fields matter. Admittedly it's best not to do that in the first place...

OwnerDisplayName: Adam Naylor

Body:
It's possible to declare variables with the below structure in C++

private:
public:
protected:
    float bla1;
    float bla2;
    float bla3;

Is there an equivalent in C#? It seems rather tedious having to repeat yourself;

protected float bla1;
protected float bla2;
protected float bla3;

OwnerDisplayName: Jon Skeet


问:
Best way to separate read and write concerns using interfaces?
Lately I've been realizing the benefit of (some would argue overuse of) immutable objects to cut down dramatically on read-write dependency issues in my object model and their resulting conditions and side-effects, to ultimately make the code simpler to manage (kind of functional-programming-esque).

This practice has led me to create read-only objects that are provided values at creation/construction time and then to make available only public getters for external callers to access the properties with. Protected, internal and private setters allow internal control to be maintained over writing to the object model.

When creating interfaces while making an API over my object model, I've started considering the same issues about immutability. For example, by providing only public getters on my interfaces, and leaving it up to implementors to decide upon setters and how to handle that aspect.

An example of a "read-only" interface for implementation that I'm talking about is this Valuable Item (just for demonstration):

```<code>public interface IValuableItem {
    decimal Amount {get;}
    string Currency {get;}
}
</code>```

However I got to wondering how I should provide a companion interface that allows for writing (and if I should), and not combine those operations within the same interface as to not "taint" its immutability.

The following ideas have come to mind, just off the top of my head. Without providing what I think are pros and cons to each, what do you think the best approach is? Is there a coding methodology common in the industry for managing this concept?

```<code>// companion writer
public interface IValuableModifier {
    decimal Amount {set;}
    string Currency {set;}
}
</code>```

or

```<code>// explicit methods to enforce importance of or deviance in the programming
public interface IValuableModifier {
    void SetAmount(decimal val);
    void SetCurrency(string cur);
}
</code>```

or

```<code>// companion writer that inherits the original interface
public interface IValuableModifier : IValuableItem { //...
</code>```

or

```<code>// Let a concrete class choose one and/or the other.
class Concrete  : IValuableModifer, IValuableItem { //...
</code>```

or

etc...

What else can help me imbue writing on my otherwise immutable programming model and keep it moderately flexible or at least to separate the concerns for better control over it?

答:
I believe combining your 3rd and 4th choice is a better way to implement mutable & immutable types.

```<code>Public interface ImmutableItem {
    decimal Amount {get;}
    string Currency {get;}
}

Public interface MutableItem: ImmutableItem {
    decimal Amount {set;}
    string Currency {set;}
}

class Concrete : ImmutableItem  {
    //Only getters
}

class Concrete : MutableItem  {
   //Both getters & setters
}
</code>```

This is clean and it let the concrete classes to decide which kind of mutability is wanted to expose to outer world.

Body:
Lately I've been realizing the benefit of (some would argue overuse of) immutable objects to cut down dramatically on read-write dependency issues in my object model and their resulting conditions and side-effects, to ultimately make the code simpler to manage (kind of functional-programming-esque).

This practice has led me to create read-only objects that are provided values at creation/construction time and then to make available only public getters for external callers to access the properties with. Protected, internal and private setters allow internal control to be maintained over writing to the object model.

When creating interfaces while making an API over my object model, I've started considering the same issues about immutability. For example, by providing only public getters on my interfaces, and leaving it up to implementors to decide upon setters and how to handle that aspect.

An example of a "read-only" interface for implementation that I'm talking about is this Valuable Item (just for demonstration):

public interface IValuableItem {
    decimal Amount {get;}
    string Currency {get;}
}

However I got to wondering how I should provide a companion interface that allows for writing (and if I should), and not combine those operations within the same interface as to not "taint" its immutability.

The following ideas have come to mind, just off the top of my head. Without providing what I think are pros and cons to each, what do you think the best approach is? Is there a coding methodology common in the industry for managing this concept?

// companion writer
public interface IValuableModifier {
    decimal Amount {set;}
    string Currency {set;}
}

or

// explicit methods to enforce importance of or deviance in the programming
public interface IValuableModifier {
    void SetAmount(decimal val);
    void SetCurrency(string cur);
}

or

// companion writer that inherits the original interface
public interface IValuableModifier : IValuableItem { //...

or

// Let a concrete class choose one and/or the other.
class Concrete  : IValuableModifer, IValuableItem { //...

or

etc...

What else can help me imbue writing on my otherwise immutable programming model and keep it moderately flexible or at least to separate the concerns for better control over it?

Body:
I believe combining your 3rd and 4th choice is a better way to implement mutable & immutable types.

Public interface ImmutableItem {
    decimal Amount {get;}
    string Currency {get;}
}

Public interface MutableItem: ImmutableItem {
    decimal Amount {set;}
    string Currency {set;}
}

class Concrete : ImmutableItem  {
    //Only getters
}

class Concrete : MutableItem  {
   //Both getters & setters
}

This is clean and it let the concrete classes to decide which kind of mutability is wanted to expose to outer world.


问:
Chrome: navigator.mediaDevices.getUserMedia is not a function
I'm on localhost and trying to use the MediaDevices.getUserMedia method in Chrome. I receive the error as titled. I understand that in Chrome it is only possible to use this function with a secure origin and that localhost is considered a secure origin. Also, this works in Firefox.

This is how I'm using it as shown on the Google Developers website https://developers.google.com/web/updates/2015/10/media-devices?hl=en:

```<code>var constraints = window.constraints = {
            audio: false,
            video: true
};

navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
            callFactory.broadcastAssembly(stream);
            ...
});
</code>```

答:
On some latest browsers navigator.getUserMedia does not perform well. So, try using navigator.mediaDevices.getUserMedia. Or, better you check if navigator.mediaDevices.getUserMedia is available for the browser use navigator.mediaDevices.getUserMedia or else use navigator.getUserMedia.

```<code>navigator.getWebcam = (navigator.getUserMedia || navigator.webKitGetUserMedia || navigator.moxGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
if (navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia({  audio: true, video: true })
    .then(function (stream) {
                  //Display the video stream in the video object
     })
     .catch(function (e) { logError(e.name + ": " + e.message); });
}
else {
navigator.getWebcam({ audio: true, video: true },
     function (stream) {
             //Display the video stream in the video object
     },
     function () { logError("Web cam is not accessible."); });
}
</code>```

Hope this will solve your problem.

Body:
I'm on localhost and trying to use the MediaDevices.getUserMedia method in Chrome. I receive the error as titled. I understand that in Chrome it is only possible to use this function with a secure origin and that localhost is considered a secure origin. Also, this works in Firefox.

This is how I'm using it as shown on the Google Developers website https://developers.google.com/web/updates/2015/10/media-devices?hl=en:

var constraints = window.constraints = {
            audio: false,
            video: true
};

navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
            callFactory.broadcastAssembly(stream);
            ...
});

Body:
On some latest browsers navigator.getUserMedia does not perform well. So, try using navigator.mediaDevices.getUserMedia. Or, better you check if navigator.mediaDevices.getUserMedia is available for the browser use navigator.mediaDevices.getUserMedia or else use navigator.getUserMedia.

navigator.getWebcam = (navigator.getUserMedia || navigator.webKitGetUserMedia || navigator.moxGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
if (navigator.mediaDevices.getUserMedia) {
    navigator.mediaDevices.getUserMedia({  audio: true, video: true })
    .then(function (stream) {
                  //Display the video stream in the video object
     })
     .catch(function (e) { logError(e.name + ": " + e.message); });
}
else {
navigator.getWebcam({ audio: true, video: true },
     function (stream) {
             //Display the video stream in the video object
     },
     function () { logError("Web cam is not accessible."); });
}

Hope this will solve your problem.


答:
get the text() of the element.

replace the $ sign

And divide by (2*6)

Apply with some Math.abs function its will calculate the result

Then apply the span and append into your body

var a = Math.abs(parseInt($('.price').text().replace('$',''))/(2*6))

$('body').append('Pay as low as $'+a+' ')```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.payment{
color:green;

}</code>```

$1500
```

Title: Simple Math with JS

Body:
Hello I need a quick hand, I have this div below

$1500

I need to do some simple math with that amount I need to divide it in half, then divide it by 6 and display the result like below.

Pay as low as $"result here"

I am a graphic designer I need this for a webpage and I know this should be simple but I just can't figure it out I really appreciate any help here.

Body:
get the text() of the element.

replace the $ sign

And divide by (2*6)

Apply with some Math.abs function its will calculate the result

Then apply the span and append into your body

var a = Math.abs(parseInt($('.price').text().replace('$',''))/(2*6))

$('body').append('<span class="payment">Pay as low as $'+a+' </span>')

.payment{
color:green;

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="price">$1500</div>


问:
Code won't work when merging a javascript code in one function
Good day everyone!

I have a problem merging the codes in one function. (If it's possible).

First:

There is a table.

When the table row click two buttons will be enabled.

Here's the code:

```<code>   function enableRegButton() {
        $('#registerExist').prop('disabled', false);
        $('#edit').prop('disabled', false);

        // regButton execute when Enter key pressed
        $(document).unbind("keyup").keyup(function(e){
            var code = e.which; // recommended to use e.which, it's normalized across browsers
            if(code==13)
            {
                $("#registerExist").click();
            }
        });
    }
</code>```

Second:

When Escape key pressed it will disable all bind buttons.

Here's the code:

```<code>   $(document).keyup(function(e) {
         if (e.keyCode == 27) { // escape key maps to keycode `27`
            $('#registerExist').prop('disabled', true);
            $('#edit').prop('disabled', true);
            document.getElementById("enStudID").value = "";
            document.getElementById("enInfoID").value = "";
            document.getElementById("enCoffID").value = "";
            document.getElementById("enYearID").value = "";
        }
    });
</code>```

Now, what I want to do are those two codes above will merge in one function and it will call the function and trigger all those codes so when I edit the code it will be centralized.

Here's my final code:

```<code>function enableRegButton() {
        $('#registerExist').prop('disabled', false);
        $('#edit').prop('disabled', false);

        // regButton execute when Enter key pressed
        $(document).unbind("keyup").keyup(function(e){
            var code = e.which; // recommended to use e.which, it's normalized across browsers

            settings();

        });
    }
// This code is for ESC button when pressed.
$(document).keyup(function(e) {

         settings();
    });

function settings(){
        if(code==13)
        {
            $("#registerExist").click();
        }
        else if (code==27){ // escape key maps to keycode `27`
            $('#registerExist').prop('disabled', true);
            $('#edit').prop('disabled', true);
            document.getElementById("enStudID").value = "";
            document.getElementById("enInfoID").value = "";
            document.getElementById("enCoffID").value = "";
            document.getElementById("enYearID").value = "";
        }
    }
</code>```

Problem:

Only the enable button is working when table row is click

Pressing Escape key will not disable the enabled buttons.

Code won't run when pressing Enter Key.

答:
You need to pass the key code to the settings method.

```<code>$(document).keyup(function(e) {
    settings(e.keyCode);
});

function settings(code) {
</code>```

Use the browser's developer console when debugging Javascript issues, it's an invaluable tool and picks up problems like this quite easily.

Body:
Good day everyone!

I have a problem merging the codes in one function. (If it's possible).

First:

There is a table.

When the table row click two buttons will be enabled.

Here's the code:

   function enableRegButton() {
        $('#registerExist').prop('disabled', false);
        $('#edit').prop('disabled', false);

        // regButton execute when Enter key pressed
        $(document).unbind("keyup").keyup(function(e){
            var code = e.which; // recommended to use e.which, it's normalized across browsers
            if(code==13)
            {
                $("#registerExist").click();
            }
        });
    }

Second:

When Escape key pressed it will disable all bind buttons.

Here's the code:

   $(document).keyup(function(e) {
         if (e.keyCode == 27) { // escape key maps to keycode `27`
            $('#registerExist').prop('disabled', true);
            $('#edit').prop('disabled', true);
            document.getElementById("enStudID").value = "";
            document.getElementById("enInfoID").value = "";
            document.getElementById("enCoffID").value = "";
            document.getElementById("enYearID").value = "";
        }
    });

Now, what I want to do are those two codes above will merge in one function and it will call the function and trigger all those codes so when I edit the code it will be centralized.

Here's my final code:

function enableRegButton() {
        $('#registerExist').prop('disabled', false);
        $('#edit').prop('disabled', false);

        // regButton execute when Enter key pressed
        $(document).unbind("keyup").keyup(function(e){
            var code = e.which; // recommended to use e.which, it's normalized across browsers

            settings();

        });
    }
// This code is for ESC button when pressed.
$(document).keyup(function(e) {

         settings();
    });

function settings(){
        if(code==13)
        {
            $("#registerExist").click();
        }
        else if (code==27){ // escape key maps to keycode `27`
            $('#registerExist').prop('disabled', true);
            $('#edit').prop('disabled', true);
            document.getElementById("enStudID").value = "";
            document.getElementById("enInfoID").value = "";
            document.getElementById("enCoffID").value = "";
            document.getElementById("enYearID").value = "";
        }
    }

Problem:

Only the enable button is working when table row is click

Pressing Escape key will not disable the enabled buttons.

Code won't run when pressing Enter Key.

Body:
You need to pass the key code to the settings method.

$(document).keyup(function(e) {
    settings(e.keyCode);
});

function settings(code) {

Use the browser's developer console when debugging Javascript issues, it's an invaluable tool and picks up problems like this quite easily.


答:
I think I might use a variant of your ideas, something like this:

```<code>public interface IValuableItem
{
    decimal Amount { get; }
    string Currency { get; }
}

public interface IMutableValuable : IValuableItem
{
    new decimal Amount { set; get; }
    new string Currency { set; get; }
}

class Item : IMutableValuable
{
    public decimal Amount { get; set; }
    public string Currency { get; set; }
}
</code>```

This way your mutable interface has full getters and setters (I don't think it makes sense to have an interface that has setters but no getters), but any object that implements it will also have an immutable version of the interface that you can use for any pure-functional code.

Title: Best way to separate read and write concerns using interfaces?

Body:
I think I might use a variant of your ideas, something like this:

public interface IValuableItem
{
    decimal Amount { get; }
    string Currency { get; }
}

public interface IMutableValuable : IValuableItem
{
    new decimal Amount { set; get; }
    new string Currency { set; get; }
}

class Item : IMutableValuable
{
    public decimal Amount { get; set; }
    public string Currency { get; set; }
}

This way your mutable interface has full getters and setters (I don't think it makes sense to have an interface that has setters but no getters), but any object that implements it will also have an immutable version of the interface that you can use for any pure-functional code.


问:
Splitting text file using indexing
I have a file example

```<code>a=1,2,3,4ptr
b=5,6,7,5ptr
c=9,10,11float
</code>```

how to split this using indexing and store into dictionary and seperate the ptr from float so that all ptr should be in a ptr file and float in a float file.
output should be like {'a':['1','2','3','4ptr']}

答:
Maybe these lines codes,</p>

```<code># -*- coding: utf-8 -*-

def convert_file(file_path):
    f = open(file_path, "rb")
    result = {}
    for line in f.xreadlines():
        line = line.replace("\n", "")
        result[line.split("=")[0]] = line.split("=")[1].split(",")
    return result

if __name__ == '__main__':
    print convert_file("./sb.txt")
</code>```

Title: Splitting text file using indexing

Body:
I have a file example

a=1,2,3,4ptr
b=5,6,7,5ptr
c=9,10,11float

how to split this using indexing and store into dictionary and seperate the ptr from float so that all ptr should be in a ptr file and float in a float file.
output should be like {'a':['1','2','3','4ptr']}

Body:
Maybe these lines codes,

# -*- coding: utf-8 -*-

def convert_file(file_path):
    f = open(file_path, "rb")
    result = {}
    for line in f.xreadlines():
        line = line.replace("\n", "")
        result[line.split("=")[0]] = line.split("=")[1].split(",")
    return result

if __name__ == '__main__':
    print convert_file("./sb.txt")


问:
How to add a property in to HTML Tag use Jquery?
I am trying to add a Property In to a tag while select that tag

I need to add Invalid property like this  ....aria-readonly="false" invalid>

Page load Code:-

```<code>function setFieldRequired1(field) {

    var dropdownField=$("[data-metatype='dropdown'][name='./jcr:content/metadata/document_type']");

      if (!field.val()) {
        dropdownField.prop('invalid', 'invalid');
        dropdownField.attr('aria-required', 'true');
        dropdownField.attr('aria-invalid', 'true');
        var icons = $(dropdownField.siblings('.coral-Form-fielderror'));
        icons.show();
      }
       else
      {
         dropdownField.attr('aria-required', 'false');
        dropdownField.attr('aria-invalid', 'false');
        dropdownField.removeProp('invalid');
        var icons = $(dropdownField.siblings('.coral-Form-fielderror'));
        icons.hide();
      }

}
</code>```

This code working fine But when I select same dropdown with empty value also i have to add that invalid property?
Any help?

答:
there are some small differences between attr and prop method in jquery. hope the samples explain it for you. and take care witch prop. second parameter has to be boolean not string.

Original HTML TAG

```<code><div id="container"></div>
</code>```

JS:

```<code>$('#container').prop('disabled', true);
</code>```

generates:

```<code><div id="container" disabled></div>
</code>```

JS:

```<code>$('#container').attr('disabled','disabled');
</code>```

generates:

```<code><div id="container" disabled="disabled"></div>
</code>```

Body:
I am trying to add a Property In to a tag while select that tag

I need to add Invalid property like this  ....aria-readonly="false" invalid>

Page load Code:-

function setFieldRequired1(field) {

    var dropdownField=$("[data-metatype='dropdown'][name='./jcr:content/metadata/document_type']");

      if (!field.val()) {
        dropdownField.prop('invalid', 'invalid');
        dropdownField.attr('aria-required', 'true');
        dropdownField.attr('aria-invalid', 'true');
        var icons = $(dropdownField.siblings('.coral-Form-fielderror'));
        icons.show();
      }
       else
      {
         dropdownField.attr('aria-required', 'false');
        dropdownField.attr('aria-invalid', 'false');
        dropdownField.removeProp('invalid');
        var icons = $(dropdownField.siblings('.coral-Form-fielderror'));
        icons.hide();
      }

}

This code working fine But when I select same dropdown with empty value also i have to add that invalid property?
Any help?

Body:
there are some small differences between attr and prop method in jquery. hope the samples explain it for you. and take care witch prop. second parameter has to be boolean not string.

Original HTML TAG

<div id="container"></div>

JS:

$('#container').prop('disabled', true);

generates:

<div id="container" disabled></div>

JS:

$('#container').attr('disabled','disabled');

generates:

<div id="container" disabled="disabled"></div>


问:
compress with tar, tar : Exiting with failure status due to previous errors
I'm trying to compress files, but I use other user

Say there are two user here, user 1 "test1" and user 2 "test2"

I logged in as user 2 "test2"

Then, I wanted to compress files in the user directory "test1"

```<code>"/Home/test1/Downloads/repos/"
</code>```

I've run the command

```<code>$ Tar -zcvf $HOME/backup_file.tar.gz /home/test1/Downloads/repos/
</code>```

When there is an error compress process

```<code>tar : Exiting with failure status due to previous errors
</code>```

I've tried the way of the link below, but still error

tar Exiting with failure status due to previous errors

Assistance and solutions is greatly appreciated

答: The original folder compressed was created by the root authority, and your implementation of the tar maybe no sudo

Body:
I'm trying to compress files, but I use other user

Say there are two user here, user 1 "test1" and user 2 "test2"

I logged in as user 2 "test2"

Then, I wanted to compress files in the user directory "test1"

"/Home/test1/Downloads/repos/"

I've run the command

$ Tar -zcvf $HOME/backup_file.tar.gz /home/test1/Downloads/repos/

When there is an error compress process

tar : Exiting with failure status due to previous errors

I've tried the way of the link below, but still error

tar Exiting with failure status due to previous errors

Assistance and solutions is greatly appreciated


问:
Facade design pattern and close coupling
When learning Facade design pattern, everywhere I find this kind of examples:

```<code>public class SystemA
{
 public void CreateCreditCard(){//implementation}
 //other methods here
}

public class SystemB
{
 public void CheckCreditCard(){//implementation}
//other methods here
}

public class Facade
{
 SystemA subsystemA = new SystemA();
 SystemB subsystemB = new SystemB();

 public void CreateAccount()
 {
   subsystemA.CreateCreditCard();
   subsystemB.CheckCreditCard();
 }
}
</code>```

I don't know if I'm wrong but doesn't it create close coupling between the Facade class and the Systems(SystemA and SystemB), even if SystemA and SystemB are inherited from some abstract class or interface.

答:
In a way you wrote your example, yes it will tightly couple your code. Mainly due to new keyword which acts like a glue to your dependencies.

Keep in mind that Facade pattern will not prevent you from creating tightly coupled dependencies or code. Main purpose of using it is to make your software component easier to use, more readable and maintainable and last but not least more testable.

If you want to avoid tightly coupling, you need to pass abstract dependencies in your Facade class:

```<code>public class Facade
{
 private readonly ISystemA subsystemA;
 private readonly ISystemB subsystemB;

 public Facade(ISystemA subsystemA, ISystemB subsystemB)
 {
    this.subsystemA = subsystemA;
    this.subsystemB = subsystemB;
 }

 public void CreateAccount()
 {
   this.subsystemA.CreateCreditCard();
   this.subsystemB.CheckCreditCard();
 }
}
</code>```

You need to create interfaces (or abstract classes):

```<code>public interface ISystemA
{
 void CreateCreditCard();
 //other methods here
}

public interface ISystemB
{
  void CheckCreditCard();
  //other methods here
}
</code>```

In that way you ensured that your Facade does not depend upon implementation, rather it depends upon abstraction. You'll be able to pass any implementation which implements ISystemA or ISystemB intefaces.

I suggest you to read more about Dependency Injection and containers which will greatly help you to wrap up classes' dependency graphs and automate constructor injection in that classes.

Body:
When learning Facade design pattern, everywhere I find this kind of examples:

public class SystemA
{
 public void CreateCreditCard(){//implementation}
 //other methods here
}

public class SystemB
{
 public void CheckCreditCard(){//implementation}
//other methods here
}

public class Facade
{
 SystemA subsystemA = new SystemA();
 SystemB subsystemB = new SystemB();

 public void CreateAccount()
 {
   subsystemA.CreateCreditCard();
   subsystemB.CheckCreditCard();
 }
}

I don't know if I'm wrong but doesn't it create close coupling between the Facade class and the Systems(SystemA and SystemB), even if SystemA and SystemB are inherited from some abstract class or interface.

Body:
In a way you wrote your example, yes it will tightly couple your code. Mainly due to new keyword which acts like a glue to your dependencies.

Keep in mind that Facade pattern will not prevent you from creating tightly coupled dependencies or code. Main purpose of using it is to make your software component easier to use, more readable and maintainable and last but not least more testable.

If you want to avoid tightly coupling, you need to pass abstract dependencies in your Facade class:

public class Facade
{
 private readonly ISystemA subsystemA;
 private readonly ISystemB subsystemB;

 public Facade(ISystemA subsystemA, ISystemB subsystemB)
 {
    this.subsystemA = subsystemA;
    this.subsystemB = subsystemB;
 }

 public void CreateAccount()
 {
   this.subsystemA.CreateCreditCard();
   this.subsystemB.CheckCreditCard();
 }
}

You need to create interfaces (or abstract classes):

public interface ISystemA
{
 void CreateCreditCard();
 //other methods here
}

public interface ISystemB
{
  void CheckCreditCard();
  //other methods here
}

In that way you ensured that your Facade does not depend upon implementation, rather it depends upon abstraction. You'll be able to pass any implementation which implements ISystemA or ISystemB intefaces.

I suggest you to read more about Dependency Injection and containers which will greatly help you to wrap up classes' dependency graphs and automate constructor injection in that classes.


问:
Iphone : How to return a image or anything from second view to first view?
please check the picture you will more clear what I want to present

This is the first launch in First View

It's an empty table view

There is a add button on the right bar

If you press the Add button it will push to the Second View

The second is a only 3 rows table view

Tap the first row it will pop up a alert view to let you set a name

Press create ,the text will appear in the first row

<That's the question 1,I don't know how to pass the text to the cell...>

And keep forward ,That's a custom radio button in the row 2 and row 3

Unless You click the radio button first , otherwise you can't call this methord

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
</code>```

This is last two view
Icon View 1

Icon View 2

There are many buttons in the view,This the second question:
If I press one of this button,it will return to the second view and show the button icon on the tableview row 2 or row 3

Finally,press the Done button(same on the right bar)

It will back to the First View and show what you type the name , and which icon you selected
(Basis on radio button is selected)

That's the last question.

I upload my source code here:Link

You can download it ...

and here is the code about how I push the view...

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.row==0) {
        [self nameInputAlertView];
    }
    RadioButtonClass *btn = [radioButtonArray objectAtIndex:[indexPath row]];
    if (btn.selected) {
        //Radio Button is selected ,use that icon
        if (indexPath.row == 1) {
            IconViewOne *iconViewOne = [[IconViewOne alloc]init];
            iconViewOne.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
            [self.navigationController pushViewController:iconViewOne animated:YES];
            [iconViewOne release];
        }
        if (indexPath.row==2) {
            IconViewTwo *iconViewTwo = [[IconViewTwo alloc]init];
            iconViewTwo.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
            [self.navigationController pushViewController:iconViewTwo animated:YES];
            [iconViewTwo release];
        }
    }
}
</code>```

so...Summary all the question...

1.How to write a text via textfield in the alert view to table view cell ?

2.How to selected an icon from last view to second view ?

3.Send all this two elements to First view : Name & Icon

I only know how to pass elements from view 1 to view 2...
Don't know how to return back......

Thanks mate , please help me to figure out this problem.I will very very appreciate ！

BTW:you can take the radio button class to add in your any project

答:
A great way to pass information from one object to another, without knowing who the recipient is (and there may be multiple objects interested in the information), is to post an NSNotification. It allows you to completely avoid direct knowledge of other objects.

Read Apple's document Notification Programming Topics and give it a try.

Body:
please check the picture you will more clear what I want to present

This is the first launch in First View

It's an empty table view

There is a add button on the right bar

If you press the Add button it will push to the Second View

The second is a only 3 rows table view

Tap the first row it will pop up a alert view to let you set a name

Press create ,the text will appear in the first row

<That's the question 1,I don't know how to pass the text to the cell...>

And keep forward ,That's a custom radio button in the row 2 and row 3

Unless You click the radio button first , otherwise you can't call this methord

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

This is last two view
Icon View 1

Icon View 2

There are many buttons in the view,This the second question:
If I press one of this button,it will return to the second view and show the button icon on the tableview row 2 or row 3

Finally,press the Done button(same on the right bar)

It will back to the First View and show what you type the name , and which icon you selected
(Basis on radio button is selected)

That's the last question.

I upload my source code here:Link

You can download it ...

and here is the code about how I push the view...

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.row==0) {
        [self nameInputAlertView];
    }
    RadioButtonClass *btn = [radioButtonArray objectAtIndex:[indexPath row]];
    if (btn.selected) {
        //Radio Button is selected ,use that icon
        if (indexPath.row == 1) {
            IconViewOne *iconViewOne = [[IconViewOne alloc]init];
            iconViewOne.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
            [self.navigationController pushViewController:iconViewOne animated:YES];
            [iconViewOne release];
        }
        if (indexPath.row==2) {
            IconViewTwo *iconViewTwo = [[IconViewTwo alloc]init];
            iconViewTwo.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
            [self.navigationController pushViewController:iconViewTwo animated:YES];
            [iconViewTwo release];
        }
    }
}

so...Summary all the question...

1.How to write a text via textfield in the alert view to table view cell ?

2.How to selected an icon from last view to second view ?

3.Send all this two elements to First view : Name & Icon

I only know how to pass elements from view 1 to view 2...
Don't know how to return back......

Thanks mate , please help me to figure out this problem.I will very very appreciate ！

BTW:you can take the radio button class to add in your any project