问:
cURL returns 302, whereas a browser returns 200
I have a script that uses a load of cURLs to log into a site and submit a series of forms, however this has recently stopped working due to the cURL requests returning 302s and redirecting to a block/endpoint page. If I do the same actions with a browser, I there are no redirects, just a 200 OK.

My cURL is using the cookie returned by the login process, so I don't think that the session is being dropped.

I'd originally thought that a CSRF Token (of some kind) was missing, given the redirect location, and that later forms in the process (using the browser) contain a hidden CSRF Token field, but the URL requires no posted data.

The cURL and response are as follows:

```<code>curl_setopt($ch, CURLOPT_URL, 'https://*******.********.co.uk/Dispatcher?menuid=pos_home');
curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_HEADER, 0);
$content = curl_exec ($ch);
echo "CURL INFO : <BR/>```" ;
print_r(curl_getinfo($ch));
```

<p>which returns:</p>

```Array
(
[url] => https://*******.********.co.uk/Dispatcher?menuid=pos_home
[content_type] => text/html
[http_code] => 302
[header_size] => 253
[request_size] => 332
[filetime] => -1
[ssl_verify_result] => 20
[redirect_count] => 0
[total_time] => 0.142718
[namelookup_time] => 2.4E-5
[connect_time] => 2.4E-5
[pretransfer_time] => 9.0E-5
[size_upload] => 43
[size_download] => 327
[speed_download] => 2291
[speed_upload] => 301
[download_content_length] => -1
[upload_content_length] => 43
[starttransfer_time] => 0.142659
[redirect_time] => 0
[certinfo] => Array
    (
    )

[primary_ip] => nnn.nnn.nnn.nn
[primary_port] => 443
[local_ip] => nnn.nnn.nnn.nn
[local_port] => 53154
[redirect_url] => https://*******.********.co.uk/Dispatcher?menuid=badorMissingCSRFT
```

)

If anyone has any ideas why or how a server can give a different response for a cURL to a browser request, I'd be very grateful - thanks.of

答:
curl with -L or --location option to follow the redirect.

curl -L google.com

Body:
I have a script that uses a load of cURLs to log into a site and submit a series of forms, however this has recently stopped working due to the cURL requests returning 302s and redirecting to a block/endpoint page. If I do the same actions with a browser, I there are no redirects, just a 200 OK.

My cURL is using the cookie returned by the login process, so I don't think that the session is being dropped.

I'd originally thought that a CSRF Token (of some kind) was missing, given the redirect location, and that later forms in the process (using the browser) contain a hidden CSRF Token field, but the URL requires no posted data.

The cURL and response are as follows:

curl_setopt($ch, CURLOPT_URL, 'https://*******.********.co.uk/Dispatcher?menuid=pos_home');
curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_HEADER, 0);
$content = curl_exec ($ch);
echo "CURL INFO :

" ;
print_r(curl_getinfo($ch));

which returns:

Array
(
[url] => https://*******.********.co.uk/Dispatcher?menuid=pos_home
[content_type] => text/html
[http_code] => 302
[header_size] => 253
[request_size] => 332
[filetime] => -1
[ssl_verify_result] => 20
[redirect_count] => 0
[total_time] => 0.142718
[namelookup_time] => 2.4E-5
[connect_time] => 2.4E-5
[pretransfer_time] => 9.0E-5
[size_upload] => 43
[size_download] => 327
[speed_download] => 2291
[speed_upload] => 301
[download_content_length] => -1
[upload_content_length] => 43
[starttransfer_time] => 0.142659
[redirect_time] => 0
[certinfo] => Array
    (
    )

[primary_ip] => nnn.nnn.nnn.nn
[primary_port] => 443
[local_ip] => nnn.nnn.nnn.nn
[local_port] => 53154
[redirect_url] => https://*******.********.co.uk/Dispatcher?menuid=badorMissingCSRFT

)

If anyone has any ideas why or how a server can give a different response for a cURL to a browser request, I'd be very grateful - thanks.of


来源: stackexchange

问:
How to add this Javascript to my AMP webpage?
This script is a countdown for Christmas

Is it possible to display in an AMP HTML web page or not? If possible, how to do it? What is the minify Javascript that I should add to the AMP web page, please help me.

```<code><script type="text/javascript">// <![CDATA[
var today=new Date()

//Enter the occasion's MONTH (1-12) and DAY (1-31):
var theoccasion=new Date(today.getFullYear(), 12, 25)

//Customize text to show before and on occasion. Follow grammer below:
var beforeOccasionText="left until Christmas :) "
var onOccasiontext="Today is Christmas. Happy Holidays!"

var monthtext=new
Array("Jan","Feb","Mar","April","May","June","July","Aug","Sep","Oct","Nov","Dec")
theoccasion.setMonth(theoccasion.getMonth()-1) //change to 0-11 month format
var showdate="("+monthtext[theoccasion.getMonth()]+" "+theoccasion.getDate()+")" //show date of occasion

var one_day=1000*60*60*24
var calculatediff=""

calculatediff=Math.ceil((theoccasion.getTime()-today.getTime())/(one_day))
if (calculatediff<0){ //if bday already passed
var nextyeartoday=new Date()
nextyeartoday.setFullYear(today.getFullYear()+1)
calculatediff=Math.ceil((nextyeartoday.getTime()-
today.getTime())/(one_day)+calculatediff)
}

//Display message accordingly
var pluraldayornot=(calculatediff==1)? "day" : "days"
if (calculatediff>0)
    document.write("<b>"+calculatediff+" "+pluraldayornot+" "+beforeOccasionText+" "+showdate+"!</b>")
else if (calculatediff==0)
document.write("<b>"+onOccasiontext+" "+showdate+"!</b>")
// ]]></script>
</code>```

答: JavaScript are forbidden in AMP Sites</p>

ContentLicense: CC BY-SA 3.0

Body: JavaScript are forbidden in AMP Sites


问:
Passe data in bundle to the activity of the gallery
I had this code, without the bundle it works very well, but when I add the bundle in the intent, in my onActivityResult I don't found this id_q in data, I found just the path of the chosen picture.

```<code>Intent intent = new Intent();
        Bundle b = new Bundle();
        b.putInt("id_q", q.getId());
        intent.putExtras(b);
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_IMAGE);
</code>```

this is onActivityResult :

```<code>public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_IMAGE)
                onSelectFromGalleryResult(data);
</code>```

and in onSelectFromGalleryResult(data) I had this :

```<code>       if (data != null && data.getExtras() != null) {
            Bundle b = data.getExtras();
            int id_q = b.getInt("id_q");}
</code>```

答:
According to the comments, I would suggest something like this.

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

    ArrayList<Question> questionsLeft;

    Question currentQ;

    /* ... */

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_IMAGE) {
                // Do what you have to do with data and currentQ
                processNext();
            }
        }
    }

    public void processNext() {
        if(questionsLeft.isEmpty()) {
            return;
        }
        currentQ = questionsLeft.get(0);
        questionsLeft.remove(0);
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_IMAGE);
    }
}
</code>```

You can also have one requestCode for each question in your list. You will know that your request is "SELECT_IMAGE" if it is in a given range instead of a single value.

Body:
I had this code, without the bundle it works very well, but when I add the bundle in the intent, in my onActivityResult I don't found this id_q in data, I found just the path of the chosen picture.

Intent intent = new Intent();
        Bundle b = new Bundle();
        b.putInt("id_q", q.getId());
        intent.putExtras(b);
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_IMAGE);

this is onActivityResult :

public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_IMAGE)
                onSelectFromGalleryResult(data);

and in onSelectFromGalleryResult(data) I had this :

       if (data != null && data.getExtras() != null) {
            Bundle b = data.getExtras();
            int id_q = b.getInt("id_q");}

Body:
According to the comments, I would suggest something like this.

public class YourActivity extends Activity {

    ArrayList<Question> questionsLeft;

    Question currentQ;

    /* ... */

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_IMAGE) {
                // Do what you have to do with data and currentQ
                processNext();
            }
        }
    }

    public void processNext() {
        if(questionsLeft.isEmpty()) {
            return;
        }
        currentQ = questionsLeft.get(0);
        questionsLeft.remove(0);
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_IMAGE);
    }
}

You can also have one requestCode for each question in your list. You will know that your request is "SELECT_IMAGE" if it is in a given range instead of a single value.


问:
laravel 5.4 undefined variable in view
I'm kind of new to laravel and trying to pull data from a database but keep hitting an error page saying there's an undefined variable within the view.

I'm supposing there's something I'm doing wrong (or not doing) within the controller. So I have a create.blade.php that posts data from a form to the database and everything works fine, however I want it such that after posting to the database to redirect to the show.blade.php showing the uploaded data and here is where I hit a brick wall with the error messages.

This is my store function within the controller -

```<code>public function store(Request $request)
    {
     $data4page = new Data4page;

     $data4page->h1Ttle = $request->h1Ttle;
     $data4page->h4Ttle = $request->h4Ttle;
     $data4page->description = $request->description;
     $data4page->save();

     /*redirecting to the content's show page*/
     return redirect()->route('content.show', $data4page->id);
}
</code>```

