问:
How do I read (i.e. understand) this Java array?
```<code>String[][][] arr  =
{{ { "a", "b" , "c"}, { "d", "e", null } },{ {"x"}, null },{{"y"}},{ { "z","p"}, {} }};
</code>```

I've reason to believe that something like this is going to come up on an exam eventually but in +10 years of coding, I've never seen such a horror. I sure could use some tips for mentally parsing this, so that I can figure out what it really means in my head. Sure, I could run it through IntelliJ but I won't have it available.

For the record, this makes perfect sense to me:

```<code>int[][] twoD = { { 1, 2, 3} , { 4, 5, 6, 7}, { 8, 9, 10 } };
</code>```

Body:
String[][][] arr  =
{{ { "a", "b" , "c"}, { "d", "e", null } },{ {"x"}, null },{{"y"}},{ { "z","p"}, {} }};

I've reason to believe that something like this is going to come up on an exam eventually but in +10 years of coding, I've never seen such a horror. I sure could use some tips for mentally parsing this, so that I can figure out what it really means in my head. Sure, I could run it through IntelliJ but I won't have it available.

For the record, this makes perfect sense to me:

int[][] twoD = { { 1, 2, 3} , { 4, 5, 6, 7}, { 8, 9, 10 } };

Body:
String[][][] arr = {

            // arr[0]
            {
                    /* arr[0][0] */
                    {
                            /* arr[0][0][0] */ "a",
                            /* arr[0][0][1] */ "b",
                            /* arr[0][0][2] */ "c"
                    },

                    /* arr[0][1] */
                    {
                            /* arr[0][1][0] */ "d",
                            /* arr[0][1][1] */ "e",
                            /* arr[0][1][2] */ null
                    }
            },

            // arr[1]
            {
                    /* arr[1][0] */
                    {
                            /* arr[1][0][0] */ "x"
                    },

                    /* arr[1][1] */
                    null
            },

            // arr[2]
            {
                    /* arr[2][0] */
                    {
                            /* arr[2][0][0] */ "y"
                    }
            },

            // arr[3]
            {
                    /* arr[3][0] */
                    {
                            /* arr[3][0][0] */ "z",
                            /* arr[3][0][1] */ "p"
                    },

                    /* arr[3][1] */
                    {}
            }
    };


来源: stackexchange

问:
How to embed H2 database into jar file delivered to the client?
I use H2 database for a desktop application in embedded mode. When I compress the application into jar file the database file is omitted. So, when I run MyApplication.jar nothing works. What is the correct way to embed/include/connect h2.jar file with MyApplication.jar? Or maybe there is another way to deliver database and application in the bundle?</p>

答:
If you are using Maven to build your project, just use maven-shade-plugin... great results and control, I've been using it a lot.

For embedding all your dependencies you would write something like:

```<code>  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>1.4</version>
    <executions>
      <execution>
        <phase>package</phase>
        <goals>
          <goal>shade</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
</code>```

Then with just a normal "mvn package" you'll have all your dependencies' jars included in your application jar.

With further configuration you can control what gets included and what not.

ContentLicense: CC BY-SA 2.5

Body:
If you are using Maven to build your project, just use maven-shade-plugin... great results and control, I've been using it a lot.

For embedding all your dependencies you would write something like:

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>1.4</version>
    <executions>
      <execution>
        <phase>package</phase>
        <goals>
          <goal>shade</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

Then with just a normal "mvn package" you'll have all your dependencies' jars included in your application jar.

With further configuration you can control what gets included and what not.


问:
PHP array_map not returning resultant array
I am trying to replace an array value's spacing with hypen and then recollect back all values of the same array but with hypen in spaces.

INPUT:

```<code>$gFontsList = array("-1", "Agency FB", "28", "Aharoni Bold", "Bookshelf Symbol", "100", "Bookshelf Symbol", "111", "Browallia New Bol");

function toReplaceSpacing($gFontsListValues, $gFontsListIndex){
   if (gettype($gFontsListValues) === 'string'){
      if(preg_match('/ /',$gFontsListValues)){
        $gFontsListValues = str_replace(' ','-',$gFontsListValues);
        $gFontsChoiceOrder[] = $gFontsListValues;
      }
    } else {
      $gFontsChoiceOrder[] = $gFontsListValues;
    }
}
$gFontsChoiceOrder = array_map('toReplaceSpacing',$gFontsList);
print_r($gFontsChoiceOrder);
</code>```

If I print it's just NULL. I don't know Why I am not getting resultant array?.

答:
Two issues:

```<code>function toReplaceSpacing($gFontsListValues){
   if (gettype($gFontsListValues) === 'string'){
        $gFontsListValues = str_replace(' ','-',$gFontsListValues);
   }
   return $gFontsListValues;
}
</code>```

You need to return the new value

The callback only takes the value, so only one argument

Also, I don't see any reason to check for a space (especially with a regex) before replacing and it makes the code longer.

As billyonecan points out in the comments, it can be done with an anonymous function, but this version doesn't check for string so can cause issues with arrays, objects, etc:

```<code>$gFontsChoiceOrder = array_map(function($v) {
                                   return str_replace(' ', '-', $v);
                               }, $gFontsList);
</code>```

For future reference, you can modify the original array with array_walk() and a reference:

```<code>function toReplaceSpacing(&$gFontsListValues){
   if (gettype($gFontsListValues) === 'string'){
        $gFontsListValues = str_replace(' ','-',$gFontsListValues);
   }
}
array_walk($gFontsList, 'toReplaceSpacing');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to replace an array value's spacing with hypen and then recollect back all values of the same array but with hypen in spaces.

INPUT:

$gFontsList = array("-1", "Agency FB", "28", "Aharoni Bold", "Bookshelf Symbol", "100", "Bookshelf Symbol", "111", "Browallia New Bol");

function toReplaceSpacing($gFontsListValues, $gFontsListIndex){
   if (gettype($gFontsListValues) === 'string'){
      if(preg_match('/ /',$gFontsListValues)){
        $gFontsListValues = str_replace(' ','-',$gFontsListValues);
        $gFontsChoiceOrder[] = $gFontsListValues;
      }
    } else {
      $gFontsChoiceOrder[] = $gFontsListValues;
    }
}
$gFontsChoiceOrder = array_map('toReplaceSpacing',$gFontsList);
print_r($gFontsChoiceOrder);

If I print it's just NULL. I don't know Why I am not getting resultant array?.

Body:
Two issues:

function toReplaceSpacing($gFontsListValues){
   if (gettype($gFontsListValues) === 'string'){
        $gFontsListValues = str_replace(' ','-',$gFontsListValues);
   }
   return $gFontsListValues;
}

You need to return the new value

The callback only takes the value, so only one argument

Also, I don't see any reason to check for a space (especially with a regex) before replacing and it makes the code longer.

As billyonecan points out in the comments, it can be done with an anonymous function, but this version doesn't check for string so can cause issues with arrays, objects, etc:

$gFontsChoiceOrder = array_map(function($v) {
                                   return str_replace(' ', '-', $v);
                               }, $gFontsList);

For future reference, you can modify the original array with array_walk() and a reference:

function toReplaceSpacing(&$gFontsListValues){
   if (gettype($gFontsListValues) === 'string'){
        $gFontsListValues = str_replace(' ','-',$gFontsListValues);
   }
}
array_walk($gFontsList, 'toReplaceSpacing');


问:
Hover over an image in one column to make text appear in a different column
Apologies as I know this question has been asked in various different forms, but I can't find an answer to my exact problem - at least not one that I understand!

I'm very new to programming, and am currently building myself a webpage for my wedding cake business to try and familiarise myself with HTML, CSS and a bit of JavaScript and JQuery. I have a list of thumbnail images in one column, which I added "onmouseover" to so that when hovered over (in addition to a css transition) they display a large version of themselves in a central column. I want to also display information about each cake in a third column to the right hand side of the main image but I have no idea how to go about doing this!

```<code><div class="col-md-3">
<ul class="cake-thumbs">
    <li>
        <figure class="cake-img">
            <img onmouseover="getElementById('preview').src=this.src" id="img10" src="Resources/img/10.jpg" alt="Pastel Pink Placard and Pearls">
        </figure>
    </li>
    <li>
        <figure class="cake-img">
            <img onmouseover="getElementById('preview').src=this.src" id="img11" src="Resources/img/11.jpg" alt="Naked Wedding Cake with fresh fruit">
        </figure>
    </li>
    <li>
        <figure class="cake-img">
            <img onmouseover="getElementById('preview').src=this.src" id="img12" src="Resources/img/12.jpg" alt="Gold Damask and Pearls">
        </figure>
    </li>
</ul>
</div>
<div class="col-md-6">
        <img id="preview" src="Resources/img/1.jpg" alt="">
</div>
<div class="col-md-3">
    <p id="info">Price and servings here</p>
</div>
</code>```

答:
Here I've removed the mouse over events that were directly attached to the elements, and created a child div with a class "info" that will get copied to the third column when hovered.  I attached an attribute "data-preview" to each img that contains the full sized image to place in the preview column.

I've also bound the event to click in addition to the mouseenter so that when mobile users visit your site, they can click the image (very few mobiles support mouse events).

$(document).on('mouseenter click','.cake-img',function(){
  $('#preview').attr('src',$('img',this).data('preview')); // Copy source to preview
  $('#info').html($('.info',this).html()); // Copy text
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{padding-top: 75px} /* Look pretty in stack overflow full screen */
.cake-thumbs figure { display: inline-block }</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

              Price and servings 1

              Price and servings 2

More complicated info

Unbox

Eat

Watch waistline grow

Price and servings here

```

Body:
Apologies as I know this question has been asked in various different forms, but I can't find an answer to my exact problem - at least not one that I understand!

I'm very new to programming, and am currently building myself a webpage for my wedding cake business to try and familiarise myself with HTML, CSS and a bit of JavaScript and JQuery. I have a list of thumbnail images in one column, which I added "onmouseover" to so that when hovered over (in addition to a css transition) they display a large version of themselves in a central column. I want to also display information about each cake in a third column to the right hand side of the main image but I have no idea how to go about doing this!

Price and servings here

Body:
Here I've removed the mouse over events that were directly attached to the elements, and created a child div with a class "info" that will get copied to the third column when hovered.  I attached an attribute "data-preview" to each img that contains the full sized image to place in the preview column.

I've also bound the event to click in addition to the mouseenter so that when mobile users visit your site, they can click the image (very few mobiles support mouse events).

$(document).on('mouseenter click','.cake-img',function(){
  $('#preview').attr('src',$('img',this).data('preview')); // Copy source to preview
  $('#info').html($('.info',this).html()); // Copy text
});

