问:
Leaflet markers refresh with ajax filter success?
I am not sure, how to reload the map or rather reload all available markers, after this ajax filter is on success. I am not really good with Jquery and JS, so please bear with me.

Here is what I have in the page:

```<code><div id="mapwrap"></div> //this is my Leaflet map div
<div id="response"></div> //this is where the results are inserted
<div id="postlist"><?php post_liste();?></div>
</code>```

The filtering of the posts works fine, the marker divs are added for each item, however I cannot get the map to resize/reload/refresh or remove/refresh/reload the marker array.

This is the ajax filter, which is called right after my divs:

```<code><script type="text/javascript">
jQuery(function($){
$('#filter').submit(function(){
    var filter = $('#filter');
    $.ajax({
        url:filter.attr('action'),
        data:filter.serialize(), // form data
        type:filter.attr('method'), // POST
        beforeSend:function(xhr){
            filter.find('button').text('Processing...'); // changing the button label
        },
        success:function(data){
            filter.find('button').text('Apply filter'); // changing the button label back
            $('#response').html(data); // insert data
            $('#postlist').remove();
            // reload markers, I tried:
            // map.clearLayers();
            // map._resetView(map.getCenter(), map.getZoom(), true);
            // map.invalidateSize();
        }
    });
    return false;
});
});
</script>
</code>```

The Map script itself is in another file.

```<code>// for rendering the Leaflet Map

var map;

(function ($) {
  $(document).ready(function () {
map = L.map('mapwrap', {scrollWheelZoom: false}).setView([51.51, 9.19], 6);

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
  maxZoom: 18,
  attribution: '© <a href="http://openstreetmap.org">OpenStreetMap</a>, ' +
    '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
    'Imagery © <a href="http://mapbox.com">Mapbox</a>',
  id: 'mapbox.streets',
  //layers: [ group ],
}).addTo( map );

var LeafIcon = L.Icon.extend({
  options: {
    iconSize:     [43, 57],
    iconAnchor:   [21, 57],
    popupAnchor:  [0, -43],
  }
});

var markers = [];

var marker = [];
$.each($('.marker'), function () {
  var lat = $(this).attr('data-lat');
  var lng = $(this).attr('data-lng');
  var name = $(this).attr('data-title');
  var link = $(this).attr('data-url');
  var icon = $(this).attr('data-icon');
  marker = [ name, lat, lng, icon, link ];
  markers.push(marker);
});

var group = new L.featureGroup().addTo(map);

for (var i=0; i<markers.length; i++) {

  var myIcon = new LeafIcon({iconUrl: markers[i][3] });
  var marker = new L.marker([markers[i][1],markers[i][2]], {icon: myIcon });
      marker.bindPopup(markers[i][0])
      marker.addTo(group);
}

// this is for getting different zoom levels on sub-pages, where the mapwrap is smaller
$(window).on('orientationchange pageshow resize', function () {
    $("#mapwrap").height();
    map.invalidateSize();
    if ($("#mapwrap").height() < 400 ) { map.fitBounds(group.getBounds(), { maxZoom: 10 }); }
}).trigger('resize');

  });
})(jQuery);
</code>```

I thought maybe I could set a kind of Timeout to the map script function, but that didn't work. The thing is, whatever I put into the function beginning with map.something, doesn't work - console doesn't give me any clues.

What would be possible? Thanks for any help in advance!

Body:
I am not sure, how to reload the map or rather reload all available markers, after this ajax filter is on success. I am not really good with Jquery and JS, so please bear with me.

Here is what I have in the page:

 //this is my Leaflet map div

 //this is where the results are inserted

<?php post_liste();?>

The filtering of the posts works fine, the marker divs are added for each item, however I cannot get the map to resize/reload/refresh or remove/refresh/reload the marker array.

This is the ajax filter, which is called right after my divs:

The Map script itself is in another file.

// for rendering the Leaflet Map

var map;

(function ($) {
  $(document).ready(function () {
map = L.map('mapwrap', {scrollWheelZoom: false}).setView([51.51, 9.19], 6);

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
  maxZoom: 18,
  attribution: '© OpenStreetMap, ' +
    'CC-BY-SA, ' +
    'Imagery © Mapbox',
  id: 'mapbox.streets',
  //layers: [ group ],
}).addTo( map );

var LeafIcon = L.Icon.extend({
  options: {
    iconSize:     [43, 57],
    iconAnchor:   [21, 57],
    popupAnchor:  [0, -43],
  }
});

var markers = [];

var marker = [];
$.each($('.marker'), function () {
  var lat = $(this).attr('data-lat');
  var lng = $(this).attr('data-lng');
  var name = $(this).attr('data-title');
  var link = $(this).attr('data-url');
  var icon = $(this).attr('data-icon');
  marker = [ name, lat, lng, icon, link ];
  markers.push(marker);
});

var group = new L.featureGroup().addTo(map);

for (var i=0; i<markers.length; i++) {

  var myIcon = new LeafIcon({iconUrl: markers[i][3] });
  var marker = new L.marker([markers[i][1],markers[i][2]], {icon: myIcon });
      marker.bindPopup(markers[i][0])
      marker.addTo(group);
}

// this is for getting different zoom levels on sub-pages, where the mapwrap is smaller
$(window).on('orientationchange pageshow resize', function () {
    $("#mapwrap").height();
    map.invalidateSize();
    if ($("#mapwrap").height() < 400 ) { map.fitBounds(group.getBounds(), { maxZoom: 10 }); }
}).trigger('resize');

  });
})(jQuery);

I thought maybe I could set a kind of Timeout to the map script function, but that didn't work. The thing is, whatever I put into the function beginning with map.something, doesn't work - console doesn't give me any clues.

What would be possible? Thanks for any help in advance!

Body:
Not exactly sure why you wrap your code into so many IIFE's.

You are trying to re-use a variable map between different <script>'s, but it is defined in a function scope / closure. Therefore it is not accessible from outside that scope. Instead, you should declare it globally (either map, window.map or var map at the root scope, i.e. not inside any function)

// AJAX code unchanged, using map variable.

// In your map script
var map;

$(document).ready(function () {
  // do your stuff but DO NOT re-declare `var map`, just re-use `map`.
  map = L.map('mapwrap', options);
});

Make sure you understand How do JavaScript closures work?


来源: stackexchange

问:
.htaccess - Force https, force to subfolder, force www, don't break site
I have been having a very difficult time editing my .htaccess file to do these three things together.  I have been able to get each part separately but I just do not understand how the logic flow works to get them all to work.

This is the best I have been able to pull together using the demo at bluehost support
http://helpdesk.bluehost.com/index.php/kb/article/000347

I appreciate any help resolving this issue.

```<code># Use PHP5 Single php.ini as default
AddHandler application/x-httpd-php5s .php
# Bluehost.com
# .htaccess main domain to subdirectory redirect
# Copy and paste the following code into the .htaccess file
# in the public_html folder of your hosting account
# make the changes to the file according to the instructions.
# Do not change this line.
RewriteEngine on
# Change yourdomain.com to be your main domain.
RewriteCond %{HTTP_HOST} ^(www.)?sampleurl.com$
# Change 'subdirectory' to be the directory you will use for your main domain.
RewriteCond %{REQUEST_URI} !^/folder/
# Don't change this line.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Change 'subdirectory' to be the directory you will use for your main domain.
RewriteRule ^(.*)$ /folder/$1
# Change yourdomain.com to be your main domain again.
# Change 'subdirectory' to be the directory you will use for your main domain
# followed by / then the main file for your folder, index.php, index.html, etc.
RewriteCond %{HTTP_HOST} ^(www.)?sampleurl.com$
RewriteRule ^(/)?$ folder/index.php

RewriteCond %{HTTP_HOST} ^sampleurl\.com$ [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{SERVER_PORT} 80
RewriteRule (.*) https://www.sampleurl.com/$1 [L]

# For security reasons, Option all cannot be overridden.
# Options All -Indexes
# Options ExecCGI Includes IncludesNOEXEC SymLinksIfOwnerMatch -Indexes
</code>```

Update:

Well after a long time using the following I have run into issues.

```<code>IndexIgnore *
RewriteEngine On

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} !^/site/
RewriteRule (.*) https://www.example.com/site/$1 [L,R]

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} ^/site/
RewriteRule (.*) https://www.example.com/$1 [L,R]

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 443
RewriteCond %{REQUEST_URI} !^/site/
RewriteRule (.*) https://www.example.com/site/$1 [L,R]
</code>```

New Issues.

Bluehost has an application that quickly installs and updates open source applications like wordpress, joomla, phpbb etc.  Well apparently my new super .htaccess file completely breaks their system.  The only way I can run updates and installs is to move the .htaccess to .htaccess.bak until the upgrade or install is complete.  Then move it back.

I can't create any .htaccess on other sites that I host in other directories.  e.g. I have a master account that I store in /www/site/ that this script forces requests into.  Unfortunately my other sites stored in /www/site2/ and /www/site3/ don't work well.  First I have to create a blank .htaccess to prevent it from pulling the .htaccess above found in /www/.  For some reason if I try to do anything like force www.site2.com I get 500 error's saying I am forcing too many redirects.

I have a theory that my solution above needs to be a little more specific, to make sure it only effects request sent to example.com.  (I think the line with anything not containing /site/ is a little to broad).

I appreciate any support resolving this.  Would save me a bit of headaches!

Update II:

I do not believe I have access to apache config.  Only option I see in cpanel is apache handlers (not really sure what that section does).

I will submit a ticket to see what location the simplescripts server runs from.  I believe it runs from "https://www.simplescripts.com".  What edit would you recommend I add to ignore this domain?

My host bluehost starts you with a primary account and then subdomains.  The primary account's location is set at user\www.  Unfortunatly this gets messy when you try to host multiple domains.  That is why I use .htaccess to force requests that hit that directory into the \site\ directory.  Thus trapping the primary site into the \site\ directory.