And this is the show function within the same controller -

```<code>public function show($id)
    {
        //
        $data4page = Data4page::find($id);
        return view('digital.show')->with(compact('data4page'));
    }
</code>```

The error message I'm getting is -

```<code>Undefined variable: data4page (View: /var/www/html/theproject/resources/views/content/show.blade.php)
</code>```

And in the show.blade.php this is a sample of what I have -

```<code><h1>{{ $data4page->h4Ttle }}</h1>
<p>{{ $data4page->description }}</p>
<h4>{{ $data4page->h4Ttle }}</h4>
</code>```

Having said all that, I have also tried various means of returning the view within the show function of the controller but all these result in the same error message above. These variants include -

```<code>return view('content.show')->with('data4page', $data4page);
return view('content.show',['data4page'=>$data4page]);
</code>```

Update: I earlier had typos but now the error I get is -

```<code>undefined variable: {"id":9,"h1Ttle":"h1 sample text","h4Ttle":"h4 sample text","description":"body text goes here"} (View: /var/www/html/theproject/resources/views/content/show.blade.php)
</code>```

This is the show.blade.php -

```<code>@extends('main')
@section('title')
@section('content')
      <div class="app-template">
         <main class="wrapperMain">
            <div class="">
               <aside class="navSidebar">
                  <nav class="navProperty">
                     <h1 class="navProperty-title">{{ $data4page->h1Ttle }}</h1>
                  </nav>
                  <footer class="footerProperty">
                     <div class="upcomingSchedule">
                        <h4 class="upcomingSchedule-heading">{{ $data4page->h4Ttle }}</h4>
                     </div>
                  </footer>
               </aside>
            </div>
            <div class="content content--withSidebar">
               <div class="lead--Home">
                  <p>{{ $data4page->description }}</p>
               </div>
            </div>
         </main>
@endsection
</code>```

答:
Why have you resorted to typing the variable name with the wrong case when the answers given below are absolutely fine? PHP variables are case sensitive. You're passing $Data4page to your view in the code you've shown and then trying to use the access $data4page. Any of the below will work.

```<code>return view('content.show', ['data4page' => $data4page]);
return view('content.show', compact('data4page'));
return view('content.show')->with('data4page', $data4page);
return view('content.show')->with(['data4page' => $data4page]);
return view('content.show')->with(compact('data4page'));
</code>```

Title: laravel 5.4 undefined variable in view

Body:
I'm kind of new to laravel and trying to pull data from a database but keep hitting an error page saying there's an undefined variable within the view.

I'm supposing there's something I'm doing wrong (or not doing) within the controller. So I have a create.blade.php that posts data from a form to the database and everything works fine, however I want it such that after posting to the database to redirect to the show.blade.php showing the uploaded data and here is where I hit a brick wall with the error messages.

This is my store function within the controller -

public function store(Request $request)
    {
     $data4page = new Data4page;

     $data4page->h1Ttle = $request->h1Ttle;
     $data4page->h4Ttle = $request->h4Ttle;
     $data4page->description = $request->description;
     $data4page->save();

     /*redirecting to the content's show page*/
     return redirect()->route('content.show', $data4page->id);
}

And this is the show function within the same controller -

public function show($id)
    {
        //
        $data4page = Data4page::find($id);
        return view('digital.show')->with(compact('data4page'));
    }

The error message I'm getting is -

Undefined variable: data4page (View: /var/www/html/theproject/resources/views/content/show.blade.php)

And in the show.blade.php this is a sample of what I have -

{{ $data4page->h4Ttle }}

{{ $data4page->description }}

{{ $data4page->h4Ttle }}

Having said all that, I have also tried various means of returning the view within the show function of the controller but all these result in the same error message above. These variants include -

return view('content.show')->with('data4page', $data4page);
return view('content.show',['data4page'=>$data4page]);

Update: I earlier had typos but now the error I get is -

undefined variable: {"id":9,"h1Ttle":"h1 sample text","h4Ttle":"h4 sample text","description":"body text goes here"} (View: /var/www/html/theproject/resources/views/content/show.blade.php)

This is the show.blade.php -

@extends('main')
@section('title')
@section('content')

{{ $data4page->h1Ttle }}

{{ $data4page->h4Ttle }}

{{ $data4page->description }}

@endsection

Body:
Why have you resorted to typing the variable name with the wrong case when the answers given below are absolutely fine? PHP variables are case sensitive. You're passing $Data4page to your view in the code you've shown and then trying to use the access $data4page. Any of the below will work.

return view('content.show', ['data4page' => $data4page]);
return view('content.show', compact('data4page'));
return view('content.show')->with('data4page', $data4page);
return view('content.show')->with(['data4page' => $data4page]);
return view('content.show')->with(compact('data4page'));


问:
Custom Post Type rewrite slug always takes me to homepage
I know there are number of posts already available here regarding this particular issue and I have gone through a number of them but could not make my page to work. So I want to put here what I exactly have and looking forward to a solution.

I have registered the following Custom Post Type.

```<code>$labels = array('name' => 'Hotel','singular_name' => 'Hotel','admin_menu' => 'Hotel', 'name_admin_bar' => 'Hotel');

$supports = array(
    'title',
    'editor',
    'thumbnail'
);

$args = array(
    'labels' => $labels,
    'public' => true,
    'publicly_queryable' => true,
    'query_var' => true,
    'has_archive' => true,
    'capability_type' => 'post',
    'taxonomies' => array ('hotel_type', 'room_type', 'amenities'),
    'show_ui' => true,
    'show_in_menu' => true,
    'menu_position' => 28,
    'hierarchical' => false,
    'rewrite' => array('slug' => 'hotels'),
    'supports' => $supports,
    'exclude_from_search' => false
);

register_post_type('hotel-info', $args);
</code>```

Created a template page called hotel-list.php

Created a page using the above template (List of Hotels) in admin called Staying Options and updated its permalink to /hotels/.

Re-saved permalink structure from Settings > Permalink

But whenever I am trying to access http://local.tourplanner.com/hotels/ WordPress is taking me back to my homepage.

Somebody please tell me what I am doing wrong.

EDIT:

When I am accessing http://local.tourplanner.com/hotels/cliff-top-club-auli/ I am able to land on the correct page with information about the hotel.

答:
You have created a slug only for individual hotels, and not for all hotels. Wordpress simply doesn't know how to list your hotels.

In order to make /hotels/ accessible, you'll need to create an archive page, which will be used to list the hotels. First have a quick look at the Post Type Template documentation here: https://codex.wordpress.org/Post_Type_Templates. Then follow the guide on how to create the archive page here http://www.wpbeginner.com/wp-tutorials/how-to-create-a-custom-post-types-archive-page-in-wordpress/

Body:
I know there are number of posts already available here regarding this particular issue and I have gone through a number of them but could not make my page to work. So I want to put here what I exactly have and looking forward to a solution.

I have registered the following Custom Post Type.

$labels = array('name' => 'Hotel','singular_name' => 'Hotel','admin_menu' => 'Hotel', 'name_admin_bar' => 'Hotel');

$supports = array(
    'title',
    'editor',
    'thumbnail'
);

$args = array(
    'labels' => $labels,
    'public' => true,
    'publicly_queryable' => true,
    'query_var' => true,
    'has_archive' => true,
    'capability_type' => 'post',
    'taxonomies' => array ('hotel_type', 'room_type', 'amenities'),
    'show_ui' => true,
    'show_in_menu' => true,
    'menu_position' => 28,
    'hierarchical' => false,
    'rewrite' => array('slug' => 'hotels'),
    'supports' => $supports,
    'exclude_from_search' => false
);

register_post_type('hotel-info', $args);

Created a template page called hotel-list.php

Created a page using the above template (List of Hotels) in admin called Staying Options and updated its permalink to /hotels/.

Re-saved permalink structure from Settings > Permalink

But whenever I am trying to access http://local.tourplanner.com/hotels/ WordPress is taking me back to my homepage.

Somebody please tell me what I am doing wrong.

EDIT:

When I am accessing http://local.tourplanner.com/hotels/cliff-top-club-auli/ I am able to land on the correct page with information about the hotel.


问:
execute php after json output
i am sending few data as json from php file and it works without any issue. but i want to keep executing php file after json output. if i comment this line then those php codes are executing else they are not executing.

```<code>header('Content-Type: application/json', true);
 some more code here
   exit(json_encode($response));
</code>```

next is few more php codes which makes database connection and executes.

```<code>   $res2 = $con->query("SELECT * FROM `tableA` where status='0' order by id desc limit 5");
</code>```

update code and change the status to 1
if i comment below code

```<code>      exit(json_encode($response));
</code>```

then update code works and updates the status to 1 else it is 0. mainly because its a json file as per header and it advises to close the script execution after exit code. i tried toset header as none and echo the output but it does not work. i tried to flush also. it did not work either. any idea will be great