body{padding-top: 75px} /* Look pretty in stack overflow full screen */
.cake-thumbs figure { display: inline-block }

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
<ul class="cake-thumbs">
    <li>
        <figure class="cake-img">
            <img id="img10" src="http://via.placeholder.com/100/00ffff?text=Thumbnail" alt="Pastel Pink Placard and Pearls" data-preview="http://via.placeholder.com/250/00ffff&text=Full Image 1">
            <div class="info hide">
              Price and servings 1
            </div>
        </figure>
    </li>
    <li>
        <figure class="cake-img">
            <img d="img11" src="http://via.placeholder.com/100/0000ff?text=Thumbnail" alt="Naked Wedding Cake with fresh fruit" data-preview="http://via.placeholder.com/250/0000ff&text=Full Image 2">
            <div class="info hide">
              Price and servings 2
            </div>
        </figure>
    </li>
    <li>
        <figure class="cake-img">
            <img id="img12" src="http://via.placeholder.com/100/00ff00?text=Thumbnail" alt="Gold Damask and Pearls" data-preview="http://via.placeholder.com/250/00ff00&text=Full Image 3">
            <div class="info hide">
              <h3>More complicated info</h3>
              <ul>
                <li>Unbox</li>
                <li>Eat</li>
                <li>Watch waistline grow</li>
              </ul>
            </div>
        </figure>
    </li>
</ul>
</div>
<div class="col-md-6">
        <img id="preview" src="Resources/img/1.jpg" alt="">
</div>
<div class="col-md-3">
    <p id="info">Price and servings here</p>
</div>


问:
Laravel 5.4 - How to change the Laravel log file name?
Laravel Version: 5.4.25
PHP Version: 7.0

In the previous versions of laravel there was a ConfigureLogging class to do this. But in the lastest version of laravel the class was deleted instead there is a new LogServiceProvider:

```<code>protected function configureDailyHandler(Application $app, Writer $log)
{

    $log->useDailyFiles(
        $app->storagePath() . '/logs/customLogName.log',
        $app->make('config')->get('app.log_max_files', 5)
    );
}
</code>```

I want to override this method.

How Can I do this ?

Please help.

Thanks.

答:
Finally I've got it.

Add this in your app/bootstrap/app.php file after returning the $app instance:

```<code>$app->configureMonologUsing(function($monolog) use ($app) {
    $monolog->pushHandler(
        (new Monolog\Handler\RotatingFileHandler(
        // Set the log path
            $app->storagePath().'/logs/customLogName.log',
            // Set the number of daily files you want to keep
            $app->make('config')->get('app.log_max_files', 5)
        ))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true, true))
    );
});

return $app;
</code>```

That do the trick

Body:
Laravel Version: 5.4.25
PHP Version: 7.0

In the previous versions of laravel there was a ConfigureLogging class to do this. But in the lastest version of laravel the class was deleted instead there is a new LogServiceProvider:

protected function configureDailyHandler(Application $app, Writer $log)
{

    $log->useDailyFiles(
        $app->storagePath() . '/logs/customLogName.log',
        $app->make('config')->get('app.log_max_files', 5)
    );
}

I want to override this method.

How Can I do this ?

Please help.

Thanks.

Body:
Finally I've got it.

Add this in your app/bootstrap/app.php file after returning the $app instance:

$app->configureMonologUsing(function($monolog) use ($app) {
    $monolog->pushHandler(
        (new Monolog\Handler\RotatingFileHandler(
        // Set the log path
            $app->storagePath().'/logs/customLogName.log',
            // Set the number of daily files you want to keep
            $app->make('config')->get('app.log_max_files', 5)
        ))->setFormatter(new Monolog\Formatter\LineFormatter(null, null, true, true))
    );
});

return $app;

That do the trick


问:
elastic-serach -- how to execute wildcard kibana query
I'm trying to query data from kibana using
for example if the input format is:

```<code>message:"someString"
</code>```

and I want to query for all the messages that start with "msg" and contains "789"

(so message:"msgfdfd789fdfd" will fetched).

how I can fetched it with only one condition and not using

```<code>message: "msg" AND message: "789"
</code>```

I've tried "message:

```<code>"msg*789*"
</code>```

but it does not works..

答:
Try the next query string

message:msg* AND 789

Body:
I'm trying to query data from kibana using
for example if the input format is:

message:"someString"

and I want to query for all the messages that start with "msg" and contains "789"

(so message:"msgfdfd789fdfd" will fetched).

how I can fetched it with only one condition and not using

message: "msg" AND message: "789"

I've tried "message:

"msg*789*"

but it does not works..


问:
Publish app in playstore
I published my app last day on playstore. But I didn't find it on playstore. And when I tried following solution to find that.

```<code>https://play.google.com/store/apps/details?id=yourpackagename
</code>```

I got a blank page with the message "We're sorry, the requested URL was not found on this server.". What is the problem?

On playstore app published option is ticked. Status of the app in Alpha.

答:
Make sure your app status is not under "Submitting update" state.

https://play.google.com/apps/testing/yourpackagename should work.

If closed alpha:
Also under playstore app, the account which you have added in your alpha testers list should be selected. Then tap on above URL by replacing package name and you should see the "Become a tester" page. Agree and download the app from playstore.

If in Open Alpha mode then simply tap on the above url, it should work.

Title: Publish app in playstore

Body:
I published my app last day on playstore. But I didn't find it on playstore. And when I tried following solution to find that.

https://play.google.com/store/apps/details?id=yourpackagename

I got a blank page with the message "We're sorry, the requested URL was not found on this server.". What is the problem?

On playstore app published option is ticked. Status of the app in Alpha.


问:
Eclipse CVS Project inside Remote SSH Project
I have Eclipse PHP Helios and I've setup successfully a new SSH connection to my remote server. One of the directories has Drupal installed and this directory is set up as Remote project. I have the right permissions and everything works perfectly. Now I am trying to import a new project from CVS and check it out into the existing remote project. Unfortunately I get the following error:

Errors saving CVS synchronization information to disk. Please fix the problems listed below and then update the affected resources from the CVS repository.
Missing element for : '': rse://192.168.1.253/srv/apachesolr2/CVS/Entries
Missing element for : '': rse://192.168.1.253/srv/apachesolr2/CVS/Entries
Missing element for : ''

What can I do to be able to import the cvs project into the remote location?

答: I don't think Eclipse CVS supports remote locations. You can try to work with a work copy on your local disk and then synchronize it with remote using RSE sync features.</p>


问:
Passing variables from QTP/UFT to Excel macros
I have some txt files to import to Excel. These files are grouped by date. I recorded macro in Excel where each time I have to change the path to file for each date as ...\files(date)\filename.txt. Here is the macro:

```<code>Sub DataImport2()
'
' DataImport2 Macro
'
With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;d:\testfiles\project1\20170528\filename.txt" _
        , Destination:=Range("$A$2"))
'        .CommandType = 0
        .Name = "filename.txt"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileOtherDelimiter = "|"
        .TextFileColumnDataTypes = Array(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
        2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub
</code>```

In automated test, UFT should pick a date in webpage and compare data on the webpage with data in files for that date.

Question is: How to pass that picked date from UFT to Excel and use it in Excel as path to file? I guess it should look like

```<code>..."TEXT;d:\testfiles\project1\(uft-passed-date)\filename.txt" _...
</code>```

Maybe passing variables as following might work, but from Excel/macro side how should I use them?

```<code>objExcel.Run "macroname", "params1", "param2"
</code>```

I tried to copy above macro to UFT, but it did not work (General Error).
Working on UFT 12.52, IE11 and Office 16.

答:
You need to change the macro to this so that it can take the picked date

```<code>Sub DataImport2(sFilePart As String)
    With ActiveSheet.QueryTables.Add(Connection:= _
            "TEXT;d:\testfiles\project1\" & sFilePart & "\filename.txt" _
            , Destination:=Range("$A$2"))
    '
    '~~> Rest of the code
    '
End Sub
</code>```

Body:
I have some txt files to import to Excel. These files are grouped by date. I recorded macro in Excel where each time I have to change the path to file for each date as ...\files(date)\filename.txt. Here is the macro:

Sub DataImport2()
'
' DataImport2 Macro
'
With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;d:\testfiles\project1\20170528\filename.txt" _
        , Destination:=Range("$A$2"))