I think the relocation issue I was having with one of my subdomains was due to wordpress trying to force a domain without www and then me writing an .htaccess file forcing www.  That caused the infinite loop, not my .htaccess file this thread is about.  If I can resolve the simplescripts issue I am gmoney ;)

答:
This seems to do everything I needed.  Probably a shorter way to get this done but it works!
    IndexIgnore *
    RewriteEngine On</p>

```<code>RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} !^/folder/
RewriteRule (.*) https://www.example.com/folder/$1 [L,R]

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} ^/folder/
RewriteRule (.*) https://www.example.com/$1 [L,R]

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 443
RewriteCond %{REQUEST_URI} !^/folder/
RewriteRule (.*) https://www.example.com/folder/$1 [L,R]
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have been having a very difficult time editing my .htaccess file to do these three things together.  I have been able to get each part separately but I just do not understand how the logic flow works to get them all to work.

This is the best I have been able to pull together using the demo at bluehost support
http://helpdesk.bluehost.com/index.php/kb/article/000347

I appreciate any help resolving this issue.

# Use PHP5 Single php.ini as default
AddHandler application/x-httpd-php5s .php
# Bluehost.com
# .htaccess main domain to subdirectory redirect
# Copy and paste the following code into the .htaccess file
# in the public_html folder of your hosting account
# make the changes to the file according to the instructions.
# Do not change this line.
RewriteEngine on
# Change yourdomain.com to be your main domain.
RewriteCond %{HTTP_HOST} ^(www.)?sampleurl.com$
# Change 'subdirectory' to be the directory you will use for your main domain.
RewriteCond %{REQUEST_URI} !^/folder/
# Don't change this line.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Change 'subdirectory' to be the directory you will use for your main domain.
RewriteRule ^(.*)$ /folder/$1
# Change yourdomain.com to be your main domain again.
# Change 'subdirectory' to be the directory you will use for your main domain
# followed by / then the main file for your folder, index.php, index.html, etc.
RewriteCond %{HTTP_HOST} ^(www.)?sampleurl.com$
RewriteRule ^(/)?$ folder/index.php

RewriteCond %{HTTP_HOST} ^sampleurl\.com$ [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{SERVER_PORT} 80
RewriteRule (.*) https://www.sampleurl.com/$1 [L]

# For security reasons, Option all cannot be overridden.
# Options All -Indexes
# Options ExecCGI Includes IncludesNOEXEC SymLinksIfOwnerMatch -Indexes

Update:

Well after a long time using the following I have run into issues.

IndexIgnore *
RewriteEngine On

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} !^/site/
RewriteRule (.*) https://www.example.com/site/$1 [L,R]

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} ^/site/
RewriteRule (.*) https://www.example.com/$1 [L,R]

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 443
RewriteCond %{REQUEST_URI} !^/site/
RewriteRule (.*) https://www.example.com/site/$1 [L,R]

New Issues.

Bluehost has an application that quickly installs and updates open source applications like wordpress, joomla, phpbb etc.  Well apparently my new super .htaccess file completely breaks their system.  The only way I can run updates and installs is to move the .htaccess to .htaccess.bak until the upgrade or install is complete.  Then move it back.

I can't create any .htaccess on other sites that I host in other directories.  e.g. I have a master account that I store in /www/site/ that this script forces requests into.  Unfortunately my other sites stored in /www/site2/ and /www/site3/ don't work well.  First I have to create a blank .htaccess to prevent it from pulling the .htaccess above found in /www/.  For some reason if I try to do anything like force www.site2.com I get 500 error's saying I am forcing too many redirects.

I have a theory that my solution above needs to be a little more specific, to make sure it only effects request sent to example.com.  (I think the line with anything not containing /site/ is a little to broad).

I appreciate any support resolving this.  Would save me a bit of headaches!

Update II:

I do not believe I have access to apache config.  Only option I see in cpanel is apache handlers (not really sure what that section does).

I will submit a ticket to see what location the simplescripts server runs from.  I believe it runs from "https://www.simplescripts.com".  What edit would you recommend I add to ignore this domain?

My host bluehost starts you with a primary account and then subdomains.  The primary account's location is set at user\www.  Unfortunatly this gets messy when you try to host multiple domains.  That is why I use .htaccess to force requests that hit that directory into the \site\ directory.  Thus trapping the primary site into the \site\ directory.

I think the relocation issue I was having with one of my subdomains was due to wordpress trying to force a domain without www and then me writing an .htaccess file forcing www.  That caused the infinite loop, not my .htaccess file this thread is about.  If I can resolve the simplescripts issue I am gmoney ;)

Body:
This seems to do everything I needed.  Probably a shorter way to get this done but it works!
    IndexIgnore *
    RewriteEngine On

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} !^/folder/
RewriteRule (.*) https://www.example.com/folder/$1 [L,R]

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} ^/folder/
RewriteRule (.*) https://www.example.com/$1 [L,R]

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 443
RewriteCond %{REQUEST_URI} !^/folder/
RewriteRule (.*) https://www.example.com/folder/$1 [L,R]


问:
How to display names instead of id's in GridView Yii2?
I have a question here. I set the relations between item and sale tables and now my GridView column of Item name is displaying id's of it. But what I need is that it would display Item names instead of ID's. How should I do that?

Here is my GridView column:

```<code>[
     'attribute' => 'item_id',
      'value' =>
],
</code>```

I was thinking that I should write a function with if statement, but I have a lot of names and it would be very long. Is there an easier way to solve it?

答:
In my case it is company table and products table.
    comp_id is is the primary key in the company table and it has related with products table.

```<code><?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'prod_id',
            'name',
            'description:ntext',
            [
                'attribute' => 'comp_id',
                'value'     => 'comp.name' //getComp()
            ],

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