答:
use echo instead of exit

```<code>echo json_encode($response);
</code>```

exit will terminate code at that line.

Title: execute php after json output

Body:
i am sending few data as json from php file and it works without any issue. but i want to keep executing php file after json output. if i comment this line then those php codes are executing else they are not executing.

header('Content-Type: application/json', true);
 some more code here
   exit(json_encode($response));

next is few more php codes which makes database connection and executes.

   $res2 = $con->query("SELECT * FROM `tableA` where status='0' order by id desc limit 5");

update code and change the status to 1
if i comment below code

      exit(json_encode($response));

then update code works and updates the status to 1 else it is 0. mainly because its a json file as per header and it advises to close the script execution after exit code. i tried toset header as none and echo the output but it does not work. i tried to flush also. it did not work either. any idea will be great

Body:
use echo instead of exit

echo json_encode($response);

exit will terminate code at that line.


问:
Configure launchd to run shell script when Android device is connected
I want to launch a program on my computer when a particular Android device is connected to my computer running macOS. I know this is possible because when I plug in an Android device. I'm using this answer as an example

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd >
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.example.program</string>
    <key>ProgramArguments</key>
    <array>
    <string>/path/to/program</string>
    </array>
    <key>LaunchEvents</key>
    <dict>
            <key>com.apple.iokit.matching</key>
            <dict>
                    <key>com.apple.device-attach</key>
                    <dict>
                            <key>idProduct</key>
                            <integer>1234</integer>
                            <key>idVendor</key>
                            <integer>1337</integer>
                            <key>IOProviderClass</key>
                            <string>IOUSBDevice</string>
                            <key>IOMatchLaunchStream</key>
                            <true/>
                    </dict>
            </dict>
    </dict>
</dict>
</plist>
</code>```

Instead of an Apple device, I want it to launch when an Android device with a particular IMEI number is connected to my computer.

答: It would be possible with matching android device ids ,vendor id and further adding adb getprop command and read specific result about imei ,other things.i have no knowldege about mac but same can be done in linux with init bg script . You acn further peep into this app source https://github.com/mortenjust/androidtool-mac</p>

Body:
I want to launch a program on my computer when a particular Android device is connected to my computer running macOS. I know this is possible because when I plug in an Android device. I'm using this answer as an example

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd >
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.example.program</string>
    <key>ProgramArguments</key>
    <array>
    <string>/path/to/program</string>
    </array>
    <key>LaunchEvents</key>
    <dict>
            <key>com.apple.iokit.matching</key>
            <dict>
                    <key>com.apple.device-attach</key>
                    <dict>
                            <key>idProduct</key>
                            <integer>1234</integer>
                            <key>idVendor</key>
                            <integer>1337</integer>
                            <key>IOProviderClass</key>
                            <string>IOUSBDevice</string>
                            <key>IOMatchLaunchStream</key>
                            <true/>
                    </dict>
            </dict>
    </dict>
</dict>
</plist>

Instead of an Apple device, I want it to launch when an Android device with a particular IMEI number is connected to my computer.


问:
Ada: interfacing with Matlab
since Ada doesn't possess any good libraries for scientific computing, I was wondering if anyone has been able to use Matlab mathematical functions such as eig (for calculations of eigenvalues and eigenvectors) within Ada.

I see that some interfaces exist for simulink and Ada. But I'm not a user of Simulink. I would like just to be able to use Matlab mathematical functions through perhaps Ada functions and procedures.

PS: In earlier Ada documents there were lots of talks and promises to create good numerical libraries similar to NAG or NUMAL. I do wonder why this has never been concretized successfully, and any good and robust scientific computing library made available. For sure the Ada language doesn't pale before any other scientific computing language in my opinion.

Thanks a lot...

答: It is very easy to use lapack from Ada. You do not need to call Matlab for that. Lapcak is the same library which Matlab uses as well.

ContentLicense: CC BY-SA 2.5

Title: Ada: interfacing with Matlab


问:
uncheck selected checkbox when one of the checkbox option has been selected
I have 2 groups of checkbox options on same page. below is the code.

```<code><div class="col-xs-12">
<label class="checkbox-inline">
<input type="checkbox" th:field="*{borrowerRace1}"  th:value="1"  th:text="borrower1" />
 </label>
 </div>
 <div class="col-xs-12">
 <label class="checkbox-inline">
 <input type="checkbox" th:field="*{borrowerRace1}"  th:value="2"  th:text="borrower2" />
  </label>
  </div>
  <div class="col-xs-12">
  <label class="checkbox-inline">
   <input type="checkbox" th:field="*{borrowerRace1}"  th:value="3"  th:text="borrower3" />
       </label>
   </div>
     <div class="col-xs-12">
        <label class="checkbox-inline">
          <input type="checkbox" th:field="*{borrowerRace1}"  th:value="4" th:text="borrower4" />
        </label>
        </div>

        <div class="col-xs-12">
              <label class="checkbox-inline">
  <input type="checkbox" th:field="*{borrowerEthnicity1}"  th:value="1" th:text="Ethnicity1" />
           </label>
        </div>
           <div class="col-xs-12">
         <label class="checkbox-inline">
         <input type="checkbox" th:field="*{borrowerEthnicity2}"  th:value="2" th:text="Ethnicity2" />
      </label>
          </div>
     <div class="col-xs-12">
      <label class="checkbox-inline">
 <input type="checkbox" th:field="*{borrowerEthnicity3}"  th:value="3"  th:text="Ethnicity3" />
</label>
</div>
<div class="col-xs-12">
<label class="checkbox-inline">
 <input type="checkbox" th:field="*{borrowerEthnicity4}"  th:value="4" th:text="Ethnicity4" />
   </label>
    </div>
</code>```

Now,

User can select first 3 check boxes but clicking the 4th (last) one should
select the 4th (last) one and deselect all other of the set. Same should
happen for all checkbox sets.

Example : User can select A,B,C checkbox at a same time but when he checks D
all the above selected checkboxes should get unselected. Similarly for E,F,G
and H. I hope I am clear now.

Please help me on this. I hope I am clear, if not please do let me know

答:
```<code>$('checkbox1').on('click'function(){
$('checkbox').attr('checked',false)
$(this).attr('checked',true)
})
</code>```

try something like this

Body:
I have 2 groups of checkbox options on same page. below is the code.

<input type="checkbox" th:field="*{borrowerRace1}"  th:value="1"  th:text="borrower1" />

 <input type="checkbox" th:field="*{borrowerRace1}"  th:value="2"  th:text="borrower2" />

   <input type="checkbox" th:field="*{borrowerRace1}"  th:value="3"  th:text="borrower3" />

          <input type="checkbox" th:field="*{borrowerRace1}"  th:value="4" th:text="borrower4" />

  <input type="checkbox" th:field="*{borrowerEthnicity1}"  th:value="1" th:text="Ethnicity1" />

         <input type="checkbox" th:field="*{borrowerEthnicity2}"  th:value="2" th:text="Ethnicity2" />

 <input type="checkbox" th:field="*{borrowerEthnicity3}"  th:value="3"  th:text="Ethnicity3" />

 <input type="checkbox" th:field="*{borrowerEthnicity4}"  th:value="4" th:text="Ethnicity4" />

Now,

User can select first 3 check boxes but clicking the 4th (last) one should
select the 4th (last) one and deselect all other of the set. Same should
happen for all checkbox sets.

Example : User can select A,B,C checkbox at a same time but when he checks D
all the above selected checkboxes should get unselected. Similarly for E,F,G
and H. I hope I am clear now.

Please help me on this. I hope I am clear, if not please do let me know

Body:
$('checkbox1').on('click'function(){
$('checkbox').attr('checked',false)
$(this).attr('checked',true)
})

try something like this


问:
Not able to retrieve data field from Firebase database
I have been trying to retrieve data fields from my firebase database for the past 5 days without any success. This is what my database looks like:

Code for fetching data:

```<code>private void alterTextView(final String id) {
        if(id!=null) {
        mDatabase.child("Users").child(id).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                UserInformation userInformation = dataSnapshot.getValue(UserInformation.class);
                String name = (String) userInformation.getName();

                Log.d("Main Activity",name);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        mWelcomeUserMessage.setText("Welcome, "+name);

    }
}`
</code>```

I have no idea why the name is 'null' (refer to log).
Can someone tell me what I'm doing wrong?

PS: I have defined a blank default constructor, getters, and setters in my UserInformation.java class.

Also, mDatabase is initialized as follows:
mDatabase = FirebaseDatabase.getInstance().getReference();

答:
dataSnapshot.getValue(Class) will only load and set values into public fields. I see you already have a default constructor.

Make name field in UserInformation class public. Also make sure the snapshot you are calling getValue on is a valid JSON representation of UserInformation class and has an exact same "name" field (it must exactly match the name field in class).

Please note:
addValueEventListener adds a listener, which will be called when data is available.

Please note that the data is available after onDataChange has been called. That's why you should set your text right after you get the data you need from the DataSnapshot. Like that:

```<code>private void alterTextView(final String id) {
            if(id!=null) {
            mDatabase.child("Users").child(id).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    UserInformation userInformation = dataSnapshot.getValue(UserInformation.class);
                    String name = (String) userInformation.getName();
                    Log.d("Main Activity",name);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run(){
                            mWelcomeUserMessage.setText("Welcome, "+name);
                        }
                    });
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

        }
    }
</code>```

Body:
I have been trying to retrieve data fields from my firebase database for the past 5 days without any success. This is what my database looks like:

Code for fetching data:

private void alterTextView(final String id) {
        if(id!=null) {
        mDatabase.child("Users").child(id).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                UserInformation userInformation = dataSnapshot.getValue(UserInformation.class);
                String name = (String) userInformation.getName();

                Log.d("Main Activity",name);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        mWelcomeUserMessage.setText("Welcome, "+name);

    }
}`

I have no idea why the name is 'null' (refer to log).
Can someone tell me what I'm doing wrong?

PS: I have defined a blank default constructor, getters, and setters in my UserInformation.java class.

Also, mDatabase is initialized as follows:
mDatabase = FirebaseDatabase.getInstance().getReference();

Body:
dataSnapshot.getValue(Class) will only load and set values into public fields. I see you already have a default constructor.

Make name field in UserInformation class public. Also make sure the snapshot you are calling getValue on is a valid JSON representation of UserInformation class and has an exact same "name" field (it must exactly match the name field in class).

Please note:
addValueEventListener adds a listener, which will be called when data is available.

Please note that the data is available after onDataChange has been called. That's why you should set your text right after you get the data you need from the DataSnapshot. Like that:

private void alterTextView(final String id) {
            if(id!=null) {
            mDatabase.child("Users").child(id).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    UserInformation userInformation = dataSnapshot.getValue(UserInformation.class);
                    String name = (String) userInformation.getName();
                    Log.d("Main Activity",name);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run(){
                            mWelcomeUserMessage.setText("Welcome, "+name);
                        }
                    });
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

        }
    }


问:
cannot resolve the name "xs.string" to a(n) type definetion component
this is an assignment file. schema must be developed.
XYZ school wants to store the details of student and staff in a xml file. The following scenario helps in designing the XML document.
    Persons will the root tag. Persons will have the entry of each person with name, age, gender, address. A person can be either a student or staff. student will have rollno, standard and section. If staff, then staffid and subject. Every student must have an address with the following entry- doorno,street,city and state.

```<code>`<?xml version = "1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="persons">
   <xs:complexType>
   <xs:sequence>
      <xs:element name="person">
        <xs:complexType>
        <xs:sequence>
            <xs:element name="name" type="xs.string"/>
            <xs:element name="age" type="xs.integer"/>
            <xs:element name="gender" type="xs.string"/>
              <xs:element name="address">
                <xs:complexType>
                <xs:sequence>
                    <xs:element name="doorno" type="xs.integer"/>
                    <xs:element name="street" type="xs.string"/>
                    <xs:element name="city" type="xs.string"/>
                    <xs:element name="state" type="xs.string"/>
                </xs:sequence>
                </xs:complexType>
              </xs:element>
              <xs:element name="student" minOccurs="0">
                <xs:complexType>
                <xs:sequence>
                    <xs:element name="rollno" type="xs.integer"/>
                    <xs:element name="standard" type="xs.integer"/>
                    <xs:element name="section" type="xs.string"/>
               </xs:sequence>
               </xs:complexType>
              </xs:element>
              <xs:element name="staff" minOccurs="0">
                <xs:complexType>
                <xs:sequence>
                    <xs:element name="staffid" type="xs.integer"/>
                    <xs:element name="subject" type="xs.string"/>
                </xs:sequence>
                </xs:complexType>
              </xs:element>
        </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
    </xs:complexType>
</xs:element>
</xs:schema>`
</code>```

could anyone please help me out.

答: Change xs.string to xs:string.

Body:
this is an assignment file. schema must be developed.
XYZ school wants to store the details of student and staff in a xml file. The following scenario helps in designing the XML document.
    Persons will the root tag. Persons will have the entry of each person with name, age, gender, address. A person can be either a student or staff. student will have rollno, standard and section. If staff, then staffid and subject. Every student must have an address with the following entry- doorno,street,city and state.

`<?xml version = "1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="persons">
   <xs:complexType>
   <xs:sequence>
      <xs:element name="person">
        <xs:complexType>
        <xs:sequence>
            <xs:element name="name" type="xs.string"/>
            <xs:element name="age" type="xs.integer"/>
            <xs:element name="gender" type="xs.string"/>
              <xs:element name="address">
                <xs:complexType>
                <xs:sequence>
                    <xs:element name="doorno" type="xs.integer"/>
                    <xs:element name="street" type="xs.string"/>
                    <xs:element name="city" type="xs.string"/>
                    <xs:element name="state" type="xs.string"/>
                </xs:sequence>
                </xs:complexType>
              </xs:element>
              <xs:element name="student" minOccurs="0">
                <xs:complexType>
                <xs:sequence>
                    <xs:element name="rollno" type="xs.integer"/>
                    <xs:element name="standard" type="xs.integer"/>
                    <xs:element name="section" type="xs.string"/>
               </xs:sequence>
               </xs:complexType>
              </xs:element>
              <xs:element name="staff" minOccurs="0">
                <xs:complexType>
                <xs:sequence>
                    <xs:element name="staffid" type="xs.integer"/>
                    <xs:element name="subject" type="xs.string"/>
                </xs:sequence>
                </xs:complexType>
              </xs:element>
        </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
    </xs:complexType>
</xs:element>
</xs:schema>`

could anyone please help me out.

Body: Change xs.string to xs:string.


问:
java parsing a string like "0:ADD(10)"
i am having a string array like this {"0:ADD(10)","1:ADD(20)"} how can i parse this and get the value '10','20' from this string ,

Scenario is : i am trying to write a client and server app using Apache Mina server , when i sent message between client and server i am getting response as "0:ADD(10)"

答:
You can try</p>

```<code>int num = Integer.parseInt("0:ADD(10)".split("[()]")[1]);
</code>```

Title: java parsing a string like "0:ADD(10)"

Body:
You can try

int num = Integer.parseInt("0:ADD(10)".split("[()]")[1]);


问:
C# Linq - Combobox not filled
I have a problem with the comboBoxContainer. While comboBoxategory and comboBoxMarket are filled, comboBoxContainer is not filled.

selected.Container has the right variable but the combobox doesn't get this variable.

```<code>private void listBoxProducts_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        ProductList_Variables selected = ProductList_Variables)listBoxProducts.SelectedItem;

        textBoxProduct.Text = selected.Product;
        comboBoxCategory.SelectedItem = selected.Category;
        comboBoxMarket.SelectedItem = selected.Market;
        comboBoxContainer.SelectedItem = selected.Container;
        textBoxPrice1.Text = selected.Price.ToString();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
class ProductList_Variables
{
    public int Id { get; set; }
    public string Product { get; set; }
    public string Category { get; set; }
    public string Size { get; set; }
    public string Market { get; set; }
    public string ProductName { get { return Product + " - " + Category + " - Size: " + Size +", Market: "+ Market; } }
    public string Flavour { get; set; }
    public decimal Price { get; set; }
    public string Container { get; set; }
    public int IdContainer { get; set; }

}
void Fillcombo()// is filling the combobox
{
    try
    {
        using (var db = new GelatoProjectDBEntities())
        {
            var products = (from x in db.ProductsLists
                            select new ProductList_Variables { Id = x.Id, Product = x.Product, Category = x.Category, Size = x.Size, Market = x.Market, Container=x.Container, Price=x.Price, IdContainer=x.IdContainer }
                            ).OrderBy(c => c.Product).ToArray();
            listBoxProducts.Items.AddRange(products);
            listBoxProducts.DisplayMember = "ProductName";
            listBoxProducts.ValueMember = "Id";
            var goods = (from x in db.Goods
                         select new ProductList_Variables { Id = x.Id, Product=x.item, Container = x.item}
                         ).OrderBy(c => c.Product).ToArray();

           comboBoxContainer.Items.AddRange(goods);
           comboBoxContainer.DisplayMember = "Product";
           comboBoxContainer.ValueMember = "Id";
       }
   }
   catch (Exception ex)
   {
       MessageBox.Show(ex.Message);
   }
    }