'        .CommandType = 0
        .Name = "filename.txt"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileOtherDelimiter = "|"
        .TextFileColumnDataTypes = Array(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
        2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

In automated test, UFT should pick a date in webpage and compare data on the webpage with data in files for that date.

Question is: How to pass that picked date from UFT to Excel and use it in Excel as path to file? I guess it should look like

..."TEXT;d:\testfiles\project1\(uft-passed-date)\filename.txt" _...

Maybe passing variables as following might work, but from Excel/macro side how should I use them?

objExcel.Run "macroname", "params1", "param2"

I tried to copy above macro to UFT, but it did not work (General Error).
Working on UFT 12.52, IE11 and Office 16.

Body:
You need to change the macro to this so that it can take the picked date

Sub DataImport2(sFilePart As String)
    With ActiveSheet.QueryTables.Add(Connection:= _
            "TEXT;d:\testfiles\project1\" & sFilePart & "\filename.txt" _
            , Destination:=Range("$A$2"))
    '
    '~~> Rest of the code
    '
End Sub


问:
How to redirect a form based on radio button selection
I have a registration form that checks to see if he/she is a customer of ours. If the user selects yes, then two fields are displayed (customer number and zipcode). However, if the user selects no, i want the form to just send and go to the next page.

As it works right now, when the user selects no, the form errors out when trying to submit because the customer number + and zipcode is left blank.

What is the best approach to redirect a form on radio button selection? Or is it possible to pre-fill the customer number + zipcdoe fields if the user selects no? Is there a workable way to redirect this?

My radio button code:

```<code>Yes <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="yesCheck"> No <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="noCheck" onChange="OnChangeForm" value="epc">
</code>```

JSFiddle: https://jsfiddle.net/7ycha0ge/

答:
Youre not being very specific with your case, however i belive theres 3 posibilities:

is that you are validating the filling of the fields in javascript and not taking in consideration that your inputs are hidden, in wich case you should revisit your code and only throw error if the field is visible or add/remove completly the fields from the HTML based on the choice of the radio.

Your server side code is always expectng the parameters to have your unfilled data filled and it throws error on that.

Consider use the form like this (with novalidate attribute):

< form novalidate>< /form>

this way youll not be tight to the browser validation, but you have to validate by yourself

EDIT: attached live examples of add and remove elements

function yesnoCheck(resp) {

var yes = '
'+
        'Account Number'+
        '
'+
            '<input type="text" class="form-control" id="account" name="account" placeholder="Enter Account Number">'+
        '
'+
    '
'+

    '
'+
        'Zip Code'+
        '
'+
            '<input type="text" class="form-control" id="zip" name="zip" placeholder="Enter Zip Code">'+
        '
'+
    '
';

   if(resp == 'yes') {
      $('#ifYes').append(yes);
   } else {
      $('#ifYes').html('');
   }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="section section-breadcrumbs">
   <div class="container">
    <div class="row">
     <div class="col-md-12">
      <h1>Register</h1>
     </div>
    </div>
   </div>
  </div>

<div class="section">
  <div class="container">
      <div class="row">
     <div class="col-sm-8 col-sm-offset-2">
              <div class="panel panel-default">
                <div class="panel-body">
                  <h2>Online Training Access</h2>
                  <p><em>We need to verify if you are a retailer first. Please enter your account number without spaces or dashes, or select 'no' if you are a consumer.</em></p><br>

<form class="form-horizontal" role="form" id="my-account-form" method="post"  action="">
    <div class="col-sm-offset-3"></div>

<div class="form-group">
    <label for="lastname" class="col-sm-3 control-label">Are you a retailer?</label>
        <div class="col-sm-9">
         Yes <input type="radio" onclick="javascript:yesnoCheck('yes');" name="yesno" id="yesCheck">
         No <input type="radio" onclick="javascript:yesnoCheck('no');" name="yesno" id="noCheck">
        </div>
</div>

<!-- the contents will only be added if yes -->
<div id="ifYes">
</div>

</form>
</div>
</div>
</div>
</div>
</div></code>```

Body:
I have a registration form that checks to see if he/she is a customer of ours. If the user selects yes, then two fields are displayed (customer number and zipcode). However, if the user selects no, i want the form to just send and go to the next page.

As it works right now, when the user selects no, the form errors out when trying to submit because the customer number + and zipcode is left blank.

What is the best approach to redirect a form on radio button selection? Or is it possible to pre-fill the customer number + zipcdoe fields if the user selects no? Is there a workable way to redirect this?

My radio button code:

Yes <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="yesCheck"> No <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="noCheck" onChange="OnChangeForm" value="epc">

JSFiddle: https://jsfiddle.net/7ycha0ge/

Body:
Youre not being very specific with your case, however i belive theres 3 posibilities:

is that you are validating the filling of the fields in javascript and not taking in consideration that your inputs are hidden, in wich case you should revisit your code and only throw error if the field is visible or add/remove completly the fields from the HTML based on the choice of the radio.

Your server side code is always expectng the parameters to have your unfilled data filled and it throws error on that.

Consider use the form like this (with novalidate attribute):

< form novalidate>< /form>

this way youll not be tight to the browser validation, but you have to validate by yourself

EDIT: attached live examples of add and remove elements

function yesnoCheck(resp) {

var yes = '<div class="form-group">'+
        '<label for="account" class="col-sm-3 control-label">Account Number</label>'+
        '<div class="col-sm-9">'+
            '<input type="text" class="form-control" id="account" name="account" placeholder="Enter Account Number">'+
        '</div>'+
    '</div>'+

    '<div class="form-group">'+
        '<label for="lastname" class="col-sm-3 control-label">Zip Code</label>'+
        '<div class="col-sm-9">'+
            '<input type="text" class="form-control" id="zip" name="zip" placeholder="Enter Zip Code">'+
        '</div>'+
    '</div>';

   if(resp == 'yes') {
      $('#ifYes').append(yes);
   } else {
      $('#ifYes').html('');
   }

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="section section-breadcrumbs">
   <div class="container">
    <div class="row">
     <div class="col-md-12">
      <h1>Register</h1>
     </div>
    </div>
   </div>
  </div>

<div class="section">
  <div class="container">
      <div class="row">
     <div class="col-sm-8 col-sm-offset-2">
              <div class="panel panel-default">
                <div class="panel-body">
                  <h2>Online Training Access</h2>
                  <p><em>We need to verify if you are a retailer first. Please enter your account number without spaces or dashes, or select 'no' if you are a consumer.</em></p><br>

<form class="form-horizontal" role="form" id="my-account-form" method="post"  action="">
    <div class="col-sm-offset-3"></div>

<div class="form-group">
    <label for="lastname" class="col-sm-3 control-label">Are you a retailer?</label>
        <div class="col-sm-9">
         Yes <input type="radio" onclick="javascript:yesnoCheck('yes');" name="yesno" id="yesCheck">
         No <input type="radio" onclick="javascript:yesnoCheck('no');" name="yesno" id="noCheck">
        </div>
</div>

<!-- the contents will only be added if yes -->
<div id="ifYes">
</div>

</form>
</div>
</div>
</div>
</div>
</div>


问:
Spring HttpServerErrorException custom response body not being serialized
I have a Controller like this example:

```<code>@RestController
@RequestMapping(value = "/risk", produces = {MediaType.APPLICATION_JSON_VALUE})
public class CalculationController {
    @RequestMapping(value = "/calculate", method = RequestMethod.POST)
    public CalculationResult calculate(InputFields i) {
       try {
           return calcService.calculate(i);
       } catch (CustomException custEx) {
            throw new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR,
                                                null,
                                                null,
                                                getReportLogAsBytes(custEx), //for some reason not working when serialized in Json
                                                Charset.defaultCharset());
        }
    }

    private byte[] getReportLogAsBytes(CustomException e) {
        try {
            return objectMapper.writeValueAsBytes(e.getReportLog()); //
        } catch (JsonProcessingException e1) {
            throw new RuntimeException("Unable to serialize Simulation report log to bytes ", e1);
        }
    }

    class CustomException extends Exception {

        private List<String> reportLog;

        public CustomException(List<String> reportLog) {
            super();
            this.setReportLog(reportLog);
        }

        public List<String> getReportLog() {
            return reportLog;
        }

        public void setReportLog(List<String> reportLog) {
            this.reportLog = reportLog;
        }
    }
}
</code>```

When posting the inputs to the controller and a CustomException occurs, I instantiate HttpServerErrorException using the constructor that accepts a byte array for responseBody. I basically give it a list of String error messages converted to byte array.

The problem is the response body still does not show the list of errors messages I passed to it. I tried looking for examples on using HttpServerErrorException  with response body but cannot seem to find any... Any help would be greatly appreciated.

答:
You throw your HttpServerErrorException but don't handle it in the proper way.

Read this: https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

Body:
I have a Controller like this example:

@RestController
@RequestMapping(value = "/risk", produces = {MediaType.APPLICATION_JSON_VALUE})
public class CalculationController {
    @RequestMapping(value = "/calculate", method = RequestMethod.POST)
    public CalculationResult calculate(InputFields i) {
       try {
           return calcService.calculate(i);
       } catch (CustomException custEx) {
            throw new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR,
                                                null,
                                                null,
                                                getReportLogAsBytes(custEx), //for some reason not working when serialized in Json
                                                Charset.defaultCharset());
        }
    }

    private byte[] getReportLogAsBytes(CustomException e) {
        try {
            return objectMapper.writeValueAsBytes(e.getReportLog()); //
        } catch (JsonProcessingException e1) {
            throw new RuntimeException("Unable to serialize Simulation report log to bytes ", e1);
        }
    }

    class CustomException extends Exception {

        private List<String> reportLog;

        public CustomException(List<String> reportLog) {
            super();
            this.setReportLog(reportLog);
        }

        public List<String> getReportLog() {
            return reportLog;
        }

        public void setReportLog(List<String> reportLog) {
            this.reportLog = reportLog;
        }
    }
}

When posting the inputs to the controller and a CustomException occurs, I instantiate HttpServerErrorException using the constructor that accepts a byte array for responseBody. I basically give it a list of String error messages converted to byte array.

The problem is the response body still does not show the list of errors messages I passed to it. I tried looking for examples on using HttpServerErrorException  with response body but cannot seem to find any... Any help would be greatly appreciated.


问:
C++/CLI Open XML SDK Excel cannot use AddNewPart
I am using C++/CLI for a school project and I need to export some data into Excel format (xlsx). The problem is that this code has parts like AddNewPart that are underlined with red by Visual Studio (it says that the specified class has no member AddNewPart) but the code is compiled and the application runs but the result is a corrupted xlsx file (when I tried to open it with excel it says that is corrupt).</p>

```<code>SpreadsheetDocument ^doc = SpreadsheetDocument::Create(path_get, SpreadsheetDocumentType::Workbook);

WorkbookPart ^wbookpart = doc->AddWorkbookPart();
wbookpart->Workbook = gcnew Workbook();

WorksheetPart^ worksheetPart = wbookpart->AddNewPart<WorksheetPart^>();
SheetData^ sheetData = gcnew SheetData();
worksheetPart->Worksheet = gcnew Worksheet();
worksheetPart->Worksheet->AppendChild(sheetData);

Sheets^ sheets = doc->WorkbookPart->Workbook->AppendChild<Sheets^>(gcnew Sheets());
Sheet^ sheet = gcnew Sheet();
sheet->Id = doc->WorkbookPart->GetIdOfPart(worksheetPart);
sheet->SheetId = 1;
sheet->Name = "mySheet";
sheets->Append(sheet);
wbookpart->Workbook->Save();
doc->Close();
</code>```

答:
I had the same problem as you, Visual Studio reports that the class has no member, but it still compiles and still seems to populate the parameters for me.  Try stepping through with the debugger and see if this is the same for you. If I try to rename AddNewPart to something that definitely doesn't exist, it doesn't compile for me.

As a less complicated check, GetIdOfPart is also reporting the same error message for me, but that parameter definitely fills in on the debugger despite visual studio claiming the class has no member.

Body:
I am using C++/CLI for a school project and I need to export some data into Excel format (xlsx). The problem is that this code has parts like AddNewPart that are underlined with red by Visual Studio (it says that the specified class has no member AddNewPart) but the code is compiled and the application runs but the result is a corrupted xlsx file (when I tried to open it with excel it says that is corrupt).

SpreadsheetDocument ^doc = SpreadsheetDocument::Create(path_get, SpreadsheetDocumentType::Workbook);

WorkbookPart ^wbookpart = doc->AddWorkbookPart();
wbookpart->Workbook = gcnew Workbook();

WorksheetPart^ worksheetPart = wbookpart->AddNewPart<WorksheetPart^>();
SheetData^ sheetData = gcnew SheetData();
worksheetPart->Worksheet = gcnew Worksheet();
worksheetPart->Worksheet->AppendChild(sheetData);

Sheets^ sheets = doc->WorkbookPart->Workbook->AppendChild<Sheets^>(gcnew Sheets());
Sheet^ sheet = gcnew Sheet();
sheet->Id = doc->WorkbookPart->GetIdOfPart(worksheetPart);
sheet->SheetId = 1;
sheet->Name = "mySheet";
sheets->Append(sheet);
wbookpart->Workbook->Save();
doc->Close();


问:
connecting to AWS server where docker is deployed through template
I am following the article that I found here...

https://docs.docker.com/datacenter/install/aws/

I am able to deploy the template, but I do not see the UCP and DTR URLs in the output tab.

Actually there are only 2 parameters in the output tab. DefaultDNSTarget and Managers. How do I connect to docker swarm?

答: In the "Managers" Parameter of the output tab the value should be a URL that will redirect you to a filtered view of the EC2 Instances that are the managers. There you will see the PublicIpAddresses of the managers. </p>


问:
How to parse text file with multiple delimiters
I have a text file I'm trying to parse. The data is a single string and uses four types of deliminators. There's also a record count at the end of the file that's not pertinent to the data that I can ignore.

Deliminators:

Beginning of data: ~

Field Seperator: |

End of record: #

End of data: ^

Sample text file:

```<code>~001|John|Smith|300#002|Abby|Williams|250#003|Tom|Jones|400#004|Claire|Benton|300^
Count:4
</code>```

The parsed data should be stored in a list or collection of objects "Account"

```<code>public class Account
        {
            public string IdNum { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string AmtDue { get; set; }
        }
</code>```

I'm still new to programming so please teach me what would be the best way to parse and store this data?
Thanks in advance.

答:
If you know all delimiters, you can use something like this:

```<code>var s = "~001|John|Smith|300#002|Abby|Williams|250#003|Tom|Jones|400#004|Claire|Benton|300^Count: 4";

// select a line between "~" and "^".
var data = new string(s.SkipWhile(c => c == '~').TakeWhile(c => c != '^').ToArray());
var records = data.Split('#');
var accounts = records.Select(record => record.Split('|'))
  .Select(items => new Account
  {
    IdNum = items[0],
    FirstName = items[1],
    LastName = items[2],
    AmtDue = items[3]
  })
  .ToList();

foreach (var account in accounts)
{
  Console.WriteLine(account.IdNum);
  Console.WriteLine(account.FirstName);
  Console.WriteLine(account.LastName);
  Console.WriteLine(account.AmtDue);
  Console.WriteLine();
}
</code>```

Just first of all split by row delimiters, then split by field delimiter.

P.S. Don't forget check variables on null or array length like you need.

Body:
I have a text file I'm trying to parse. The data is a single string and uses four types of deliminators. There's also a record count at the end of the file that's not pertinent to the data that I can ignore.

Deliminators:

Beginning of data: ~

Field Seperator: |

End of record: #

End of data: ^

Sample text file:

~001|John|Smith|300#002|Abby|Williams|250#003|Tom|Jones|400#004|Claire|Benton|300^
Count:4

The parsed data should be stored in a list or collection of objects "Account"

public class Account
        {
            public string IdNum { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string AmtDue { get; set; }
        }

I'm still new to programming so please teach me what would be the best way to parse and store this data?
Thanks in advance.

Body:
If you know all delimiters, you can use something like this:

var s = "~001|John|Smith|300#002|Abby|Williams|250#003|Tom|Jones|400#004|Claire|Benton|300^Count: 4";

// select a line between "~" and "^".
var data = new string(s.SkipWhile(c => c == '~').TakeWhile(c => c != '^').ToArray());
var records = data.Split('#');
var accounts = records.Select(record => record.Split('|'))
  .Select(items => new Account
  {
    IdNum = items[0],
    FirstName = items[1],
    LastName = items[2],
    AmtDue = items[3]
  })
  .ToList();

foreach (var account in accounts)
{
  Console.WriteLine(account.IdNum);
  Console.WriteLine(account.FirstName);
  Console.WriteLine(account.LastName);
  Console.WriteLine(account.AmtDue);
  Console.WriteLine();
}

Just first of all split by row delimiters, then split by field delimiter.

P.S. Don't forget check variables on null or array length like you need.


问:
How DO I disable minimize, maximize button in the browser?
'm trying to make an application for chrome and I have the manifest file background.js and then the window.html. I'm trying to disable/remove the maximize/minimize button where it says x on the top of the right hand side of the page but I'm doing it for a chrome application . How do I disable it so people cant change the size of it? Code is needed tried looking for code and myself but couldn't find anything. Would be amazing if you could I know stack overflow is see code and get better code but I don't know any code for this please help me I'm desperate! thanks!</p>

答:
This is a browser limitation - you can't do this. Malicious actions like these are disabled by browsers.

However, you can open a window without a toolbar or menubar:

```<code>window.open("mypage.html","mywindowname", "toolbar=no,menubar=no");
</code>```

Check out this reference for more information on window.open.

Body:
This is a browser limitation - you can't do this. Malicious actions like these are disabled by browsers.

However, you can open a window without a toolbar or menubar:

window.open("mypage.html","mywindowname", "toolbar=no,menubar=no");

Check out this reference for more information on window.open.


问:
Elegantly handle different parameter types
I have a function that, in the simplest of cases, operates on an iterable of items.

```<code>def foo(items):
    for item in items:
        # do stuff
</code>```

Sometimes, I do not want to pass it an iterable of items directly, but rather an object that provides a method to get the iterable:

```<code>def foo(obj):
    for item in obj.iteritems():
        # do same stuff as above
</code>```

I can merge these two cases like this:

```<code>def foo(obj):
    try:
        items = obj.iteritems()
    except ValueError:
        items = obj
    for item in items:
        # do stuff
</code>```

This works just fine. Now I get a third use case that looks like this:

```<code>def foo(objs):
    for item in itertools.chain.from_iterable(obj.iteritems() for obj in objs):
        # do same stuff again
</code>```

I can still use the try-except approach, since the interfaces are incompatible. However, the nested try catch would start to become very ugly. More so when I want to add a fourth use-case. Is there any way to solve this without nesting the try-blocks?

答:
To check if an object is iterable:

```<code>import collections
isinstance(obj, collections.Iterable)
</code>```

This should get you rid of some problems.

Also, a way to handle such problems is by using recursivity (don't know if it's applicable though):

```<code>def foo(obj):
    if isinstance(obj, collections.Iterable):
        for el in obj:
            foo(el)
    # now do stuff
</code>```

Body:
I have a function that, in the simplest of cases, operates on an iterable of items.

def foo(items):
    for item in items:
        # do stuff

Sometimes, I do not want to pass it an iterable of items directly, but rather an object that provides a method to get the iterable:

def foo(obj):
    for item in obj.iteritems():
        # do same stuff as above

I can merge these two cases like this:

def foo(obj):
    try:
        items = obj.iteritems()
    except ValueError:
        items = obj
    for item in items:
        # do stuff

This works just fine. Now I get a third use case that looks like this:

def foo(objs):
    for item in itertools.chain.from_iterable(obj.iteritems() for obj in objs):
        # do same stuff again

I can still use the try-except approach, since the interfaces are incompatible. However, the nested try catch would start to become very ugly. More so when I want to add a fourth use-case. Is there any way to solve this without nesting the try-blocks?

Body:
To check if an object is iterable:

import collections
isinstance(obj, collections.Iterable)

This should get you rid of some problems.

Also, a way to handle such problems is by using recursivity (don't know if it's applicable though):

def foo(obj):
    if isinstance(obj, collections.Iterable):
        for el in obj:
            foo(el)
    # now do stuff


答:
First modify your macro like this to add date parameter:

```<code>Sub DataImport2(dDate as String)
'
' DataImport2 Macro
'
With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;d:\testfiles\project1\" & dDate & "\filename.txt" _
        , Destination:=Range("$A$2"))
</code>```

Then in UFT, capture the date from GUI and convert it to format of your file name(if require).

And lastly run your macro from UFT like this:

```<code>Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("ExcelFilePath\FileName.xlsm", 0, True)
objExcel.Visible = False
objExcel.DisplayAlerts = False
objExcel.Run "DataImport2", sDate 'sDate variable holding date
objExcel.Application.Quit
Set objWorkbook = Nothing : Set objExcel = Nothing
</code>```

Title: Passing variables from QTP/UFT to Excel macros

Body:
First modify your macro like this to add date parameter:

Sub DataImport2(dDate as String)
'
' DataImport2 Macro
'
With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;d:\testfiles\project1\" & dDate & "\filename.txt" _
        , Destination:=Range("$A$2"))

Then in UFT, capture the date from GUI and convert it to format of your file name(if require).

And lastly run your macro from UFT like this:

Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("ExcelFilePath\FileName.xlsm", 0, True)
objExcel.Visible = False
objExcel.DisplayAlerts = False
objExcel.Run "DataImport2", sDate 'sDate variable holding date
objExcel.Application.Quit
Set objWorkbook = Nothing : Set objExcel = Nothing


问:
Special characters printed bold on iOS
On some parts of the site I am maintaining German umlauts are displayed in bold (see screenshot). I am using font-family: Source Sans Pro, Arial, sans-serif; with font-weight: 300. The font is embedded from Google Fonts.

Changing the font weight to 400 and above or using a different font works flawlessly. The thing that really weirds me out that it only occurs for the lower paragraph. I tried disabling every font-related style in Safari Web Inspector for both paragraphs without success.

This seems to only happen in Safari and Chrome on iOS (Chrome on macOS and Android works fine).

Affected site: https://sentience-politics.org/de/positionspapiere/

答: Found the solution. The umlauts were actually different ASCII characters than the standard ones (e.g. 097 204 136 instead of 195 164 for ä). We suspect they come from a time when the website was using an outdated LaTeX plugin. Swapping the characters for normal umlauts fixed the problem.

Title: Special characters printed bold on iOS


问:
Qt SQLite search query speed
I'm creating a database in SQLite as follows:

```<code>QSqlQuery create_address;
create_address.prepare("CREATE TABLE addresses (addressid INTEGER PRIMARY KEY AUTOINCREMENT, address TEXT UNIQUE)");
QSqlQuery create_devices;
create_devices.prepare("CREATE TABLE devices (ch TEXT PRIMARY KEY, addressid INTEGER REFERENCES addresses(addressid))");

create_devices.exec();
create_address.exec();
</code>```

I need to access this database a lot of times (~660'000) passing ch and retrieving the corresponding address, the ch passed could not be in the database (empty string is returned).

To do so i made the following query

```<code>//outside loop
QSqlQuery find_address;
find_address.prepare("SELECT address FROM addresses,devices WHERE devices.addressid = addresses.addressid AND devices.ch = :chcode");

//in loop
find_address.bindValue(":chcode",QString::fromStdString(ch_code));

find_address.exec();
</code>```

The problem is that this process is very slow (it takes almost 12 minutes to finish all the 660'000 searches).

Before this i tried with an INNER JOIN but the performance was pretty much the same.

Is there a better way to write the query and/or structure the DB to get a faster execution time?

答:
Without any measurement or insights how the tables addresses and devices look like it's hard to give a precise advice.

Maybe the join is the bottleneck so you can try to create a view first. This would avoid joining two tables 659000 times. See here on how to create a view.

Next (shot in the dark), instead of executing 660000 queries, make batches. For example replace AND devices.ch = :chcode by AND devices.ch IN(:chcodelist) and glue multiple chcodes together. Depending on the content, take care of their escaping yourself.

Title: Qt SQLite search query speed

Body:
I'm creating a database in SQLite as follows:

QSqlQuery create_address;
create_address.prepare("CREATE TABLE addresses (addressid INTEGER PRIMARY KEY AUTOINCREMENT, address TEXT UNIQUE)");
QSqlQuery create_devices;
create_devices.prepare("CREATE TABLE devices (ch TEXT PRIMARY KEY, addressid INTEGER REFERENCES addresses(addressid))");

create_devices.exec();
create_address.exec();

I need to access this database a lot of times (~660'000) passing ch and retrieving the corresponding address, the ch passed could not be in the database (empty string is returned).

To do so i made the following query

//outside loop
QSqlQuery find_address;
find_address.prepare("SELECT address FROM addresses,devices WHERE devices.addressid = addresses.addressid AND devices.ch = :chcode");

//in loop
find_address.bindValue(":chcode",QString::fromStdString(ch_code));

find_address.exec();

The problem is that this process is very slow (it takes almost 12 minutes to finish all the 660'000 searches).

Before this i tried with an INNER JOIN but the performance was pretty much the same.

Is there a better way to write the query and/or structure the DB to get a faster execution time?


问:
Visual Studio: How can I see the same file in two separate tab groups?
I want to be able to edit one method while looking at another method in the same file, as reference.
Can this be done?</p>

答:
You can open the file in another tab (Window -> New Window).

Doing so you have two copies of the same file. Then you can right-click the tab bar and select New Vertical Tab Group (or New Horizontal Tab Group, the one you like more).

Hope I understood you question..

OwnerDisplayName: Ofer


问:
Is there a predefined enumeration for Month in the .NET library?
I'm looking to see if there is an official enumeration for months in the .net framework.

It seems possible to me that there is one, because of how common the use of month is, and because there are other such enumerations in the .net framework.

For instance, there is an enumeration for the days in the week, System.DayOfWeek, which includes Monday, Tuesday, etc..

I'm wondering if there is one for the months in the year, i.e. January, February, etc?

Does anyone know?

答:
Some calender do indeed have more than 12 months: http://en.wikipedia.org/wiki/Month but I can't say if it was the reason MS did not built an enum in .NET.

For the lazy like me who would have liked a copy/paste, in VB:

```<code>Public Enum MonthsOfYear
    January = 1
    February = 2
    March = 3
    April = 4
    May = 5
    June = 6
    July = 7
    August = 8
    September = 9
    October = 10
    November = 11
    December = 12
End Enum
</code>```

Body:
Some calender do indeed have more than 12 months: http://en.wikipedia.org/wiki/Month but I can't say if it was the reason MS did not built an enum in .NET.

For the lazy like me who would have liked a copy/paste, in VB:

Public Enum MonthsOfYear
    January = 1
    February = 2
    March = 3
    April = 4
    May = 5
    June = 6
    July = 7
    August = 8
    September = 9
    October = 10
    November = 11
    December = 12
End Enum


问:
Python: is using "..%(var)s.." % locals() a good practice?
I discovered this pattern (or anti-pattern) and I am very happy with it.

I feel it is very agile:

```<code>def example():
    age = ...
    name = ...
    print "hello %(name)s you are %(age)s years old" % locals()
</code>```

Sometimes I use its cousin:

```<code>def example2(obj):
    print "The file at %(path)s has %(length)s bytes" % obj.__dict__
</code>```

I don't need to create an artificial tuple and count parameters and keep the %s matching positions inside the tuple.

Do you like it? Do/Would you use it? Yes/No, please explain.

答:
There is now an official way to do this, as of Python 3.6.0: formatted string literals.

It works like this:

```<code>f'normal string text {local_variable_name}'
</code>```

E.g. instead of these:

```<code>"hello %(name)s you are %(age)s years old" % locals()
"hello {name} you are {age} years old".format(**locals())
"hello {} you are {} years old".format(name, age)
</code>```

just do this:

```<code>f"hello {name} you are {age} years old"
</code>```

Here's the official example:

```<code>>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}"  # nested fields
'result:      12.35'
</code>```

Reference:

Python 3.6 What's New

PEP 498

Lexical analysis description

Body:
I discovered this pattern (or anti-pattern) and I am very happy with it.

I feel it is very agile:

def example():
    age = ...
    name = ...
    print "hello %(name)s you are %(age)s years old" % locals()

Sometimes I use its cousin:

def example2(obj):
    print "The file at %(path)s has %(length)s bytes" % obj.__dict__

I don't need to create an artificial tuple and count parameters and keep the %s matching positions inside the tuple.

Do you like it? Do/Would you use it? Yes/No, please explain.

Body:
There is now an official way to do this, as of Python 3.6.0: formatted string literals.

It works like this:

f'normal string text {local_variable_name}'

E.g. instead of these:

"hello %(name)s you are %(age)s years old" % locals()
"hello {name} you are {age} years old".format(**locals())
"hello {} you are {} years old".format(name, age)

just do this:

f"hello {name} you are {age} years old"

Here's the official example:

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}"  # nested fields
'result:      12.35'

Reference:

Python 3.6 What's New

PEP 498

Lexical analysis description


问:
How to select all checkboxes with a class name inside a table by table id
I have several tables on my page, and a table with the id of workOneTable. I have several rows in the table with class name of .rsvLine and more with class name .vtoLine. I need to be able to select all checkboxes in workOneTable with class name .rsvLine.
I have tried several things.

```<code>$( '#workOneTable :checkbox.rsvLine' ).prop( 'checked', this.checked );