//getcomp function the product model page.
 public function getComp()
    {`enter code here`
        return $this->hasOne(Company::className(), ['comp_id' => 'comp_id']);
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a question here. I set the relations between item and sale tables and now my GridView column of Item name is displaying id's of it. But what I need is that it would display Item names instead of ID's. How should I do that?

Here is my GridView column:

[
     'attribute' => 'item_id',
      'value' =>
],

I was thinking that I should write a function with if statement, but I have a lot of names and it would be very long. Is there an easier way to solve it?

Body:
In my case it is company table and products table.
    comp_id is is the primary key in the company table and it has related with products table.

<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'prod_id',
            'name',
            'description:ntext',
            [
                'attribute' => 'comp_id',
                'value'     => 'comp.name' //getComp()
            ],

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

//getcomp function the product model page.
 public function getComp()
    {`enter code here`
        return $this->hasOne(Company::className(), ['comp_id' => 'comp_id']);
    }


问:
Built in function for searching sorted array in C
Is there a built in function in C for searching an integer array that has been sorted?

I can easily implement it but it seems like such a common thing - would be weird if there is no library/built in C function.

答: stdlib.h actually contains some sorting and searching functions. qsort will let you sort an array in place, and bsearch will perform binary search on a sorted array for you. You do have to provide a comparison function in both cases.


问:
Android: Same Image needs to be added in all drawable folders?
I am directly adding images in drawable folders and it is coming fine with ImageView tag android:src="@drawable/image_name" but I wonder what to do with the other drawable folders as shown below.

Do I need to add same image in all drawable folders or my way of adding images in drawable folders is wrong?

Please help me!

答: Just put it in the drawable folder, no need to put it in other drawable-... folders because those folders and contents inside are created automatically by android studio.</p>


问:
prototype PeriodicalExecuter move div effect
Trying to move a div down while the request is being made then move the div back up in it's original position on complete. But its only getting up with each request. Here is the code</p>

```<code>new PeriodicalExecuter(function() {
    new Effect.Move('content', {
        x:0,
        y:15,
        duration:1
    });;
    new Ajax.Updater('content','/getcontent', {
        asynchronous:true,
        evalScripts:true,
        onComplete:function(request, json) {
            new Effect.Move('content', {x:0,y:-15,duration:1});
        },
        insertion:Insertion.Top,
        requestHeaders:['X-Update', 'content']
    })
}, 5)
</code>```

答:
You're expecting the onComplete Move to execute after the first Move has completed. This is unlikely to happen because both Move and Ajax.Updater are asynchronous. The solution is to switch to absolute Moves and to cancel the original Move before the second one conflicts with it. </p>

```<code>$('content').store('originalOffset', $('content').cumulativeOffset());

new PeriodicalExecuter(function() {
    $('content').store(
     'move',
      new Effect.Move('content', {
        x:$('content').retrieve('originalOffset').left,
        y:$('content').retrieve('originalOffset').top + 15,
        duration:1,
        mode: 'absolute'
      })
    );
    new Ajax.Updater('content','/getcontent', {
        asynchronous:true,
        evalScripts:true,
        onCreate: function() {
         $('content').retrieve('move').cancel();
        },
        onComplete:function(request, json) {
            new Effect.Move(
             'content', {
              x:$('content').retrieve('originalOffset').left,
              y:$('content').retrieve('originalOffset').top,
              duration:1,
              mode: 'absolute'
             }
            );
        },
        insertion:Insertion.Top,
        requestHeaders:['X-Update', 'content']
    })
}, 5);
</code>```

Body:
Trying to move a div down while the request is being made then move the div back up in it's original position on complete. But its only getting up with each request. Here is the code

new PeriodicalExecuter(function() {
    new Effect.Move('content', {
        x:0,
        y:15,
        duration:1
    });;
    new Ajax.Updater('content','/getcontent', {
        asynchronous:true,
        evalScripts:true,
        onComplete:function(request, json) {
            new Effect.Move('content', {x:0,y:-15,duration:1});
        },
        insertion:Insertion.Top,
        requestHeaders:['X-Update', 'content']
    })
}, 5)

Body:
You're expecting the onComplete Move to execute after the first Move has completed. This is unlikely to happen because both Move and Ajax.Updater are asynchronous. The solution is to switch to absolute Moves and to cancel the original Move before the second one conflicts with it.

$('content').store('originalOffset', $('content').cumulativeOffset());

new PeriodicalExecuter(function() {
    $('content').store(
     'move',
      new Effect.Move('content', {
        x:$('content').retrieve('originalOffset').left,
        y:$('content').retrieve('originalOffset').top + 15,
        duration:1,
        mode: 'absolute'
      })
    );
    new Ajax.Updater('content','/getcontent', {
        asynchronous:true,
        evalScripts:true,
        onCreate: function() {
         $('content').retrieve('move').cancel();
        },
        onComplete:function(request, json) {
            new Effect.Move(
             'content', {
              x:$('content').retrieve('originalOffset').left,
              y:$('content').retrieve('originalOffset').top,
              duration:1,
              mode: 'absolute'
             }
            );
        },
        insertion:Insertion.Top,
        requestHeaders:['X-Update', 'content']
    })
}, 5);


问:
bootstrap modal ajax petition
I have tried to show the data into the dialog but this does not work, the modal show the data as written in the html...any help? </p>

```<code> $(document).ready(function(){

   $('#billDetail').on('show.bs.modal', function (event) {

    var button = $(event.relatedTarget); // Button that triggered the modal
    var billId = button.data('whatever');

    var url = "/admin/bills/find";
    $.ajax({
            type: "GET",
            dataType: 'json',
            url: url,
            data: {
                "billId" : billId
                }, // Adjuntar los campos del formulario enviado.
            success: function(data)
            {
                var modal = $(this)
                modal.find('.modal-title').text('New message to ' + data)
                modal.find('.modal-body input').val(data)
                modal.show();
           }

      });

    });

});
</code>```

答:
It should be .html not .text

```<code>modal.find('.modal-title').html('New message to ' + data);
</code>```

Hope this will help you.

Title: bootstrap modal ajax petition

Body:
I have tried to show the data into the dialog but this does not work, the modal show the data as written in the html...any help?

 $(document).ready(function(){

   $('#billDetail').on('show.bs.modal', function (event) {

    var button = $(event.relatedTarget); // Button that triggered the modal
    var billId = button.data('whatever');

    var url = "/admin/bills/find";
    $.ajax({
            type: "GET",
            dataType: 'json',
            url: url,
            data: {
                "billId" : billId
                }, // Adjuntar los campos del formulario enviado.
            success: function(data)
            {
                var modal = $(this)
                modal.find('.modal-title').text('New message to ' + data)
                modal.find('.modal-body input').val(data)
                modal.show();
           }

      });

    });

});

Body:
It should be .html not .text

modal.find('.modal-title').html('New message to ' + data);

Hope this will help you.


问:
Deploy Rails app using capstrano from inside a docker container
I managed to dockerize my rails application for development and it works great. Before this I had a deploy setup using Capistrano. Now I would like to try and deploy using the same Capistrano but executed from within the docker container. My question is can i use the same ssh key from my host machine or should I generate a new key inside the container? The last option does not sound good to me since it would have to be recreated when the container gets destroyed. I am aware that in the long run I would probably be better off setting the production server to run docker and install through docker machine but so far I just like to keep the setup I have already on production.

Anyone else have tried this?

答:
You can mount your SSH key into the container at runtime.

docker run -v /path/to/host/ssh-key:/path/to/container/ssh-key <image> <command>

ssh-key will be available in the container at /path/to/container/ssh-key


问:
Clicking an element and adding a class to an element to a different element which has the same index in another node list
I have 2 sets of the same images.
1 is the gallery
another is the list of images that are display: none; until the corresponding image is clicked.
(essentially a light box)

eg:

```<code><ul id="gallery">
    <li><img class="gallery-image" src="dog"></li>
    <li><img class="gallery-image" src="cat"></li>
    <li><img class="gallery-image" src="rabbit"></li>
</ul>

<ul id="modal">
    <li><img class="modal-image" src="dog"></li>
    <li><img class="modal-image" src="cat"></li>
    <li><img class="modal-image" src="rabbit"></li>
</ul>
</code>```

I have looped over images in the gallery and added an even listener to each img.

These images are in the same order in both lists and have the same index when i use document.getElementsByClassName and am returned the nodelist. (both have different variable names. eg galleryImage[0] and modalImage[0])
Is there a way for me add a class to the corresponding "modal-image" when clicking a "gallery-image" using the node list?
Essentially when galleryImage[0] is closed I want to add a class to modalImage[0].

Are there methods to do this? What is the approach to take?

I have found examples and have been given "answers" but so far all include assigning an id with an index number to each image and would prefer to have all the js in 1 file and keep both tidy and also learn how to play with nodelists.

Also would appreciate if someone can explain their answer to understand the logic behind it rather than an "answer"

Thank you in advance

答:
Seems to me that your question boils down to this: "Given a reference to a DOM element, how can I determine its index in a NodeList?" Because the second part about getting the corresponding element in another list is simple once you have the index.

So you can use the array .indexOf() method to find the index of an item within an array, or via .call() you can use that method on a NodeList:

```<code>var index = Array.prototype.indexOf.call(galleryImages, elementToFind)
</code>```

...after which index will be the index of the element you're looking for. (Or -1 if it wasn't found, but in your case you know it will be found.) So then modalImages[index] is the corresponding item in the other list.

Also, not what you're asking about, but rather than binding click handlers to every image in a loop, I would bind a single handler to the containing UL element, and within that handler test the event.target to see if it was an IMG element. This is called delegated event handling: click events on elements "bubble up" through their containing elements, so clicks on any of your gallery IMG elements can be handled at the level of the UL.

For demonstration purposes, on click I'm assigning a selected class that make the corresponding item yellow (and removing any previous selection).

// Get references to the UL elements:
var galleryContainer = document.getElementById("gallery")
var modalContainer = document.getElementById("modal")

// Get the lists of IMG elements:
var galleryImages = galleryContainer.querySelectorAll(".gallery-image")
var modalImages = modalContainer.querySelectorAll(".modal-image")