</code>```

答:
When your property Container contains the value (the property Id of your data element of the comboBoxContainer), you can use </p>

```<code>comboBoxContainer.SelectedValue = selected.Container;
</code>```

Title: C# Linq - Combobox not filled

Body:
I have a problem with the comboBoxContainer. While comboBoxategory and comboBoxMarket are filled, comboBoxContainer is not filled.

selected.Container has the right variable but the combobox doesn't get this variable.

private void listBoxProducts_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        ProductList_Variables selected = ProductList_Variables)listBoxProducts.SelectedItem;

        textBoxProduct.Text = selected.Product;
        comboBoxCategory.SelectedItem = selected.Category;
        comboBoxMarket.SelectedItem = selected.Market;
        comboBoxContainer.SelectedItem = selected.Container;
        textBoxPrice1.Text = selected.Price.ToString();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
class ProductList_Variables
{
    public int Id { get; set; }
    public string Product { get; set; }
    public string Category { get; set; }
    public string Size { get; set; }
    public string Market { get; set; }
    public string ProductName { get { return Product + " - " + Category + " - Size: " + Size +", Market: "+ Market; } }
    public string Flavour { get; set; }
    public decimal Price { get; set; }
    public string Container { get; set; }
    public int IdContainer { get; set; }

}
void Fillcombo()// is filling the combobox
{
    try
    {
        using (var db = new GelatoProjectDBEntities())
        {
            var products = (from x in db.ProductsLists
                            select new ProductList_Variables { Id = x.Id, Product = x.Product, Category = x.Category, Size = x.Size, Market = x.Market, Container=x.Container, Price=x.Price, IdContainer=x.IdContainer }
                            ).OrderBy(c => c.Product).ToArray();
            listBoxProducts.Items.AddRange(products);
            listBoxProducts.DisplayMember = "ProductName";
            listBoxProducts.ValueMember = "Id";
            var goods = (from x in db.Goods
                         select new ProductList_Variables { Id = x.Id, Product=x.item, Container = x.item}
                         ).OrderBy(c => c.Product).ToArray();

           comboBoxContainer.Items.AddRange(goods);
           comboBoxContainer.DisplayMember = "Product";
           comboBoxContainer.ValueMember = "Id";
       }
   }
   catch (Exception ex)
   {
       MessageBox.Show(ex.Message);
   }
    }

Body:
When your property Container contains the value (the property Id of your data element of the comboBoxContainer), you can use

comboBoxContainer.SelectedValue = selected.Container;


问:
TransactionTooLargeException in Nougat
Exception

```<code> 05-12 15:42:45.791 11043-11043/ E/UncaughtException: java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                       at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3776)
                                                                       at android.os.Handler.handleCallback(Handler.java:751)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:154)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
                                                                    Caused by: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                       at android.os.BinderProxy.transactNative(Native Method)
                                                                       at android.os.BinderProxy.transact(Binder.java:615)
                                                                       at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3700)
                                                                       at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3768)
                                                                       at android.os.Handler.handleCallback(Handler.java:751)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:154)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
05-12 15:42:47.247 11043-11043/ E/AndroidRuntime: FATAL EXCEPTION: main
                                                                Process: , PID: 11043
                                                                java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3776)
                                                                    at android.os.Handler.handleCallback(Handler.java:751)
                                                                    at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                    at android.os.Looper.loop(Looper.java:154)
                                                                    at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
                                                                 Caused by: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                    at android.os.BinderProxy.transactNative(Native Method)
                                                                    at android.os.BinderProxy.transact(Binder.java:615)
                                                                    at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3700)
                                                                    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3768)
                                                                    at android.os.Handler.handleCallback(Handler.java:751)
                                                                    at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                    at android.os.Looper.loop(Looper.java:154)
                                                                    at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
</code>```

Fragment OnItemClick:-

```<code> listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {

            Bundle bundle = new Bundle();
            ProdModel mProdModel = prodList.get(position);
            bundle.putSerializable("object", mProdModel);
            Intent intent = new Intent(getActivity(), DetailActivity.class);
            intent.putExtra("bundle", bundle);
            startActivityForResult(intent, 1);

        }

    });
</code>```

In DetailActivity,

```<code>Bundle bundle = getIntent().getBundleExtra("bundle");
    if (bundle != null) {
        ProdModel model = (ProdModel) bundle.getSerializable("object");
    }
</code>```

DetailActivity Manifest,

```<code>  <activity
        android:name="com.mass.mysample.DetailActivity"
        android:screenOrientation="portrait" />
</code>```

Image Loading Using Picasso,

```<code> Picasso.with(this).load(model.getImage())
             .placeholder(R.drawable.logo_without)
             .fit().into(productimage);
</code>```

Model Class

```<code>public class ProdModel implements Serializable {
private String seller_id;
String name;
private String image;
private float price;
private float specialprice;
private String entity_id;
private String productNumQuantity;
private String storetitle;
private String description;
private String discount;
private String max_price;
private String store_name;
private String StoreUrl;

public String getProductNumQuantity() {
    return productNumQuantity;
}

public void setProductNumQuantity(String productNumQuantity) {
    this.productNumQuantity = productNumQuantity;
}

public String getDiscount() {
    return discount;
}

public void setDiscount(String discount) {
    this.discount = discount;
}

public String getMax_price() {
    return max_price;
}

public void setMax_price(String max_price) {
    this.max_price = max_price;
}

public String getStore_name() {
    return store_name;
}

public void setStore_name(String store_name) {
    this.store_name = store_name;
}

public String getStoreUrl() {
    return StoreUrl;
}

public void setStoreUrl(String storeUrl) {
    StoreUrl = storeUrl;
}

public String getStoretitle() {
    return storetitle;
}

public void setStoretitle(String storetitle) {
    this.storetitle = storetitle;
}

public String getSeller_id() {
    return seller_id;
}

public void setSeller_id(String seller_id) {
    this.seller_id = seller_id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getEntity_id() {
    return entity_id;
}

public void setEntity_id(String entity_id) {
    this.entity_id = entity_id;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public float getPrice() {
    return price;
}

public void setPrice(float price) {
    this.price = price;
}

public float getSpecialPrice() {
    return specialprice;
}

public void setSpecialPrice(float specialprice) {
    this.specialprice = specialprice;
}

}
</code>```

Data flow from TabActivity to fragment,

```<code>1.I have a TabActivity with ViewPager and Fragment.
2.In Fragment, I have a ListView.
3.The Data to fragment is passed from view pager adapter by set arguments.
</code>```

Solutions I tried

```<code>1.A POJO class that implements Serialization.
2.I use Picasso to load the image from image URL.
3.This exception is thrown when OnItemClick on ListView in fragment passes data to DetailActivity to show all passed data.
4.I get this exception after the DetailActivity load's image and other data then app suddenly crashes.
5.I pass data in Intent was all POJO Object with Id, Name, Image URL, Price etc.,
</code>```

Note:-
App Crash only in NOUGAT

Finally, The fix I implemented

changing the targetSdkVersion to 23 from 25

After changing, my application not crashing in Nougat too.

All I have to Know is this proper solution or is there any workaround.

Please Guide to the proper way.

Thanks in advance.

Fragment

```<code>public class ProdFragment extends Fragment {
ListView listview;
SharedPreferences spref;
Boolean isInternetPresent = false;
ConnectionDetector cd;

private String toBeDisplayed,CatID;
private static final String TAG = ProdFragment.class.getSimpleName();
String totalProductCart;
private ArrayList<Root_SubCatModel> subCatList;
private ArrayList<ProdModel> prodList;
ProdAdapter adapter;

public ProdFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    spref = getActivity().getSharedPreferences(getResources().getString(R.string.myPref),
            Context.MODE_PRIVATE);
    Bundle bundle = getArguments();
    if (bundle != null) {
        int tabPosition = bundle.getInt("Tab_Position");
        toBeDisplayed = bundle.getString("Tab_ToBeDisplayed");
        CatID = bundle.getString("CategoryId");
        subCatList = (ArrayList<Root_SubCatModel>) bundle.getSerializable("Tab_Data");
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.prod_listview, container, false);

    cd = new ConnectionDetector(getActivity());
    listview = (ListView) rootView.findViewById(R.id.prodlist);
    if (subCatList != null) {
        adapter = new ProdAdapter(getActivity(),
                CatID,
                toBeDisplayed,
                R.layout.list_product,
                subCatList,
                (ProductCartCountListener)getActivity());
        listview.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        prodList = new ArrayList<>();
        for(int i = 0; i<subCatList.size();i++){
            if (subCatList.get(i).getProd() != null) {
                if(toBeDisplayed.equals("SubCategory")){
                    if (CatID.equals(subCatList.get(i).getCategory_id())) {
                        this.prodList = subCatList.get(i).getProd();
                    }
                }else if(toBeDisplayed.equals("Products")) {
                    this.prodList = subCatList.get(i).getProd();
                }
            }
        }

    }

    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {

            Bundle bundle = new Bundle();
            bundle.putSerializable("object", prodList.get(position));
            Intent intent = new Intent(getActivity(), DetailActivity.class);
            intent.putExtra("bundle", bundle);
            startActivityForResult(intent,1);
        }

    });

    return rootView;
}