$( '#workOneTable' ).find( 'input[type=checkbox]' ).prop( 'checked', true );

$( '#workOneTable tbody .rsvLine :checkbox' ).prop( 'checked' );
</code>```

Any help is greatly appreciated.

EDIT

Here is the most relevant part of the html code.

```<code><table id=workOneTable>
<thead>
    several rows here
</thead>
<tbody>
    <tr>
        <td class="rsvLine"><input type="checkbox" ></td>
        <td class="rsvLine"><input type="checkbox" ></td>
        <td class="rsvLine"><input type="checkbox" ></td>
        <td class="vtoLine"><input type="checkbox" ></td>
        <td class="vtoLine"><input type="checkbox" ></td>
        <td class="vtoLine"><input type="checkbox" ></td>
        <td class="rsvLine">other stuff</td>
        <td class="rsvLine">other stuff</td>
    </tr>
</tbody>
</code>```

I can select the right ones if I do not use the table id. It will select the .rsvLine in all tables. this is the code I used for that.

```<code>$( '.rsvLine :checkbox' ).each( function ()
            {
                if ( !$( this ).prop( "checked" ) )
                {
                    this.click();
                }
            } );
</code>```

答:
If you are trying to set .checked property to opposite of current Boolean value of .checked property use ! operator preceding this.checked at .prop() value

$(function() {
  $('#workOneTable .rsvLine :checkbox')
  .each(function() {
    $(this).prop('checked', !this.checked)
  });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="workOneTable">
  <thead>
    several rows here
  </thead>
  <tbody>
    <tr>
      <td class="rsvLine"><input type="checkbox"></td>
      <td class="rsvLine"><input type="checkbox"></td>
      <td class="rsvLine"><input type="checkbox"></td>
      <td class="vtoLine"><input type="checkbox"></td>
      <td class="vtoLine"><input type="checkbox"></td>
      <td class="vtoLine"><input type="checkbox"></td>
      <td class="rsvLine">other stuff</td>
      <td class="rsvLine">other stuff</td>
    </tr>
  </tbody>
</table></code>```

