问:
Image is not responsive inside carousel using ng2-bootstrap
Anybody know why is the image inside first carousel not responsive?
And how to make it responsive like the second one (Normal Bootstrap version) below. First one was created using ng2-bootstrap

Here is the html I have:

```<code><h1>ng2-bootstrap carousel</h1>
<carousel>
    <slide>
        <img class="first-slide" src="http://placehold.it/800x400" alt="First slide" class="center-block">
        <div class="container">
            <div class="carousel-caption">
                <h1>Example headline.</h1>
                <p>Descr1</p>
                <p><a class="btn btn-lg btn-primary" href="#" role="button">Sign up today</a></p>
            </div>
        </div>
    </slide>
    <slide>
        <img class="second-slide" src="http://placehold.it/800x400" alt="Second slide" class="center-block">
        <div class="container">
            <div class="carousel-caption">
                <h1>Another example headline.</h1>
                <p>Descr2.</p>
                <p><a class="btn btn-lg btn-primary" href="#" role="button">Learn more</a></p>
            </div>
        </div>
    </slide>
</carousel>

<h1>Normal Bootstrap carousel</h1>

<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
      <!-- Indicators -->
      <ol class="carousel-indicators">
        <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
        <li data-target="#carousel-example-generic" data-slide-to="1"></li>
        <li data-target="#carousel-example-generic" data-slide-to="2"></li>
      </ol>

      <!-- Wrapper for slides -->
      <div class="carousel-inner">
        <div class="item active">
          <img src="http://placehold.it/800x400" alt="...">
          <div class="carousel-caption">
            <h2>Heading</h2>
          </div>
        </div>
        <div class="item">
          <img src="http://placehold.it/800x400" alt="...">
          <div class="carousel-caption">
            <h2>Heading</h2>
          </div>
        </div>
        <div class="item">
          <img src="http://placehold.it/800x400" alt="...">
          <div class="carousel-caption">
            <h2>Heading</h2>
          </div>
        </div>
      </div>

      <!-- Controls -->
      <a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">
        <span class="glyphicon glyphicon-chevron-left"></span>
      </a>
      <a class="right carousel-control" href="#carousel-example-generic" data-slide="next">
        <span class="glyphicon glyphicon-chevron-right"></span>
      </a>
    </div>
</code>```

答:
Turns out, bootstrap hierarchy gets broken with ng2's tags in-between. adding img-responsive class to the  resolved the issue.

Only For the sake of completeness:

```<code><h1>ng2-bootstrap carousel</h1>
<carousel>
    <slide>
        <img class="first-slide" src="http://placehold.it/800x400" alt="First slide" class="center-block img-responsive">
        <div class="container">
            <div class="carousel-caption">
                <h1>Example headline.</h1>
                <p>Descr1</p>
                <p><a class="btn btn-lg btn-primary" href="#" role="button">Sign up today</a></p>
            </div>
        </div>
    </slide>
    <slide>
        <img class="second-slide" src="http://placehold.it/800x400" alt="Second slide" class="center-block img-responsive">
        <div class="container">
            <div class="carousel-caption">
                <h1>Another example headline.</h1>
                <p>Descr2.</p>
                <p><a class="btn btn-lg btn-primary" href="#" role="button">Learn more</a></p>
            </div>
        </div>
    </slide>
</carousel>
</code>```

Body:
Anybody know why is the image inside first carousel not responsive?
And how to make it responsive like the second one (Normal Bootstrap version) below. First one was created using ng2-bootstrap

Here is the html I have:

ng2-bootstrap carousel

<carousel>
    <slide>

Example headline.

Descr1

Sign up today

    </slide>
    <slide>

Another example headline.

Descr2.

Learn more

    </slide>
</carousel>

Normal Bootstrap carousel

Heading

Heading

Heading

Body:
Turns out, bootstrap hierarchy gets broken with ng2's tags in-between. adding img-responsive class to the <img ..> resolved the issue.

Only For the sake of completeness:

<h1>ng2-bootstrap carousel</h1>
<carousel>
    <slide>
        <img class="first-slide" src="http://placehold.it/800x400" alt="First slide" class="center-block img-responsive">
        <div class="container">
            <div class="carousel-caption">
                <h1>Example headline.</h1>
                <p>Descr1</p>
                <p><a class="btn btn-lg btn-primary" href="#" role="button">Sign up today</a></p>
            </div>
        </div>
    </slide>
    <slide>
        <img class="second-slide" src="http://placehold.it/800x400" alt="Second slide" class="center-block img-responsive">
        <div class="container">
            <div class="carousel-caption">
                <h1>Another example headline.</h1>
                <p>Descr2.</p>
                <p><a class="btn btn-lg btn-primary" href="#" role="button">Learn more</a></p>
            </div>
        </div>
    </slide>
</carousel>


来源: stackexchange

问:
Controller not calling in AngularJS
I am facing problem in call to controller in child ui state router.

URL is changing but controller not call.

no console error*

Please check code:

HTML

```<code><a style="cursor: pointer;" class="btn btn-default btn-xs"  ui-sref="interactions.details({id:n.id})">Detail</a>
</code>```

Router

```<code>.state('interactions', {
            url: '/interactions',
            data: {
                pageTitle: 'Interaction',
                IsLoginPage: false
            },
            templateUrl: '../../modules/interaction/views/interaction.html',
            controller: 'interactionCtl'
        })
        .state('interactions.details', {
            url:'/details/:id',
            data: {
                pageTitle: 'Interaction Details',
                IsLoginPage: false
            },
            templateUrl: '../../modules/interaction/views/interactionDetail.html',
            controller:'interactionCtlDetails'
        }).run(function ($rootScope, settings, $cookies, $http, $location, AuthenticationService, $state, $stateParams) {

    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;

});
</code>```

Controller

```<code>    warApp.controller('interactionCtlDetails', ["$scope", '$rootScope','$stateParams', 'settings', 'categoryService', 'blockUI',
        function ($scope, interactionService, $rootScope, $stateParams ,settings, categoryService, blockUI) {

            var id = $stateParams.id;
console.log(id);

    });
</code>```

答:
Simpler example of routing, maybe you can narrow down the problem by adding one controller at a time and build the rest. Fiddle or error will help.</p>