public void showAlertDialog(Context context, String title, String message, Boolean status) {
    AlertDialog alertDialog = new AlertDialog.Builder(context).create();

    // Setting Dialog Title
    alertDialog.setTitle(title);

    // Setting Dialog Message
    alertDialog.setMessage(message);

    // Setting alert dialog icon
    //alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

    // Setting OK Button
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
        if (resultCode == Activity.RESULT_OK) {
            Bundle b = data.getExtras();
            if (b != null) {
                ProdModel myobj = (ProdModel) b.getSerializable("Cart_Quantity");
                if (myobj != null) {
                    if (prodList != null) {
                        for (ProdModel P : prodList) {
                            if (P.getEntity_id().equals(myobj.getEntity_id())) {
                                P.setProductNumQuantity(myobj.getProductNumQuantity());
                            }
                        }
                    }
                    Log.d(TAG,"Product_Id : " + myobj.getEntity_id()
                            + ", Product_Cart_Count : " + myobj.getProductNumQuantity());
                }
            }
        } else if (resultCode == 0) {
            Log.d(TAG,"RESULT CANCELLED");
        }
    }
    adapter.notifyDataSetChanged();
    String totalProductCart = spref.getString("Cart_Count_Tool", "0");
    Activity activity = getActivity();
    if(activity instanceof TabActivity){
        TabActivity myActivity = (TabActivity) activity;
        Toolbar toolbar = (Toolbar) myActivity.findViewById(R.id.back_toolbar);
        ImageView cart_imageview = (ImageView) toolbar.findViewById(R.id.cart_imageview);
        cart_imageview.setImageDrawable(myActivity.buildCounterDrawable(
                Integer.parseInt(totalProductCart)));
    }
    Log.d(TAG,"RESULT NOTIFIED");
}

public void refreshData(String productId, boolean isAddAsyncTaskComplete,
                        boolean isAddAsyncTaskLimitReached, boolean isDeleteAsyncTaskComplete){
    adapter.setQuantityCount(prodList, productId, isAddAsyncTaskComplete,
            isAddAsyncTaskLimitReached, isDeleteAsyncTaskComplete);

}
</code>```

TabActivity Layout

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

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/storeimage"
        android:textAlignment="center"
        android:elevation="2dp"
        android:minHeight="?attr/actionBarSize"
        app:tabMode="scrollable"
        app:tabTextColor="@color/color_dark_blue"
        app:tabSelectedTextColor="@color/color_orange"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />
 </android.support.design.widget.CoordinatorLayout>
</code>```

ListView

```<code> listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {

            Bundle bundle = new Bundle();
            ProdModel mProdModel = prodList.get(position);
            bundle.putSerializable("object", mProdModel);
            Intent intent = new Intent(getActivity(), DetailActivity.class);
            intent.putExtra("bundle", bundle);
            startActivityForResult(intent, 1);

        }

    });
</code>```0

答:
Read this article http://nemanjakovacevic.net/blog/english/2015/03/24/yet-another-post-on-serializable-vs-parcelable/ should help you.

My solution:

Save your objects in some storage (SharedPreferences, raw JSON, SQLLite or Realm database etc.)

Put to your bundle only object 'id' (simple type: int long etc.)

Get 'id' from intent and find it in your storage, then retrieve the object.

Title: TransactionTooLargeException in Nougat

Body:
Exception

 05-12 15:42:45.791 11043-11043/ E/UncaughtException: java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                       at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3776)
                                                                       at android.os.Handler.handleCallback(Handler.java:751)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:154)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
                                                                    Caused by: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                       at android.os.BinderProxy.transactNative(Native Method)
                                                                       at android.os.BinderProxy.transact(Binder.java:615)
                                                                       at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3700)
                                                                       at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3768)
                                                                       at android.os.Handler.handleCallback(Handler.java:751)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                       at android.os.Looper.loop(Looper.java:154)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
05-12 15:42:47.247 11043-11043/ E/AndroidRuntime: FATAL EXCEPTION: main
                                                                Process: , PID: 11043
                                                                java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3776)
                                                                    at android.os.Handler.handleCallback(Handler.java:751)
                                                                    at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                    at android.os.Looper.loop(Looper.java:154)
                                                                    at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
                                                                 Caused by: android.os.TransactionTooLargeException: data parcel size 631792 bytes
                                                                    at android.os.BinderProxy.transactNative(Native Method)
                                                                    at android.os.BinderProxy.transact(Binder.java:615)
                                                                    at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3700)
                                                                    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3768)
                                                                    at android.os.Handler.handleCallback(Handler.java:751)
                                                                    at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                    at android.os.Looper.loop(Looper.java:154)
                                                                    at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)

Fragment OnItemClick:-

 listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {

            Bundle bundle = new Bundle();
            ProdModel mProdModel = prodList.get(position);
            bundle.putSerializable("object", mProdModel);
            Intent intent = new Intent(getActivity(), DetailActivity.class);
            intent.putExtra("bundle", bundle);
            startActivityForResult(intent, 1);

        }

    });

In DetailActivity,

Bundle bundle = getIntent().getBundleExtra("bundle");
    if (bundle != null) {
        ProdModel model = (ProdModel) bundle.getSerializable("object");
    }

DetailActivity Manifest,

  <activity
        android:name="com.mass.mysample.DetailActivity"
        android:screenOrientation="portrait" />

Image Loading Using Picasso,

 Picasso.with(this).load(model.getImage())
             .placeholder(R.drawable.logo_without)
             .fit().into(productimage);

Model Class

public class ProdModel implements Serializable {
private String seller_id;
String name;
private String image;
private float price;
private float specialprice;
private String entity_id;
private String productNumQuantity;
private String storetitle;
private String description;
private String discount;
private String max_price;
private String store_name;
private String StoreUrl;

public String getProductNumQuantity() {
    return productNumQuantity;
}

public void setProductNumQuantity(String productNumQuantity) {
    this.productNumQuantity = productNumQuantity;
}

public String getDiscount() {
    return discount;
}

public void setDiscount(String discount) {
    this.discount = discount;
}

public String getMax_price() {
    return max_price;
}

public void setMax_price(String max_price) {
    this.max_price = max_price;
}

public String getStore_name() {
    return store_name;
}

public void setStore_name(String store_name) {
    this.store_name = store_name;
}

public String getStoreUrl() {
    return StoreUrl;
}

public void setStoreUrl(String storeUrl) {
    StoreUrl = storeUrl;
}

public String getStoretitle() {
    return storetitle;
}

public void setStoretitle(String storetitle) {
    this.storetitle = storetitle;
}

public String getSeller_id() {
    return seller_id;
}

public void setSeller_id(String seller_id) {
    this.seller_id = seller_id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

public String getEntity_id() {
    return entity_id;
}

public void setEntity_id(String entity_id) {
    this.entity_id = entity_id;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public float getPrice() {
    return price;
}

public void setPrice(float price) {
    this.price = price;
}

public float getSpecialPrice() {
    return specialprice;
}

public void setSpecialPrice(float specialprice) {
    this.specialprice = specialprice;
}

}

Data flow from TabActivity to fragment,

1.I have a TabActivity with ViewPager and Fragment.
2.In Fragment, I have a ListView.
3.The Data to fragment is passed from view pager adapter by set arguments.

Solutions I tried

1.A POJO class that implements Serialization.
2.I use Picasso to load the image from image URL.
3.This exception is thrown when OnItemClick on ListView in fragment passes data to DetailActivity to show all passed data.
4.I get this exception after the DetailActivity load's image and other data then app suddenly crashes.
5.I pass data in Intent was all POJO Object with Id, Name, Image URL, Price etc.,

Note:-
App Crash only in NOUGAT

Finally, The fix I implemented

changing the targetSdkVersion to 23 from 25

After changing, my application not crashing in Nougat too.

All I have to Know is this proper solution or is there any workaround.

Please Guide to the proper way.

Thanks in advance.

Fragment

public class ProdFragment extends Fragment {
ListView listview;
SharedPreferences spref;
Boolean isInternetPresent = false;
ConnectionDetector cd;

private String toBeDisplayed,CatID;
private static final String TAG = ProdFragment.class.getSimpleName();
String totalProductCart;
private ArrayList<Root_SubCatModel> subCatList;
private ArrayList<ProdModel> prodList;
ProdAdapter adapter;

public ProdFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    spref = getActivity().getSharedPreferences(getResources().getString(R.string.myPref),
            Context.MODE_PRIVATE);
    Bundle bundle = getArguments();
    if (bundle != null) {
        int tabPosition = bundle.getInt("Tab_Position");
        toBeDisplayed = bundle.getString("Tab_ToBeDisplayed");
        CatID = bundle.getString("CategoryId");
        subCatList = (ArrayList<Root_SubCatModel>) bundle.getSerializable("Tab_Data");
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.prod_listview, container, false);

    cd = new ConnectionDetector(getActivity());
    listview = (ListView) rootView.findViewById(R.id.prodlist);
    if (subCatList != null) {
        adapter = new ProdAdapter(getActivity(),
                CatID,
                toBeDisplayed,
                R.layout.list_product,
                subCatList,
                (ProductCartCountListener)getActivity());
        listview.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        prodList = new ArrayList<>();
        for(int i = 0; i<subCatList.size();i++){
            if (subCatList.get(i).getProd() != null) {
                if(toBeDisplayed.equals("SubCategory")){
                    if (CatID.equals(subCatList.get(i).getCategory_id())) {
                        this.prodList = subCatList.get(i).getProd();
                    }
                }else if(toBeDisplayed.equals("Products")) {
                    this.prodList = subCatList.get(i).getProd();
                }
            }
        }

    }

    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {

            Bundle bundle = new Bundle();
            bundle.putSerializable("object", prodList.get(position));
            Intent intent = new Intent(getActivity(), DetailActivity.class);
            intent.putExtra("bundle", bundle);
            startActivityForResult(intent,1);
        }

    });