// Bind click handler to gallery UL:
galleryContainer.addEventListener("click", function(event) {
  // If the target of the click wasn't an element we care about just return immediately
  if (event.target.tagName.toLowerCase() != "img")
    return

  // Check for a current .selected element, and if it exists remove the class from it
  var currentSelected = document.querySelector(".selected")
  if (currentSelected)
    currentSelected.classList.remove("selected")

  // Find the index of the current IMG in the list, and use that index
  // to get the corresponding item in the other list
  var index = Array.prototype.indexOf.call(galleryImages, event.target)
  modalImages[index].classList.add("selected")
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.selected { background-color: yellow; }</code>```

```

Body:
I have 2 sets of the same images.
1 is the gallery
another is the list of images that are display: none; until the corresponding image is clicked.
(essentially a light box)

eg:

I have looped over images in the gallery and added an even listener to each img.

These images are in the same order in both lists and have the same index when i use document.getElementsByClassName and am returned the nodelist. (both have different variable names. eg galleryImage[0] and modalImage[0])
Is there a way for me add a class to the corresponding "modal-image" when clicking a "gallery-image" using the node list?
Essentially when galleryImage[0] is closed I want to add a class to modalImage[0].

Are there methods to do this? What is the approach to take?

I have found examples and have been given "answers" but so far all include assigning an id with an index number to each image and would prefer to have all the js in 1 file and keep both tidy and also learn how to play with nodelists.

Also would appreciate if someone can explain their answer to understand the logic behind it rather than an "answer"

Thank you in advance

Body:
Seems to me that your question boils down to this: "Given a reference to a DOM element, how can I determine its index in a NodeList?" Because the second part about getting the corresponding element in another list is simple once you have the index.

So you can use the array .indexOf() method to find the index of an item within an array, or via .call() you can use that method on a NodeList:

var index = Array.prototype.indexOf.call(galleryImages, elementToFind)

...after which index will be the index of the element you're looking for. (Or -1 if it wasn't found, but in your case you know it will be found.) So then modalImages[index] is the corresponding item in the other list.

Also, not what you're asking about, but rather than binding click handlers to every image in a loop, I would bind a single handler to the containing UL element, and within that handler test the event.target to see if it was an IMG element. This is called delegated event handling: click events on elements "bubble up" through their containing elements, so clicks on any of your gallery IMG elements can be handled at the level of the UL.

For demonstration purposes, on click I'm assigning a selected class that make the corresponding item yellow (and removing any previous selection).

// Get references to the UL elements:
var galleryContainer = document.getElementById("gallery")
var modalContainer = document.getElementById("modal")

// Get the lists of IMG elements:
var galleryImages = galleryContainer.querySelectorAll(".gallery-image")
var modalImages = modalContainer.querySelectorAll(".modal-image")

// Bind click handler to gallery UL:
galleryContainer.addEventListener("click", function(event) {
  // If the target of the click wasn't an element we care about just return immediately
  if (event.target.tagName.toLowerCase() != "img")
    return

  // Check for a current .selected element, and if it exists remove the class from it
  var currentSelected = document.querySelector(".selected")
  if (currentSelected)
    currentSelected.classList.remove("selected")

  // Find the index of the current IMG in the list, and use that index
  // to get the corresponding item in the other list
  var index = Array.prototype.indexOf.call(galleryImages, event.target)
  modalImages[index].classList.add("selected")
});

.selected { background-color: yellow; }

<ul id="gallery">
    <li><img class="gallery-image" src="dog" alt="dog"></li>
    <li><img class="gallery-image" src="cat" alt="cat"></li>
    <li><img class="gallery-image" src="rabbit" alt="rabbit"></li>
</ul>
<ul id="modal">
    <li><img class="modal-image" src="dog" alt="dog"></li>
    <li><img class="modal-image" src="cat" alt="cat"></li>
    <li><img class="modal-image" src="rabbit" alt="rabbit"></li>
</ul>


问:
Which one is better about PHP class for query?
I have PHP class that contain function for query data from database. The first one is

```<code>class x{

  public $var1;
  public $var2;

  function __construct(){ }

  function getX($primkey){
    $sql = mysql_qyery("SELECT * FROM x_table WHERE primkey='$primkey'");
    $row = mysq;_fetch_assoc($sql);
    $this->var1 = $row['var1'];
    $this->var2 = $row['var2'];
  }

}
</code>```

and another on is

```<code>class x{

  public $var1;
  public $var2;

  function __construct(){ }

  function getX($primkey){
    $sql = mysql_qyery("SELECT * FROM x_table WHERE primkey='$primkey'");
    $row = mysq;_fetch_assoc($sql);
    return $row;
  }

}
</code>```

two class has some difference on function getX(). The first class put data from database to class variables but the second one return whole data from database via array.

I would like to know about performance of two class, which one is better. and which one is good for programming or any idea?

Regards.

答:
With the first form, you have the flexibility to do additional conversions and asymmetrical mappings. So in that sense, you're truly creating a Model class that does an abstract representation of your actual data source.

With the second form, if you follow the Convention Over Configuration (CoC) paradigm and clearly define your conventions, it may work. But, down the line, you may run into situations where you'll have to make exceptions. I would recommend the more flexible approach above, as an anticipation of future exceptions.

Tangential: In case you're not writing your own object mappings purely for educational purposes, or for some other plausible reason, have you looked at RedBeanPHP or other alternatives?

Body:
I have PHP class that contain function for query data from database. The first one is

class x{

  public $var1;
  public $var2;

  function __construct(){ }

  function getX($primkey){
    $sql = mysql_qyery("SELECT * FROM x_table WHERE primkey='$primkey'");
    $row = mysq;_fetch_assoc($sql);
    $this->var1 = $row['var1'];
    $this->var2 = $row['var2'];
  }

}

and another on is

class x{

  public $var1;
  public $var2;

  function __construct(){ }

  function getX($primkey){
    $sql = mysql_qyery("SELECT * FROM x_table WHERE primkey='$primkey'");
    $row = mysq;_fetch_assoc($sql);
    return $row;
  }

}

two class has some difference on function getX(). The first class put data from database to class variables but the second one return whole data from database via array.

I would like to know about performance of two class, which one is better. and which one is good for programming or any idea?

Regards.


问:
What should be the number of hidden neurons?
In a regression problem,to predict travel time based on some traffic data.I have

1500 data,input feature is 7 and output is single node,I want to use MLP(Multi layer perceptron),activation function = ReLU and backpropagation algo.

How many neurons should i choose for 1 hidden layer and also how many node i choose if i use 2 hidden layers? Any suggestion,please?

答:
The number of hidden layers and dimensions generally must be determined empirically.

Here's some information to think about:

Many problems only require one hidden layer. Problems that are easy to break down into multiple steps (image processing for example) might benefit from more layers.

Adding more layers can allow the network to simply memorize training data (overfitting the function), so make sure you use separate testing data from your training set to test for this. The same issue arises with too many neurons in a layer.

Generally, choose a number of hidden neurons between the input size and the output size, then experiment from there.


问:
Is (!activity.isFinishing()) the way to check that activity has not been destroyed? isFinishing() vs. isDestoryed()
I am getting an error message that activity has already been destroyed when FragmentManager is called. Is there a check that the FragmentManager can do before making it's transaction call or do I need to get the activity and check that it is not null or !activity.isFinishing() ?  Are there any other checks I need to do? This is what I used to do but not sure this is still the way to do it? Just curious why fragment manager would not know about the state of the activity ... I need to cover both the case where the activity is about to be destroyed and where it has already been destroyed(). In either case I don't want to commit the transaction.

UPDATE: For API 17+ activity.isDestroyed() is available. For API < 17 still need to confirm that activity.isFinishing() will detect a destroyed activity or if there is another way to do this?

```<code>  if ((activity != null) && !activity.isFinishing()) {
      fm.FragmentTransaction fragmentTransaction =
      fm.beginTransaction().replace(R.id.fragment_container, mFeedFragment).commitAllowingStatelessLoss();
  }
</code>```

答:
The best bet would be to check if Activity.isFinishing(). If true, then it is not safe to work with such Activity, if false at least we know the Activity's destruction has not been triggered.

Reasoning

Checking if an Activityis null does not mean the Activity is
destroyed. The Activity can be destroyed and still hold data
created in it.

Checking if Activity.isDestroyed() from the docs states,

Returns true if the final onDestroy() call has been made on the Activity, so this instance is now dead.

What does DEAD instance means idk, I could not find out on the
internet a complete answer but clearly it does not mean null in this scenario.
Hence, dead instance != null.

Checking if Activity.isFinishing() from the docs states,

Check to see whether this activity is in the process of finishing, either because you called finish() on it or someone else has
  requested that it finished. This is often used in onPause() to
  determine whether the activity is simply pausing or completely
  finishing.

Calling Activity.finish() will call Activity.onDestroy().
However, after doing some tests with help of Robolectric it holds that after calling
Activity.finish()

Activity.isFinishing() == true
   Activity.isDestroyed() == false

Why, check what exactly Activity.finish() method is doing?

Body:
I am getting an error message that activity has already been destroyed when FragmentManager is called. Is there a check that the FragmentManager can do before making it's transaction call or do I need to get the activity and check that it is not null or !activity.isFinishing() ?  Are there any other checks I need to do? This is what I used to do but not sure this is still the way to do it? Just curious why fragment manager would not know about the state of the activity ... I need to cover both the case where the activity is about to be destroyed and where it has already been destroyed(). In either case I don't want to commit the transaction.

UPDATE: For API 17+ activity.isDestroyed() is available. For API < 17 still need to confirm that activity.isFinishing() will detect a destroyed activity or if there is another way to do this?

  if ((activity != null) && !activity.isFinishing()) {
      fm.FragmentTransaction fragmentTransaction =
      fm.beginTransaction().replace(R.id.fragment_container, mFeedFragment).commitAllowingStatelessLoss();
  }


问:
How can I authenticate with facebook when in an iframe? Safari blocks the cookies
This is a question for anyone who's ever made an iFrame app in facebook, or a 3rd party widget that would run in a website (I'm doing the latter).
How can I authenticate with facebook? It seems that the fbs_ cookie isn't being set when I'm on Safari, because the iframe is showing my widget which is on another domain.

I heard that submitting a form with target="self" might cause Safari to treat my domain as "visited" and then the cookies would be set. It seems to work. However, the fbs cookie is STILL not being set after the whole facebook authentication popup is done. Does anyone know why? Please help me figure out how to actually auth with facebook when I'm in an iframe!

答:
Hmm strange -- I found that even in Safari facebook iframe apps work: How does Facebook set cross-domain cookies for iFrames on canvas pages?.

Does http://apps.facebook.com/runwithfriends/ not work for you in Safari?


问:
Somthing wrong with using CSV as database for a webapp?
I am using Flask to make a small webapp to manage a group project, in this website I need to manage attendances, and also meetings reports. I don't have the time to get into SQLAlchemy, so I need to know what might be the bad things about using CSV as a database.</p>

答:
I think there's nothing wrong with that as long as you abstract away from it. I.e. make sure you have a clean separation between what you write and how you implement i . That will bloat your code a bit, but it will make sure you can swap your CSV storage in a matter of days.

I.e. pretend that you can persist your data as if you're keeping it in memory. Don't write "openCSVFile" in you flask app. Use initPersistence(). Don't write "csvFile.appendRecord()". Use "persister.saveNewReport()". When and if you actually realise CSV to be a bottleneck, you can just write a new persister plugin.

There are added benefits like you don't have to use a mock library in tests to make them faster. You just provide another persister.


问:
What is the difference between compileSdkVersion and targetSdkVersion?
I have looked at the documentation for building with Gradle, but I'm still not sure what the difference between compileSdkVersion and targetSdkVersion is.

All it says is:

```<code>The `compileSdkVersion` property specifies the compilation target.
</code>```

Well, what is the "compilation target"?

I see two possible ways to interpret this:

compileSdkVersion is the version of the compiler used in building the app, while targetSdkVersion is the "API level that the application targets". (If this were the case, I'd assume compileSdkVersion must be greater than or equal to the targetSdkVersion?

They mean the same thing. "compilation target" == "the API level that the application targets"

Something else?

I see that this question has been asked before, but the one answer just quotes the doc, which is what is unclear to me.

答:
My 2 cents: Compile against any version of the SDK but take care not to call any APIs that your "minimum SDK version" does not support. That means you "could" compile against the latest version of the SDK.

As for "target version" it simply refers to what you planned to target in the first place and have possibly tested against. If you haven't done the due diligence then this is the way to inform Android that it needs to perform some additional checks before it deploys your lets say "Lollipop" targeted app on "Oreo".

So the "target version" is obviously not lower than your "minimum SDK version" but it can't be higher than your "compiled version".

ContentLicense: CC BY-SA 4.0

Body:
I have looked at the documentation for building with Gradle, but I'm still not sure what the difference between compileSdkVersion and targetSdkVersion is.

All it says is:

The `compileSdkVersion` property specifies the compilation target.

Well, what is the "compilation target"?

I see two possible ways to interpret this:

compileSdkVersion is the version of the compiler used in building the app, while targetSdkVersion is the "API level that the application targets". (If this were the case, I'd assume compileSdkVersion must be greater than or equal to the targetSdkVersion?

They mean the same thing. "compilation target" == "the API level that the application targets"

Something else?

I see that this question has been asked before, but the one answer just quotes the doc, which is what is unclear to me.


问:
How do I output a result of an each statement to a variable?
I have this code that prints each character of a string twice:

```<code>r = "12345"
r.split("").each do |ch|
  puts "#{ch}#{ch}"
end
</code>```

I get this output:

```<code>11
22
33
44
55
</code>```

I want to store the output "1122334455" in a variable. How do I rewrite the code to do this?

答:
Sagar and Sebastian's answers are the straightforward way to do this, but if you want to stick to your original code (iterate over the characters), then this is another way:</p>

```<code>variable = r.each_char.with_object(""){|c, s| s << c * 2}
# => "1122334455"
</code>```

Body:
I have this code that prints each character of a string twice:

r = "12345"
r.split("").each do |ch|
  puts "#{ch}#{ch}"
end

I get this output:

11
22
33
44
55

I want to store the output "1122334455" in a variable. How do I rewrite the code to do this?

Body:
Sagar and Sebastian's answers are the straightforward way to do this, but if you want to stick to your original code (iterate over the characters), then this is another way:

variable = r.each_char.with_object(""){|c, s| s << c * 2}
# => "1122334455"


问:
statements run in main but not when called from a function
Sorry. I really tried to solve this myself. But i don't understand. The statements ran okay when i place them in main. But when i call them in a function from main, segmentation fault happens. Does it mean memory overflowed?

```<code>void displayTime(char state[]) {
    time_t totalSec = time(NULL);//total no of secs since EPOCH
    struct tm *currTime = localtime(&totalSec); //store local time in struct declared in time.h
    char *result;
    strftime(result, 20, "%Y:%m:%d %H:%M:%S", currTime); //E.g. 2017:11:12 12:30:48 Max is 20 characters including \0
    printf("Program at %s\n", result );
}

int main() {
    displayTime("started");
    return 0;
}
</code>```

答:
Allocate memory in result that is what is causing problem.

In your case it will be

```<code>result = malloc(sizeof(char)*BUFFSIZE);
if( result == NULL ){
   fprintf(stderr,"Error");
    exit(1);
}
</code>```

There must be a corresponding free call to the allocated memory, here it will be

free(result);

Also accessing uninitialized variable is undefined behavior.

Also without malloc you can simply do this

```<code>char result[20];

strftime(result,20, "%Y:%m:%d %H:%M:%S", currTime);
</code>```

Also my earlier edit with state is not possible. (Didn't notice that it's literal string) Since string literals belong to the read only section of memory. Now here we were trying to edit or modify it. That is wrong.

Secondly, even if it was not read only it will still not have memory to hold the characters that you would write. Because the size would not be big enough for that.

Further Explanation

To clarify the problem, look at the result variable. It is type char*. It is supposed to contain address of a char variable. Now when you declare it. Then it contains an indeterminate value.

Does it point to anything meaningful? No.

Now when you pass the variable to the function it tries to write something to a location whose address is contained in result variable. But it is not something useful and you will try to access some memory which is not even meant for you.(not permitted).

Segfaults are caused by a program trying read or write an illegal memory location.

That's what happened in your case.

Does it mean memory overflowed?

No. It has nothing to do with overflow.

Also what is the purpose of the state in your code? You are not using it anywhere in the code. You can avoid it.

Body:
Sorry. I really tried to solve this myself. But i don't understand. The statements ran okay when i place them in main. But when i call them in a function from main, segmentation fault happens. Does it mean memory overflowed?

void displayTime(char state[]) {
    time_t totalSec = time(NULL);//total no of secs since EPOCH
    struct tm *currTime = localtime(&totalSec); //store local time in struct declared in time.h
    char *result;
    strftime(result, 20, "%Y:%m:%d %H:%M:%S", currTime); //E.g. 2017:11:12 12:30:48 Max is 20 characters including \0
    printf("Program at %s\n", result );
}

int main() {
    displayTime("started");
    return 0;
}

Body:
Allocate memory in result that is what is causing problem.

In your case it will be

result = malloc(sizeof(char)*BUFFSIZE);
if( result == NULL ){
   fprintf(stderr,"Error");
    exit(1);
}

There must be a corresponding free call to the allocated memory, here it will be

free(result);

Also accessing uninitialized variable is undefined behavior.

Also without malloc you can simply do this

char result[20];

strftime(result,20, "%Y:%m:%d %H:%M:%S", currTime);

Also my earlier edit with state is not possible. (Didn't notice that it's literal string) Since string literals belong to the read only section of memory. Now here we were trying to edit or modify it. That is wrong.

Secondly, even if it was not read only it will still not have memory to hold the characters that you would write. Because the size would not be big enough for that.

Further Explanation

To clarify the problem, look at the result variable. It is type char*. It is supposed to contain address of a char variable. Now when you declare it. Then it contains an indeterminate value.

Does it point to anything meaningful? No.

Now when you pass the variable to the function it tries to write something to a location whose address is contained in result variable. But it is not something useful and you will try to access some memory which is not even meant for you.(not permitted).

Segfaults are caused by a program trying read or write an illegal memory location.

That's what happened in your case.

Does it mean memory overflowed?

No. It has nothing to do with overflow.

Also what is the purpose of the state in your code? You are not using it anywhere in the code. You can avoid it.


问:
Using strtok() to store numeric values in a 2D array
I'm trying to write a program that takes a list of numbers from a file and stores each row of numbers in a 2D array using strtok(). The problem I'm having is that when I try to store values in the rows of my 2D array, the while loop goes into an infinite loop, but when i use the line token = strtok(NULL, " ") to stop the loop, I just store the first value of each line into the first cell of each column.

What am I doing wrong? Heres is my code

```<code>int main() {
  int myArray[240][30];
  char line[240];
  char *token;
  int i, n, j;
  FILE *fp;
  fp = fopen("array_list.txt", "rt");
  j = 0;
  i = 0;
  while (fgets(line, sizeof(line), fp)) {
    token = strtok(line, " ");

    while (token != NULL) {
      n = atoi(token);
      myArray[i][j] = n;
      token = strtok(line, " ");
      printf("%d ", myArray[i][j]);
      token = strtok(NULL, " ");
      j++;
    }

    printf("\n");
    i++;
  }
  return 0;
}
</code>```

Here is an example of the file I'm trying to read.

1 98 48 55 46 12 48 43 7 73 47 33

                                                                                97 26 67 25 67 47 46 74 67 43 78 98 90 58 6 5 53 19 37 42

81 84 36 70 59 65 99 56 94 23
79 73 27 47 98 78 8 2 3 43 84 19 59 98 51 72 2 13 55 3
20 61 25 84 28 70 56 23 52 69
86 70 60 90 72
51 71 92 91 55 6 72 67 73 64 78 43 65 30 49
99 82 40 72 5 44 20 21 22 72 99 74 27 59 25 1 26 26 22 66
63 27 54 46 46
91 65 77 45 94 94 95 11 77 46 64 14
69 70 75 48 68 22 55 78 1 4
31 76 55 12 93

答:
While you can use strtok to split words in your file and then use atoi to perform the conversion to int, there are significant drawbacks to that approach. First and foremost, atoi (and all the atoX functions) provide absolutely no way to validate whether you actually converted atoi(word) to a number. (Is it really 0? -- or did the conversion just fail?)

Further, strtok + atoi is part of what strtol does for you. The rest of what long strtol (const char *nptr, char **endptr, int base) does for you is provide extensive error checking through errno, and range checking returning LONG_MIN on underflow and LONG_MAX on overflow. It provides further checking by setting endptr = nptr in the case no digits were found during conversion. Even better, when the conversion succeeds, endptr is set to the next character following the last character that was converted. (it sets you up for your next read!)

Further, with minimal effort, you can test whether the next character should be skipped before calling strtol again, allowing you to parse numbers from the file regardless of what is contained in the file. In other words, you can write an integer read routine once, and then use it with minimum modification for reading whatever file you are given.

While you do not specify how you want to fill myArray[240][30]; from the 144-values you show for your file, the following example shows you how to read those values (and values from just about any file) into an array. You need only add an additional counter or loop to put x-number of values per-row in your array, etc..

Use the constants provided for you in the various header files (e.g. errno.h, limits.h) to help you with your task. The following example reads from the filename  given on the command line (or from stdin by default if no filename is given) and will read any integer found in the file into the array arr up to a maximum of 1024 values, e.g.

```<code>#include <stdio.h>
#include <stdlib.h>     /* for strtol */
#include <string.h>     /* for strlen */
#include <limits.h>     /* for INT_MIN, INT_MAX */
#include <errno.h>      /* for errno */

#ifndef BUF_SIZ         /* set input buffer size */
#define BUF_SIZ 8192    /* gcc default, cl.exe (VS) uses 512 */
#endif

#define BASE 10         /* conversion base 10 */
#define AMAX 1024       /* max number of values to read */

int main (int argc, char **argv) {

    int arr[AMAX] = {0},            /* array to hold values */
        n = 0;                      /* number of values read */
    char buf[BUF_SIZ] = "";         /* line buffer */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    while (fgets (buf, BUF_SIZ, fp)) {      /* read each line */
        char *p = buf,                      /* pointer to buf */
            *ep = p;                        /* end pointer for strtol */
        size_t len = strlen (buf);          /* length of buf */

        /* validate complete line read */
        if (len == BUF_SIZ - 1 && buf[len - 1] != '\n') {
            fprintf (stderr, "error: line too long.\n");
            break;
        }

        while (n < AMAX && *p) {    /* n < AMAX & each starting char */
            errno = 0;                          /* reset errno */
            long tmp = strtol (p, &ep, BASE);   /* convert to long */

            /* validate conversion */
            if (p != ep) {                  /* digits converted */
                /* if no error and in range - assign to array */
                if (!errno && INT_MIN <= tmp && tmp <= INT_MAX)
                    arr[n++] = (int)tmp;
                p = ep;     /* set p to 1-past converted string */
            }

            /* find beginning of next number in buf */
            for (; *p; p++) {
                if ('0' <= *p && *p <= '9')  /* positive value */
                    break;          /* explicitly signed value */
                if ((*p == '+' || *p == '-') && '0' <= *(p+1) && *(p+1) <= '9')
                    break;
            }
        }
    }
    if (fp != stdin) fclose (fp);   /* close file if not stdin */

    for (int i = 0; i < n; i++)     /* output values read */
        printf (" arr[%3d] = %d\n", i, arr[i]);

    return 0;
}
</code>```

Example Input Files

This way, you can read from just about any file containing integer values. The following files all contain the same 10-integer values. The read does not require a POSIX EOF for the read of the last value in the file to succeed (e.g. '\n' following the last line). Each of the files below are read and properly parsed by the code above -- without modification.

```<code>$ cat dat/10int_comma.txt
8572,-2213,6434,16330,3034,12346,4855,16985,11250,1495

$ cat dat/10int.csv
8572, -2213, 6434, 16330, 3034
12346, 4855, 16985, 11250, 1495

$ cat dat/10int_5x2.txt
[[  8572  -2213  ]
 [  6434  16330  ]
 [  3034  12346  ]
 [  4855  16985  ]
 [ 11250   1495  ]]

$ cat dat/10intmess.txt
8572,;a -2213,;--a 6434,;
a- 16330,;a

- The Quick
Brown%3034 Fox
12346Jumps Over
A
4855,;*;Lazy 16985/,;a
Dog.
11250
1495
</code>```

Example Use/Output

The output produced by reading each of the files above is the same.

```<code>$ ./bin/fgets_strtol <dat/10intmess.txt
 arr[  0] = 8572
 arr[  1] = -2213
 arr[  2] = 6434
 arr[  3] = 16330
 arr[  4] = 3034
 arr[  5] = 12346
 arr[  6] = 4855
 arr[  7] = 16985
 arr[  8] = 11250
 arr[  9] = 1495
</code>```

While you are free to use strtok and atoi, the C library provides a tool for that job in strtol (and for all the different numeric types in the remaining strtoX functions). Look things over and let me know if you have further questions.

Body:
I'm trying to write a program that takes a list of numbers from a file and stores each row of numbers in a 2D array using strtok(). The problem I'm having is that when I try to store values in the rows of my 2D array, the while loop goes into an infinite loop, but when i use the line token = strtok(NULL, " ") to stop the loop, I just store the first value of each line into the first cell of each column.

What am I doing wrong? Heres is my code

int main() {
  int myArray[240][30];
  char line[240];
  char *token;
  int i, n, j;
  FILE *fp;
  fp = fopen("array_list.txt", "rt");
  j = 0;
  i = 0;
  while (fgets(line, sizeof(line), fp)) {
    token = strtok(line, " ");

    while (token != NULL) {
      n = atoi(token);
      myArray[i][j] = n;
      token = strtok(line, " ");
      printf("%d ", myArray[i][j]);
      token = strtok(NULL, " ");
      j++;
    }

    printf("\n");
    i++;
  }
  return 0;
}

Here is an example of the file I'm trying to read.

1 98 48 55 46 12 48 43 7 73 47 33

                                                                                97 26 67 25 67 47 46 74 67 43 78 98 90 58 6 5 53 19 37 42

81 84 36 70 59 65 99 56 94 23
79 73 27 47 98 78 8 2 3 43 84 19 59 98 51 72 2 13 55 3
20 61 25 84 28 70 56 23 52 69
86 70 60 90 72
51 71 92 91 55 6 72 67 73 64 78 43 65 30 49
99 82 40 72 5 44 20 21 22 72 99 74 27 59 25 1 26 26 22 66
63 27 54 46 46
91 65 77 45 94 94 95 11 77 46 64 14
69 70 75 48 68 22 55 78 1 4
31 76 55 12 93

Body:
While you can use strtok to split words in your file and then use atoi to perform the conversion to int, there are significant drawbacks to that approach. First and foremost, atoi (and all the atoX functions) provide absolutely no way to validate whether you actually converted atoi(word) to a number. (Is it really 0? -- or did the conversion just fail?)

Further, strtok + atoi is part of what strtol does for you. The rest of what long strtol (const char *nptr, char **endptr, int base) does for you is provide extensive error checking through errno, and range checking returning LONG_MIN on underflow and LONG_MAX on overflow. It provides further checking by setting endptr = nptr in the case no digits were found during conversion. Even better, when the conversion succeeds, endptr is set to the next character following the last character that was converted. (it sets you up for your next read!)

Further, with minimal effort, you can test whether the next character should be skipped before calling strtol again, allowing you to parse numbers from the file regardless of what is contained in the file. In other words, you can write an integer read routine once, and then use it with minimum modification for reading whatever file you are given.

While you do not specify how you want to fill myArray[240][30]; from the 144-values you show for your file, the following example shows you how to read those values (and values from just about any file) into an array. You need only add an additional counter or loop to put x-number of values per-row in your array, etc..

Use the constants provided for you in the various header files (e.g. errno.h, limits.h) to help you with your task. The following example reads from the filename  given on the command line (or from stdin by default if no filename is given) and will read any integer found in the file into the array arr up to a maximum of 1024 values, e.g.

#include <stdio.h>
#include <stdlib.h>     /* for strtol */
#include <string.h>     /* for strlen */
#include <limits.h>     /* for INT_MIN, INT_MAX */
#include <errno.h>      /* for errno */

#ifndef BUF_SIZ         /* set input buffer size */
#define BUF_SIZ 8192    /* gcc default, cl.exe (VS) uses 512 */
#endif

#define BASE 10         /* conversion base 10 */
#define AMAX 1024       /* max number of values to read */

int main (int argc, char **argv) {

    int arr[AMAX] = {0},            /* array to hold values */
        n = 0;                      /* number of values read */
    char buf[BUF_SIZ] = "";         /* line buffer */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    while (fgets (buf, BUF_SIZ, fp)) {      /* read each line */
        char *p = buf,                      /* pointer to buf */
            *ep = p;                        /* end pointer for strtol */
        size_t len = strlen (buf);          /* length of buf */

        /* validate complete line read */
        if (len == BUF_SIZ - 1 && buf[len - 1] != '\n') {
            fprintf (stderr, "error: line too long.\n");
            break;
        }

        while (n < AMAX && *p) {    /* n < AMAX & each starting char */
            errno = 0;                          /* reset errno */
            long tmp = strtol (p, &ep, BASE);   /* convert to long */

            /* validate conversion */
            if (p != ep) {                  /* digits converted */
                /* if no error and in range - assign to array */
                if (!errno && INT_MIN <= tmp && tmp <= INT_MAX)
                    arr[n++] = (int)tmp;
                p = ep;     /* set p to 1-past converted string */
            }

            /* find beginning of next number in buf */
            for (; *p; p++) {
                if ('0' <= *p && *p <= '9')  /* positive value */
                    break;          /* explicitly signed value */
                if ((*p == '+' || *p == '-') && '0' <= *(p+1) && *(p+1) <= '9')
                    break;
            }
        }
    }
    if (fp != stdin) fclose (fp);   /* close file if not stdin */

    for (int i = 0; i < n; i++)     /* output values read */
        printf (" arr[%3d] = %d\n", i, arr[i]);

    return 0;
}

Example Input Files

This way, you can read from just about any file containing integer values. The following files all contain the same 10-integer values. The read does not require a POSIX EOF for the read of the last value in the file to succeed (e.g. '\n' following the last line). Each of the files below are read and properly parsed by the code above -- without modification.

$ cat dat/10int_comma.txt
8572,-2213,6434,16330,3034,12346,4855,16985,11250,1495

$ cat dat/10int.csv
8572, -2213, 6434, 16330, 3034
12346, 4855, 16985, 11250, 1495

$ cat dat/10int_5x2.txt
[[  8572  -2213  ]
 [  6434  16330  ]
 [  3034  12346  ]
 [  4855  16985  ]
 [ 11250   1495  ]]

$ cat dat/10intmess.txt
8572,;a -2213,;--a 6434,;
a- 16330,;a

- The Quick
Brown%3034 Fox
12346Jumps Over
A
4855,;*;Lazy 16985/,;a
Dog.
11250
1495

Example Use/Output

The output produced by reading each of the files above is the same.

$ ./bin/fgets_strtol <dat/10intmess.txt
 arr[  0] = 8572
 arr[  1] = -2213
 arr[  2] = 6434
 arr[  3] = 16330
 arr[  4] = 3034
 arr[  5] = 12346
 arr[  6] = 4855
 arr[  7] = 16985
 arr[  8] = 11250
 arr[  9] = 1495

While you are free to use strtok and atoi, the C library provides a tool for that job in strtol (and for all the different numeric types in the remaining strtoX functions). Look things over and let me know if you have further questions.


问:
When should the dimens.xml file be used in Android?
For instance, in a specific layout I have the following XML:

```<code><GridView
    android:id="@+id/gridView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="3dp"
    android:columnWidth="48dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="spacingWidth" />
</code>```

This grid view is specific to this layout and I don't think I'll be using any other grid views with similar properties. That to say that the dimension values in the code are specific to that grid view.

Should I still move them to a dimens.xml file or it's fine to just leave them like that? If so, should I place values in the dimens.xml file only when that value is used across multiple layouts?

答:
Supplemental answer

@Devunwired lists 3 reasons to use dimens.xml. Here are the details of how to do that.

1. Reuse

If you set some dp or sp value in dimens.xml once like this

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="textview_padding">16dp</dimen>
    <dimen name="large_text_size">30sp</dimen>
</resources>
</code>```

you can reuse it throughout your app in multiple locations.

```<code><TextView
    android:padding="@dimen/textview_padding"
    android:textSize="@dimen/large_text_size"
    ... />

<TextView
    android:padding="@dimen/textview_padding"
    android:textSize="@dimen/large_text_size"
    ... />
</code>```

Then when you need to make a change, you only need to do it in one place.

Notes

This is basically the same effect as using a style or theme.

Be careful not to give two different views the same dimen value if they really shouldn't be. If you need to make changes to one set of views but not another, then you will have to go back to each one individually, which defeats the purpose.

2. Size Difference

@Devunwired called this Density difference, but if you are using dp (density independent pixels), this already takes care are the density difference problem for all but the most minor cases. So in my opinion, screen size is a more important factor for using dimens.xml.

An 8dp padding might look great on a phone, but when the app is run on a tablet, it looks too narrow. You can solve this problem by making two (or more) different versions of dimens.xml.

Right click your res folder and choose New > Value resource file. Then write in dimens and choose Smallest Screen Width. Write in 600 for the width (7” tablet). (There are other ways of choosing the sizes. See the documentation and this answer for more.)

This will make another values folder that will be used for devices whose smallest screen width is 600dp. In the Android view the two dimens.xml files look like this.

Now you can modify them independently.

values/dimens.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="my_default_padding">16dp</dimen>
</resources>
</code>```

values-sw600dp/dimens.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="my_default_padding">64dp</dimen>
</resources>
</code>```

When using your dimen you only have to set it with the name you used in both dimens.xml files.

```<code><LinearLayout
    ...
    android:padding="@dimen/my_default_padding">

</LinearLayout>
</code>```

The system will automatically choose the right value for you depending on the device the user is using.

3. Reading in from code

Sometimes it is a pain scaling programmatically between px and dp (see this answer for how).

If you have a fixed dp value already defined in dimens.xml like this

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="my_dp_value">16dp</dimen>
</resources>
</code>```

Then you can easily get it with

```<code>int sizeInPixels = getResources().getDimensionPixelSize(R.dimen.my_dp_value);
</code>```

and it will already be converted to pixels for whatever density device the user has.

Body:
For instance, in a specific layout I have the following XML:

<GridView
    android:id="@+id/gridView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="3dp"
    android:columnWidth="48dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="spacingWidth" />

This grid view is specific to this layout and I don't think I'll be using any other grid views with similar properties. That to say that the dimension values in the code are specific to that grid view.

Should I still move them to a dimens.xml file or it's fine to just leave them like that? If so, should I place values in the dimens.xml file only when that value is used across multiple layouts?

Body:
Supplemental answer

@Devunwired lists 3 reasons to use dimens.xml. Here are the details of how to do that.

1. Reuse

If you set some dp or sp value in dimens.xml once like this

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="textview_padding">16dp</dimen>
    <dimen name="large_text_size">30sp</dimen>
</resources>

you can reuse it throughout your app in multiple locations.

<TextView
    android:padding="@dimen/textview_padding"
    android:textSize="@dimen/large_text_size"
    ... />

<TextView
    android:padding="@dimen/textview_padding"
    android:textSize="@dimen/large_text_size"
    ... />

Then when you need to make a change, you only need to do it in one place.

Notes

This is basically the same effect as using a style or theme.

Be careful not to give two different views the same dimen value if they really shouldn't be. If you need to make changes to one set of views but not another, then you will have to go back to each one individually, which defeats the purpose.

2. Size Difference

@Devunwired called this Density difference, but if you are using dp (density independent pixels), this already takes care are the density difference problem for all but the most minor cases. So in my opinion, screen size is a more important factor for using dimens.xml.

An 8dp padding might look great on a phone, but when the app is run on a tablet, it looks too narrow. You can solve this problem by making two (or more) different versions of dimens.xml.

Right click your res folder and choose New > Value resource file. Then write in dimens and choose Smallest Screen Width. Write in 600 for the width (7” tablet). (There are other ways of choosing the sizes. See the documentation and this answer for more.)

This will make another values folder that will be used for devices whose smallest screen width is 600dp. In the Android view the two dimens.xml files look like this.

Now you can modify them independently.

values/dimens.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="my_default_padding">16dp</dimen>
</resources>

values-sw600dp/dimens.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="my_default_padding">64dp</dimen>
</resources>

When using your dimen you only have to set it with the name you used in both dimens.xml files.

<LinearLayout
    ...
    android:padding="@dimen/my_default_padding">

</LinearLayout>

The system will automatically choose the right value for you depending on the device the user is using.

3. Reading in from code

Sometimes it is a pain scaling programmatically between px and dp (see this answer for how).

If you have a fixed dp value already defined in dimens.xml like this

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="my_dp_value">16dp</dimen>
</resources>

Then you can easily get it with

int sizeInPixels = getResources().getDimensionPixelSize(R.dimen.my_dp_value);

and it will already be converted to pixels for whatever density device the user has.


问:
Too much nested class in my Swing class
I needed to use these nested class because nested class can use the variable from the class been nested. How do I move these class to a something.java to simplify my code and the class still have the control of the gui class , such as Jlabel?

this is the cleaned version to show the important part

```<code>public class GUI {

        public GUI(){

            VitaminDEngineStarter vdes = new VitaminDEngineStarter();
            Registry registry = null;
            try {
                registry = LocateRegistry.getRegistry();
            } catch (RemoteException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            try {
                vd = (VitaminD)registry.lookup(VitaminD.SERVICE_NAME);
            } catch(Exception e) {
                e.printStackTrace();
            }

            SMS a = new SMS(5);
            try {
                arduino.connect("COM3");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("connecting:"+ a.connect());
            System.out.println("connected? :" + a.checkConnect());
            System.out.println("signal: "+a.checkSignal());
            System.out.println("deliver report :" + a.DeliveryReportOn());
            SMS.Read read = a.new Read(arduino);

        }

        class ShowSense implements Runnable {

            @Override
            public void run() {
                String[] temp;
                String light = "";
                String temperature = "";
                String hum = "";
                String sens = "";
                boolean humanact = false;

                // TODO Auto-generated method stub
                while (true){
                    try {
                        humanact = vd.gethumanActivity();
                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    sens = arduino.getSensor();
                    temp = sens.split(",");
                    light = temp[1];
                    temperature = temp[0];
                    hum = temp[2];

                    LightIntensity.setText(light);
                    Temperature.setText(temperature);
                    humidity.setText(hum);

                    if (humanact){
                        personActivity.setText("in place");
                    }
                    else{
                        personActivity.setText("absent");
                    }

                }
            }

        }

        private JPanel getInputs() {
            if (Inputs == null) {
                personActivity = new JLabel();
                personActivity.setBounds(new Rectangle(114, 137, 77, 27));
                personActivity.setText("");
                personActivityLabel = new JLabel();
                personActivityLabel.setBounds(new Rectangle(7, 137, 99, 25));
                personActivityLabel.setText("Person Activity:");
                humidity = new JLabel();
                humidity.setBounds(new Rectangle(106, 91, 84, 27));
                humidity.setText("");
                humidityLabel = new JLabel();
                humidityLabel.setBounds(new Rectangle(6, 92, 88, 26));
                humidityLabel.setText("Humidity:");
                Temperature = new JLabel();
                Temperature.setBounds(new Rectangle(101, 50, 89, 30));
                Temperature.setText("");
                TemperatureLabel = new JLabel();
                TemperatureLabel.setBounds(new Rectangle(4, 50, 91, 30));
                TemperatureLabel.setText("Temperature:");
                LightIntensity = new JLabel();
                LightIntensity.setBounds(new Rectangle(110, 6, 84, 34));
                lightLabel = new JLabel();
                lightLabel.setBounds(new Rectangle(5, 5, 97, 34));
                lightLabel.setText("Light Intensity:");
                Inputs = new JPanel();
                Inputs.setLayout(null);
                Inputs.setBounds(new Rectangle(14, 63, 200, 183));
                Inputs.add(lightLabel, null);
                Inputs.add(LightIntensity, null);
                Inputs.add(TemperatureLabel, null);
                Inputs.add(Temperature, null);
                Inputs.add(humidityLabel, null);
                Inputs.add(humidity, null);
                Inputs.add(personActivityLabel, null);
                Inputs.add(personActivity, null);
                th.start();
            }
            return Inputs;
        }

        class autopilotthread implements Runnable{

            /** The temp. */
            private String[] temp;

            /** The lightintensty. */
            private double lightintensty ;

            /** The temperature. */
            private double temperature ;

            /** The hum. */
            private double hum ;

            /** The sens. */
            private String sens = null;

            /** The humanact. */
            private double humanact;

            /** The result. */
            private boolean [] result = {false , false};

            /** The fan. */
            private boolean fan =false;

            /** The light. */
            private boolean light = false;

            /** The pstop. */
            boolean pstop = false;

            /* (non-Javadoc)
             * @see java.lang.Runnable#run()
             */
            @Override
            public void run() {
                System.out.println("thread start!");
                while(true){
                    System.out.println("thread loop!");
                        try {
                            if(vd.gethumanActivity()){
                                humanact = 250;
                            }else{
                                humanact = 0;
                            }
                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        sens = arduino.getSensor();
                        temp = sens.split(",");
                        lightintensty = Double.parseDouble(temp[1]);
                        temperature = Double.parseDouble(temp[0]);
                        hum = Double.parseDouble(temp[2]);
                        double [] out ={humanact ,lightintensty , hum, Time.now(),temperature };
                        System.out.println(""+out[0]+" "+out[1]+" "+out[2]+" "+out[3]+" "+out[4]);
                        result = Matlab.output(out);
                        light = result[1];
                        fan = result[0];
                        System.out.println("light:" + light);
                        System.out.println("fan:" + fan );
                        if(light){
                            try {X10.lightsOn();}
                            catch (IOException e) {e.printStackTrace();}

                        }else{
                            try {X10.lightsOff();}
                            catch (IOException e) {e.printStackTrace();}

                        }

                        if(fan){
                            try {X10.fanOn();}
                            catch (IOException e) {e.printStackTrace();}

                        }else{
                            try {X10.fanOff();}
                            catch (IOException e) {e.printStackTrace();}

                        }

                    try {TimeUnit.SECONDS.sleep(10);}
                    catch (InterruptedException e) {e.printStackTrace();}

                    if (pstop){
                        break;
                    }
                }
                System.out.println("thread stop!");

            }

        }

        class Pilotmouse implements MouseListener{

            /** The p thread. */
            autopilotthread pThread = null;

            /** The pt. */
            Thread pt = null;

            /**
             * Instantiates a new pilotmouse.
             */
            Pilotmouse(){

            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
             */
            @Override
            public void mouseClicked(MouseEvent arg0) {
                // TODO Auto-generated method stub

            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
             */
            @Override
            public void mouseEntered(MouseEvent arg0) {
                // TODO Auto-generated method stub

            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
             */
            @Override
            public void mouseExited(MouseEvent arg0) {
                // TODO Auto-generated method stub

            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
             */
            @Override
            public void mousePressed(MouseEvent arg0) {
                // TODO Auto-generated method stub

            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
             */
            @Override
            public void mouseReleased(java.awt.event.MouseEvent e) {
                if ((autopilotlable.getText().equalsIgnoreCase("off"))){
                    autopilotlable.setText("on");
                    pThread = new autopilotthread();
                    pt = new Thread(pThread);
                    pt.start();

                } else if ((autopilotlable.getText().equalsIgnoreCase("on"))){
                    autopilotlable.setText("off");
                    pThread.pstop = true;
                }
            }

        }

        private JButton getAutopilot() {

            if (autopilot == null) {
                autopilot = new JButton();
                autopilot.setBounds(new Rectangle(18, 14, 112, 28));
                autopilot.setText("Auto Pilot");

                autopilot.addMouseListener(new Pilotmouse());
            }
            return autopilot;
        }

        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    GUI application = new GUI();
                    application.getJFrame().setVisible(true);
                }
            });

        }

    }
</code>```

答:
As Jochen mentioned you could use Eclipse Refactoring Tools. That won't solve design issues though.

Generally:

GUI knows about 14 classes and acts
as big mediator... Is it possible to
group logic into some    higher level
classes and have GUI use them?

Your code mixes object construction
with logic. Try to move those actions
to different places

Don't start a thread inside
constructor!

Revise usage of logical
statements. Eg. :
 while(true){  ... if
       (pstop){    break; }}

Is X10 3rd party class or your own?
If it's yours try to remove global
state(eg  use single instance of X10
and instance variables for state
change. Not static ones)

The most important advise: Please try to write unit tests for this functionality first using (for example) junit and mockito, and good design will come naturally. Believe me!

EDIT:

Good talk about JMM

Good book about concurrency.

EDIT:

The Clean Code Talks - "Global State and Singletons"

Title: Too much nested class in my Swing class

Body:
I needed to use these nested class because nested class can use the variable from the class been nested. How do I move these class to a something.java to simplify my code and the class still have the control of the gui class , such as Jlabel?

this is the cleaned version to show the important part

public class GUI {

        public GUI(){

            VitaminDEngineStarter vdes = new VitaminDEngineStarter();
            Registry registry = null;
            try {
                registry = LocateRegistry.getRegistry();
            } catch (RemoteException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            try {
                vd = (VitaminD)registry.lookup(VitaminD.SERVICE_NAME);
            } catch(Exception e) {
                e.printStackTrace();
            }

            SMS a = new SMS(5);
            try {
                arduino.connect("COM3");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("connecting:"+ a.connect());
            System.out.println("connected? :" + a.checkConnect());
            System.out.println("signal: "+a.checkSignal());
            System.out.println("deliver report :" + a.DeliveryReportOn());
            SMS.Read read = a.new Read(arduino);

        }

        class ShowSense implements Runnable {

            @Override
            public void run() {
                String[] temp;
                String light = "";
                String temperature = "";
                String hum = "";
                String sens = "";
                boolean humanact = false;

                // TODO Auto-generated method stub
                while (true){
                    try {
                        humanact = vd.gethumanActivity();
                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    sens = arduino.getSensor();
                    temp = sens.split(",");
                    light = temp[1];
                    temperature = temp[0];
                    hum = temp[2];

                    LightIntensity.setText(light);
                    Temperature.setText(temperature);
                    humidity.setText(hum);

                    if (humanact){
                        personActivity.setText("in place");
                    }
                    else{
                        personActivity.setText("absent");
                    }

                }
            }

        }

        private JPanel getInputs() {
            if (Inputs == null) {
                personActivity = new JLabel();
                personActivity.setBounds(new Rectangle(114, 137, 77, 27));
                personActivity.setText("");
                personActivityLabel = new JLabel();
                personActivityLabel.setBounds(new Rectangle(7, 137, 99, 25));
                personActivityLabel.setText("Person Activity:");
                humidity = new JLabel();
                humidity.setBounds(new Rectangle(106, 91, 84, 27));
                humidity.setText("");
                humidityLabel = new JLabel();
                humidityLabel.setBounds(new Rectangle(6, 92, 88, 26));
                humidityLabel.setText("Humidity:");
                Temperature = new JLabel();
                Temperature.setBounds(new Rectangle(101, 50, 89, 30));
                Temperature.setText("");
                TemperatureLabel = new JLabel();
                TemperatureLabel.setBounds(new Rectangle(4, 50, 91, 30));
                TemperatureLabel.setText("Temperature:");
                LightIntensity = new JLabel();
                LightIntensity.setBounds(new Rectangle(110, 6, 84, 34));
                lightLabel = new JLabel();
                lightLabel.setBounds(new Rectangle(5, 5, 97, 34));
                lightLabel.setText("Light Intensity:");
                Inputs = new JPanel();
                Inputs.setLayout(null);
                Inputs.setBounds(new Rectangle(14, 63, 200, 183));
                Inputs.add(lightLabel, null);
                Inputs.add(LightIntensity, null);
                Inputs.add(TemperatureLabel, null);
                Inputs.add(Temperature, null);
                Inputs.add(humidityLabel, null);
                Inputs.add(humidity, null);
                Inputs.add(personActivityLabel, null);
                Inputs.add(personActivity, null);
                th.start();
            }
            return Inputs;
        }

        class autopilotthread implements Runnable{

            /** The temp. */
            private String[] temp;

            /** The lightintensty. */
            private double lightintensty ;

            /** The temperature. */
            private double temperature ;

            /** The hum. */
            private double hum ;

            /** The sens. */
            private String sens = null;

            /** The humanact. */
            private double humanact;

            /** The result. */
            private boolean [] result = {false , false};

            /** The fan. */
            private boolean fan =false;

            /** The light. */
            private boolean light = false;

            /** The pstop. */
            boolean pstop = false;

            /* (non-Javadoc)
             * @see java.lang.Runnable#run()
             */
            @Override
            public void run() {
                System.out.println("thread start!");
                while(true){
                    System.out.println("thread loop!");
                        try {
                            if(vd.gethumanActivity()){
                                humanact = 250;
                            }else{
                                humanact = 0;
                            }
                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        sens = arduino.getSensor();
                        temp = sens.split(",");
                        lightintensty = Double.parseDouble(temp[1]);
                        temperature = Double.parseDouble(temp[0]);
                        hum = Double.parseDouble(temp[2]);
                        double [] out ={humanact ,lightintensty , hum, Time.now(),temperature };
                        System.out.println(""+out[0]+" "+out[1]+" "+out[2]+" "+out[3]+" "+out[4]);
                        result = Matlab.output(out);
                        light = result[1];
                        fan = result[0];
                        System.out.println("light:" + light);
                        System.out.println("fan:" + fan );
                        if(light){
                            try {X10.lightsOn();}
                            catch (IOException e) {e.printStackTrace();}

                        }else{
                            try {X10.lightsOff();}
                            catch (IOException e) {e.printStackTrace();}

                        }

                        if(fan){
                            try {X10.fanOn();}
                            catch (IOException e) {e.printStackTrace();}

                        }else{
                            try {X10.fanOff();}
                            catch (IOException e) {e.printStackTrace();}

                        }

                    try {TimeUnit.SECONDS.sleep(10);}
                    catch (InterruptedException e) {e.printStackTrace();}

                    if (pstop){
                        break;
                    }
                }
                System.out.println("thread stop!");

            }

        }

        class Pilotmouse implements MouseListener{

            /** The p thread. */
            autopilotthread pThread = null;

            /** The pt. */
            Thread pt = null;

            /**
             * Instantiates a new pilotmouse.
             */
            Pilotmouse(){

            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
             */
            @Override
            public void mouseClicked(MouseEvent arg0) {
                // TODO Auto-generated method stub

            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
             */
            @Override
            public void mouseEntered(MouseEvent arg0) {
                // TODO Auto-generated method stub

            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
             */
            @Override
            public void mouseExited(MouseEvent arg0) {
                // TODO Auto-generated method stub

            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
             */
            @Override
            public void mousePressed(MouseEvent arg0) {
                // TODO Auto-generated method stub

            }

            /* (non-Javadoc)
             * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
             */
            @Override
            public void mouseReleased(java.awt.event.MouseEvent e) {
                if ((autopilotlable.getText().equalsIgnoreCase("off"))){
                    autopilotlable.setText("on");
                    pThread = new autopilotthread();
                    pt = new Thread(pThread);
                    pt.start();

                } else if ((autopilotlable.getText().equalsIgnoreCase("on"))){
                    autopilotlable.setText("off");
                    pThread.pstop = true;
                }
            }

        }

        private JButton getAutopilot() {

            if (autopilot == null) {
                autopilot = new JButton();
                autopilot.setBounds(new Rectangle(18, 14, 112, 28));
                autopilot.setText("Auto Pilot");

                autopilot.addMouseListener(new Pilotmouse());
            }
            return autopilot;
        }

        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    GUI application = new GUI();
                    application.getJFrame().setVisible(true);
                }
            });

        }

    }