Body:
I have several tables on my page, and a table with the id of workOneTable. I have several rows in the table with class name of .rsvLine and more with class name .vtoLine. I need to be able to select all checkboxes in workOneTable with class name .rsvLine.
I have tried several things.

$( '#workOneTable :checkbox.rsvLine' ).prop( 'checked', this.checked );

$( '#workOneTable' ).find( 'input[type=checkbox]' ).prop( 'checked', true );

$( '#workOneTable tbody .rsvLine :checkbox' ).prop( 'checked' );

Any help is greatly appreciated.

EDIT

Here is the most relevant part of the html code.

    several rows here

        <input type="checkbox" >
        <input type="checkbox" >
        <input type="checkbox" >
        <input type="checkbox" >
        <input type="checkbox" >
        <input type="checkbox" >
        other stuff
        other stuff

I can select the right ones if I do not use the table id. It will select the .rsvLine in all tables. this is the code I used for that.

$( '.rsvLine :checkbox' ).each( function ()
            {
                if ( !$( this ).prop( "checked" ) )
                {
                    this.click();
                }
            } );

Body:
If you are trying to set .checked property to opposite of current Boolean value of .checked property use ! operator preceding this.checked at .prop() value

$(function() {
  $('#workOneTable .rsvLine :checkbox')
  .each(function() {
    $(this).prop('checked', !this.checked)
  });
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="workOneTable">
  <thead>
    several rows here
  </thead>
  <tbody>
    <tr>
      <td class="rsvLine"><input type="checkbox"></td>
      <td class="rsvLine"><input type="checkbox"></td>
      <td class="rsvLine"><input type="checkbox"></td>
      <td class="vtoLine"><input type="checkbox"></td>
      <td class="vtoLine"><input type="checkbox"></td>
      <td class="vtoLine"><input type="checkbox"></td>
      <td class="rsvLine">other stuff</td>
      <td class="rsvLine">other stuff</td>
    </tr>
  </tbody>
</table>


问:
Convert multiple year and month pay data in a monthly sum R
In R: I had two files that I have joined. Both contain commission pay data, I had two files because the pay structure periods of the jobs codes were different. For example, all the job codes in file one are paid commission monthly and all the job codes in file two are paid commission bi-monthly.
  In order to accurately and fairly analyze the data I need to aggregate (sum) pay into a new field (let's call it "monthlypay") by month for each employee id (currently a factor), my problem is that I appear to successfully sum the pay for month for each employee, but currently it ignores the differing years. I'm not opposed to spreading year and month OR dummy coding from 6/2015-6/2017 as pay months 1-24, but I'm wondering if there is a way to do this all at once?

Current:

```<code>Check_DT   EMPLID   DEPTID JOBCODE PAY_FREQUENCY MAX._TTL.GROSS
2015-12-18 99999999 23231606  100880             W           1203
2015-12-24 99999999 23231606  100880             W            597
2015-12-31 99999999 23231606  100880             W            625
2016-01-08 99999999 23231606  100880             W            245
2016-01-13 99999999 23231606  100880             W            480
2016-01-15 99999999 23231606  100880             W            758
2016-01-22 99999999 23231606  100880             W            599
2016-01-29 99999999 23231606  100880             W            551
2016-02-05 99999999 23231606  100880             W            767
2016-02-12 99999999 23231606  100880             W            880
2016-02-19 99999999 23231606  100880             W            557
2016-02-26 99999999 20441606  100880             W            909
2016-03-04 99999999 20441606  100880             W            989
2016-03-11 99999999 20441606  100880             W            751
2016-03-18 99999999 20441606  100880             W            776
2016-03-25 99999999 20441606  100880             W            770
2016-04-01 99999999 20441606  100880             W            712
2016-04-08 99999999 20441606  100880             W            602
2016-04-15 99999999 20441606  100880             W            798
2016-04-22 99999999 20441606  100880             W            527
</code>```

What I want (need actually, I am going to be running cluster analysis):

```<code>>Check_DT   EMPLID   DEPTID JOBCODE PAY_FREQUENCY MAX._TTL.GROSS Year Month Pay
>2015-12-18 99999999 23231606  100880             W           1203 2015 12 2425
>2015-12-24 99999999 23231606  100880             W            597
>2015-12-31 99999999 23231606  100880             W            625
>2016-01-08 99999999 23231606  100880             W            245 2016 01 2633
>2016-01-13 99999999 23231606  100880             W            480
>2016-01-15 99999999 23231606  100880             W            758
>2016-01-22 99999999 23231606  100880             W            599
>2016-01-29 99999999 23231606  100880             W            551
>2016-02-05 99999999 23231606  100880             W            767
>2016-02-12 99999999 23231606  100880             W            880
>2016-02-19 99999999 23231606  100880             W            557
>2016-02-26 99999999 20441606  100880             W            909
>2016-03-04 99999999 20441606  100880             W            989
>2016-03-11 99999999 20441606  100880             W            751
>2016-03-18 99999999 20441606  100880             W            776
>2016-03-25 99999999 20441606  100880             W            770
>2016-04-01 99999999 20441606  100880             W            712
>2016-04-08 99999999 20441606  100880             W            602
>2016-04-15 99999999 20441606  100880             W            798
>2016-04-22 99999999 20441606  100880             W            527
</code>```

etc...I am not even opposed to the year month and date for every year and month combo to repeated, I can get rid of duplicates. As a reminder some people in the file are paid weekly and others a paid bi-monthly.

Here is what I've done:

```<code>#Convert weekly/bimonthly pay to monthly sum of pay
  paydat_all$monthlypay <- month(paydat_all$Check_DT)
  aggregate(MAX._TTL.GROSS~monthlypay+EMPLID, FUN = sum, data = paydat_all)
</code>```

Body:
In R: I had two files that I have joined. Both contain commission pay data, I had two files because the pay structure periods of the jobs codes were different. For example, all the job codes in file one are paid commission monthly and all the job codes in file two are paid commission bi-monthly.
  In order to accurately and fairly analyze the data I need to aggregate (sum) pay into a new field (let's call it "monthlypay") by month for each employee id (currently a factor), my problem is that I appear to successfully sum the pay for month for each employee, but currently it ignores the differing years. I'm not opposed to spreading year and month OR dummy coding from 6/2015-6/2017 as pay months 1-24, but I'm wondering if there is a way to do this all at once?

Current:

Check_DT   EMPLID   DEPTID JOBCODE PAY_FREQUENCY MAX._TTL.GROSS
2015-12-18 99999999 23231606  100880             W           1203
2015-12-24 99999999 23231606  100880             W            597
2015-12-31 99999999 23231606  100880             W            625
2016-01-08 99999999 23231606  100880             W            245
2016-01-13 99999999 23231606  100880             W            480
2016-01-15 99999999 23231606  100880             W            758
2016-01-22 99999999 23231606  100880             W            599
2016-01-29 99999999 23231606  100880             W            551
2016-02-05 99999999 23231606  100880             W            767
2016-02-12 99999999 23231606  100880             W            880
2016-02-19 99999999 23231606  100880             W            557
2016-02-26 99999999 20441606  100880             W            909
2016-03-04 99999999 20441606  100880             W            989
2016-03-11 99999999 20441606  100880             W            751
2016-03-18 99999999 20441606  100880             W            776
2016-03-25 99999999 20441606  100880             W            770
2016-04-01 99999999 20441606  100880             W            712
2016-04-08 99999999 20441606  100880             W            602
2016-04-15 99999999 20441606  100880             W            798
2016-04-22 99999999 20441606  100880             W            527

What I want (need actually, I am going to be running cluster analysis):

>Check_DT   EMPLID   DEPTID JOBCODE PAY_FREQUENCY MAX._TTL.GROSS Year Month Pay
>2015-12-18 99999999 23231606  100880             W           1203 2015 12 2425
>2015-12-24 99999999 23231606  100880             W            597
>2015-12-31 99999999 23231606  100880             W            625
>2016-01-08 99999999 23231606  100880             W            245 2016 01 2633
>2016-01-13 99999999 23231606  100880             W            480
>2016-01-15 99999999 23231606  100880             W            758
>2016-01-22 99999999 23231606  100880             W            599
>2016-01-29 99999999 23231606  100880             W            551
>2016-02-05 99999999 23231606  100880             W            767
>2016-02-12 99999999 23231606  100880             W            880
>2016-02-19 99999999 23231606  100880             W            557
>2016-02-26 99999999 20441606  100880             W            909
>2016-03-04 99999999 20441606  100880             W            989
>2016-03-11 99999999 20441606  100880             W            751
>2016-03-18 99999999 20441606  100880             W            776
>2016-03-25 99999999 20441606  100880             W            770
>2016-04-01 99999999 20441606  100880             W            712
>2016-04-08 99999999 20441606  100880             W            602
>2016-04-15 99999999 20441606  100880             W            798
>2016-04-22 99999999 20441606  100880             W            527

etc...I am not even opposed to the year month and date for every year and month combo to repeated, I can get rid of duplicates. As a reminder some people in the file are paid weekly and others a paid bi-monthly.

Here is what I've done:

#Convert weekly/bimonthly pay to monthly sum of pay
  paydat_all$monthlypay <- month(paydat_all$Check_DT)
  aggregate(MAX._TTL.GROSS~monthlypay+EMPLID, FUN = sum, data = paydat_all)

Body:
This should get you the results you're looking for

library(lubridate)
library(dplyr)

 data = 'Check_DT   EMPLID   DEPTID JOBCODE PAY_FREQUENCY MAX._TTL.GROSS
"2015-12-18" 99999999 23231606  100880             W           1203
"2015-12-24" 99999999 23231606  100880             W            597
"2015-12-31" 99999999 23231606  100880             W            625
"2016-01-08" 99999999 23231606  100880             W            245
"2016-01-13" 99999999 23231606  100880             W            480
"2016-01-15" 99999999 23231606  100880             W            758
"2016-01-22" 99999999 23231606  100880             W            599
"2016-01-29" 99999999 23231606  100880             W            551
"2016-02-05" 99999999 23231606  100880             W            767
"2016-02-12" 99999999 23231606  100880             W            880
"2016-02-19" 99999999 23231606  100880             W            557
"2016-02-26" 99999999 20441606  100880             W            909
"2016-03-04" 99999999 20441606  100880             W            989
"2016-03-11" 99999999 20441606  100880             W            751
"2016-03-18" 99999999 20441606  100880             W            776
"2016-03-25" 99999999 20441606  100880             W            770
"2016-04-01" 99999999 20441606  100880             W            712
"2016-04-08" 99999999 20441606  100880             W            602
"2016-04-15" 99999999 20441606  100880             W            798
"2016-04-22" 99999999 20441606  100880             W            527'

paydat_all <- read.table(text=data, header=TRUE,
                         colClasses=c("Date", "character", "character",
                                      "character", "factor", "integer"))

paydat_all <- paydat_all %>%
              mutate(Year = year(Check_DT),
                     Month = month(Check_DT)) %>%
              group_by(EMPLID, DEPTID, JOBCODE, Year, Month) %>%
              summarise(sum(MAX._TTL.GROSS))


问:
Python - remove a word or matching string from a text file
I am trying to remove a word from a text file and found a code that seems to be working.

However, it doesn't match an exact word, instead removes all matching letters.

```<code>fin = open("input.txt")
fout = open("output.txt", "w+")
delete_list = input('delete : ')
for line in fin:
    for word in delete_list:
        line = line.replace(word, '')
    fout.write(line)
fin.close()
fout.close()
print ('done')
</code>```

input.txt

```<code>http://www.google.co.ma
google.com.mm
https://google.mn
www.google.com.mt
</code>```

Result for trying to remove http:// (only) is as following-

output.txt

```<code>www.google.co.ma
google.com.mm
sgoogle.mn
www.google.com.m
</code>```

答:
Let's take a look at what's happening here:

You call input, which returns a string, "http://". You assign this to the variable delete_list.

You loop through delete_list using a for loop. But note: delete_list is a string, not a list. When you use a for loop to iterate through a string, it loops through the letters of the string.

You go through each letter and remove it from the line.

There are three things you could do to fix this:

Change your assignment of delete_list to assign to a single-element list: delete_list = [input("word to delete: ")]

Rename delete_list to more accurately reflect its true value, something like word_to_delete, then don't use a for loop -- just do line.replace(word_to_delete, '') directly.

Use a loop to get a list of words from the user.

Hope that clears things up!

Body:
I am trying to remove a word from a text file and found a code that seems to be working.

However, it doesn't match an exact word, instead removes all matching letters.

fin = open("input.txt")
fout = open("output.txt", "w+")
delete_list = input('delete : ')
for line in fin:
    for word in delete_list:
        line = line.replace(word, '')
    fout.write(line)
fin.close()
fout.close()
print ('done')

input.txt

http://www.google.co.ma
google.com.mm
https://google.mn
www.google.com.mt

Result for trying to remove http:// (only) is as following-

output.txt

www.google.co.ma
google.com.mm
sgoogle.mn
www.google.com.m


问:
Jackson / JavaTimeModule - handle different timezone offset formats
I'm calling an API (using Jersey) which returns Date Time with zone offset. Sometimes the data is in this format:

```<code>"2017-03-28T14:40:00+01:00"
</code>```

and sometimes it is in this format  (I've no control over this)

```<code>"2017-03-28T14:40:00+0100"  (where the ':' in timezone offset is missing).
</code>```

I want to marshal these into java.time.ZonedDateTime objects. I'm using JavaTimeModule() in my Jersey ObjectMapper.

```<code>objectMapper.registerModule(new JavaTimeModule());
</code>```

The Question : Is there any way to get make the object mapper flexible enough to handle time zone offset in +01:00 or +0100?

答:
You can specify a pattern with optional sections (delimited by []), to indicate that the offset can have 2 different formats, and add this to the respective field using the @JsonFormat annotation.

I've created this test class:

```<code>public class SampleType {

    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss[XXX][XX]")
    private ZonedDateTime date;

    // getter and setter
}
</code>```

Note the last part ([XXX][XX]): each pair of [] is an optional section, so the parser tries to parse each one, if present. XXX is the offset with : and XX is the offset without it (for more details, take a look at the javadoc)

With this, both formats can be read:

```<code>ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());

// offset with ":"
String json = "{ \"date\": \"2017-03-28T14:40:00+01:00\" }";
SampleType value = mapper.readValue(json, SampleType.class);
System.out.println(value.getDate()); // 2017-03-28T13:40Z[UTC]

// offset without ":"
json = "{ \"date\": \"2017-03-28T14:40:00+0100\" }";
value = mapper.readValue(json, SampleType.class);
System.out.println(value.getDate()); // 2017-03-28T13:40Z[UTC]
</code>```

Note that the resulting ZonedDateTime's value is converted to UTC: 2017-03-28T13:40Z[UTC]

If you want to keep the original offset, just use the com.fasterxml.jackson.databind.DeserializationFeature class to configure the ObjectMapper:

```<code>// add this to preserve the same offset (don't convert to UTC)
mapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, false);
</code>```

With this, the offset is preserved (value is not converted to UTC), and the output for the tests above will be 2017-03-28T14:40+01:00.

Body:
I'm calling an API (using Jersey) which returns Date Time with zone offset. Sometimes the data is in this format:

"2017-03-28T14:40:00+01:00"

and sometimes it is in this format  (I've no control over this)

"2017-03-28T14:40:00+0100"  (where the ':' in timezone offset is missing).

I want to marshal these into java.time.ZonedDateTime objects. I'm using JavaTimeModule() in my Jersey ObjectMapper.

objectMapper.registerModule(new JavaTimeModule());

The Question : Is there any way to get make the object mapper flexible enough to handle time zone offset in +01:00 or +0100?

Body:
You can specify a pattern with optional sections (delimited by []), to indicate that the offset can have 2 different formats, and add this to the respective field using the @JsonFormat annotation.

I've created this test class:

public class SampleType {

    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss[XXX][XX]")
    private ZonedDateTime date;

    // getter and setter
}

Note the last part ([XXX][XX]): each pair of [] is an optional section, so the parser tries to parse each one, if present. XXX is the offset with : and XX is the offset without it (for more details, take a look at the javadoc)

With this, both formats can be read:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());

// offset with ":"
String json = "{ \"date\": \"2017-03-28T14:40:00+01:00\" }";
SampleType value = mapper.readValue(json, SampleType.class);
System.out.println(value.getDate()); // 2017-03-28T13:40Z[UTC]

// offset without ":"
json = "{ \"date\": \"2017-03-28T14:40:00+0100\" }";
value = mapper.readValue(json, SampleType.class);
System.out.println(value.getDate()); // 2017-03-28T13:40Z[UTC]

Note that the resulting ZonedDateTime's value is converted to UTC: 2017-03-28T13:40Z[UTC]

If you want to keep the original offset, just use the com.fasterxml.jackson.databind.DeserializationFeature class to configure the ObjectMapper:

// add this to preserve the same offset (don't convert to UTC)
mapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, false);

With this, the offset is preserved (value is not converted to UTC), and the output for the tests above will be 2017-03-28T14:40+01:00.


问:
Miles Away not updating on reload
I have a tableview cell with a uilabel inside of it and its getting the distance between two points(the users current location and another point I choose). The problem is that when I change the point in my database and reload the tableview, the miles away in each cell updates. But when I change my current location in the simulator and reload the tableview, the miles away doesnt update. Here is my code. </p>

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath, object: PFObject?) -> PFTableViewCell? {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cells", for: indexPath as IndexPath) as! MyCell
cell.object = object
let currentLocation = CLLocation()
locManager.distanceFilter = 50
if( CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse ||
    CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways){
    let coordinate₀ = CLLocation(latitude: CLLocationDegrees(-41)!, longitude: CLLocationDegrees(52.3)!)
    let coordinate₁ = CLLocation(latitude: currentLocation.coordinate.longitude, longitude: currentLocation.coordinate.latitude)
    let distanceInMeters = coordinate₀.distance(from: coordinate₁)
    if(distanceInMeters <= 1609)
    {
        cell.Distance.text = "\(Float(round(distanceInMeters * 3.28084)).cleanValue) ft"
    }
    else
    {
        cell.Distance.text = "\(Float(round(distanceInMeters / 1609)).cleanValue) mi"
      }
   }
}
</code>```

答:
You need to define your CLLocationManager in your viewController and then in the didUpdateLocations you need reload your tableView

```<code>import UIKit
import CoreLocation

class MyViewController: UIViewController, CLLocationManagerDelegate {

    @IBOutlet weak var LabelTest: UILabel!
    var manager = CLLocationManager()
    @IBOutlet weak var tableView: UITableView!

    //your default position
    var userLoc = CLLocation(latitude: 42.6977,longitude: 23.3219)
        {
        didSet{
            self.tableView.reloadData()
        }
    }
    //**Your class implementation**/

    override func viewDidLoad() {
        super.viewDidLoad()

        //**Your implementation*//

        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestWhenInUseAuthorization()
        manager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let userlocation: CLLocation = locations[0] as CLLocation
        self.userLoc = userlocation
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath, object: PFObject?) -> PFTableViewCell? {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cells", for: indexPath as IndexPath) as! MyCell
        cell.object = object
        let currentLocation = self.userLoc

        let coordinate₀ = CLLocation(latitude: CLLocationDegrees(-41), longitude: CLLocationDegrees(52.3))
        let coordinate₁ = CLLocation(latitude: currentLocation.coordinate.longitude, longitude: currentLocation.coordinate.latitude)
        let distanceInMeters = coordinate₀.distance(from: coordinate₁)
        if(distanceInMeters <= 1609)
        {
            cell.Distance.text = "\(Float(round(distanceInMeters * 3.28084)).cleanValue) ft"
        }
        else
        {
            cell.Distance.text = "\(Float(round(distanceInMeters / 1609)).cleanValue) mi"
        }
    }
}
</code>```

I hope this helps

Title: Miles Away not updating on reload

Body:
I have a tableview cell with a uilabel inside of it and its getting the distance between two points(the users current location and another point I choose). The problem is that when I change the point in my database and reload the tableview, the miles away in each cell updates. But when I change my current location in the simulator and reload the tableview, the miles away doesnt update. Here is my code.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath, object: PFObject?) -> PFTableViewCell? {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cells", for: indexPath as IndexPath) as! MyCell
cell.object = object
let currentLocation = CLLocation()
locManager.distanceFilter = 50
if( CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse ||
    CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways){
    let coordinate₀ = CLLocation(latitude: CLLocationDegrees(-41)!, longitude: CLLocationDegrees(52.3)!)
    let coordinate₁ = CLLocation(latitude: currentLocation.coordinate.longitude, longitude: currentLocation.coordinate.latitude)
    let distanceInMeters = coordinate₀.distance(from: coordinate₁)
    if(distanceInMeters <= 1609)
    {
        cell.Distance.text = "\(Float(round(distanceInMeters * 3.28084)).cleanValue) ft"
    }
    else
    {
        cell.Distance.text = "\(Float(round(distanceInMeters / 1609)).cleanValue) mi"
      }
   }
}

Body:
You need to define your CLLocationManager in your viewController and then in the didUpdateLocations you need reload your tableView

import UIKit
import CoreLocation

class MyViewController: UIViewController, CLLocationManagerDelegate {

    @IBOutlet weak var LabelTest: UILabel!
    var manager = CLLocationManager()
    @IBOutlet weak var tableView: UITableView!

    //your default position
    var userLoc = CLLocation(latitude: 42.6977,longitude: 23.3219)
        {
        didSet{
            self.tableView.reloadData()
        }
    }
    //**Your class implementation**/

    override func viewDidLoad() {
        super.viewDidLoad()

        //**Your implementation*//

        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestWhenInUseAuthorization()
        manager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let userlocation: CLLocation = locations[0] as CLLocation
        self.userLoc = userlocation
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath, object: PFObject?) -> PFTableViewCell? {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cells", for: indexPath as IndexPath) as! MyCell
        cell.object = object
        let currentLocation = self.userLoc

        let coordinate₀ = CLLocation(latitude: CLLocationDegrees(-41), longitude: CLLocationDegrees(52.3))
        let coordinate₁ = CLLocation(latitude: currentLocation.coordinate.longitude, longitude: currentLocation.coordinate.latitude)
        let distanceInMeters = coordinate₀.distance(from: coordinate₁)
        if(distanceInMeters <= 1609)
        {
            cell.Distance.text = "\(Float(round(distanceInMeters * 3.28084)).cleanValue) ft"
        }
        else
        {
            cell.Distance.text = "\(Float(round(distanceInMeters / 1609)).cleanValue) mi"
        }
    }
}

I hope this helps


问:
Android: How to perform Url Request via Wifi
is there a possiblity to explicitely use the wifi connection for doing Http Url requests?
In fact i just need to know if an internet connection (access to google.com for example) is possible via wifi.
(not via 2g / 3g / ..)</p>

答:
You may find this useful:</p>

```<code>public class ConnectivityHelper {

    public static boolean isWiFiNetworkConnected(Context context) {
        return getWiFiNetworkInfo(context).isConnected();
    }

    private static NetworkInfo getWiFiNetworkInfo(Context context) {
        return getConnectivityManager(context).getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    }

    private static ConnectivityManager getConnectivityManager(Context context) {
        return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    }
}
</code>```

Body:
You may find this useful:

public class ConnectivityHelper {

    public static boolean isWiFiNetworkConnected(Context context) {
        return getWiFiNetworkInfo(context).isConnected();
    }

    private static NetworkInfo getWiFiNetworkInfo(Context context) {
        return getConnectivityManager(context).getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    }

    private static ConnectivityManager getConnectivityManager(Context context) {
        return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    }
}


问:
How do I define root for tkinter in Python 3? I'm using an online Python editor
I am trying to make a label, but I can't define the root variable! Please help me!

Update: I am using an online Python editor called repl.it

I am using Python 3.0

This is my code:

```<code>import time
from tkinter import *

root = Tk()

def w(t):
  if t == t:
    time.sleep(t)
print("In the following story, you are a mouse. Please fill out the following information (the story will use this name and gender).")
w(2)
print('\n')

while(True):
  name = input("Your Name:")
  if name.isalpha():
    break
  elif name != str:
    print('\n')
    print("Error! Please enter a name!")
    print('\n')

w(0.5)
print('\n')

while(True):
  gender = input("Your Gender (Male / Female):").lower()
  if gender == "male":
    heorshe = "he"
    hisher = "his"
    himher = "him"
    himselfherself = "himself"
    HeShe = "He"
    break
  elif gender == "female":
    heorshe = "she"
    hisher = "her"
    himher = "her"
    himselfherself = "herself"
    HeShe = "He"
    break
  else:
    print('\n')
    print("Error Please enter a valid gender!")
    print('\n')

w(0.5)
print('\n')
input("Press Enter to Begin The Story")
w(0.5)
print('\n')
print("The Lion and The Mouse")
print("A Short Tale by Aesop")
w(1)
print('\n')
print("Once upon a time in a secluded jungle, there was a mouse.")
w(1.25)
print('\n')
print("%s was a very curious little mouse. Whenever %s saw something that caught %s eye, %s would always go and investigate." % (name, heorshe, hisher, heorshe))
w(2.5)
print('\n')
print("One day, %s came across a mighty lion. At first the lion didn't see %s, but due to %s curiosity, %s revealed %s. The lion had spotted %s." % (heorshe, himher, hisher, heorshe, himselfherself, himher))
w(3.25)
print('\n')
print("Hungry for a meal, the lion lunged at the mouse.")
print('\n')
w(1.75)
print("With the mouse in the lion's grip, the lion licked his lips, ready to bite in.")
print('\n')
w(1.5)
while(True):
  mercyoryell = input("Do you 'ASK FOR MERCY' or 'YELL HELP'?").lower()
  if mercyoryell == "ask for mercy":
    print('\n')
    print("Mouse: Oh please, great lion, let me go free! I promise I can repay you later!")
    w(1)
    print('\n')
    print("Lion: Ha! The thought of a mere mouse repaying me? I shall let you go, but only because you have given me such a great laugh!")
    w(.75)
    print('\n')
    print("The lion let the mouse go, and the mouse scurried away as fast as %s could." % (heorshe))
    print('\n')
    break
  elif mercyoryell == "yell help":
    print('\n')
    print("Mouse: HELLLLPPPP! I AM GOING TO GET EATEN BY A NASTY LION! SOMEBODY HELP ME! ANYBODY! AHHHH!!!")
    w(1.35)
    print('\n')
    print("Alas, the mouse's attempts were not successful. The lion quickly gobbled %s up." % (himher))
    w(1.5)
    print('\n')
    label = Label(root, text="The End!", bg="white", fg="black", font=("Comic Sans MS", 35, "bold"), height=75, width=75)
    print(label)
  else:
    print('\n')
    print("Error. Please type either ASK FOR MERCY or YELL HELP.")
    print('\n')
  w(1)
  print("A couple of days later, the mouse explores the forest again. %s comes across the lion, all bundled up in rope, moaning in pain." % (HeShe))
  print('\n')
  w(1.5)
  print("Mouse: What happened? How did you get caught in this net?")
  print('\n')
  w(1)
  print("Lion: The stupid hunters set up a net right outside of my den! Thats how! Now hurry up and get me out of here before they come back, you stupid mouse!")
  w(1.75)
  print('\n')
  while(True):
    lastscene = input("Do you 'HELP HIM OUT' or 'IGNORE HIM'?").lower()
    if lastscene == "help him out":
      w(.5)
      print('\n')
      print("The mouse starts chewing on the rope. %s finally makes a hole big enough for the lion to escape from, and the lion jumps out of the net")
      w(1.5)
      print('\n')
      break
    elif lastscene == "ignore him":
      w(.5)
      print('\n')
      print("Mouse: Why would I help you when you show me no kindness? I'll leave you to the hunters, stupid lion!")
      w(.75)
      print('\n')
      print("The mouse runs away from the lion, ignoring him.")
      print('\n')
      w(1.5)
      print("Later on that day, a deafening growl is heard. The lion had been found by the hunters, and was killed.")
      w(1.5)
      print('\n')
      label = Label(root, text="The End!", bg="white", fg="black", font=("Comic Sans MS", 35, "bold"), height=75, width=75)
      print(label)
    else:
      w(.5)
      print('\n')
      print("Error! Please enter either HELP HIM OUT or IGNORE HIM !")
      print('\n')
w(.5)
print("Lion: Thank you so much, kind mouse! I saved you, and you did indeed repay me! I will now forever show my gratitude towards you, my humble friend!")
w(1.5)
print('\n')
print("No act of kindness, no matter how small, is ever wasted.      -Aesop")
print('\n')
w(1.5)
label = Label(root, text="The End!", bg="white", fg="black", font=("Comic Sans MS", 35, "bold"), height=75, width=75)
print(label)
</code>```

And finally, this is the error message I get when I run the code:

```<code>    Traceback (most recent call last):
  File "python", line 4, in <module>
_tkinter.TclError: no display name and no $DISPLAY environment variable
</code>```

I have no idea what to do, and none of the several guides I've looked up have helped me.

答:
In a comment you wrote:

I'm using an online editor for python as i do not have it downloaded.

You can't run tkinter via a web server. There is simply nothing you can do to make that work.

Body:
I am trying to make a label, but I can't define the root variable! Please help me!

Update: I am using an online Python editor called repl.it

I am using Python 3.0

This is my code:

import time
from tkinter import *

root = Tk()

def w(t):
  if t == t:
    time.sleep(t)
print("In the following story, you are a mouse. Please fill out the following information (the story will use this name and gender).")
w(2)
print('\n')

while(True):
  name = input("Your Name:")
  if name.isalpha():
    break
  elif name != str:
    print('\n')
    print("Error! Please enter a name!")
    print('\n')

w(0.5)
print('\n')

while(True):
  gender = input("Your Gender (Male / Female):").lower()
  if gender == "male":
    heorshe = "he"
    hisher = "his"
    himher = "him"
    himselfherself = "himself"
    HeShe = "He"
    break
  elif gender == "female":
    heorshe = "she"
    hisher = "her"
    himher = "her"
    himselfherself = "herself"
    HeShe = "He"
    break
  else:
    print('\n')
    print("Error Please enter a valid gender!")
    print('\n')

w(0.5)
print('\n')
input("Press Enter to Begin The Story")
w(0.5)
print('\n')
print("The Lion and The Mouse")
print("A Short Tale by Aesop")
w(1)
print('\n')
print("Once upon a time in a secluded jungle, there was a mouse.")
w(1.25)
print('\n')
print("%s was a very curious little mouse. Whenever %s saw something that caught %s eye, %s would always go and investigate." % (name, heorshe, hisher, heorshe))
w(2.5)
print('\n')
print("One day, %s came across a mighty lion. At first the lion didn't see %s, but due to %s curiosity, %s revealed %s. The lion had spotted %s." % (heorshe, himher, hisher, heorshe, himselfherself, himher))
w(3.25)
print('\n')
print("Hungry for a meal, the lion lunged at the mouse.")
print('\n')
w(1.75)
print("With the mouse in the lion's grip, the lion licked his lips, ready to bite in.")
print('\n')
w(1.5)
while(True):
  mercyoryell = input("Do you 'ASK FOR MERCY' or 'YELL HELP'?").lower()
  if mercyoryell == "ask for mercy":
    print('\n')
    print("Mouse: Oh please, great lion, let me go free! I promise I can repay you later!")
    w(1)
    print('\n')
    print("Lion: Ha! The thought of a mere mouse repaying me? I shall let you go, but only because you have given me such a great laugh!")
    w(.75)
    print('\n')
    print("The lion let the mouse go, and the mouse scurried away as fast as %s could." % (heorshe))
    print('\n')
    break
  elif mercyoryell == "yell help":
    print('\n')
    print("Mouse: HELLLLPPPP! I AM GOING TO GET EATEN BY A NASTY LION! SOMEBODY HELP ME! ANYBODY! AHHHH!!!")
    w(1.35)
    print('\n')
    print("Alas, the mouse's attempts were not successful. The lion quickly gobbled %s up." % (himher))
    w(1.5)
    print('\n')
    label = Label(root, text="The End!", bg="white", fg="black", font=("Comic Sans MS", 35, "bold"), height=75, width=75)
    print(label)
  else:
    print('\n')
    print("Error. Please type either ASK FOR MERCY or YELL HELP.")
    print('\n')
  w(1)
  print("A couple of days later, the mouse explores the forest again. %s comes across the lion, all bundled up in rope, moaning in pain." % (HeShe))
  print('\n')
  w(1.5)
  print("Mouse: What happened? How did you get caught in this net?")
  print('\n')
  w(1)
  print("Lion: The stupid hunters set up a net right outside of my den! Thats how! Now hurry up and get me out of here before they come back, you stupid mouse!")
  w(1.75)
  print('\n')
  while(True):
    lastscene = input("Do you 'HELP HIM OUT' or 'IGNORE HIM'?").lower()
    if lastscene == "help him out":
      w(.5)
      print('\n')
      print("The mouse starts chewing on the rope. %s finally makes a hole big enough for the lion to escape from, and the lion jumps out of the net")
      w(1.5)
      print('\n')
      break
    elif lastscene == "ignore him":
      w(.5)
      print('\n')
      print("Mouse: Why would I help you when you show me no kindness? I'll leave you to the hunters, stupid lion!")
      w(.75)
      print('\n')
      print("The mouse runs away from the lion, ignoring him.")
      print('\n')
      w(1.5)
      print("Later on that day, a deafening growl is heard. The lion had been found by the hunters, and was killed.")
      w(1.5)
      print('\n')
      label = Label(root, text="The End!", bg="white", fg="black", font=("Comic Sans MS", 35, "bold"), height=75, width=75)
      print(label)
    else:
      w(.5)
      print('\n')
      print("Error! Please enter either HELP HIM OUT or IGNORE HIM !")
      print('\n')
w(.5)
print("Lion: Thank you so much, kind mouse! I saved you, and you did indeed repay me! I will now forever show my gratitude towards you, my humble friend!")
w(1.5)
print('\n')
print("No act of kindness, no matter how small, is ever wasted.      -Aesop")
print('\n')
w(1.5)
label = Label(root, text="The End!", bg="white", fg="black", font=("Comic Sans MS", 35, "bold"), height=75, width=75)
print(label)

And finally, this is the error message I get when I run the code:

    Traceback (most recent call last):
  File "python", line 4, in <module>
_tkinter.TclError: no display name and no $DISPLAY environment variable

I have no idea what to do, and none of the several guides I've looked up have helped me.