    return rootView;
}

public void showAlertDialog(Context context, String title, String message, Boolean status) {
    AlertDialog alertDialog = new AlertDialog.Builder(context).create();

    // Setting Dialog Title
    alertDialog.setTitle(title);

    // Setting Dialog Message
    alertDialog.setMessage(message);

    // Setting alert dialog icon
    //alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

    // Setting OK Button
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
        if (resultCode == Activity.RESULT_OK) {
            Bundle b = data.getExtras();
            if (b != null) {
                ProdModel myobj = (ProdModel) b.getSerializable("Cart_Quantity");
                if (myobj != null) {
                    if (prodList != null) {
                        for (ProdModel P : prodList) {
                            if (P.getEntity_id().equals(myobj.getEntity_id())) {
                                P.setProductNumQuantity(myobj.getProductNumQuantity());
                            }
                        }
                    }
                    Log.d(TAG,"Product_Id : " + myobj.getEntity_id()
                            + ", Product_Cart_Count : " + myobj.getProductNumQuantity());
                }
            }
        } else if (resultCode == 0) {
            Log.d(TAG,"RESULT CANCELLED");
        }
    }
    adapter.notifyDataSetChanged();
    String totalProductCart = spref.getString("Cart_Count_Tool", "0");
    Activity activity = getActivity();
    if(activity instanceof TabActivity){
        TabActivity myActivity = (TabActivity) activity;
        Toolbar toolbar = (Toolbar) myActivity.findViewById(R.id.back_toolbar);
        ImageView cart_imageview = (ImageView) toolbar.findViewById(R.id.cart_imageview);
        cart_imageview.setImageDrawable(myActivity.buildCounterDrawable(
                Integer.parseInt(totalProductCart)));
    }
    Log.d(TAG,"RESULT NOTIFIED");
}

public void refreshData(String productId, boolean isAddAsyncTaskComplete,
                        boolean isAddAsyncTaskLimitReached, boolean isDeleteAsyncTaskComplete){
    adapter.setQuantityCount(prodList, productId, isAddAsyncTaskComplete,
            isAddAsyncTaskLimitReached, isDeleteAsyncTaskComplete);

}

TabActivity Layout

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

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/storeimage"
        android:textAlignment="center"
        android:elevation="2dp"
        android:minHeight="?attr/actionBarSize"
        app:tabMode="scrollable"
        app:tabTextColor="@color/color_dark_blue"
        app:tabSelectedTextColor="@color/color_orange"/>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />
 </android.support.design.widget.CoordinatorLayout>

ListView

<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ListView
    android:id="@+id/prodlist"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

</FrameLayout>


问:
Loaded event for WebBrowser control in winforms
I need to access the below property of WebBrowser control when it is loaded completely.

```<code>webBrowser1.ActiveXInstance
</code>```

this is null if the control is not loaded completely.

What property/event  can I check like Form_Load?

答:
There is WebBrowser.LoadComplete event for top-level only (the WebBrowser here I guess). If you're looking for an non top-level element, DocumentCompleted event occurs for all elements.

As ActiveXInstance is inherited from WebBrowserBase, there is also the Control.HandleCreated event, being fired when the control is displayed for the first time, though I don't know if it is applicable here.