```<code>angular.module('myApp').config(function ($stateProvider){

    $stateProvider
        .state('form', {
        url:"/form",
            views:  {
                "listColumn": {
                     templateUrl: "/form1.html",
                     controller:'myController1'
                  },
                "formColumn": {
                      templateUrl: "/form2.html"
                  }
            }
        })
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Controller not calling in AngularJS

Body:
I am facing problem in call to controller in child ui state router.

URL is changing but controller not call.

no console error*

Please check code:

HTML

Detail

Router

.state('interactions', {
            url: '/interactions',
            data: {
                pageTitle: 'Interaction',
                IsLoginPage: false
            },
            templateUrl: '../../modules/interaction/views/interaction.html',
            controller: 'interactionCtl'
        })
        .state('interactions.details', {
            url:'/details/:id',
            data: {
                pageTitle: 'Interaction Details',
                IsLoginPage: false
            },
            templateUrl: '../../modules/interaction/views/interactionDetail.html',
            controller:'interactionCtlDetails'
        }).run(function ($rootScope, settings, $cookies, $http, $location, AuthenticationService, $state, $stateParams) {

    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;

});

Controller

    warApp.controller('interactionCtlDetails', ["$scope", '$rootScope','$stateParams', 'settings', 'categoryService', 'blockUI',
        function ($scope, interactionService, $rootScope, $stateParams ,settings, categoryService, blockUI) {

            var id = $stateParams.id;
console.log(id);

    });

Body:
Simpler example of routing, maybe you can narrow down the problem by adding one controller at a time and build the rest. Fiddle or error will help.

angular.module('myApp').config(function ($stateProvider){

    $stateProvider
        .state('form', {
        url:"/form",
            views:  {
                "listColumn": {
                     templateUrl: "/form1.html",
                     controller:'myController1'
                  },
                "formColumn": {
                      templateUrl: "/form2.html"
                  }
            }
        })
});


问:
Difference between the  tag and get request
I have a perhaps simple question. What would be the difference between an  tag and a normal GET request with any element. I know the  tag automatically sends you to the url specified in its href attribute. So I assume that a Get request does something similar in it's success callback (as demonstrated below)

But let's say that I also want to send some information along with a normal get request when a for example  element is clicked on so I write:

```<code>   $('span').click(() => {
    $.ajax({
        url: '/someurl',
        type: 'GET',
        data: {
            title: someTitle,
            email: someEmail
        },
        success: (data) => {
                window.location = '/someurl';

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

Is there any way to achieve this with an  tag? Sending information to the server so it's available in req.query.title and req.query.email ?

Doing the ajax request above will run my app.get('/someurl',(req,res)=>{})twice because I am sending a GET request to send the data (title and email) and then I am making another GET request when I write window.location = '/someurl' How can I redo this so that it only sends the GET request ONCE but also allows for the sending and storing information to the req object AND ensures that the browser is now displaying /someurl.

答:
Just create the appropriate query string in the URL you put in the href of the  tag and it will work just like your ajax call.  Suppose someTitle has the value of "The Hobbit" and someEmail has the value of foo@whatever.com, then you can construct that URL like this:

```<code><a href="/someurl?title=The%20Hobbit&email=foo%40whatever.com">Click Me</a>
</code>```

A number of non-letter characters have to be escaped in URLs.  In the above URL, the space is replaced with %20 and the @ with %40.  In your particular example, you could open the network tab in the chrome debugger and see the EXACT URL that Chrome was sending for your ajax call, copy that to the clipboard and insert it into your  tag.

Here's a table that shows what characters have to be replaced in a query string component (the part after & or after =):

I'm just wondering then, aside from semantic reasons, is there any other advantages to using an a tag instead of anything else?

 tags are understood by all sorts of machines that may read your page such as screen readers for the disabled or crawlers indexing your site.  In addition, they work automatically with browser keyboard support, Ctrl-click to open a new tab.  Whereas a piece of Javascript may not automatically support any of that functionality.  So, basically, if the  tag can do what you need it is widely preferred because it has so much other default functionality that can be necessary or handy for users.

Title: Difference between the <a> tag and get request

Body:
I have a perhaps simple question. What would be the difference between an  tag and a normal GET request with any element. I know the  tag automatically sends you to the url specified in its href attribute. So I assume that a Get request does something similar in it's success callback (as demonstrated below)

But let's say that I also want to send some information along with a normal get request when a for example  element is clicked on so I write:

   $('span').click(() => {
    $.ajax({
        url: '/someurl',
        type: 'GET',
        data: {
            title: someTitle,
            email: someEmail
        },
        success: (data) => {
                window.location = '/someurl';

        }
    });
});

Is there any way to achieve this with an  tag? Sending information to the server so it's available in req.query.title and req.query.email ?

Doing the ajax request above will run my app.get('/someurl',(req,res)=>{})twice because I am sending a GET request to send the data (title and email) and then I am making another GET request when I write window.location = '/someurl' How can I redo this so that it only sends the GET request ONCE but also allows for the sending and storing information to the req object AND ensures that the browser is now displaying /someurl.

Body:
Just create the appropriate query string in the URL you put in the href of the <a> tag and it will work just like your ajax call.  Suppose someTitle has the value of "The Hobbit" and someEmail has the value of foo@whatever.com, then you can construct that URL like this:

<a href="/someurl?title=The%20Hobbit&email=foo%40whatever.com">Click Me</a>

A number of non-letter characters have to be escaped in URLs.  In the above URL, the space is replaced with %20 and the @ with %40.  In your particular example, you could open the network tab in the chrome debugger and see the EXACT URL that Chrome was sending for your ajax call, copy that to the clipboard and insert it into your <a> tag.

Here's a table that shows what characters have to be replaced in a query string component (the part after & or after =):

I'm just wondering then, aside from semantic reasons, is there any other advantages to using an a tag instead of anything else?

<a> tags are understood by all sorts of machines that may read your page such as screen readers for the disabled or crawlers indexing your site.  In addition, they work automatically with browser keyboard support, Ctrl-click to open a new tab.  Whereas a piece of Javascript may not automatically support any of that functionality.  So, basically, if the <a> tag can do what you need it is widely preferred because it has so much other default functionality that can be necessary or handy for users.


问:
How to use awk to search for min and max values of column in certain files
I know that awk is helpful in trying to find certain things in columns in files, but I'm not sure how to use it to find the min and max values of a column in a group of files. Any advice? To be specific I have four files in a directory that I want to go through awk with.</p>

答:
If you're looking for the absolute maximum and minimum of column N over all the files, then you might use:

```<code>N=6
awk -v N=$N 'NR == 1 { min = max = $N }
                     { if ($N > max) max = $N; else if ($N < min) min = $N }
             END     { print min, max }' "$@"
</code>```

You can change the column number using a command line option or by editing the script (crude, but effective — go with option handling), or any other method that takes your fancy.

If you want the maximum and minimum of column N for each file, then you have to detect new files, and you probably want to identify the files, too:

```<code> awk -v N=$N 'FNR == 1 { if (NR != 1) print file, min, max; min = max = $N; file = FILENAME }
                       { if ($N > max) max = $N; else if ($N < min) min = $N }
              END      { print file, min, max }' "$@"
</code>```

Body:
If you're looking for the absolute maximum and minimum of column N over all the files, then you might use:

N=6
awk -v N=$N 'NR == 1 { min = max = $N }
                     { if ($N > max) max = $N; else if ($N < min) min = $N }
             END     { print min, max }' "$@"

You can change the column number using a command line option or by editing the script (crude, but effective — go with option handling), or any other method that takes your fancy.

If you want the maximum and minimum of column N for each file, then you have to detect new files, and you probably want to identify the files, too:

 awk -v N=$N 'FNR == 1 { if (NR != 1) print file, min, max; min = max = $N; file = FILENAME }
                       { if ($N > max) max = $N; else if ($N < min) min = $N }
              END      { print file, min, max }' "$@"


问:
Font-face web fonts looks bolder
I'm stuck with a problem. I'm trying to embed fonts with @font-face but they always looks bolder. I have tried everything: other fonts, change font-weight to "ligher" or "100" etc...
The font looks always as it is bolded. I'm pretty sure it could look good because I've seen it used in many other websites with @font-face and it looks thin and fine.

See the attached image link text (I know it would never look as in PS, but so different?)

thanks

答:
The way the font looks on photoshop is obviously a graphical version of the font, specially, when photoshop has 5 types of blurring for fonts: none, sharp, crisp, strong and smooth. Those beside the original fonts, which they commonly are in one TTF and have the versions inside or, varios fonts for the different weights and faces.

Maybe if you enlighten us about the font type, the weight, blurring and whatever is useful for reproducing purposes would be useful to help you...

ContentLicense: CC BY-SA 2.5

Title: Font-face web fonts looks bolder


问:
PHP show return from python script
I am unable to get php to show full results of my python script, only the last basic print statement is printed. What am I doing wrong here? Why is the php not showing the output from the python script?

php

```<code>$result = exec('python list.py');
echo $result;
</code>```

list.py

```<code>import subprocess

print "start"

a = subprocess.Popen(["ls", "-a"], stdout=subprocess.PIPE)
a.wait()
result_str = a.stdout.read()
print result_str

print "stop"
</code>```

the command line output for that python script is as below

```<code>start
...filename
...filename
...etc...etc

stop
</code>```

The php output from executing the python script is only

stop

Thank you

答:
You need to pass $result as a param into exec() otherwise you only get the last statement.

```<code>exec('python list.py', $result);
print_r($result);
</code>```

This will get an array of output, $result[0] will contain stop and $result[sizeof($result)-1] will contain stop and everything in between will contain the rest of your program output.

Title: PHP show return from python script

Body:
I am unable to get php to show full results of my python script, only the last basic print statement is printed. What am I doing wrong here? Why is the php not showing the output from the python script?

php

$result = exec('python list.py');
echo $result;

list.py

import subprocess

print "start"

a = subprocess.Popen(["ls", "-a"], stdout=subprocess.PIPE)
a.wait()
result_str = a.stdout.read()
print result_str

print "stop"

the command line output for that python script is as below

start
...filename
...filename
...etc...etc

stop

The php output from executing the python script is only

stop

Thank you

Body:
You need to pass $result as a param into exec() otherwise you only get the last statement.

exec('python list.py', $result);
print_r($result);

This will get an array of output, $result[0] will contain stop and $result[sizeof($result)-1] will contain stop and everything in between will contain the rest of your program output.


问:
Converting input number to Mysql decimal
I'm trying to store decimals taken from input in a Mysql decimal (10,2) row. But when I enter 37.50 in the input, Mysql only stores 37.00 It seems to disregard everything after the dot. How can I store decimals?

this the input

```<code><input class='form-control formBlock' name='payrate' value='' step="0.01" type='number' placeholder="Pay Rate..." required>
</code>```

So far I tried float:

```<code>$payrate=floatval($_POST['payrate']);
</code>```

答:
It's unclear what you are asking. (Was there a question? Or was all that just  intended as a status report?)

In a numeric context ...

MySQL interprets a "dot" character in a numeric literal as a decimal point.

MySQL interprets a "comma" character as invalid. MySQL reads the value from left to right until it hits an invalid character, and takes whatever it has read as the value.

As a demonstration, consider

```<code>SELECT '123,456.78' + 0     --> 123
SELECT '4t2' + 0            --> 4
</code>```

If we need to pass a numeric value into MySQL that contains commas, and we want MySQL to disregard the commas, then we can remove the commas

```<code>SELECT REPLACE('123,456.78',',','') + 0  -->  123456.78
</code>```

If we want a comma treated as the decimal separator, we can replace it with a dot character

```<code>SELECT REPLACE('456,78',',','.') + 0  -->  456.78
</code>```

Of course, we could also do that string manipulation and cleanup of the value in the client, before we pass the value to MySQL.

Not sure if any of that answers the question you asked. Was there a question?

Body:
I'm trying to store decimals taken from input in a Mysql decimal (10,2) row. But when I enter 37.50 in the input, Mysql only stores 37.00 It seems to disregard everything after the dot. How can I store decimals?

this the input

<input class='form-control formBlock' name='payrate' value='' step="0.01" type='number' placeholder="Pay Rate..." required>

So far I tried float:

$payrate=floatval($_POST['payrate']);

Body:
It's unclear what you are asking. (Was there a question? Or was all that just  intended as a status report?)

In a numeric context ...

MySQL interprets a "dot" character in a numeric literal as a decimal point.

MySQL interprets a "comma" character as invalid. MySQL reads the value from left to right until it hits an invalid character, and takes whatever it has read as the value.

As a demonstration, consider

SELECT '123,456.78' + 0     --> 123
SELECT '4t2' + 0            --> 4

If we need to pass a numeric value into MySQL that contains commas, and we want MySQL to disregard the commas, then we can remove the commas

SELECT REPLACE('123,456.78',',','') + 0  -->  123456.78

If we want a comma treated as the decimal separator, we can replace it with a dot character

SELECT REPLACE('456,78',',','.') + 0  -->  456.78

Of course, we could also do that string manipulation and cleanup of the value in the client, before we pass the value to MySQL.

Not sure if any of that answers the question you asked. Was there a question?


问:
How to Use Split in perl with regular expression
I want to Split the Content from a number followed by .

```<code>my $info = "8. 9         Run
       Keywords :- RUN;

    9. 10        spreadsheet
       Keywords :- spreadsheet;

   10. 11        Book
       Keywords :- Book;

   11. 15        Hide
       Keywords :- Hide;

   12. 132        Pick
       Keywords :- Pick;
</code>```

This the string that i have split the content according to the numbers like 8., 9., 10., 11.,12.
Any suggestion how to do this in Perl and make sure that numbers like 8. does't appear after spiting.

答:
If the objective is to split by 8., 9. (etc)

```<code>my @contents = grep { /./ } split /\d+\./, $info;
</code>```

The array @contents has 9   Run ...(up to 9.), etc, with newlines and all.  The pattern /.../ in split is a full regular expression, which when matched in the string is taken to be a separator to split by. The regex above specifies a number followed by a period, so the string is split by any such.

Since split in this case also captures (the empty string) before the first match (8.), we use grep to filter out empty strings, by requiring that each element matches at least one character.

You may also want to opt  for more substantial filtering, like with grep { /\S/ }, which would require that each element has at least one non-space thus discarding those which have only spaces.

Or, you can check only the first element

```<code>my @contents = split /\d+\./, $info;
shift @contents if $contents[0] eq '';
</code>```

In the shown example there surely will be an empty string first.

What the most suitable approach is in general depends on what may actually be before 8., what you want to do with it, and what you want to do with possible elements containing only spaces (like from 14.  15.), or even empty strings (from 14.15.).

If the objective was to capture 8., 9. (etc) then regex is better

```<code>my @num_dot = $info =~ /(\d+\.)/g;
</code>```

The array @num_dot contains: 8. 9. 10. 11. 12.

Body:
I want to Split the Content from a number followed by .

my $info = "8. 9         Run
       Keywords :- RUN;

    9. 10        spreadsheet
       Keywords :- spreadsheet;

   10. 11        Book
       Keywords :- Book;

   11. 15        Hide
       Keywords :- Hide;

   12. 132        Pick
       Keywords :- Pick;

This the string that i have split the content according to the numbers like 8., 9., 10., 11.,12.
Any suggestion how to do this in Perl and make sure that numbers like 8. does't appear after spiting.

Body:
If the objective is to split by 8., 9. (etc)

my @contents = grep { /./ } split /\d+\./, $info;

The array @contents has 9   Run ...(up to 9.), etc, with newlines and all.  The pattern /.../ in split is a full regular expression, which when matched in the string is taken to be a separator to split by. The regex above specifies a number followed by a period, so the string is split by any such.

Since split in this case also captures (the empty string) before the first match (8.), we use grep to filter out empty strings, by requiring that each element matches at least one character.

You may also want to opt  for more substantial filtering, like with grep { /\S/ }, which would require that each element has at least one non-space thus discarding those which have only spaces.

Or, you can check only the first element

my @contents = split /\d+\./, $info;
shift @contents if $contents[0] eq '';

In the shown example there surely will be an empty string first.

What the most suitable approach is in general depends on what may actually be before 8., what you want to do with it, and what you want to do with possible elements containing only spaces (like from 14.  15.), or even empty strings (from 14.15.).

If the objective was to capture 8., 9. (etc) then regex is better

my @num_dot = $info =~ /(\d+\.)/g;

The array @num_dot contains: 8. 9. 10. 11. 12.


问:
Printing sorted dictionary keys along with sorted values
I am sorting a dictionary based on a particular value which is 3rd element on the list(in values) by using:

```<code>print sorted(dict.keys(), key=lambda k: dict[k][2], reverse=True)[:3]
</code>```

How can I also display the keys to which those sorted values correspond to ?

Thank you for looking.

答:
You can save the sorted list and print  in format you want.</p>

```<code>sorted_list = sorted(dict.keys(), key=lambda k: dict[k][2], reverse=True)[:3]
for key in sorted_list:
    print 'key is '+ key + ' value is '+ sorted_list[key][3]
</code>```

Body:
I am sorting a dictionary based on a particular value which is 3rd element on the list(in values) by using:

print sorted(dict.keys(), key=lambda k: dict[k][2], reverse=True)[:3]

How can I also display the keys to which those sorted values correspond to ?

Thank you for looking.

Body:
You can save the sorted list and print  in format you want.

sorted_list = sorted(dict.keys(), key=lambda k: dict[k][2], reverse=True)[:3]
for key in sorted_list:
    print 'key is '+ key + ' value is '+ sorted_list[key][3]


问:
In a React JS / Redux Table, if we add a record to the front of an array dynamically, and use the array index as the "key", why does it actually work?
For example, if we have an array

```<code>0 => San Francisco
1 => Taipei
2 => San Jose
</code>```

and use the index as the "key" for every
 element like this

```<code>this.props.arrData.map((data, i) => {
    return (
        <tr key={i}>
        // ...
</code>```

it should be fine. When we add to the end of array:

```<code>3 => Sacramento
</code>```

And the index to data mapping is still all good -- just one more mapping is added.

However, I found that even if it is prepended to the array, and still use the index as the "key", it still work perfectly and don't know why.

I thought it should not work because at the very beginning with 1 record:

```<code>0 => San Francisco
</code>```

and it will cache the key 0 as the HTML fragment of San Francisco.

And when a record is prepended:

```<code>0 => Taipei
1 => San Francisco
</code>```

I thought React actually use the 0 as the key to this row, and somehow can "cache" this fragment, and so any
 with key=0, it would have it cached as San Francisco, so the table could become:

```<code>0 => San Francisco
1 => San Francisco
</code>```

But it doesn't. So if something was cached, why would it actually work?

P.S. I ended up using:

```<code>var countTotalItems = this.props.weatherList.length;

return this.props.weatherList.map((weather, i) => {

  return (
    <tr key={`${countTotalItems - i} ${weather.cityName} ${weather.countryCode}`}>

  // ...
</code>```

and the key is like: 1 San Francisco US for the last row all the time, even when there are more items added to the array -- essential, just reverse the order by using a key of 1 at the end of array. I used the city and country as well to better identify the row, just in case, for example, if in the future a row can be deleted by the user.  But the question is, why if not reversing the order, it still works.

P.P.S. as I put in the comment of one answer: if the row is all text, I found no difference in using key={cityName + i} vs key={i}, but if the row contains an image using  of the weather condition, I do find a difference. If it is key={i} then the newest row will have the previous image for 1 to 2 seconds, and then the correct image will get in. But if it is key={cityName + i}, then the image will be blank, and then 1 to 2 seconds later, the image will get in. The latter behavior is more desirable... the former behavior can be a little confusing to the user.

答:
I think you are misunderstanding the point of the key when rendering repeated children.  They are used to optimise the rendering when items are added, removed or rearranged and not for "caching" their value.

In your example the rendered html would look something like:

```<code><tr key='0'>Taipei</tr>
<tr key='1'>San Jose</tr>
</code>```

If a "San Francisco" is added to the front of the array React will have to change every element to the new values and then add a new one at the end for because there isn't an existing element for "San Jose".  Now the html would look like:

```<code><tr key='0'>San Francisco</tr>
<tr key='1'>Taipei</tr>
<tr key='2'>San Jose</tr>
</code>```

Now, if we had used the city name instead of the index and ran through the same example, we would start with:

```<code><tr key='Taipei'>Taipei</tr>
<tr key='San Jose'>San Jose</tr>
</code>```

Now when the new item is added, React can use the keys to know that "Taipei" and "San Jose" haven't changed and the only changes it needs to make to the DOM is to add an element at the start for the "San Francisco" item. The resulting html would look like:

```<code><tr key='San Francisco'>San Francisco</tr>
<tr key='Taipei'>Taipei</tr>
<tr key='San Jose'>San Jose</tr>
</code>```

Ultimately, the text on the screen would be the same, but it happened it far fewer updates to the DOM.  IF your array had 10000 items in, you can see how much cheaper this approach would be.

Keys must be unique to the item within the list, so if you don't have something unique to use, then the index will have to do, but be aware of the performance implications.

For more details, take a read of the relevant sections of the React docs, here and here.

Body:
For example, if we have an array

0 => San Francisco
1 => Taipei
2 => San Jose

and use the index as the "key" for every
 element like this

this.props.arrData.map((data, i) => {
    return (

        // ...

it should be fine. When we add to the end of array:

3 => Sacramento

And the index to data mapping is still all good -- just one more mapping is added.

However, I found that even if it is prepended to the array, and still use the index as the "key", it still work perfectly and don't know why.

I thought it should not work because at the very beginning with 1 record:

0 => San Francisco

and it will cache the key 0 as the HTML fragment of San Francisco.

And when a record is prepended:

0 => Taipei
1 => San Francisco

I thought React actually use the 0 as the key to this row, and somehow can "cache" this fragment, and so any
 with key=0, it would have it cached as San Francisco, so the table could become:

0 => San Francisco
1 => San Francisco

But it doesn't. So if something was cached, why would it actually work?

P.S. I ended up using:

var countTotalItems = this.props.weatherList.length;

return this.props.weatherList.map((weather, i) => {

  return (
    <tr key={`${countTotalItems - i} ${weather.cityName} ${weather.countryCode}`}>

  // ...

and the key is like: 1 San Francisco US for the last row all the time, even when there are more items added to the array -- essential, just reverse the order by using a key of 1 at the end of array. I used the city and country as well to better identify the row, just in case, for example, if in the future a row can be deleted by the user.  But the question is, why if not reversing the order, it still works.

P.P.S. as I put in the comment of one answer: if the row is all text, I found no difference in using key={cityName + i} vs key={i}, but if the row contains an image using  of the weather condition, I do find a difference. If it is key={i} then the newest row will have the previous image for 1 to 2 seconds, and then the correct image will get in. But if it is key={cityName + i}, then the image will be blank, and then 1 to 2 seconds later, the image will get in. The latter behavior is more desirable... the former behavior can be a little confusing to the user.

Body:
I think you are misunderstanding the point of the key when rendering repeated children.  They are used to optimise the rendering when items are added, removed or rearranged and not for "caching" their value.

In your example the rendered html would look something like:

<tr key='0'>Taipei</tr>
<tr key='1'>San Jose</tr>

If a "San Francisco" is added to the front of the array React will have to change every element to the new values and then add a new one at the end for because there isn't an existing element for "San Jose".  Now the html would look like:

<tr key='0'>San Francisco</tr>
<tr key='1'>Taipei</tr>
<tr key='2'>San Jose</tr>

Now, if we had used the city name instead of the index and ran through the same example, we would start with:

<tr key='Taipei'>Taipei</tr>
<tr key='San Jose'>San Jose</tr>

Now when the new item is added, React can use the keys to know that "Taipei" and "San Jose" haven't changed and the only changes it needs to make to the DOM is to add an element at the start for the "San Francisco" item. The resulting html would look like:

<tr key='San Francisco'>San Francisco</tr>
<tr key='Taipei'>Taipei</tr>
<tr key='San Jose'>San Jose</tr>

Ultimately, the text on the screen would be the same, but it happened it far fewer updates to the DOM.  IF your array had 10000 items in, you can see how much cheaper this approach would be.

Keys must be unique to the item within the list, so if you don't have something unique to use, then the index will have to do, but be aware of the performance implications.

For more details, take a read of the relevant sections of the React docs, here and here.


问:
Why isn't Angular's `$location.url` working after my Bootstrap Modal close?

Problem:

Anyone know why in my cb.register function below, my Modal window closes OK, but the $location.url('/dashboard') does not properly run?

I don't get any console errors, and the page does not redirect. However, console.log('TRANSITION DONE') still prints out in the code below after the modal window closes, so I know the event is being recognized:

Code:

```<code>app.controller('userController', ['$scope', 'userFactory', '$location', function($scope, userFactory, $location) {
    var cb = {
        register: function(createdUser) {
            // Closes Modal window:
            $('#myModal').modal('hide');
            // Runs after close with completed transition effects:
            $('#myModal').on('hidden.bs.modal', function (e) {
                console.log('TRANSITION DONE');
                $location.url('/dashboard');
            })
        },
    };

}]);
</code>```

Questions:

Why does the $location service not behave properly when nested inside of my .on() function?

Should I be using angular-ui instead? (Of which I was not familiar until researching solutions to this issue, and instead started my project by framing out all the views first using bootstrap3 and including the JS files, etc).

What I've Tried:

I've tried passing the $location parameter into the .on()'s callback function, along with e, but that made no real change and the function should still have access to $location in the larger scope.

Console logging $location or $location.url works properly, so I know the methods are accessible in the scope.

Moving the $location function outside of the on() function does load the dashboard page, however the fade-out modal close does not complete. A light-grey transparent BG is overlaying my dashboard page, which is why I chose to utilize the hidden.bs.modal event per the documentation: http://getbootstrap.com/javascript/#modals

```<code>// Closes window:
$('#myModal').modal('hide');
// Redirects to page but fade-out on Modal not completed:
$location.url('/dashboard');
</code>```

Desired Behavior/Pseudo-Code:

Modal window closes (when callback runs)

After Modal fade out:

$location.url('/dashboard') runs, loading dashboard page

Thank you to any angular/bootstrap ninjas whom can help!

答:
Why does the $location service not behave properly when nested inside of my .on() function?

You're directly using Bootstrap modals in your application -- which is OK. But, this requires you to manipulate the modal with jQuery. It is not advisable to use jQuery in an AngularJS application as AngularJS has its own methods of DOM manipulation and therefore you shouldn't manually manipulate the DOM via jQuery.

To answer your question, since you're using jQuery to directly manipulate the DOM, it is likely that AngularJS' digest cycle has not picked up on the modal closing. You could get around this by telling AngularJS to activate a digest cycle via $scope.$apply(). However, this will easily dirty up your code and just doesn't make sense according to best AngularJS principles.

Should I be using angular-ui instead? (Of which I was not familiar until researching solutions to this issue, and instead started my project by framing out all the views first using bootstrap3 and including the JS files, etc).

Yes. I would highly suggest using angular-ui. As per the documentation:

This repository contains a set of native AngularJS directives based on Bootstrap's markup and CSS. As a result no dependency on jQuery or Bootstrap's JavaScript is required.

As you can see, all of the Bootstrap functionality has been wrapped up into AngularJS directives that can easily be dropped into your application without worrying about jQuery.

Body:
Problem:

Anyone know why in my cb.register function below, my Modal window closes OK, but the $location.url('/dashboard') does not properly run?

I don't get any console errors, and the page does not redirect. However, console.log('TRANSITION DONE') still prints out in the code below after the modal window closes, so I know the event is being recognized:

Code:

app.controller('userController', ['$scope', 'userFactory', '$location', function($scope, userFactory, $location) {
    var cb = {
        register: function(createdUser) {
            // Closes Modal window:
            $('#myModal').modal('hide');
            // Runs after close with completed transition effects:
            $('#myModal').on('hidden.bs.modal', function (e) {
                console.log('TRANSITION DONE');
                $location.url('/dashboard');
            })
        },
    };

}]);

Questions:

Why does the $location service not behave properly when nested inside of my .on() function?

Should I be using angular-ui instead? (Of which I was not familiar until researching solutions to this issue, and instead started my project by framing out all the views first using bootstrap3 and including the JS files, etc).

What I've Tried:

I've tried passing the $location parameter into the .on()'s callback function, along with e, but that made no real change and the function should still have access to $location in the larger scope.

Console logging $location or $location.url works properly, so I know the methods are accessible in the scope.

Moving the $location function outside of the on() function does load the dashboard page, however the fade-out modal close does not complete. A light-grey transparent BG is overlaying my dashboard page, which is why I chose to utilize the hidden.bs.modal event per the documentation: http://getbootstrap.com/javascript/#modals

// Closes window:
$('#myModal').modal('hide');
// Redirects to page but fade-out on Modal not completed:
$location.url('/dashboard');

Desired Behavior/Pseudo-Code:

Modal window closes (when callback runs)

After Modal fade out:

$location.url('/dashboard') runs, loading dashboard page

Thank you to any angular/bootstrap ninjas whom can help!


问:
Safely retrieve values from element that can contain different values
We have some xml elements in a database that [for older data] can sometimes contain guids and sometimes contain integers.

is there a nice way of pulling out all the integrs only?

This will fail if the value element contains a guid!

```<code>select
ra.*,
t.c.value('.', 'int') as organisationId
from
   Audit.EmployeeAudit ra
   cross apply ra.EmployeeXml.nodes('//*:employee/*:property[*:name="ORG"]/*:value') t(c)
</code>```

Sample Xml

```<code><employee>
  <property>
    <name>ORG</name>
    <value>39</value> <!-- Sometimes this will be a guid -->
    <description>Leeds</description>
  </property>
</employee>
</code>```

答:
You could add a predicate to only match entries of less than or equal to 10 characters.

```<code>;with EmployeeAudit as
(

SELECT CAST('<employee><property>
   <name>ORG</name>
   <value>39</value> <!-- Sometimes this will be a guid -->
   <description>Leeds</description>
</property></employee>
' AS XML) AS EmployeeXml
UNION ALL
SELECT CAST('<employee><property>
   <name>ORG</name>
   <value>2FD29F11-59FC-47FD-BC30-DD330A53284E</value>
   <description>Leeds</description>
</property></employee>
' AS XML)
)
select
ra.*,
t.c.value('.', 'int') as organisationId
from
   EmployeeAudit ra
   cross apply
   ra.EmployeeXml.nodes
   ('//*:employee/*:property[*:name="ORG"]/*:value[string-length() <= 10]') t(c)
</code>```

Or actually this might be a bit more robust

```<code>('//*:employee/*:property[*:name="ORG"]/*:value[ceiling(.) = .]') t(c)
</code>```

Body:
We have some xml elements in a database that [for older data] can sometimes contain guids and sometimes contain integers.

is there a nice way of pulling out all the integrs only?

This will fail if the value element contains a guid!

select
ra.*,
t.c.value('.', 'int') as organisationId
from
   Audit.EmployeeAudit ra
   cross apply ra.EmployeeXml.nodes('//*:employee/*:property[*:name="ORG"]/*:value') t(c)

Sample Xml

<employee>
  <property>
    <name>ORG</name>
    <value>39</value>
    <description>Leeds</description>
  </property>
</employee>

Body:
You could add a predicate to only match entries of less than or equal to 10 characters.

;with EmployeeAudit as
(

SELECT CAST('<employee><property>
   <name>ORG</name>
   <value>39</value> <!-- Sometimes this will be a guid -->
   <description>Leeds</description>
</property></employee>
' AS XML) AS EmployeeXml
UNION ALL
SELECT CAST('<employee><property>
   <name>ORG</name>
   <value>2FD29F11-59FC-47FD-BC30-DD330A53284E</value>
   <description>Leeds</description>
</property></employee>
' AS XML)
)
select
ra.*,
t.c.value('.', 'int') as organisationId
from
   EmployeeAudit ra
   cross apply
   ra.EmployeeXml.nodes
   ('//*:employee/*:property[*:name="ORG"]/*:value[string-length() <= 10]') t(c)

Or actually this might be a bit more robust

('//*:employee/*:property[*:name="ORG"]/*:value[ceiling(.) = .]') t(c)


问:
How to upload file and other textbox data using plain javascript
I want to upload an image and other input datas using plain javascript. I already searched a lot of stuff but it's different from what I wanted. So I decided to post it here. What I want is to upload an image together with other input datas.

```<code><form enctype="multipart/form-data" id="form">
      <input type="text" placeholder="Description" name="desc">
      <input type="file" name="file" id="image">
      <input type="submit" class="btn btn-primary">
</form>
</code>```

JS

```<code>var myform = document.getElementById('form');

    myform.addEventListener('submit', function(e){
        e.preventDefault();
        var fileInput = document.getElementById('image');
        var file = fileInput.files[0];

        var datas = new FormData(myform);
        var xhr = new XMLHttpRequest();
        var url = "sample.php";
            xhr.open('POST', url, true);
            xhr.setRequestHeader('Content-type', 'multipart/form-data');

        xhr.onreadystatechange = function(){
             if(xhr.readyState == 4 && xhr.status == 200){
                  var response = xhr.responseText;
                      console.log(response);
              }
        };

         xhr.send(datas);
    });
</code>```

PHP

```<code>echo $_FILES['file']['name'];
</code>```

OUTPUT

Undefined index: file

答: The content type for your request needs to be multipart/form-data instead of application/x-www-form-urlencoded.

Body:
I want to upload an image and other input datas using plain javascript. I already searched a lot of stuff but it's different from what I wanted. So I decided to post it here. What I want is to upload an image together with other input datas.

<form enctype="multipart/form-data" id="form">
      <input type="text" placeholder="Description" name="desc">
      <input type="file" name="file" id="image">
      <input type="submit" class="btn btn-primary">
</form>

JS

var myform = document.getElementById('form');

    myform.addEventListener('submit', function(e){
        e.preventDefault();
        var fileInput = document.getElementById('image');
        var file = fileInput.files[0];

        var datas = new FormData(myform);
        var xhr = new XMLHttpRequest();
        var url = "sample.php";
            xhr.open('POST', url, true);
            xhr.setRequestHeader('Content-type', 'multipart/form-data');

        xhr.onreadystatechange = function(){
             if(xhr.readyState == 4 && xhr.status == 200){
                  var response = xhr.responseText;
                      console.log(response);
              }
        };

         xhr.send(datas);
    });

PHP

echo $_FILES['file']['name'];

OUTPUT

Undefined index: file


问:
Python - How to convert escaped sequence to string literals
Somewhat new to python, to be honest not very familiar with encoding in Python

Suppose while parsing text/html inputs, I end up with a path that look like following

```<code>line = \\dfslocation\prj\gct\asw\sw_archive
</code>```

However in the earlier part of processing, it seems like the escaped sequence '\a' and \'t' is already no longer stored as literal.

```<code>literal_line = "%r"%(line)
print literal_line

\\dfslocation\prj\gct\x07sw\\sw_archive
</code>```

My best guess is it happened when I tried to convert email into text

```<code>for part in self.msg.walk():
  if part.get_content_type().startswith('text/plain'):
    plain_text_part = part.get_payload(decode=False)
    received_text += '\n'
    received_text += plain_text_part

received_text = received_text.encode('ascii', 'ignore')
</code>```

Later on I want to use this as a network path, which would require this to be in its literal form - ie \a, not \x07 (ASCII Bel character)

The brute force way I can think of, would be searching all escaped sequence https://docs.python.org/2.0/ref/strings.html, and replacing them with corresponding string literals.

Is there a better way to do this?

Thanks

答:
Try storing line variable content as raw instead of ASCII.

If you store as it is, the \a will get converted to x07.

```<code>>>> line = "\\dfslocation\prj\gct\asw\sw_archive"
>>> line
'\\dfslocation\\prj\\gct\x07sw\\sw_archive'
</code>```

However, if you store as raw, using r'<your_ascii_text>' format, it will not convert to special characters.

```<code>>>> line  = r'\\dfslocation\prj\gct\asw\sw_archive'
>>> print line
\\dfslocation\prj\gct\asw\sw_archive
>>>
</code>```

Raw strings treat \a as \a, making them well adapted for windows filenames and regular expressions.

Body:
Somewhat new to python, to be honest not very familiar with encoding in Python

Suppose while parsing text/html inputs, I end up with a path that look like following

line = \\dfslocation\prj\gct\asw\sw_archive

However in the earlier part of processing, it seems like the escaped sequence '\a' and \'t' is already no longer stored as literal.

literal_line = "%r"%(line)
print literal_line

\\dfslocation\prj\gct\x07sw\\sw_archive

My best guess is it happened when I tried to convert email into text

for part in self.msg.walk():
  if part.get_content_type().startswith('text/plain'):
    plain_text_part = part.get_payload(decode=False)
    received_text += '\n'
    received_text += plain_text_part

received_text = received_text.encode('ascii', 'ignore')

Later on I want to use this as a network path, which would require this to be in its literal form - ie \a, not \x07 (ASCII Bel character)

The brute force way I can think of, would be searching all escaped sequence https://docs.python.org/2.0/ref/strings.html, and replacing them with corresponding string literals.

Is there a better way to do this?

Thanks

Body:
Try storing line variable content as raw instead of ASCII.

If you store as it is, the \a will get converted to x07.

>>> line = "\\dfslocation\prj\gct\asw\sw_archive"
>>> line
'\\dfslocation\\prj\\gct\x07sw\\sw_archive'

However, if you store as raw, using r'<your_ascii_text>' format, it will not convert to special characters.

>>> line  = r'\\dfslocation\prj\gct\asw\sw_archive'
>>> print line
\\dfslocation\prj\gct\asw\sw_archive
>>>

Raw strings treat \a as \a, making them well adapted for windows filenames and regular expressions.


问:
java.net.ConnectException: Connection refused: connect
My problem when I try to send a simple "hello world" msg from the pc "client " to the phone "server " and
I tried all possible solution like : starting the server app which is on the phone first then the client but didn't work,
I changed the ip address too but didn't work,
I closed the firewall nothing happened too

Server's code:

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class MainActivity extends AppCompatActivity {

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

 public class Server{

    public  void main(String args[]) {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(5000);} catch (IOException e) {
            e.printStackTrace();
        }

        while (true) {
                // Wait for a client connection.
            Socket clientSocket = null;
            try {
                clientSocket = serverSocket.accept();
            } catch (IOException e) {
                e.printStackTrace();
            }

            // Create and start a thread to handle the new client

                    try {
                        // Get the socket's InputStream, to read bytes
                        // from the socket
                        InputStream in = clientSocket.getInputStream();
                        // wrap the InputStream in a reader so you can
                        // read a String instead of bytes
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(in, Charset.forName("UTF-8")));
                        // Read from the socket and print line by line
                        String  line;
                        while ((line = reader.readLine()) != null) {
                            Toast.makeText(getApplicationContext(),line,Toast.LENGTH_LONG).show();
                        }
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        // This finally block ensures the socket is closed.
                        // A try-with-resources block cannot be used because
                        // the socket is passed into a thread, so it isn't
                        // created and closed in the same block
                        try {
                            clientSocket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }

            }
        }

 }}
</code>```

Client's code:

```<code>import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class ClientClass {
    public static void main(String args[]) {
        try (Socket socket = new Socket("192.168.1.3", 5000);) {
            // We'll reach this code once we've connected to the server

            // Write a string into the socket, and flush the buffer
            OutputStream outStream = socket.getOutputStream();
            PrintWriter writer = new PrintWriter(
                    new OutputStreamWriter(outStream, StandardCharsets.UTF_8));
            writer.println("Hello world!");
            writer.flush();
        } catch (IOException e) {
            // Exception should be handled.
            e.printStackTrace();
        }
    }
}
</code>```

error:

```<code>java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at java.net.Socket.<init>(Socket.java:434)
    at java.net.Socket.<init>(Socket.java:211)
    at ClientClass.main(ClientClass.java:10)
BUILD SUCCESSFUL (total time: 2 seconds)
</code>```

答:
I was having same error, and i managed to know what causes this error in my case,  you have to check two things:

1-Router configuration if you are connected using WiFi because you have to forward your port correctly.(How to Set Up Port Forwarding on a Router, it differs according to router type)

2-If this IP address here is the correct IP address of your mobile or not:

Socket socket = new Socket("192.168.1.3", 5000);

(How To Check Your Android IP Address)

ContentLicense: CC BY-SA 4.0

Body:
My problem when I try to send a simple "hello world" msg from the pc "client " to the phone "server " and
I tried all possible solution like : starting the server app which is on the phone first then the client but didn't work,
I changed the ip address too but didn't work,
I closed the firewall nothing happened too

Server's code:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class MainActivity extends AppCompatActivity {

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

 public class Server{

    public  void main(String args[]) {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(5000);} catch (IOException e) {
            e.printStackTrace();
        }

        while (true) {
                // Wait for a client connection.
            Socket clientSocket = null;
            try {
                clientSocket = serverSocket.accept();
            } catch (IOException e) {
                e.printStackTrace();
            }

            // Create and start a thread to handle the new client

                    try {
                        // Get the socket's InputStream, to read bytes
                        // from the socket
                        InputStream in = clientSocket.getInputStream();
                        // wrap the InputStream in a reader so you can
                        // read a String instead of bytes
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(in, Charset.forName("UTF-8")));
                        // Read from the socket and print line by line
                        String  line;
                        while ((line = reader.readLine()) != null) {
                            Toast.makeText(getApplicationContext(),line,Toast.LENGTH_LONG).show();
                        }
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        // This finally block ensures the socket is closed.
                        // A try-with-resources block cannot be used because
                        // the socket is passed into a thread, so it isn't
                        // created and closed in the same block
                        try {
                            clientSocket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }

            }
        }

 }}

Client's code:

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class ClientClass {
    public static void main(String args[]) {
        try (Socket socket = new Socket("192.168.1.3", 5000);) {
            // We'll reach this code once we've connected to the server

            // Write a string into the socket, and flush the buffer
            OutputStream outStream = socket.getOutputStream();
            PrintWriter writer = new PrintWriter(
                    new OutputStreamWriter(outStream, StandardCharsets.UTF_8));
            writer.println("Hello world!");
            writer.flush();
        } catch (IOException e) {
            // Exception should be handled.
            e.printStackTrace();
        }
    }
}

error:

java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at java.net.Socket.<init>(Socket.java:434)
    at java.net.Socket.<init>(Socket.java:211)
    at ClientClass.main(ClientClass.java:10)
BUILD SUCCESSFUL (total time: 2 seconds)


问:
global function in Ionic 2 / Angular 2
How can I setup a global function that can be accessed throughout all views?

In app.component.ts I added a simple method

```<code>  openShare() {console.log("button clicked")}
</code>```

and then in my nav I have

```<code>  <button ion-button right (click)="openShare()">
  <ion-icon name="md-share"></ion-icon>
</button>
</code>```

When I try to access this from any page I get the following.

```<code>self.context.openShare is not a function
</code>```

It does however execute fine if I put it directly in the constructor (e.g this.openShare(); ), but when calling from any page using a (click) function it just doesn't work.

Is app.component.ts not global? I thought this is where I would place it, but maybe I am missing something.

Basically its a function for a simple button on the nav, I need it to be global though since its used on every page.

Any help would be appreciated, still figuring Ionic 2 out.

答:
Just like @Sampath mentioned, one way would be to use a custom provider. But since you method is just a simple one, I think you can use Events instead. It'd be like this:

In your app.component.ts file, subscribe to the new event:

```<code>import { Events } from 'ionic-angular';

constructor(public events: Events, ...) {

  // ...

  events.subscribe('social:share', () => {

    // your code...
    console.log("button clicked");

  });

}
</code>```

And then in any other page, just publish the event to execute that logic:

```<code>function anotherPageMethod() {
  this.events.publish('social:share');
}
</code>```

Title: global function in Ionic 2 / Angular 2

Body:
How can I setup a global function that can be accessed throughout all views?

In app.component.ts I added a simple method

  openShare() {console.log("button clicked")}

and then in my nav I have

  <button ion-button right (click)="openShare()">
  <ion-icon name="md-share"></ion-icon>
</button>

When I try to access this from any page I get the following.

self.context.openShare is not a function

It does however execute fine if I put it directly in the constructor (e.g this.openShare(); ), but when calling from any page using a (click) function it just doesn't work.

Is app.component.ts not global? I thought this is where I would place it, but maybe I am missing something.

Basically its a function for a simple button on the nav, I need it to be global though since its used on every page.

Any help would be appreciated, still figuring Ionic 2 out.

Body:
Just like @Sampath mentioned, one way would be to use a custom provider. But since you method is just a simple one, I think you can use Events instead. It'd be like this:

In your app.component.ts file, subscribe to the new event:

import { Events } from 'ionic-angular';

constructor(public events: Events, ...) {

  // ...

  events.subscribe('social:share', () => {

    // your code...
    console.log("button clicked");

  });

}

And then in any other page, just publish the event to execute that logic:

function anotherPageMethod() {
  this.events.publish('social:share');
}


答:
Definitely your controller should throw an error in console, the order of dependency parameters injected in the controller is wrong, you are missing interactionService

change it as,

```<code>warApp.controller('interactionCtlDetails', ["$scope", 'interactionService','$rootScope','$stateParams', 'settings', 'categoryService', 'blockUI',
        function ($scope, interactionService, $rootScope, $stateParams ,settings, categoryService, blockUI) {

    });
</code>```

Title: Controller not calling in AngularJS

Body:
I am facing problem in call to controller in child ui state router.

URL is changing but controller not call.

no console error*

Please check code:

HTML

Detail

Router

.state('interactions', {
            url: '/interactions',
            data: {
                pageTitle: 'Interaction',
                IsLoginPage: false
            },
            templateUrl: '../../modules/interaction/views/interaction.html',
            controller: 'interactionCtl'
        })
        .state('interactions.details', {
            url:'/details/:id',
            data: {
                pageTitle: 'Interaction Details',
                IsLoginPage: false
            },
            templateUrl: '../../modules/interaction/views/interactionDetail.html',
            controller:'interactionCtlDetails'
        }).run(function ($rootScope, settings, $cookies, $http, $location, AuthenticationService, $state, $stateParams) {

    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;

});

Controller

    warApp.controller('interactionCtlDetails', ["$scope", '$rootScope','$stateParams', 'settings', 'categoryService', 'blockUI',
        function ($scope, interactionService, $rootScope, $stateParams ,settings, categoryService, blockUI) {

            var id = $stateParams.id;
console.log(id);

    });

Body:
Definitely your controller should throw an error in console, the order of dependency parameters injected in the controller is wrong, you are missing interactionService

change it as,

warApp.controller('interactionCtlDetails', ["$scope", 'interactionService','$rootScope','$stateParams', 'settings', 'categoryService', 'blockUI',
        function ($scope, interactionService, $rootScope, $stateParams ,settings, categoryService, blockUI) {

    });


问:
Pass individual elements of an array to a case statement in Ruby - LCD display numbers
I am trying to pass an array of numbers to a case statement.
For example: I ask the user to input a value, for example 12. Then I split it into an array [1,2]. I then pass it to my method case statement. My case statement is to output the digital format of 1 and 2.

My Issue:
I cannot get it to print more than an input of 1 element.
How can I output both the 1 and 2 as a digital number with 1 array? Or with a users input? Is my code far off?

My Code:

```<code>puts "Enter numbers between 0-9 up to 2 digits: "

x = gets.chomp
x = x.split('')

def digital_number(n)

digits = n

#Start case for digit input
  case digits
  when ["1"]
  puts " | "
  puts "   "
  puts " | "
  puts "   "
  puts n

  when ["2"]
  puts " - "
  puts "  |"
  puts " - "
  puts "|  "
  puts " - "

  else
  puts "That is not an available number."

  end
end

digital_number(x)
</code>```

答:
The code below solves my problem. Can delete '#' for ARGV if you want to put in an argument to the code. But just for terminal use, we have gets.chomp. Thank you for your help. This solves my problem, even if it may not be the most efficient.</p>

```<code># Add an argument in the terminal and
# .to_s converts the argument into a string
# so that ".scan" can take a string argument

#x = ARGV.to_s

x = gets.chomp
puts "Arguments entered is between 0-9: #{x}"

#These are empty arrays that get added in the cases
@arr1 = []
@arr2 = []
@arr3 = []
@arr4 = []
@arr5 = []

def digital_number(n)

#Start case for digit input
case n

when "0"
@arr1 << " - "
@arr2 << "| |"
@arr3 << "   "
@arr4 << "| |"
@arr5 << " - "

when "1"
@arr1 << "   "
@arr2 << " | "
@arr3 << "   "
@arr4 << " | "
@arr5 << "   "

when "2"
@arr1 << " - "
@arr2 << "  |"
@arr3 << " - "
@arr4 << "|  "
@arr5 << " - "

when '3'
@arr1 << " - "
@arr2 << "  |"
@arr3 << " - "
@arr4 << "  |"
@arr5 << " - "

when '4'
@arr1 << "   "
@arr2 << "| |"
@arr3 << " - "
@arr4 << "  |"
@arr5 << "   "

when '5'
@arr1 << " - "
@arr2 << "|  "
@arr3 << " - "
@arr4 << "  |"
@arr5 << " - "

when '6'
@arr1 << " - "
@arr2 << "|  "
@arr3 << " - "
@arr4 << "| |"
@arr5 << " - "

when '7'
@arr1 << "-- "
@arr2 << "  |"
@arr3 << "   "
@arr4 << "  |"
@arr5 << "   "

when '8'
@arr1 << " - "
@arr2 << "| |"
@arr3 << " - "
@arr4 << "| |"
@arr5 << " - "

when '9'
@arr1 << " - "
@arr2 << "| |"
@arr3 << " - "
@arr4 << "  |"
@arr5 << " - "

else
  puts "That is not an available number."
end
end
# This part iterates the method for each numbers inputted
x.scan(/\w/).each{|d| digital_number(d)}

# Output #
puts "   "
puts @arr1.join(' ')
puts @arr2.join(' ')
puts @arr3.join(' ')
puts @arr4.join(' ')
puts @arr5.join(' ')
</code>```

Body:
I am trying to pass an array of numbers to a case statement.
For example: I ask the user to input a value, for example 12. Then I split it into an array [1,2]. I then pass it to my method case statement. My case statement is to output the digital format of 1 and 2.

My Issue:
I cannot get it to print more than an input of 1 element.
How can I output both the 1 and 2 as a digital number with 1 array? Or with a users input? Is my code far off?

My Code:

puts "Enter numbers between 0-9 up to 2 digits: "

x = gets.chomp
x = x.split('')

def digital_number(n)

digits = n

#Start case for digit input
  case digits
  when ["1"]
  puts " | "
  puts "   "
  puts " | "
  puts "   "
  puts n

  when ["2"]
  puts " - "
  puts "  |"
  puts " - "
  puts "|  "
  puts " - "

  else
  puts "That is not an available number."

  end
end

digital_number(x)

Body:
The code below solves my problem. Can delete '#' for ARGV if you want to put in an argument to the code. But just for terminal use, we have gets.chomp. Thank you for your help. This solves my problem, even if it may not be the most efficient.

# Add an argument in the terminal and
# .to_s converts the argument into a string
# so that ".scan" can take a string argument

#x = ARGV.to_s

x = gets.chomp
puts "Arguments entered is between 0-9: #{x}"

#These are empty arrays that get added in the cases
@arr1 = []
@arr2 = []
@arr3 = []
@arr4 = []
@arr5 = []

def digital_number(n)

#Start case for digit input
case n

when "0"
@arr1 << " - "
@arr2 << "| |"
@arr3 << "   "
@arr4 << "| |"
@arr5 << " - "

when "1"
@arr1 << "   "
@arr2 << " | "
@arr3 << "   "
@arr4 << " | "
@arr5 << "   "

when "2"
@arr1 << " - "
@arr2 << "  |"
@arr3 << " - "
@arr4 << "|  "
@arr5 << " - "

when '3'
@arr1 << " - "
@arr2 << "  |"
@arr3 << " - "
@arr4 << "  |"
@arr5 << " - "

when '4'
@arr1 << "   "
@arr2 << "| |"
@arr3 << " - "
@arr4 << "  |"
@arr5 << "   "

when '5'
@arr1 << " - "
@arr2 << "|  "
@arr3 << " - "
@arr4 << "  |"
@arr5 << " - "

when '6'
@arr1 << " - "
@arr2 << "|  "
@arr3 << " - "
@arr4 << "| |"
@arr5 << " - "

when '7'
@arr1 << "-- "
@arr2 << "  |"
@arr3 << "   "
@arr4 << "  |"
@arr5 << "   "

when '8'
@arr1 << " - "
@arr2 << "| |"
@arr3 << " - "
@arr4 << "| |"
@arr5 << " - "

when '9'
@arr1 << " - "
@arr2 << "| |"
@arr3 << " - "
@arr4 << "  |"
@arr5 << " - "

else
  puts "That is not an available number."
end
end
# This part iterates the method for each numbers inputted
x.scan(/\w/).each{|d| digital_number(d)}

# Output #
puts "   "
puts @arr1.join(' ')
puts @arr2.join(' ')
puts @arr3.join(' ')
puts @arr4.join(' ')
puts @arr5.join(' ')


问:
extract specific data from numpy ndarray
New to pandas any help is appreciated

```<code>def csv_reader(fileName):
    reqcols=['_id__$oid','payload','channel']
    io = pd.read_csv(fileName,sep=",",usecols=reqcols)
    print(io['payload'].values)
    return io
</code>```

Output row of io['payload']:

```<code>{
    "destination_ip": "172.31.14.66",
    "date": "2014-10-19T01:32:36.669861",
    "classification": "Potentially Bad Traffic",
    "proto": "UDP",
    "source_ip": "172.31.0.2",
    "priority": "`2",
    "header": "1:2003195:5",
    "signature": "ET POLICY Unusual number of DNS No Such Name Responses ",
    "source_port": "53",
    "destination_port": "34638",
    "sensor": "5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"
}
</code>```

I am trying to extract specific data from the ndarray object. What is the method that can be used to extract from the dataframe

```<code>"destination_ip": "172.31.13.124",
"proto": "ICMP",
"source_ip": "201.158.32.1",
"date": "2014-09-28T14:49:43.391463",
"sensor": "139cfdf2-471e-11e4-9ee4-0a0b6e7c3e9e"
</code>```

答:
The issue is that payload is a column of your CSV input data, and it is a JSON string.  So you first can read_csv() as you have done to parse the overall file, but the you need to parse each JSON object inside.  Let's use this example data:

```<code>payload = pd.Series(['{"a":1, "b":2}', '{"b":4, "c":5}'])
</code>```

Now make a single JSON string:

```<code>json = ','.join(payload).join('[]')
</code>```

Which gives:

```<code>'[{"a":1, "b":2}, {"b":4, "c":5}]'
</code>```

Then parse it:

```<code>pd.read_json(json)
</code>```

To get:

```<code>     a  b    c
0  1.0  2  NaN
1  NaN  4  5.0
</code>```

Body:
New to pandas any help is appreciated

def csv_reader(fileName):
    reqcols=['_id__$oid','payload','channel']
    io = pd.read_csv(fileName,sep=",",usecols=reqcols)
    print(io['payload'].values)
    return io

Output row of io['payload']:

{
    "destination_ip": "172.31.14.66",
    "date": "2014-10-19T01:32:36.669861",
    "classification": "Potentially Bad Traffic",
    "proto": "UDP",
    "source_ip": "172.31.0.2",
    "priority": "`2",
    "header": "1:2003195:5",
    "signature": "ET POLICY Unusual number of DNS No Such Name Responses ",
    "source_port": "53",
    "destination_port": "34638",
    "sensor": "5cda4a12-4730-11e4-9ee4-0a0b6e7c3e9e"
}

I am trying to extract specific data from the ndarray object. What is the method that can be used to extract from the dataframe

"destination_ip": "172.31.13.124",
"proto": "ICMP",
"source_ip": "201.158.32.1",
"date": "2014-09-28T14:49:43.391463",
"sensor": "139cfdf2-471e-11e4-9ee4-0a0b6e7c3e9e"

Body:
The issue is that payload is a column of your CSV input data, and it is a JSON string.  So you first can read_csv() as you have done to parse the overall file, but the you need to parse each JSON object inside.  Let's use this example data:

payload = pd.Series(['{"a":1, "b":2}', '{"b":4, "c":5}'])

Now make a single JSON string:

json = ','.join(payload).join('[]')

Which gives:

'[{"a":1, "b":2}, {"b":4, "c":5}]'

Then parse it:

pd.read_json(json)

To get:

     a  b    c
0  1.0  2  NaN
1  NaN  4  5.0


问:
PRE TAG not working in theme, created pre tag not working with break line
I am using wordpress theme , but there was not working pre tag , so i have created my pre tag , all is good but when break line not working.

答:
```<code>  pre {
  word-break: break-all; /* webkit */
  word-wrap: break-word;
    white-space: pre;
    white-space: -moz-pre-wrap; /* fennec */
  white-space: pre-wrap;
    white-space: pre\9; /* IE7+ */
}
</code>```

try using this, might be it works.

Body:
  pre {
  word-break: break-all; /* webkit */
  word-wrap: break-word;
    white-space: pre;
    white-space: -moz-pre-wrap; /* fennec */
  white-space: pre-wrap;
    white-space: pre\9; /* IE7+ */
}

try using this, might be it works.


问:
Use of " for(string str: tmp) " in c++?
I came accross this for(string str: tmp) s.insert(str) in a C++ code for LCS and I don't know what it means. I saw it used in Java. Can it be written in any other way in C++?

答:
```<code>for(string str: tmp) s.insert(str)
</code>```

is a range-based for loop

It can be rewritten as

```<code>for (auto it = std::begin(tmp); it != std::end(tmp); ++it) s,insert(*it);
</code>```

and dozens of other ways with a variety of different types of loops. If the type of tmp is known it can possibly be simplified further.

Documentation on std::begin

Documentation on std::end

Title: Use of " for(string str: tmp) " in c++?

Body:
for(string str: tmp) s.insert(str)

is a range-based for loop

It can be rewritten as

for (auto it = std::begin(tmp); it != std::end(tmp); ++it) s,insert(*it);

and dozens of other ways with a variety of different types of loops. If the type of tmp is known it can possibly be simplified further.

Documentation on std::begin

Documentation on std::end


问:
In custom Prototype Cell in UITableView, UITextField value replaces with other Prototype Cell
I have taken one UITableView and inside that I have used 2 prototype cells, now in those prototype cells, i have taken 1 UITextField.

Now when I run the app and enter value in first prototype cell then i scroll UITableView, then first prototype cell's textfield value come to last prototype cell's textfield value. so it replace everytime i scrolldown or scroll up. sometime it goes blank.

here is my code

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   if(indexPath.row==0)
   {

    Client_MobileCell *cell     = [tableView dequeueReusableCellWithIdentifier:cellIdentifier_MobileCell forIndexPath:indexPath];
    cell.lblTitle.text          = [arrTitle objectAtIndex:indexPath.row];
    cell.txtMobile.placeholder  = [arrPlaceholder objectAtIndex:indexPath.row];
   // cell.txtMobile.tag = indexPath.row+100;
    return cell;
}
else
{
//        Client_Common_Cell *cell = (Client_Common_Cell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier_CommonCell forIndexPath:indexPath];
    Client_Common_Cell *cell = (Client_Common_Cell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier_CommonCell];

   // cell.txtCommon.tag = indexPath.row+100;
    cell.delegate = self;

    if(indexPath.row == 1 || indexPath.row == 2 || indexPath.row == 3 || indexPath.row == 4){
        if(indexPath.row == 2)
            cell.txtCommon.secureTextEntry = YES;
        else if(indexPath.row == 4){
            cell.txtCommon.keyboardType = UIKeyboardTypeEmailAddress;
        }
        cell.imgArrow.hidden = YES;
        cell.btnSelection.hidden = YES;
    }
    else{
        cell.btnSelection.hidden = NO;
        cell.imgArrow.hidden = NO;
    }
        cell.lblTitle.text       = [arrTitle objectAtIndex:indexPath.row];
        cell.txtCommon.placeholder      = [arrPlaceholder objectAtIndex:indexPath.row];
        return cell;
}
</code>```

}

答:
TL;DR (Just give me the code)

The Github link: https://github.com/starkindustries/CustomTableView

The Problem

As others have pointed out, dequeueReusableCellWithIdentifier will reuse the same cell references when scrolling. Take a look at the gif below for a visual demonstration of this problem.

The table in the gif has 20 rows (more rows than can fit on screen). Each row has a single textfield. I typed in "one", "two", "three", "four" into rows one through four respectively.

As you can see, when I scroll down, "two", "three", and "one" magically appear at the bottom (unwanted behavior). This is because those cells dequeued from the top when scrolled off screen and got reused again on the bottom.

Discussion

After much research on the web and stack overflow, I suggest you store the values of the textfields in an array when they change. Then you can set the textfield text accordingly in the cellForRowAt method. @Rob perfectly explains how to solve this using the model-view-controller pattern in his answer here: https://stackoverflow.com/a/38272077/2179970. I've implemented his suggestion into this following example.

How It Works

First, you'll setup a protocol so that the custom UITableViewCell (the view) can send a
message back to the ViewController to notify it that its textfield
changed. ViewController will implement the protocol. The cell will call the protocol method.

The user of your app will type in text. This will trigger
textFieldDidChange(_:) within the custom UITableViewCell class.

The textFieldDidChange(_:) will call the TableViewController's
delegate method cell(cell: UITableViewCell, updatedCustomTextField
textField: UITextField) to notify the controller that it's text
changed.

The controller will update its text array (the model) to save the
change.

The cellForRowAt will update the cell's textfield's
contents appropriately if it needs to be reused.

The Solution

Protocol:

```<code>// Protocol from Step 1
protocol CustomCellDelegate: class {
    // This is the function that the ViewController will implement
    func cell(cell: UITableViewCell, updatedCustomTextField textField: UITextField)
}
</code>```

Custom UITableViewCell:

```<code>class MyTableViewCell: UITableViewCell, UITextFieldDelegate {
    // Protocol reference (Step 1)
    weak var delegate: CustomCellDelegate?
    @IBOutlet weak var textField: UITextField!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        // (Step 2) Add a "textFieldDidChange" notification method to the text field control.
        textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: UIControlEvents.editingChanged)
    }

    // Step 2
    func textFieldDidChange(_ textField: UITextField) {
        delegate?.cell(cell: self, updatedCustomTextField: textField)
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        // Configure the view for the selected state
    }

}
</code>```

View Controller:

```<code>class MyTableViewController: UITableViewController, CustomCellDelegate {

    var myTexts: [String?]!

    override func viewDidLoad() {
        super.viewDidLoad()

        myTexts = Array(repeating: nil, count: 20)

        let nib = UINib(nibName: "MyTableViewCell", bundle: nil)
        self.tableView.register(nib, forCellReuseIdentifier: "MyTableViewCell")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 20
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        print("CellForRowAt: " + indexPath.row.description)
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyTableViewCell", for: indexPath) as! MyTableViewCell
        // Step 5: TableView updates cell contents if reused
        cell.delegate = self
        cell.textField.text = myTexts[indexPath.row]
        return cell
    }

    // MARK: - CustomCellDelegate Method
    // Step 3: The cell will call this protocol method to message the controller
    func cell(cell: UITableViewCell, updatedCustomTextField textField: UITextField) {
        // when the cell tells us that its text field's value changed, update our own model
        if let indexPath = tableView.indexPath(for: cell), let string = textField.text {
            // Step 4: The controller updates the model:
            print("delegate method cell updatedCustomTextField")
            myTexts[indexPath.row] = string
        }
    }
}
</code>```

The Result

I typed in the same "one", "two", "three", "four" into the first four rows as before. This time, the table behaves as expected: the textfield contents appear where I put them and they don't disappear/appear randomly.

Github Link

Here is the link to the project: https://github.com/starkindustries/CustomTableView

References

Init custom UITableViewCell from nib without dequeueReusableCellWithIdentifier

UITextFields in UITableView, entered values reappearing in other cells

UITextField in UITableViewCell and validation in modal view

Body:
I have taken one UITableView and inside that I have used 2 prototype cells, now in those prototype cells, i have taken 1 UITextField.

Now when I run the app and enter value in first prototype cell then i scroll UITableView, then first prototype cell's textfield value come to last prototype cell's textfield value. so it replace everytime i scrolldown or scroll up. sometime it goes blank.

here is my code

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   if(indexPath.row==0)
   {

    Client_MobileCell *cell     = [tableView dequeueReusableCellWithIdentifier:cellIdentifier_MobileCell forIndexPath:indexPath];
    cell.lblTitle.text          = [arrTitle objectAtIndex:indexPath.row];
    cell.txtMobile.placeholder  = [arrPlaceholder objectAtIndex:indexPath.row];
   // cell.txtMobile.tag = indexPath.row+100;
    return cell;
}
else
{
//        Client_Common_Cell *cell = (Client_Common_Cell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier_CommonCell forIndexPath:indexPath];
    Client_Common_Cell *cell = (Client_Common_Cell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier_CommonCell];

   // cell.txtCommon.tag = indexPath.row+100;
    cell.delegate = self;

    if(indexPath.row == 1 || indexPath.row == 2 || indexPath.row == 3 || indexPath.row == 4){
        if(indexPath.row == 2)
            cell.txtCommon.secureTextEntry = YES;
        else if(indexPath.row == 4){
            cell.txtCommon.keyboardType = UIKeyboardTypeEmailAddress;
        }
        cell.imgArrow.hidden = YES;
        cell.btnSelection.hidden = YES;
    }
    else{
        cell.btnSelection.hidden = NO;
        cell.imgArrow.hidden = NO;
    }
        cell.lblTitle.text       = [arrTitle objectAtIndex:indexPath.row];
        cell.txtCommon.placeholder      = [arrPlaceholder objectAtIndex:indexPath.row];
        return cell;
}

}

Body:
TL;DR (Just give me the code)

The Github link: https://github.com/starkindustries/CustomTableView

The Problem

As others have pointed out, dequeueReusableCellWithIdentifier will reuse the same cell references when scrolling. Take a look at the gif below for a visual demonstration of this problem.

The table in the gif has 20 rows (more rows than can fit on screen). Each row has a single textfield. I typed in "one", "two", "three", "four" into rows one through four respectively.

As you can see, when I scroll down, "two", "three", and "one" magically appear at the bottom (unwanted behavior). This is because those cells dequeued from the top when scrolled off screen and got reused again on the bottom.

Discussion

After much research on the web and stack overflow, I suggest you store the values of the textfields in an array when they change. Then you can set the textfield text accordingly in the cellForRowAt method. @Rob perfectly explains how to solve this using the model-view-controller pattern in his answer here: https://stackoverflow.com/a/38272077/2179970. I've implemented his suggestion into this following example.

How It Works

First, you'll setup a protocol so that the custom UITableViewCell (the view) can send a
message back to the ViewController to notify it that its textfield
changed. ViewController will implement the protocol. The cell will call the protocol method.

The user of your app will type in text. This will trigger
textFieldDidChange(_:) within the custom UITableViewCell class.

The textFieldDidChange(_:) will call the TableViewController's
delegate method cell(cell: UITableViewCell, updatedCustomTextField
textField: UITextField) to notify the controller that it's text
changed.

The controller will update its text array (the model) to save the
change.

The cellForRowAt will update the cell's textfield's
contents appropriately if it needs to be reused.

The Solution

Protocol:

// Protocol from Step 1
protocol CustomCellDelegate: class {
    // This is the function that the ViewController will implement
    func cell(cell: UITableViewCell, updatedCustomTextField textField: UITextField)
}

Custom UITableViewCell:

class MyTableViewCell: UITableViewCell, UITextFieldDelegate {
    // Protocol reference (Step 1)
    weak var delegate: CustomCellDelegate?
    @IBOutlet weak var textField: UITextField!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        // (Step 2) Add a "textFieldDidChange" notification method to the text field control.
        textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: UIControlEvents.editingChanged)
    }

    // Step 2
    func textFieldDidChange(_ textField: UITextField) {
        delegate?.cell(cell: self, updatedCustomTextField: textField)
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        // Configure the view for the selected state
    }

}

View Controller:

class MyTableViewController: UITableViewController, CustomCellDelegate {

    var myTexts: [String?]!

    override func viewDidLoad() {
        super.viewDidLoad()

        myTexts = Array(repeating: nil, count: 20)

        let nib = UINib(nibName: "MyTableViewCell", bundle: nil)
        self.tableView.register(nib, forCellReuseIdentifier: "MyTableViewCell")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 20
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        print("CellForRowAt: " + indexPath.row.description)
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyTableViewCell", for: indexPath) as! MyTableViewCell
        // Step 5: TableView updates cell contents if reused
        cell.delegate = self
        cell.textField.text = myTexts[indexPath.row]
        return cell
    }

    // MARK: - CustomCellDelegate Method
    // Step 3: The cell will call this protocol method to message the controller
    func cell(cell: UITableViewCell, updatedCustomTextField textField: UITextField) {
        // when the cell tells us that its text field's value changed, update our own model
        if let indexPath = tableView.indexPath(for: cell), let string = textField.text {
            // Step 4: The controller updates the model:
            print("delegate method cell updatedCustomTextField")
            myTexts[indexPath.row] = string
        }
    }
}

The Result

I typed in the same "one", "two", "three", "four" into the first four rows as before. This time, the table behaves as expected: the textfield contents appear where I put them and they don't disappear/appear randomly.

Github Link

Here is the link to the project: https://github.com/starkindustries/CustomTableView

References

Init custom UITableViewCell from nib without dequeueReusableCellWithIdentifier

UITextFields in UITableView, entered values reappearing in other cells

UITextField in UITableViewCell and validation in modal view