(Sadly I'm not able to give the class and event links, but should be possible to find them yourself, right?)

Body:
I need to access the below property of WebBrowser control when it is loaded completely.

webBrowser1.ActiveXInstance

this is null if the control is not loaded completely.

What property/event  can I check like Form_Load?


问:
Is declaring an header file essential?
Is declaring an header file essential? This code:

```<code>main()
{
  int i=100;

  printf("%d\n",i);
}
</code>```

seems to work, the output that I get is 100. Even without using stdio.h header file. How is this possible?

答:
C supprots three types of function argument forms:

Known fixed arguments: this is when you declare function with arguments: foo(int x, double y).

Unknown fixed arguments: this is when you declare it with empty parentheses: foo() (not be confused with foo(void): it is the first form without arguments), or not declare it at all.

Variable arguments: this is when you declare it with ellipsis: foo(int x, ...).

When you see standard function working then function definition (which is in form 1 or 3) is compatible with form 2 (using same calling convention). Many old std. library functions are so (as desugned to be), because they are there form early versions of C, where was no function declarations and they all was in form 2. Other function may be unintentionally be compatible with form 2, if they have arguments as declared in argument promotion rules for this form. But some may not be so.

But form 2 need programmer to pass arguments of same types everywhere, because compiler not able to check arguments with prototype and have to determine calling convention osing actual passed arguments.

For example, on MC68000 machine first two integer arguments for fixed arg functions (for both forms 1 and 2) will be passed in registers D0 and D1, first two pointers in A0 and A1, all others passed through stack. So, for example function fwrite(const void * ptr, size_t size, size_t count, FILE * stream); will get arguments as: ptr in A0, size in D0, count in D1 and stream in A1 (and return a result in D0). When you included stdio.h it will be so whatever you pass to it.

When you do not include stdio.h another thing happens. As you call fwrite with fwrite(data, sizeof(*data), 5, myfile) compiler looks on argruments and see that function is called as fwrite(*, int, int, *). So what it do? It pass first pointer in A0, first int in D0, second int in D1 and second pointer in A1, so it what we need.

But when you try to call it as fwrite(data, sizeof(*data), 5.0, myfile), with count is of double type, compiler will try to pass count through stack, as it is not integer. But function require is in D1. Shit happens: D1 contain some garbage and not count, so further behaviour is unpredictable. But than you use prototype defined in stdio.h all will be ok: compiler automatically convert this argument to int and pass it as needed. It is not abstract example as double in arument may be just result of computation involving floating point numbers and you may just miss this assuming result is int.

Another example is variable argument function (form 3) like printf(char *fmt, ...). For it calling convention require last named argument (fmt here) to be passed through stack regardess of its type. So, then you call printf("%d", 10) it will put pointer to "%d" and number 10 on stack and call function as need.

But when you do not include stdio.h comiler will not know that printf is vararg function and will suppose that printf("%d", 10) is calling to function with fixed arguments of type pointer and int. So MC68000 will place pointer to A0 and int to D0 instead of stack and result is again unpredictable.

There may be luck that arguments was previously on stack and occasionally read there and you get correct result... this time... but another time is will fail. Another luck is that compiler takes care if not declared function may be vararg (and somehow makes call compatible with both forms). Or all arguments in all forms are just passed through stack on your machine, so fixed, unknown and vararg forms are just called identically.

So: do not do this even you feel lucky and it works. Unknown fixed argument form is there just for compatibility with old code and is strictly discouraged to use.

Also note: C++ will not allow this at all, as it require function to be declared with known arguments.

Title: Is declaring an header file essential?

Body:
Is declaring an header file essential? This code:

main()
{
  int i=100;

  printf("%d\n",i);
}

seems to work, the output that I get is 100. Even without using stdio.h header file. How is this possible?


问:
How to export video as .mp4 using openCV?
I am trying to export video as .mp4 with openCV. I have tried several codecs but for now I had no success.

This is a function that constructs a video from frames:

```<code>def create_movie(self, out_directory, fps, total_frames):
    img1 = cv2.imread("temp/scr0.png")
    height, width, layers =  img1.shape
    codec = cv2.cv.CV_FOURCC('X','V','I','D')
    video = cv2.VideoWriter(out_directory, codec, fps, (width, height))

    for i in range(total_frames):
        img_name = "temp/scr" + str(i) + ".png"
        img = cv2.imread(img_name)
        video.write(img)

    video.release()
    cv2.destroyAllWindows()
</code>```

I usually get next error message, using different codecs:

```<code>Tag XVID/0x44495658 incompatible with output codec id '13'
</code>```

Is is possible to do this and how?

答:
May be a little bit late to answer this, but if you want to write an .MP4 file with OpenCV try this:</p>

```<code>import cv2
#your previous code here

fourcc = cv2.VideoWriter_fourcc(*'a\0\0\0')
out = cv2.VideoWriter('out.mp4', fourcc, fps, res)

#the character '\0' is the Null-Terminator or simply 0x00 in the ASCII-Table
#tag: *'a\0\0\0' corresponds to 0x00000061

#your following code here
</code>```

Body:
I am trying to export video as .mp4 with openCV. I have tried several codecs but for now I had no success.

This is a function that constructs a video from frames:

def create_movie(self, out_directory, fps, total_frames):
    img1 = cv2.imread("temp/scr0.png")
    height, width, layers =  img1.shape
    codec = cv2.cv.CV_FOURCC('X','V','I','D')
    video = cv2.VideoWriter(out_directory, codec, fps, (width, height))

    for i in range(total_frames):
        img_name = "temp/scr" + str(i) + ".png"
        img = cv2.imread(img_name)
        video.write(img)

    video.release()
    cv2.destroyAllWindows()

I usually get next error message, using different codecs:

Tag XVID/0x44495658 incompatible with output codec id '13'

Is is possible to do this and how?

Body:
May be a little bit late to answer this, but if you want to write an .MP4 file with OpenCV try this:

import cv2
#your previous code here

fourcc = cv2.VideoWriter_fourcc(*'a\0\0\0')
out = cv2.VideoWriter('out.mp4', fourcc, fps, res)

#the character '\0' is the Null-Terminator or simply 0x00 in the ASCII-Table
#tag: *'a\0\0\0' corresponds to 0x00000061

#your following code here


问:
Appending files name along with path in a variable in batch file reading from folder
I am trying to read files name along with path and store it in single variable differentiate each path by comma. below is my try but every time if i run it is showing single file name even though it is running in for loop.

code:

```<code>@echo off
for %%F  in ("C:\Users\a5100893\Desktop\source_files\*.*") do (
set file=%%F
echo done copying files: %file%
)
</code>```

Folder contains files:
C:\Users\a5100893\Desktop\source_files\

```<code>Pwm_1.txt
Pwm_2.txt
Pwm_3.txt
Pwm_4.txt
Pwm_5.txt
</code>```

Output:

```<code>C:\Users\a5100893\Desktop>File_Read.bat
done copying files: C:\Users\a5100893\Desktop\source_files\Pwm_5.txt
done copying files: C:\Users\a5100893\Desktop\source_files\Pwm_5.txt
done copying files: C:\Users\a5100893\Desktop\source_files\Pwm_5.txt
done copying files: C:\Users\a5100893\Desktop\source_files\Pwm_5.txt
done copying files: C:\Users\a5100893\Desktop\source_files\Pwm_5.txt
</code>```

Expected output:

variable "file" should contain:

"C:\Users\a5100893\Desktop\source_files\Pwm_1.txt,C:\Users\a5100893\Desktop\source_files\Pwm_2.txt,C:\Users\a5100893\Desktop\source_files\Pwm_3.txt,C:\Users\a5100893\Desktop\source_files\Pwm_4.txt,C:\Users\a5100893\Desktop\source_files\Pwm_5.txt"

答:
You could use the following:

@Echo Off
For %%A In ("C:\Users\a5100893\Desktop\source_files\*") Do If Not Defined file (
    Set "file=%%A") Else Call Set "file=%%file%%,%%A"
Echo %file%
Timeout -1
```

Body:
I am trying to read files name along with path and store it in single variable differentiate each path by comma. below is my try but every time if i run it is showing single file name even though it is running in for loop.

code:

@echo off
for %%F  in ("C:\Users\a5100893\Desktop\source_files\*.*") do (
set file=%%F
echo done copying files: %file%
)

Folder contains files:
C:\Users\a5100893\Desktop\source_files\

Pwm_1.txt
Pwm_2.txt
Pwm_3.txt
Pwm_4.txt
Pwm_5.txt

Output:

C:\Users\a5100893\Desktop>File_Read.bat
done copying files: C:\Users\a5100893\Desktop\source_files\Pwm_5.txt
done copying files: C:\Users\a5100893\Desktop\source_files\Pwm_5.txt
done copying files: C:\Users\a5100893\Desktop\source_files\Pwm_5.txt
done copying files: C:\Users\a5100893\Desktop\source_files\Pwm_5.txt
done copying files: C:\Users\a5100893\Desktop\source_files\Pwm_5.txt

Expected output:

variable "file" should contain:

"C:\Users\a5100893\Desktop\source_files\Pwm_1.txt,C:\Users\a5100893\Desktop\source_files\Pwm_2.txt,C:\Users\a5100893\Desktop\source_files\Pwm_3.txt,C:\Users\a5100893\Desktop\source_files\Pwm_4.txt,C:\Users\a5100893\Desktop\source_files\Pwm_5.txt"


问:
android studio gradle erro
Android studio 3.0
in android studio 3.0
 م  Executing tasks: [:app:generateDebugSources, :app:mockableAndroidJar, :app:generateDebugAndroidTestSources]
at this gardle stops and gives me

Failed to complete grandle excution

Cause:
connection was forcibly closed by the remote host

What can i do?

答:
Try this:

```<code>buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.3.2'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
    }
}
</code>```

Hope this helps. And make sure your internet is connected.

Title: android studio gradle erro

Body:
Try this:

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.3.2'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
    }
}

Hope this helps. And make sure your internet is connected.


问:
getting null pass String from fragment to the activiy using bundle
Well this will sound silly but I am using bundle to store my Data within, and trying to pass this bundle from the fragment to the hosting activity, and testing the data using a toast, but the toast is empty! I cant find the reason why this is happening since i made sure to fill the data correctly
My code in the fragment is:

```<code> @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_parent_register, container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        setUpViews();
        setRecyclerAdapter();
    }

    private void setUpViews() {
        fullNameEditText = (EditText) rootView.findViewById(R.id.fragment_parent_register_fullName);
        emailEditText = (EditText) rootView.findViewById(R.id.fragment_parent_register_email);
        passwordEditText = (EditText) rootView.findViewById(R.id.fragment_parent_register_password);
        fullName = fullNameEditText.getText().toString();
        email= emailEditText.getText().toString();
        password = passwordEditText.getText().toString();
        Bundle parentData = new Bundle();
        parentData.putString(KEY_PARENT_FULL_NAME,fullName);
        parentData.putString(KEY_PARENT_EMAIL,email);
        parentData.putString(KEY_PARENT_PASSWORD,password);

        Intent intent = getActivity().getIntent();
        intent.putExtras(parentData);
</code>```

in the activity is :

```<code>  registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (DataHolder.getInstance().getAccountType() == 0) {
                    Intent intent = new Intent(RegisterActivity.this, TeacherLocationActivity.class);
                    startActivity(intent);
                } else {
                /*    Intent intent = new Intent(RegisterActivity.this, StudentLocationActivity.class);
                    startActivity(intent);*/
                    Bundle parentData = getIntent().getExtras();
                    if (parentData != null)
                    {
                        Toast.makeText(RegisterActivity.this, parentData.getString(KEY_PARENT_FULL_NAME)+parentData.getString(KEY_PARENT_EMAIL)+parentData.getString(KEY_PARENT_PASSWORD), Toast.LENGTH_SHORT).show();
                    }
                    else if (parentData == null)
                    {
                        Toast.makeText(RegisterActivity.this, "Bundle is empty", Toast.LENGTH_SHORT).show();                    }
                }
            }
        });
</code>```

答: SetupViews is executed right after views are created, which means they are most likelly empty. You need to first make onClickListener that sets the data after the user fills it in. The other code seems to be correct

Body:
Well this will sound silly but I am using bundle to store my Data within, and trying to pass this bundle from the fragment to the hosting activity, and testing the data using a toast, but the toast is empty! I cant find the reason why this is happening since i made sure to fill the data correctly
My code in the fragment is:

 @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_parent_register, container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        setUpViews();
        setRecyclerAdapter();
    }

    private void setUpViews() {
        fullNameEditText = (EditText) rootView.findViewById(R.id.fragment_parent_register_fullName);
        emailEditText = (EditText) rootView.findViewById(R.id.fragment_parent_register_email);
        passwordEditText = (EditText) rootView.findViewById(R.id.fragment_parent_register_password);
        fullName = fullNameEditText.getText().toString();
        email= emailEditText.getText().toString();
        password = passwordEditText.getText().toString();
        Bundle parentData = new Bundle();
        parentData.putString(KEY_PARENT_FULL_NAME,fullName);
        parentData.putString(KEY_PARENT_EMAIL,email);
        parentData.putString(KEY_PARENT_PASSWORD,password);

        Intent intent = getActivity().getIntent();
        intent.putExtras(parentData);

in the activity is :

  registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (DataHolder.getInstance().getAccountType() == 0) {
                    Intent intent = new Intent(RegisterActivity.this, TeacherLocationActivity.class);
                    startActivity(intent);
                } else {
                /*    Intent intent = new Intent(RegisterActivity.this, StudentLocationActivity.class);
                    startActivity(intent);*/
                    Bundle parentData = getIntent().getExtras();
                    if (parentData != null)
                    {
                        Toast.makeText(RegisterActivity.this, parentData.getString(KEY_PARENT_FULL_NAME)+parentData.getString(KEY_PARENT_EMAIL)+parentData.getString(KEY_PARENT_PASSWORD), Toast.LENGTH_SHORT).show();
                    }
                    else if (parentData == null)
                    {
                        Toast.makeText(RegisterActivity.this, "Bundle is empty", Toast.LENGTH_SHORT).show();                    }
                }
            }
        });