问:
Google Maps rails 5
I have a CRUD for "Imovels" (properties), so in the data base I have the address in different fields. That is:

```<code><%= f.text_field :logradouro %> # street name
<%= f.number_field :numero %> # number
<%= f.collection_select :bairro_id, @bairros, :id, :nome, {} %> # neighborhood
<%= f.collection_select :cidade_id, @cidades, :id, :nome, {} %> # city
</code>```

I am using the gem gmaps4rails for show the location on the map. I follow the tutorial on the gem documentation but the map doesn't render.

On the Puma log shows up two errors

```<code>ActionController::RoutingError (No route matches [GET] "/assets/underscore-min.map"):

NoMethodError (undefined method `geocoded_by' for #<Class:0x007fe7c02f2fb0>):
</code>```

Model:

```<code>class Imovel < ApplicationRecord
  geocoded_by :enderecoCompleto
  after_validation :geocode
end
</code>```

Concatenate:

```<code>def show
    @enderecoCompleto = "#{@imovel.logradouro}, #{@imovel.cidade.nome}"
end
</code>```

The view:
Here I want to show the map basing on the endereçoCompleto, that is the Street Name and City. I really doesn't Know how to proceed here.

```<code><div style='width: 800px;'>
  <div id="map" style='width: 800px; height: 400px;'></div>
</div>
    <script>
    handler = Gmaps.build('Google');
    handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
      markers = handler.addMarkers([
        {
          "lat": 0,
          "lng": 0,
          "picture": {
            "url": "http://people.mozilla.com/~faaborg/files/shiretoko/firefoxIcon/firefox-32.png",
            "width":  32,
            "height": 32
          },
          "infowindow": "hello!"
        }
      ]);
    handler.bounds.extendWith(markers);
    handler.fitMapToBounds();
    });
    </script>
</div>
</code>```

If I let that code on the Model, the returned error is:

```<code>NoMethodError (undefined method `geocoded_by' for #<Class:0x007fe7c02f2fb0>):
</code>```

How I mentioned above.
How can I render this map basing on the address in the database (without latitude and longitude) ?

After the help of @simple lime the geocoded problem was solved, but now the page render but the map doesn't show up. Actually messed up the other javascript code. Seems to be something relationed with the turbo links.

On the view:

```<code><script async defer
  src="https://maps.googleapis.com/maps/api/js?key=XXXXXX&callback=initMap">
</script>
<script src="//cdn.rawgit.com/mahnunchik/markerclustererplus/master/dist/markerclusterer.min.js"></script>
<script src='//cdn.rawgit.com/printercu/google-maps-utility-library-v3-read-only/master/infobox/src/infobox_packed.js' type='text/javascript'></script>
</code>```

On the application.js:

```<code>//= require underscore
//= require gmaps/google
</code>```

On the console:

答:
Looking at the gem + the youtube video on it's GitHub page. It appears you need to install the geocoder gem as well. That's what giving you the geocoded_by method.

Looking at the geocoder, if you add latitude:float longitude:float to your model, it should automatically fetch and update those in the after_validation :geocode you have in your model. From there, you can just pass your latitude and longitude to your view and replace

```<code>      "lat": 0,
      "lng": 0,
</code>```

with them. Make sure to read through the geocoder gem page, got a couple of useful things on there.

Edit

For the newest issue, I'm not great with javascript, but I'd try removing the async defer and that &callback=initMap from your google maps javascript tag (since you don't have a function defined with that name).

Original answer, may have been a typo in the question not an actual problem with the code.

The NoMethodError is being caused by a typo gecoded_by should probably be geocoded_by. The RoutingError is just for a source map file which shouldn't cause any issues.

Title: Google Maps rails 5

Body:
I have a CRUD for "Imovels" (properties), so in the data base I have the address in different fields. That is:

<%= f.text_field :logradouro %> # street name
<%= f.number_field :numero %> # number
<%= f.collection_select :bairro_id, @bairros, :id, :nome, {} %> # neighborhood
<%= f.collection_select :cidade_id, @cidades, :id, :nome, {} %> # city

I am using the gem gmaps4rails for show the location on the map. I follow the tutorial on the gem documentation but the map doesn't render.

On the Puma log shows up two errors

ActionController::RoutingError (No route matches [GET] "/assets/underscore-min.map"):

NoMethodError (undefined method `geocoded_by' for #<Class:0x007fe7c02f2fb0>):

Model:

class Imovel < ApplicationRecord
  geocoded_by :enderecoCompleto
  after_validation :geocode
end

Concatenate:

def show
    @enderecoCompleto = "#{@imovel.logradouro}, #{@imovel.cidade.nome}"
end

The view:
Here I want to show the map basing on the endereçoCompleto, that is the Street Name and City. I really doesn't Know how to proceed here.

If I let that code on the Model, the returned error is:

NoMethodError (undefined method `geocoded_by' for #<Class:0x007fe7c02f2fb0>):

How I mentioned above.
How can I render this map basing on the address in the database (without latitude and longitude) ?

After the help of @simple lime the geocoded problem was solved, but now the page render but the map doesn't show up. Actually messed up the other javascript code. Seems to be something relationed with the turbo links.

On the view:

On the application.js:

//= require underscore
//= require gmaps/google

On the console:

Body:
Looking at the gem + the youtube video on it's GitHub page. It appears you need to install the geocoder gem as well. That's what giving you the geocoded_by method.

Looking at the geocoder, if you add latitude:float longitude:float to your model, it should automatically fetch and update those in the after_validation :geocode you have in your model. From there, you can just pass your latitude and longitude to your view and replace

      "lat": 0,
      "lng": 0,

with them. Make sure to read through the geocoder gem page, got a couple of useful things on there.

Edit

For the newest issue, I'm not great with javascript, but I'd try removing the async defer and that &callback=initMap from your google maps javascript tag (since you don't have a function defined with that name).

Original answer, may have been a typo in the question not an actual problem with the code.

The NoMethodError is being caused by a typo gecoded_by should probably be geocoded_by. The RoutingError is just for a source map file which shouldn't cause any issues.


来源: stackexchange

问:
How to debug in HTML
I am trying to implement a little code in HTML; calling a PHP onclick in HTML using the solution here and it just runs to a blank page. Upon inspection, I noticed a typo in my code but after i corrected it the output is still the same i.e. it opens a blank page with no echo or anything.

My question: Is there a way to debug my code so my browser (i suspect) can notify me as to what part or line of my code the error is coming from, like in Java IDEs?

```<code><?php
function working(){
    echo 'WORKED ';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dice Game</title>
</head>
<body>
<div>
<div>
    <h1 id="player1" onclick="document.write('<?php working(); ?>')">
        ENTER PLAYER 1 NAME
    </h1>
</div>
</div>
</body>
</html>
</code>```

Note: I use Chrome

答: Browsers like Firefox, Chrome, etc. have Developer Tools. Hit F12 to activate it and then look at Console, then reload the page. That should tell you what your errors are.</p>

ContentLicense: CC BY-SA 3.0

Title: How to debug in HTML

Body:
I am trying to implement a little code in HTML; calling a PHP onclick in HTML using the solution here and it just runs to a blank page. Upon inspection, I noticed a typo in my code but after i corrected it the output is still the same i.e. it opens a blank page with no echo or anything.

My question: Is there a way to debug my code so my browser (i suspect) can notify me as to what part or line of my code the error is coming from, like in Java IDEs?

<?php
function working(){
    echo 'WORKED ';
}
?>
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Dice Game</title>

    <h1 id="player1" onclick="document.write('<?php working(); ?>')">
        ENTER PLAYER 1 NAME

Note: I use Chrome


问:
Node.js How to import and export modules with sub functions
I am writing an application and ran into a bit of trouble. I setup a "class" in JavaScript and within that class I call multiple this.demo = function(){}. When i export the module and then import on another page, then attempt to use one of the sub functions, my application tells me it does not recognize the function. Here is an example.. how should i be doing this?

```<code>function demo(){ this.test = function(msg){console.log(msg);} }
module.exports.demo = demo;
</code>```

Then inside of another class I import the demo.js file

```<code>function newClass(){
   this.demo = require('./demo');
   this.demo.test('Hello');
}
</code>```

The editor tells me that it does not recognize test...

答:
There is an export error in your code.

```<code>function demo(){ this.test = function(msg){console.log(msg);} }
module.exports.test = demo;
</code>```

Now you can call it correctly:

```<code>function newClass(){

   this.demo = require('./demo');
   this.demo.test('Hello');

   // If you're still confused, use the console.log!
   console.log(this.demo);

}
</code>```

The output of the console.log(this.demo) will show the structure or your demo file.

Edit: To get a function as result of the require call, export like this:

```<code>module.exports = function demo(){ this.test = function(msg){console.log(msg);} }
</code>```

Now you call directly:

```<code>function newClass(){

   this.demo = require('./demo');
   this.demo.test('Hello');

}
</code>```

Body:
I am writing an application and ran into a bit of trouble. I setup a "class" in JavaScript and within that class I call multiple this.demo = function(){}. When i export the module and then import on another page, then attempt to use one of the sub functions, my application tells me it does not recognize the function. Here is an example.. how should i be doing this?

function demo(){ this.test = function(msg){console.log(msg);} }
module.exports.demo = demo;

Then inside of another class I import the demo.js file

function newClass(){
   this.demo = require('./demo');
   this.demo.test('Hello');
}

The editor tells me that it does not recognize test...

Body:
There is an export error in your code.

function demo(){ this.test = function(msg){console.log(msg);} }
module.exports.test = demo;

Now you can call it correctly:

function newClass(){

   this.demo = require('./demo');
   this.demo.test('Hello');

   // If you're still confused, use the console.log!
   console.log(this.demo);

}

The output of the console.log(this.demo) will show the structure or your demo file.

Edit: To get a function as result of the require call, export like this:

module.exports = function demo(){ this.test = function(msg){console.log(msg);} }

Now you call directly:

function newClass(){

   this.demo = require('./demo');
   this.demo.test('Hello');

}


问:
jQuery file is connected but jQuery does not work properly

$(document).ready(function () {
   $('.lead')hide().fadeIn('slow');

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.lead {
        font-size: 10rem;
        font-weight: bold;
        color: #3fddff;
        text-shadow: 5px 5px 5px #000;

        position: fixed;
        bottom: 0;
        right: 0;
        margin-right: 5rem;
        margin-bottom: 6rem;
        border-bottom: 3px solid #fff;
    }

    .webdev {
        font-size: 3rem;
        font-weight: bold;
        color: #000;
        text-shadow: 3px 3px 3px #aaa;

        position: fixed;
        bottom: 0;
        right: 0;
        margin-right: 25rem;
        margin-bottom: 2rem;
    }

    .lead {
    display: none;
}</code>```

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Title Page</title>

    <link type="text/css" rel="stylesheet" href="normalize/normalize.css"/>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

    <link href="styles.css" rel="stylesheet" type="text/css">

    <link href="https://fonts.googleapis.com/css?family=Titillium+Web:400,900" rel="stylesheet">

            portfolio

            about

            contact

            YouTube Channel (comming soon!)

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggleExternalContent" aria-controls="navbarToggleExternalContent" aria-expanded="false" aria-label="Toggle navigation">

        </button>

My Name

Web Developer

```

Hello,

I'm having trouble getting my fadeIn() to work on my page. I am trying to have my name fade-in once my page is loaded but for some reason that does not happen. I know the file is linked properly because I tested it out with a console.log but the fadeIn() does not work at all. I'm pretty new to jQuery but I thought this was one of the more easier functions to do. Am I overlooking something?

Thank you for your help.

Best,
Edwin

答:
1 check Before you do anything, navigate to your jQuery file and check that it is exactly where it should be.

2load this http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js?ver=1.4.2'>

Body:
$(document).ready(function () {
   $('.lead')hide().fadeIn('slow');

});

.lead {
        font-size: 10rem;
        font-weight: bold;
        color: #3fddff;
        text-shadow: 5px 5px 5px #000;

        position: fixed;
        bottom: 0;
        right: 0;
        margin-right: 5rem;
        margin-bottom: 6rem;
        border-bottom: 3px solid #fff;
    }

    .webdev {
        font-size: 3rem;
        font-weight: bold;
        color: #000;
        text-shadow: 3px 3px 3px #aaa;

        position: fixed;
        bottom: 0;
        right: 0;
        margin-right: 25rem;
        margin-bottom: 2rem;
    }

    .lead {
    display: none;
}

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Title Page</title>

    <link type="text/css" rel="stylesheet" href="normalize/normalize.css"/>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

    <link href="styles.css" rel="stylesheet" type="text/css">

    <link href="https://fonts.googleapis.com/css?family=Titillium+Web:400,900" rel="stylesheet">

            portfolio

            about

            contact

            YouTube Channel (comming soon!)

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggleExternalContent" aria-controls="navbarToggleExternalContent" aria-expanded="false" aria-label="Toggle navigation">

        </button>

My Name

Web Developer

Hello,

I'm having trouble getting my fadeIn() to work on my page. I am trying to have my name fade-in once my page is loaded but for some reason that does not happen. I know the file is linked properly because I tested it out with a console.log but the fadeIn() does not work at all. I'm pretty new to jQuery but I thought this was one of the more easier functions to do. Am I overlooking something?

Thank you for your help.

Best,
Edwin


问:
Breeze# for Xamarin.Forms (UWP, Droid & iOS)?
In their website, Xamarin appears as one of their clients, but I'm unable to install the package Breeze.Sharp, which is also tagged with Xamarin.

It does install into the PCL project, but for it to work I need to install it into all of the platform projects. When I try to do so, I get the following errors:

iOS/Android:

Could not install package 'Microsoft.AspNet.WebApi.Client 5.2.3'. You are trying to install this package into a project that targets 'Xamarin.iOS,Version=v1.0', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

UWP:

Package Breeze.Sharp 0.6.0.9 is not compatible with uap10.0 (UAP,Version=v10.0) / win10-x86-aot. Package Breeze.Sharp 0.6.0.9 supports: net (.NETFramework,Version=v0.0)
  One or more packages are incompatible with UAP,Version=v10.0 (win10-x86-aot).

答:
In an email I got from IdeaBlade, the inventor of Breeze#, he said that while the Breeze# is not dead, it has drown much less community attention compared to BreezeJS, thus they prefer to invest their resources in the JS library.

For now, I'm just gonna use TrackableEntities by @AnthonySneed. Although not as comprehensive as Breeze#, does part of the job nicely.


问:
react-router scroll to top on every transition
I have an issue when navigating into another page, its position will remain like the page before. So it won't scroll to top automatically.
I've also tried to use window.scrollTo(0, 0) on onChange router. I've also used scrollBehavior to fix this issue but it didn't work. Any suggestions about this?

答:
This answer is only for v4 and not later versions.

The documentation for React Router v4 contains code samples for scroll restoration. Here is their first code sample, which serves as a site-wide solution for “scroll to the top” when a page is navigated to:

```<code>class ScrollToTop extends Component {
  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      window.scrollTo(0, 0)
    }
  }

  render() {
    return this.props.children
  }
}

export default withRouter(ScrollToTop)
</code>```

Then render it at the top of your app, but below Router:

```<code>const App = () => (
  <Router>
    <ScrollToTop>
      <App/>
    </ScrollToTop>
  </Router>
)

// or just render it bare anywhere you want, but just one :)
<ScrollToTop/>
</code>```

^ copied directly from the documentation

Obviously this works for most cases, but there is more on how to deal with tabbed interfaces and why a generic solution hasn't been implemented.

ContentLicense: CC BY-SA 4.0

Body:
This answer is only for v4 and not later versions.

The documentation for React Router v4 contains code samples for scroll restoration. Here is their first code sample, which serves as a site-wide solution for “scroll to the top” when a page is navigated to:

class ScrollToTop extends Component {
  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      window.scrollTo(0, 0)
    }
  }

  render() {
    return this.props.children
  }
}

export default withRouter(ScrollToTop)

Then render it at the top of your app, but below Router:

const App = () => (
  <Router>
    <ScrollToTop>
      <App/>
    </ScrollToTop>
  </Router>
)

// or just render it bare anywhere you want, but just one :)
<ScrollToTop/>

^ copied directly from the documentation

Obviously this works for most cases, but there is more on how to deal with tabbed interfaces and why a generic solution hasn't been implemented.


问:
Golang JSON-RPC Server Control at Shutdown
I am writing a Shutdown Handler for a Program which uses Golang's built-in JSON-RPC Server and I have faced a difficulty. Could you help me with it?

I stop accepting incomming Connections, stop accepting incoming Requests for existing Connections (send an Error, to be true) but I have a Moment which I can not control or, at least, I do not know how to control.

The Question is:

How do I guarantee that Results of exisiting Requests of existing Connections are given to Clients of Golang's built-in JSON-RPC Server?

I want to control that Structure which calls RPC Methods, but it is not in my Code. For Example, I have an RPC Action 'User.Get'. I have a function named 'Get' which I control. How do I control the Code which starts this 'Get' function? Do I have to modify Google's RPC Server or is there any more effecient way?

Maybe, there is some Variable in RPC Server which holds the Number of active Requests being processed?

I see a NumCalls() and numCalls in the methodType in https://golang.org/src/net/rpc/server.go. The Problem is that this Field is not public... Moreover, the .../rpc/server.go uses sync.Map which does not compile. My Version of Golang is too old? :)

Seems that for now the easiest Way is to manipulate a global Counter from all the RPC Action Functions. :-) If you know a better Solution, please, tell me. Thanks. :-)

答:
In net/rpc godoc example it just shows how to use global defaults. Instead create your own rpc and http server instances.

```<code>import "net/rpc"
import "net/http"

rpcServer := rpc.NewServer()
// rpc stuff
httpServer := &http.Server{
    Handler: rpcServer,
}
// graceful shutdown stuff
</code>```

For graceful shutdown, there's a few packages. I know of this one.

https://github.com/tylerb/graceful

Body:
In net/rpc godoc example it just shows how to use global defaults. Instead create your own rpc and http server instances.

import "net/rpc"
import "net/http"

rpcServer := rpc.NewServer()
// rpc stuff
httpServer := &http.Server{
    Handler: rpcServer,
}
// graceful shutdown stuff

For graceful shutdown, there's a few packages. I know of this one.

https://github.com/tylerb/graceful


问:
Java, sum range of numbers in a for loop
Sorry I have been trying to figure this out and it's driving me crazy.

I need to write a java program that sums a range of numbers entered by the user and by the count of numbers entered by a user.  So if a user enters 5, 25 with count of 5.  It should sum 5+10+15+20+25=75  I have gotten it to work with a while loop, but not a for loop.  Sorry if I am asking for help for something that should be simple.  I left school almost 15 years ago involuntarily and struggling to get back into in.

Do I need to nest the loop?

```<code>import java.util.Scanner;
public class example1

{
  public static void main(String[] args) {
    int s, e, c = 0, sum = 0;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a starting number:  ");
    s = sc.nextInt();
    System.out.print("Enter an end number:  ");
    e = sc.nextInt();
    System.out.print("Enter a count by number:  ");
    c = sc.nextInt();

    {

      for (; s <= e; s++)
        sum += c;
      System.out.println("Sum of your numbers  " + sum);
    }

  }
}
</code>```

答:
This is what the final code looked like and it worked with several different numbers I entered.  Is there a way to make this as "answered"?

import java.util.Scanner ;
public class example1

{
 public static void main(String[] args)
 {
  int s,e,c = 0, sum = 0;
  Scanner sc = new Scanner(System.in);
  System.out.print("Enter starting number:  ");
  s = sc.nextInt();
  System.out.print("Enter an end number:  ");
  e = sc.nextInt();
  System.out.print("Enter a count by number:  ");
  c = sc.nextInt();

    for (; s <= e; s+=c)
    sum += s;
    System.out.println("The sum of your number range is  " + sum);

 }
}```

Body:
Sorry I have been trying to figure this out and it's driving me crazy.

I need to write a java program that sums a range of numbers entered by the user and by the count of numbers entered by a user.  So if a user enters 5, 25 with count of 5.  It should sum 5+10+15+20+25=75  I have gotten it to work with a while loop, but not a for loop.  Sorry if I am asking for help for something that should be simple.  I left school almost 15 years ago involuntarily and struggling to get back into in.

Do I need to nest the loop?

import java.util.Scanner;
public class example1

{
  public static void main(String[] args) {
    int s, e, c = 0, sum = 0;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a starting number:  ");
    s = sc.nextInt();
    System.out.print("Enter an end number:  ");
    e = sc.nextInt();
    System.out.print("Enter a count by number:  ");
    c = sc.nextInt();

    {

      for (; s <= e; s++)
        sum += c;
      System.out.println("Sum of your numbers  " + sum);
    }

  }
}


问:
C# String Equals comparison method fails for strings that have special characters in them
I am currently comparing property values of type string using the string Equals method.

Example: f.rfgmodel.Equals(model, StringComparison.OrdinalIgnoreCase)

Now the problem I am running into is that for strings like ‘M&P9 Shield’ (a Firearm Model stored in my Accessories table in the DB), that has the ‘&’ symbol, the string Equals method doesn’t work.

Sadly, I cannot ignore the  ‘&’ symbol in such model values, so stripping out the ‘&’ symbol from existing DB records in the DB is not an option.

Here is what my code looks like:

```<code>[Route("filter/{pcategory}")]
        public IQueryable<AccessoryDto> GetAccessoryFilter(string pcategory = "", string model = "")
        {
            return db.Accessories.Where(f => (f.rfgacctype.Equals("holsters", StringComparison.OrdinalIgnoreCase) & f.rfgparentcategory.Equals(pcategory, StringComparison.OrdinalIgnoreCase) & f.rfgmodel.Equals(model, StringComparison.OrdinalIgnoreCase)))
            .Select(AsAccessoryDto);
        }
</code>```

Example of my DB table:
Accessory Table

I have searched quite a bit and the few matches don’t have a solution, much less provide enough hints to lead me in the right direction in attempting to resolve my current problem.

Example 1:
C# String comparison fails for string having special character in it
In this particular thread, the user @Biki left a comment to the first answer, stating that the Equals method doesn’t work. This is true.

Example 2: This one didn’t help either: Elastic Search-Search string having spaces and special characters in it using C#

Please if anyone could help with a solution of provide hints pointing me in the right direction.
Thanks in advance. Much appreciated.

答:
Since the problem occurred from the url encoded value used for 'M&P9 Shield' when passed as a input parameter at my endpoint, i realized that the special character '&' was not being encoded properly, because the url encoded value was ending up as: http://localhost:56206/api/accessories/filter/pistols?caliber=9mm%20Luger%20(9x19%20Para)&model=M&P9%20Shield

instead of:
http://localhost:56206/api/accessories/filter/pistols?caliber=9mm%20Luger%20(9x19%20Para)&model=M%26P9%20Shield

I used this resource https://www.w3schools.com/tags/ref_urlencode.asp

So the '&' which is considered a unsafe ASCII character is encoded as '%26'

Thanks everyone.

Body:
I am currently comparing property values of type string using the string Equals method.

Example: f.rfgmodel.Equals(model, StringComparison.OrdinalIgnoreCase)

Now the problem I am running into is that for strings like ‘M&P9 Shield’ (a Firearm Model stored in my Accessories table in the DB), that has the ‘&’ symbol, the string Equals method doesn’t work.

Sadly, I cannot ignore the  ‘&’ symbol in such model values, so stripping out the ‘&’ symbol from existing DB records in the DB is not an option.

Here is what my code looks like:

[Route("filter/{pcategory}")]
        public IQueryable<AccessoryDto> GetAccessoryFilter(string pcategory = "", string model = "")
        {
            return db.Accessories.Where(f => (f.rfgacctype.Equals("holsters", StringComparison.OrdinalIgnoreCase) & f.rfgparentcategory.Equals(pcategory, StringComparison.OrdinalIgnoreCase) & f.rfgmodel.Equals(model, StringComparison.OrdinalIgnoreCase)))
            .Select(AsAccessoryDto);
        }

Example of my DB table:
Accessory Table

I have searched quite a bit and the few matches don’t have a solution, much less provide enough hints to lead me in the right direction in attempting to resolve my current problem.

Example 1:
C# String comparison fails for string having special character in it
In this particular thread, the user @Biki left a comment to the first answer, stating that the Equals method doesn’t work. This is true.

Example 2: This one didn’t help either: Elastic Search-Search string having spaces and special characters in it using C#

Please if anyone could help with a solution of provide hints pointing me in the right direction.
Thanks in advance. Much appreciated.


问:
Saving all Inputs entered for display on cout - C++
I have looked in the forum but can't seem to find anything specific to what I need.

I am writing a program that asks the user to input a number of students. Depending on the number of students they enter they will then have to enter the students name and a series of 10 grades, or pressing 999 to cancel. The program will later have to display all students entered with their average grade. What I have now just overrides the previous inputs and displays the last one entered.

This is what I have so far:

```<code>#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>

int main() {

std::string teacherName = "";
std::string classDesignation ="";
int numStudents = 0;
std::string studentName = "";
double grade[10];
double  averageGrade = 0.00;
char letterGrade;

std::cout << "Enter the teacher's name: ";
getline(std::cin, teacherName);

std::cout << "Enter the class designation: ";
getline(std::cin, classDesignation);

std::cout << "Enter the number of students ( 1 or more ): ";
std::cin >> numStudents;
std::cin.ignore();

for (int x = 0; x <= numStudents - 1; x++) {
    std::cout << "Enter the student's name: ";
    getline(std::cin, studentName);

    for (int i = 0; i <= 9; i++) {
        std::cout << "Enter grade from 0 - 100 or 999 to stop: ";
        std::cin >> grade[i];

        if (grade[i] == 999){
            break;
    }
        averageGrade += grade[i];

        if (averageGrade <= 59){
            letterGrade = 'F';
        }
        if (averageGrade >= 60 || averageGrade <= 69){
            letterGrade = 'D';
        }
        if (averageGrade >= 70 || averageGrade <= 79){
            letterGrade = 'C';
        }
        if (averageGrade >= 80 || averageGrade <= 89){
            letterGrade = 'B';
        }
        if (averageGrade > 90){
            letterGrade = 'A';
        }
    }
}

std::cout << "Teacher: " << teacherName << std::endl;
std::cout << "Class: " << classDesignation << std::endl;
std::cout << "Student Name: " << studentName;
std::cout << std::setw(19) << "Average: " << averageGrade;
std::cout << " Grade: " << letterGrade << std::endl;
std::cout << "Student count: " << numStudents << std::endl;
std::cout << "Student average: " << std::endl;
std::cout << "A's: " << std::endl;
std::cout << "B's: " << std::endl;
std::cout << "C's: " << std::endl;
std::cout << "D's: " << std::endl;
std::cout << "F's: " << std::endl;

return 0;
}
</code>```

Any tips?

Thank you!

答:
From what I see, you can store them in associative vectors, one for the student name, and one for the average grade. You can also have a doubly linked list of student nodes which would look something like this:

```<code>struct student
{
    std::string student_name;
    int ave_grade;
    // Head points to the previous student in the array.
    // Tail points to the next student in the array.
    student *head;
    student *tail;
}
</code>```

Declare a struct that everything hangs from to prevent memory leaks: student list_head; and each time you have an input, add a new node to the list.

Body:
I have looked in the forum but can't seem to find anything specific to what I need.

I am writing a program that asks the user to input a number of students. Depending on the number of students they enter they will then have to enter the students name and a series of 10 grades, or pressing 999 to cancel. The program will later have to display all students entered with their average grade. What I have now just overrides the previous inputs and displays the last one entered.

This is what I have so far:

#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>

int main() {

std::string teacherName = "";
std::string classDesignation ="";
int numStudents = 0;
std::string studentName = "";
double grade[10];
double  averageGrade = 0.00;
char letterGrade;

std::cout << "Enter the teacher's name: ";
getline(std::cin, teacherName);

std::cout << "Enter the class designation: ";
getline(std::cin, classDesignation);

std::cout << "Enter the number of students ( 1 or more ): ";
std::cin >> numStudents;
std::cin.ignore();

for (int x = 0; x <= numStudents - 1; x++) {
    std::cout << "Enter the student's name: ";
    getline(std::cin, studentName);

    for (int i = 0; i <= 9; i++) {
        std::cout << "Enter grade from 0 - 100 or 999 to stop: ";
        std::cin >> grade[i];

        if (grade[i] == 999){
            break;
    }
        averageGrade += grade[i];

        if (averageGrade <= 59){
            letterGrade = 'F';
        }
        if (averageGrade >= 60 || averageGrade <= 69){
            letterGrade = 'D';
        }
        if (averageGrade >= 70 || averageGrade <= 79){
            letterGrade = 'C';
        }
        if (averageGrade >= 80 || averageGrade <= 89){
            letterGrade = 'B';
        }
        if (averageGrade > 90){
            letterGrade = 'A';
        }
    }
}

std::cout << "Teacher: " << teacherName << std::endl;
std::cout << "Class: " << classDesignation << std::endl;
std::cout << "Student Name: " << studentName;
std::cout << std::setw(19) << "Average: " << averageGrade;
std::cout << " Grade: " << letterGrade << std::endl;
std::cout << "Student count: " << numStudents << std::endl;
std::cout << "Student average: " << std::endl;
std::cout << "A's: " << std::endl;
std::cout << "B's: " << std::endl;
std::cout << "C's: " << std::endl;
std::cout << "D's: " << std::endl;
std::cout << "F's: " << std::endl;

return 0;
}

Any tips?

Thank you!

Body:
From what I see, you can store them in associative vectors, one for the student name, and one for the average grade. You can also have a doubly linked list of student nodes which would look something like this:

struct student
{
    std::string student_name;
    int ave_grade;
    // Head points to the previous student in the array.
    // Tail points to the next student in the array.
    student *head;
    student *tail;
}

Declare a struct that everything hangs from to prevent memory leaks: student list_head; and each time you have an input, add a new node to the list.


问:
How can Python access the X11 clipboard?
I want my Python script to be able to copy and paste to/from the clipboard via x11 (so that it will work on Linux). Can anyone point me to specific resources I can look at, or the concepts I would have to master?

Is this possible to do with the Python X library at http://python-xlib.sourceforge.net ?

答:
Tkinter-based solution mentioned in Cameron Laird's answer:

import Tkinter
root = Tkinter.Tk()
print(root.selection_get(selection="CLIPBOARD"))
```

<p>Replace "CLIPBOARD" with "PRIMARY" to get <code>PRIMARY</code> selection instead.</p>

<p>Also see this answer.</p>

<p><strong>python-xlib solution</strong>, based on PrintSelection() and python-xlib/examples/get_selection.py</p>

<pre class="lang-python prettyprint-override"><code>from Xlib import X, display as Xdisplay

def property2str(display, prop):
    if prop.property_type == display.get_atom("STRING"):
        return prop.value.decode('ISO-8859-1')
    elif prop.property_type == display.get_atom("UTF8_STRING"):
        return prop.value.decode('UTF-8')
    else:
        return "".join(str(c) for c in prop.value)

def get_selection(display, window, bufname, typename):
    bufid = display.get_atom(bufname)
    typeid = display.get_atom(typename)
    propid = display.get_atom('XSEL_DATA')
    incrid = display.get_atom('INCR')

    window.change_attributes(event_mask = X.PropertyChangeMask)
    window.convert_selection(bufid, typeid, propid, X.CurrentTime)
    while True:
        ev = display.next_event()
        if ev.type == X.SelectionNotify and ev.selection == bufid:
            break

    if ev.property == X.NONE:
        return None # request failed, e.g. owner can't convert to target format type
    else:
        prop = window.get_property(propid, X.AnyPropertyType, 0, 2**31-1, 1)

        if prop.property_type == incrid:
            result = ""
            while True:
                while True:
                    ev = display.next_event()
                    if ev.type == X.PropertyNotify and ev.atom == propid and ev.state == X.PropertyNewValue:
                        break

                prop = window.get_property(propid, X.AnyPropertyType, 0, 2**31-1, 1)
                if len(prop.value) == 0:
                    break

                result += property2str(display, prop)
            return result
        else:
            return property2str(display, prop)

display = Xdisplay.Display()
window = display.screen().root.create_window(0,0, 1,1, 0, X.CopyFromParent)
print( get_selection(display, window, "CLIPBOARD", "UTF8_STRING") or \
       get_selection(display, window, "CLIPBOARD", "STRING") )
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Tkinter-based solution mentioned in Cameron Laird's answer:

import Tkinter
root = Tkinter.Tk()
print(root.selection_get(selection="CLIPBOARD"))

Replace "CLIPBOARD" with "PRIMARY" to get PRIMARY selection instead.

Also see this answer.

python-xlib solution, based on PrintSelection() and python-xlib/examples/get_selection.py

from Xlib import X, display as Xdisplay

def property2str(display, prop):
    if prop.property_type == display.get_atom("STRING"):
        return prop.value.decode('ISO-8859-1')
    elif prop.property_type == display.get_atom("UTF8_STRING"):
        return prop.value.decode('UTF-8')
    else:
        return "".join(str(c) for c in prop.value)

def get_selection(display, window, bufname, typename):
    bufid = display.get_atom(bufname)
    typeid = display.get_atom(typename)
    propid = display.get_atom('XSEL_DATA')
    incrid = display.get_atom('INCR')

    window.change_attributes(event_mask = X.PropertyChangeMask)
    window.convert_selection(bufid, typeid, propid, X.CurrentTime)
    while True:
        ev = display.next_event()
        if ev.type == X.SelectionNotify and ev.selection == bufid:
            break

    if ev.property == X.NONE:
        return None # request failed, e.g. owner can't convert to target format type
    else:
        prop = window.get_property(propid, X.AnyPropertyType, 0, 2**31-1, 1)

        if prop.property_type == incrid:
            result = ""
            while True:
                while True:
                    ev = display.next_event()
                    if ev.type == X.PropertyNotify and ev.atom == propid and ev.state == X.PropertyNewValue:
                        break

                prop = window.get_property(propid, X.AnyPropertyType, 0, 2**31-1, 1)
                if len(prop.value) == 0:
                    break

                result += property2str(display, prop)
            return result
        else:
            return property2str(display, prop)

display = Xdisplay.Display()
window = display.screen().root.create_window(0,0, 1,1, 0, X.CopyFromParent)
print( get_selection(display, window, "CLIPBOARD", "UTF8_STRING") or \
       get_selection(display, window, "CLIPBOARD", "STRING") )


问:
Implement an algorithm in Scala to determin if a string has all unique characters
I am solving trivial problems to learn Scala. Here is what I have come up with

```<code>def isUnique(str: String): Boolean = {
    if (str.length > 128) return false
    val uniqueChars = new Array[Boolean](128)

    !(str.map(c => addChar(c, uniqueChars)).find(identity).isDefined)
}

def addChar(ch: Char, uniqueChars: Array[Boolean]): Boolean = {
    if (uniqueChars(ch)) return true else {
    uniqueChars(ch) = true;
    return false
}
</code>```

Is that it?

Please note that I don't care about the logic or optimization at this point. I only need to learn the Scala way of doing it.

[Edit]
Let's assume we don't want to use the string distinct method. I only need to verify the functional style of Scala.

答:
You want to "learn scala way of doing it", by actually doing it in a way, that makes no sense to use in scala? Scala way of doing it str == str.distinct. If "you don't want to use distinct", then str.toSet.size == str.length. If you don't want toSet either, then str.groupBy(identity).values.map(_.size).forall(_ == 1).
If you don't want .groupBy then
str.sorted.sliding(2).forall(s => s.head != s.last)

Etc. ... At some point, "scala way" just stops being "scala way" and becomes a java program written in scala syntax.

Body:
I am solving trivial problems to learn Scala. Here is what I have come up with

def isUnique(str: String): Boolean = {
    if (str.length > 128) return false
    val uniqueChars = new Array[Boolean](128)

    !(str.map(c => addChar(c, uniqueChars)).find(identity).isDefined)
}

def addChar(ch: Char, uniqueChars: Array[Boolean]): Boolean = {
    if (uniqueChars(ch)) return true else {
    uniqueChars(ch) = true;
    return false
}

Is that it?

Please note that I don't care about the logic or optimization at this point. I only need to learn the Scala way of doing it.

[Edit]
Let's assume we don't want to use the string distinct method. I only need to verify the functional style of Scala.


问:
REST URI parameters to filter response
I am trying to filter a list of objects retrieved from the database, as per the parameters retrieved from the REST URI. Example URI would be http://127.0.0.1:8080/api/employee?FirstName=Abigail&LastName=Ybarra which would retrieve me a list of objects with specified first names and last names.

The error I am getting while hitting such URI is the following:

```<code><ExceptionMessage>
Object reference not set to an instance of an object
</ExceptionMessage>
<ExceptionType>System.NullReferenceException</ExceptionType>

MyWebService.Controllers.EmployeeApiController+<>c__DisplayClass4_0.<ListEmployees>b__0 (MyWebService.Models.Employee x) [0x00000] in <8bf6371a770245f989f67352a05d8bb6>:0 at System.Linq.Enumerable+WhereListIterator`1[TSource].MoveNext () [0x00037] in /private/tmp/source-mono-2017-02/bockbuild-2017-02/profiles/mono-mac-xamarin/build-root/mono-x86/external/corefx/src/System.Linq/src/System/Linq/Where.cs:369 at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList
</code>```

The same thing happens for ie. URI http://127.0.0.1:8080/api/employee?id=3, while it works as expected for URI http://127.0.0.1:8080/api/employee/3. It also works as expected (retrieves all objects from the database) for URI http://127.0.0.1:8080/api/employee/.

The only thing not working are the parameters. Here is the code.

Controller.cs

```<code>    [RoutePrefix("api/employee")]
    public class EmployeeApiController : ApiController
    {

        readonly EmployeePersistence persistence;

        public EmployeeApiController()
        {
            persistence = new EmployeePersistence();
        }

        [HttpGet]
        [Route("{id:long}")]
        public IHttpActionResult GetEmployee(long id)
        {
            return Json(persistence.GetEmployee(id));
        }

        [HttpGet]
        [Route("")]
        public IHttpActionResult ListEmployees([FromUri] EmployeeParameters parameters)
        {
            return Json(persistence.GetEmployeeList().Where(x => x.FirstName.Equals(parameters.FirstName)));
        }
    }
}
</code>```

EmployeeParametes.cs

```<code>public class EmployeeParameters
{
    /**
     * First name of the employee.
     */
    public string FirstName { get; set; }

    /*
     * Last name of the employee.
     */
    public string LastName { get; set; }

    /**
     * Place of birth of the employee.
     */
    public string BirthPlace { get; set; }

    /**
     * Gender of the employee.
     */
    public int Gender { get; set; }

    /**
     * OIB of the employee.
     */
    public string OIB { get; set; }

    /**
     *  Current place of the employee.
     */
    public string CurrentPlace { get; set; }

    /**
     *  Department code of the employee.
     */
    public string Department { get; set; }

    public EmployeeParameters()
    {
    }
}
</code>```

Persistence.cs

```<code>    public List<Employee> GetEmployeeList()
        {
            string sqlString = "SELECT * FROM Employee";

            MySqlCommand cmd = new MySqlCommand(sqlString, conn);

            List<Employee> employees = new List<Employee>();

            using (MySqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    employees.Add(ReadFromDatabase(reader));
                }
            }

            return employees;
        }

Employee ReadFromDatabase(MySqlDataReader dataReader)
        {
            if (!dataReader.Read())
            {
                return null;
            }

            string firstName = null;
            string lastName = null;
            string birthPlace = null;
            string currentPlace = null;
            int gender = -1;
            string departmentCode = null;
            string OIB = null;

            try
            {
                firstName = dataReader.GetString(1);
                lastName = dataReader.GetString(2);
                birthPlace = dataReader.GetString(3);
                currentPlace = dataReader.GetString(4);
                gender = dataReader.GetInt32(5);
                departmentCode = dataReader.GetString(6);
                OIB = dataReader.GetString(7);
            }
            catch (SqlNullValueException)
            {
                // log the error
            }

            return new Employee(
                firstName != null ? firstName : "N/A",
                lastName != null ? lastName : "N/A",
                birthPlace != null ? birthPlace : "N/A",
                currentPlace != null ? currentPlace : "N/A",
                gender != -1 ? (gender == 1 ? EmployeeGender.M : EmployeeGender.F) :
                    EmployeeGender.UNDEFINED,
                departmentCode != null ?
                    DepartmentCodeExtensions.GetEnumValue(DepartmentCode.NONE, departmentCode) :
                    DepartmentCode.NONE,
                OIB != null ? OIB : "N/A"
            );
        }
</code>```

I am guessing that the problem is something with the routes, but not sure exactly what or how to fix it. Any help is appreciated.

答:
I think that the exception appears because the calls to .Read() in both the while-loop and inside the method ReadFromDatabase. You should delete the  .Read() call from the latter.

As your code is now, two calls of .Read() in the reader is performed before you're extracting data from the reader.
Another problem is that you're putting null in your list of employees if the reader can't read more, guaranteeing a NullPointerException when trying to use the FirstName property of this element.

Title: REST URI parameters to filter response

Body:
I am trying to filter a list of objects retrieved from the database, as per the parameters retrieved from the REST URI. Example URI would be http://127.0.0.1:8080/api/employee?FirstName=Abigail&LastName=Ybarra which would retrieve me a list of objects with specified first names and last names.

The error I am getting while hitting such URI is the following:

<ExceptionMessage>
Object reference not set to an instance of an object
</ExceptionMessage>
<ExceptionType>System.NullReferenceException</ExceptionType>

MyWebService.Controllers.EmployeeApiController+<>c__DisplayClass4_0.<ListEmployees>b__0 (MyWebService.Models.Employee x) [0x00000] in <8bf6371a770245f989f67352a05d8bb6>:0 at System.Linq.Enumerable+WhereListIterator`1[TSource].MoveNext () [0x00037] in /private/tmp/source-mono-2017-02/bockbuild-2017-02/profiles/mono-mac-xamarin/build-root/mono-x86/external/corefx/src/System.Linq/src/System/Linq/Where.cs:369 at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList

The same thing happens for ie. URI http://127.0.0.1:8080/api/employee?id=3, while it works as expected for URI http://127.0.0.1:8080/api/employee/3. It also works as expected (retrieves all objects from the database) for URI http://127.0.0.1:8080/api/employee/.

The only thing not working are the parameters. Here is the code.

Controller.cs

    [RoutePrefix("api/employee")]
    public class EmployeeApiController : ApiController
    {

        readonly EmployeePersistence persistence;

        public EmployeeApiController()
        {
            persistence = new EmployeePersistence();
        }

        [HttpGet]
        [Route("{id:long}")]
        public IHttpActionResult GetEmployee(long id)
        {
            return Json(persistence.GetEmployee(id));
        }

        [HttpGet]
        [Route("")]
        public IHttpActionResult ListEmployees([FromUri] EmployeeParameters parameters)
        {
            return Json(persistence.GetEmployeeList().Where(x => x.FirstName.Equals(parameters.FirstName)));
        }
    }
}

EmployeeParametes.cs

public class EmployeeParameters
{
    /**
     * First name of the employee.
     */
    public string FirstName { get; set; }

    /*
     * Last name of the employee.
     */
    public string LastName { get; set; }

    /**
     * Place of birth of the employee.
     */
    public string BirthPlace { get; set; }

    /**
     * Gender of the employee.
     */
    public int Gender { get; set; }

    /**
     * OIB of the employee.
     */
    public string OIB { get; set; }

    /**
     *  Current place of the employee.
     */
    public string CurrentPlace { get; set; }

    /**
     *  Department code of the employee.
     */
    public string Department { get; set; }

    public EmployeeParameters()
    {
    }
}

Persistence.cs

    public List<Employee> GetEmployeeList()
        {
            string sqlString = "SELECT * FROM Employee";

            MySqlCommand cmd = new MySqlCommand(sqlString, conn);

            List<Employee> employees = new List<Employee>();

            using (MySqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    employees.Add(ReadFromDatabase(reader));
                }
            }

            return employees;
        }

Employee ReadFromDatabase(MySqlDataReader dataReader)
        {
            if (!dataReader.Read())
            {
                return null;
            }

            string firstName = null;
            string lastName = null;
            string birthPlace = null;
            string currentPlace = null;
            int gender = -1;
            string departmentCode = null;
            string OIB = null;

            try
            {
                firstName = dataReader.GetString(1);
                lastName = dataReader.GetString(2);
                birthPlace = dataReader.GetString(3);
                currentPlace = dataReader.GetString(4);
                gender = dataReader.GetInt32(5);
                departmentCode = dataReader.GetString(6);
                OIB = dataReader.GetString(7);
            }
            catch (SqlNullValueException)
            {
                // log the error
            }

            return new Employee(
                firstName != null ? firstName : "N/A",
                lastName != null ? lastName : "N/A",
                birthPlace != null ? birthPlace : "N/A",
                currentPlace != null ? currentPlace : "N/A",
                gender != -1 ? (gender == 1 ? EmployeeGender.M : EmployeeGender.F) :
                    EmployeeGender.UNDEFINED,
                departmentCode != null ?
                    DepartmentCodeExtensions.GetEnumValue(DepartmentCode.NONE, departmentCode) :
                    DepartmentCode.NONE,
                OIB != null ? OIB : "N/A"
            );
        }

I am guessing that the problem is something with the routes, but not sure exactly what or how to fix it. Any help is appreciated.


问:
How to go back one page at a time (Go back to the referring page, not itself)
The history back function records requests. A page may request itself many times. So when pressing the back button, you might return to the previous request to the same page.

Here is a very simplified example:

Alice.html:

```<code><h1>This is Alice</h1>
<a href="charlie.php">Go to Charlie</a>
</code>```

Bob.html:

```<code><h1>This is Bob</h1>
<a href="charlie.php">Go to Charlie</a>
</code>```

Charlie.php:

```<code><h1>This is Charlie</h1>
<p id="output">Here goes the server output</p>
<form method="post">
<input type="hidden" id="somevalue" name="somevalue" value="0">
<button type="button" onclick="window.history.go(-1);">Back</button>
<button type="submit">Calculate</button>
</form>
<script>
// Simulate some server side action
document.getElementById("output").innerHTML = document.getElementById("somevalue").value = "Value = " + Math.random();
</script>
</code>```

Alice.html and Bob.html both links to Charlie.php.
Charlie.php has a form and call itself any number of times, to do some server manipulation of data.

The history back function steps one request back, not one page. To get back to Alice or Bob, the user has to hit the back button the same number of times that she hid the calculate button.

Question: How to step one page back, regardless of the number of requests to Charlie?

Edit: I'm looking for a generic solution for a simple "back up one page" button, without using server side variables.

A HTML5 only solutions is ok.

答:
Instead of navigating through the multiple spoof history items, you might be able to prevent them from being created in the first place, using:

location.replace() (this will replace the page in the current history item, so no extra click)

But since that's probably not possible due to your "server manipulation of data", the code below may offer a solution:

```<code>window.onload = function() {
  document.getElementById("back").onclick = function() {
    sessionStorage.setItem("href",location.href); //store current page into sessionStorage
    history.go(-1); //go back one page
  };
  if (location.href == sessionStorage.getItem("href")) {document.getElementById("back").click();} //if current page is the same as last one, go back one page
  else {sessionStorage.removeItem("href");} //clear sessionStorage
};
</code>```

In the demos below (SO doesn't allow sessionStorage) I had to simulate both "going through the history", and "page load for every history item", so the code looks a little different, using an array and other vars and functions, but the principle should be the same:

codepen: https://codepen.io/anon/pen/OgBgGg?editors=1011

jsfiddle: https://jsfiddle.net/j0ddnboq/2/

Body:
The history back function records requests. A page may request itself many times. So when pressing the back button, you might return to the previous request to the same page.

Here is a very simplified example:

Alice.html:

This is Alice

Go to Charlie

Bob.html:

This is Bob

Go to Charlie

Charlie.php:

This is Charlie

Here goes the server output

<form method="post">
<input type="hidden" id="somevalue" name="somevalue" value="0">
<button type="button" onclick="window.history.go(-1);">Back</button>
<button type="submit">Calculate</button>
</form>

Alice.html and Bob.html both links to Charlie.php.
Charlie.php has a form and call itself any number of times, to do some server manipulation of data.

The history back function steps one request back, not one page. To get back to Alice or Bob, the user has to hit the back button the same number of times that she hid the calculate button.

Question: How to step one page back, regardless of the number of requests to Charlie?

Edit: I'm looking for a generic solution for a simple "back up one page" button, without using server side variables.

A HTML5 only solutions is ok.

Body:
Instead of navigating through the multiple spoof history items, you might be able to prevent them from being created in the first place, using:

location.replace() (this will replace the page in the current history item, so no extra click)

But since that's probably not possible due to your "server manipulation of data", the code below may offer a solution:

window.onload = function() {
  document.getElementById("back").onclick = function() {
    sessionStorage.setItem("href",location.href); //store current page into sessionStorage
    history.go(-1); //go back one page
  };
  if (location.href == sessionStorage.getItem("href")) {document.getElementById("back").click();} //if current page is the same as last one, go back one page
  else {sessionStorage.removeItem("href");} //clear sessionStorage
};

In the demos below (SO doesn't allow sessionStorage) I had to simulate both "going through the history", and "page load for every history item", so the code looks a little different, using an array and other vars and functions, but the principle should be the same:

codepen: https://codepen.io/anon/pen/OgBgGg?editors=1011

jsfiddle: https://jsfiddle.net/j0ddnboq/2/


答:
None Slim version works fine

```<code><script src="https://code.jquery.com/jquery-3.2.1.min.js"
        integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
        crossorigin="anonymous">
</code>```

And you can probably remove hide() because you've already hid it using CSS.

```<code>$('.lead').fadeIn('slow');
</code>```

Double check if jQuery slim has the function fadeIn(), in dev console you probably will see this error (or at least that's what I saw):

jquery-3.2.1.slim.js:3860 jQuery.Deferred exception: $(...).fadeIn is
  not a function TypeError: $(...).fadeIn is not a function
      ......

Title: jQuery file is connected but jQuery does not work properly

Body:
None Slim version works fine

<script src="https://code.jquery.com/jquery-3.2.1.min.js"
        integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
        crossorigin="anonymous">

And you can probably remove hide() because you've already hid it using CSS.

$('.lead').fadeIn('slow');

Double check if jQuery slim has the function fadeIn(), in dev console you probably will see this error (or at least that's what I saw):

jquery-3.2.1.slim.js:3860 jQuery.Deferred exception: $(...).fadeIn is
  not a function TypeError: $(...).fadeIn is not a function
      ......


问:
Can we create a modulated GLaDOS sounding voice using JS SpeechSynthesis?
Using the built in W3 SpeechSynthesis API, is it possible to create a modulated voice like that of GLaDOS with JavaScript?

The code that I currently have (below) split()s the phrase to be synthesized into individual words, each to be uttered at a randomly determined pitch, in an attempt to create the desired effect.

There's too long a rest between the words uttered and the modulation is not satisfactory.

if ('speechSynthesis' in window) {
    var speechSynthesis = window.speechSynthesis;
    speechSynthesis.onvoiceschanged = function () {
        console.log(speechSynthesis)
        var phrase = "Hello, I am GLaDOS";
        var parts = phrase.split(" ");
        for(var i in parts){
            var word = parts[i];
            var text = new SpeechSynthesisUtterance(word);
            text.voice = speechSynthesis.getVoices[2]; //English Female Voice
            text.rate=1.2;
            text.pitch = Math.random()*.5+1.50;
            speechSynthesis.speak(text);
        }
    }
}```

Note: GLaDOS is "a fictional artificially intelligent computer system from the video game series Portal."

答:
Auto-Tune

This answer is mostly opinion, offered in good faith in an attempt to be helpful.

Unfortunately, I believe, the effect on GLaDOS's voice would have to be achieved in what Hollywood would call "Post-Production" i.e. it would have to be an after effect; the voice would need to be processed after it is uttered.

Adjusting the pitch and/or rate will always only affect the output of the entire utterance, the result of which appears to be set in stone once SpeechSynthesis.speak() is called.

Your idea to split the utterance into words, and have each word output with randomized pitches and rates is clever, and that may be as close as we can get without Post-Processing.

By the way: I have no idea if we can apply Post-Processing to the utterances, and suspect that if it is at all possible, it would require some form of browser extension/plugin.

However, several of the voices (I strongly suspect the availability of voices is subject to change in a relatively unpredictable way) can be forced to effectively Auto-Tune if the pitch and rate are set just right (dependant on the voice).

With that said, I can't offer you anything beyond the standard interface.

But I noticed several issues with your posted code example that should be addressed if you plan to experiment.

In particular, your code:

text.voice = speechSynthesis.getVoices[2];

will not select the third available voice. If you try changing the index value, you'll note that the voice doesn't change, because window.speechSynthesis.getVoices returns the function not the return of the function.

You could do:

```<code>text.voice = speechSynthesis.getVoices()[2];
</code>```

but it is a bit presumptuous.

SpeechSynthesis.getVoices()

... returns a list of SpeechSynthesisVoice objects representing all the available voices on the current device.

and (in Chrome and Edge†) SpeechSynthesis.onvoiceschanged

... will run when the list of SpeechSynthesisVoice objects that would be returned by the SpeechSynthesis.getVoices() method has changed (when the voiceschanged event fires.)

This may occur when speech synthesis is being done on the server-side and the voices list is being determined asynchronously, or when client-side voices are installed/uninstalled while a speech synthesis application is running.

and as such, the triggering of which could† be used to initiate compilation of the list of voices, which can then be accessed like:

```<code>var voices = SpeechSynthesis.getVoices();
utterance.voice = voices[ 2 ];
</code>```

† Note that Firefox doesn't support it at present, and will just return a list of voices when SpeechSynthesis.getVoices() is fired. With Chrome however, you have to wait for the event to fire before populating the list ...

"Welcome to the aperture science computer aided enrichment center"

Although the code below won't provide an Auto-Tuned GLaDOS voice magically, it will provide an easier way to experiment with the possibilities, and demonstrates how properly to access the available voices.

Inserted Update (Jan 6, 2019):

At the time of writing the code below, Google's default voice was female and the effect was, because of that, better than may now be heard. These APIs and their related resources and services are subject to change.

Also note that SpeechSynthesis.speak() in Chrome since v70 (other browsers may follow) will "immediately fire an error if the document has not received user activation".

End update.

if ( window.hasOwnProperty( "speechSynthesis" ) ) {
  var opt, voices, utterance;
  const speechSynth = window.speechSynthesis,
        form = document.querySelector( "form" ),
        playSample = () => {
          if ( speechSynth.speaking ) {
            speechSynth.cancel();
            // doesn't work as expected with default voice on Chrome on Windows
          }
          utterance = new SpeechSynthesisUtterance( form.sample.value );
          utterance.voice = voices[ form.voice.selectedIndex ];
          utterance.volume = form.volume.valueAsNumber * 0.01;
          utterance.pitch = form.pitch.valueAsNumber * 0.01;
          utterance.rate = form.rate.valueAsNumber * 0.01;
          speechSynth.speak( utterance );
        },
        init = () => {
          if ( !voices ) { // fixes triple trigger weirdness
            voices = speechSynth.getVoices();
            voices.forEach( ( v ) => {
              opt = document.createElement( "option" );
              opt.textContent = v.name;
              if ( v.name === "Google US English" ) {
                opt.selected = true;
                form.rate.value = 65;
              }
              form.voice.appendChild( opt );
            } );
            form.addEventListener( "input", playSample, false );
            form.play.addEventListener( "click", playSample, false );
            playSample();
          }
        };
  if ( speechSynth.onvoiceschanged !== undefined ) {
    // Only Chrome and Edge at time of posting
    speechSynth.onvoiceschanged = init;
  } else {
    init();
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  height: 50vh;
  float: left;
  margin-right: 1rem;
}
label {
  display: block;
}
input {
  vertical-align: middle;
}
[name=sample] {
  width: 90vw;
  margin-bottom: 1rem;
}
[name=play] {
  margin-top: 1rem;
}</code>```

<form>
  <input name="sample" type="text" value="Hello. And again, welcome to the aperture science computer aided enrichment center. We hope your brief detention in the relaxation vault has been a pleasant one.">

<select name="voice"></select>

  Volume: <input name="volume" type="range" min="0" max="100" value="50">
  Pitch: <input name="pitch" type="range" min="0" max="200" value="100">
  Rate: <input name="rate" type="range" min="1" max="1000" value="100">
  <input name="play" type="button" value="Play it again Sam">
</form>```

P.S. Although functioning perfectly whilst creating/editing the snippet, I have noticed since publishing that the results are glitchy.

I suspect this is a browser issue (experimental technology) as no errors are logged, and no code has changed.

On further examination, I noticed that the acceptable ranges for rate and pitch differ for different voices.

e.g. "Google US English" won't play at a higher rate than 2, whereas "Microsoft Anna - English (United States)" will play at the full rate of 10.

Both Google developer docs and MDN agree that rate's range should be from 0.1 to 10, but MDN states:

A float representing the rate value. It can range between 0.1 (lowest) and 10 (highest), with 1 being the default pitch for the current platform or voice, which should correspond to a normal speaking rate. ...

and then goes on to state:

Some speech synthesis engines or voices may constrain the minimum and maximum rates further. ...

There seem to be many little niggles with this fairly new API that, until it is fully standard, will require case by case targeted solutions.

Body:
Using the built in W3 SpeechSynthesis API, is it possible to create a modulated voice like that of GLaDOS with JavaScript?

The code that I currently have (below) split()s the phrase to be synthesized into individual words, each to be uttered at a randomly determined pitch, in an attempt to create the desired effect.

There's too long a rest between the words uttered and the modulation is not satisfactory.

if ('speechSynthesis' in window) {
    var speechSynthesis = window.speechSynthesis;
    speechSynthesis.onvoiceschanged = function () {
        console.log(speechSynthesis)
        var phrase = "Hello, I am GLaDOS";
        var parts = phrase.split(" ");
        for(var i in parts){
            var word = parts[i];
            var text = new SpeechSynthesisUtterance(word);
            text.voice = speechSynthesis.getVoices[2]; //English Female Voice
            text.rate=1.2;
            text.pitch = Math.random()*.5+1.50;
            speechSynthesis.speak(text);
        }
    }
}

Note: GLaDOS is "a fictional artificially intelligent computer system from the video game series Portal."

Body:
Auto-Tune

This answer is mostly opinion, offered in good faith in an attempt to be helpful.

Unfortunately, I believe, the effect on GLaDOS's voice would have to be achieved in what Hollywood would call "Post-Production" i.e. it would have to be an after effect; the voice would need to be processed after it is uttered.

Adjusting the pitch and/or rate will always only affect the output of the entire utterance, the result of which appears to be set in stone once SpeechSynthesis.speak() is called.

Your idea to split the utterance into words, and have each word output with randomized pitches and rates is clever, and that may be as close as we can get without Post-Processing.

By the way: I have no idea if we can apply Post-Processing to the utterances, and suspect that if it is at all possible, it would require some form of browser extension/plugin.

However, several of the voices (I strongly suspect the availability of voices is subject to change in a relatively unpredictable way) can be forced to effectively Auto-Tune if the pitch and rate are set just right (dependant on the voice).

With that said, I can't offer you anything beyond the standard interface.

But I noticed several issues with your posted code example that should be addressed if you plan to experiment.

In particular, your code:

text.voice = speechSynthesis.getVoices[2];

will not select the third available voice. If you try changing the index value, you'll note that the voice doesn't change, because window.speechSynthesis.getVoices returns the function not the return of the function.

You could do:

text.voice = speechSynthesis.getVoices()[2];

but it is a bit presumptuous.

SpeechSynthesis.getVoices()

... returns a list of SpeechSynthesisVoice objects representing all the available voices on the current device.

and (in Chrome and Edge†) SpeechSynthesis.onvoiceschanged

... will run when the list of SpeechSynthesisVoice objects that would be returned by the SpeechSynthesis.getVoices() method has changed (when the voiceschanged event fires.)

This may occur when speech synthesis is being done on the server-side and the voices list is being determined asynchronously, or when client-side voices are installed/uninstalled while a speech synthesis application is running.

and as such, the triggering of which could† be used to initiate compilation of the list of voices, which can then be accessed like:

var voices = SpeechSynthesis.getVoices();
utterance.voice = voices[ 2 ];

† Note that Firefox doesn't support it at present, and will just return a list of voices when SpeechSynthesis.getVoices() is fired. With Chrome however, you have to wait for the event to fire before populating the list ...

"Welcome to the aperture science computer aided enrichment center"

Although the code below won't provide an Auto-Tuned GLaDOS voice magically, it will provide an easier way to experiment with the possibilities, and demonstrates how properly to access the available voices.

Inserted Update (Jan 6, 2019):

At the time of writing the code below, Google's default voice was female and the effect was, because of that, better than may now be heard. These APIs and their related resources and services are subject to change.

Also note that SpeechSynthesis.speak() in Chrome since v70 (other browsers may follow) will "immediately fire an error if the document has not received user activation".

End update.

if ( window.hasOwnProperty( "speechSynthesis" ) ) {
  var opt, voices, utterance;
  const speechSynth = window.speechSynthesis,
        form = document.querySelector( "form" ),
        playSample = () => {
          if ( speechSynth.speaking ) {
            speechSynth.cancel();
            // doesn't work as expected with default voice on Chrome on Windows
          }
          utterance = new SpeechSynthesisUtterance( form.sample.value );
          utterance.voice = voices[ form.voice.selectedIndex ];
          utterance.volume = form.volume.valueAsNumber * 0.01;
          utterance.pitch = form.pitch.valueAsNumber * 0.01;
          utterance.rate = form.rate.valueAsNumber * 0.01;
          speechSynth.speak( utterance );
        },
        init = () => {
          if ( !voices ) { // fixes triple trigger weirdness
            voices = speechSynth.getVoices();
            voices.forEach( ( v ) => {
              opt = document.createElement( "option" );
              opt.textContent = v.name;
              if ( v.name === "Google US English" ) {
                opt.selected = true;
                form.rate.value = 65;
              }
              form.voice.appendChild( opt );
            } );
            form.addEventListener( "input", playSample, false );
            form.play.addEventListener( "click", playSample, false );
            playSample();
          }
        };
  if ( speechSynth.onvoiceschanged !== undefined ) {
    // Only Chrome and Edge at time of posting
    speechSynth.onvoiceschanged = init;
  } else {
    init();
  }
}

div {
  height: 50vh;
  float: left;
  margin-right: 1rem;
}
label {
  display: block;
}
input {
  vertical-align: middle;
}
[name=sample] {
  width: 90vw;
  margin-bottom: 1rem;
}
[name=play] {
  margin-top: 1rem;
}

<form>
  <input name="sample" type="text" value="Hello. And again, welcome to the aperture science computer aided enrichment center. We hope your brief detention in the relaxation vault has been a pleasant one.">
  <div><select name="voice"></select></div>
  <label>Volume: <input name="volume" type="range" min="0" max="100" value="50"></label>
  <label>Pitch: <input name="pitch" type="range" min="0" max="200" value="100"></label>
  <label>Rate: <input name="rate" type="range" min="1" max="1000" value="100"></label>
  <input name="play" type="button" value="Play it again Sam">
</form>

P.S. Although functioning perfectly whilst creating/editing the snippet, I have noticed since publishing that the results are glitchy.

I suspect this is a browser issue (experimental technology) as no errors are logged, and no code has changed.

On further examination, I noticed that the acceptable ranges for rate and pitch differ for different voices.

e.g. "Google US English" won't play at a higher rate than 2, whereas "Microsoft Anna - English (United States)" will play at the full rate of 10.

Both Google developer docs and MDN agree that rate's range should be from 0.1 to 10, but MDN states:

A float representing the rate value. It can range between 0.1 (lowest) and 10 (highest), with 1 being the default pitch for the current platform or voice, which should correspond to a normal speaking rate. ...

and then goes on to state:

Some speech synthesis engines or voices may constrain the minimum and maximum rates further. ...

There seem to be many little niggles with this fairly new API that, until it is fully standard, will require case by case targeted solutions.


问:
React.Children.only expected to receive a single React element child in React Router v4
I installed react-router-dom 4.1.1 and keep receiving the following error when trying to render my components:

Uncaught Error: React.Children.only expected to receive a single React element child.

Here's my app.js file:

```<code>import React from 'react';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import Nav from './components/Nav/nav';
import Search from './components/Search/search';
import Favorites from './components/Favorites/favorites';

const App = () => (
 <Router>
    <div className="app">
      <Nav />
      <Route exact path="/" component={Search}/>
      <Route path="/favorites" component={Favorites}/>
    </div>
  </Router>
);

export default App;
</code>```

And here is nav.jsx:

```<code>import React from 'react';
import {BrowserRouter as NavLink} from 'react-router-dom';

const Nav = () => (
    <ul className="nav">
        <li><NavLink exact to="/" activeClassname="active">Search</NavLink></li>
        <li><NavLink to="/favorites" activeClassname="active">Favorites</NavLink></li>
    </ul>
);

export default Nav;
</code>```

When I remove  from app.js it renders, but I don't see what's wrong with the nav.jsx file.

答:
You're, for some odd reason, aliasing BrowserRouter as NavLink instead of just importing NavLink:

```<code>import { BrowserRouter as NavLink } from 'react-router-dom';
</code>```

Get rid of that and import directly as a name:

```<code>import { NavLink } from 'react-router-dom';
</code>```

Because BrowserRouter expects one React element child, not text, the error is thrown.

Body:
I installed react-router-dom 4.1.1 and keep receiving the following error when trying to render my components:

Uncaught Error: React.Children.only expected to receive a single React element child.

Here's my app.js file:

import React from 'react';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import Nav from './components/Nav/nav';
import Search from './components/Search/search';
import Favorites from './components/Favorites/favorites';

const App = () => (
 <Router>

      <Route exact path="/" component={Search}/>
      <Route path="/favorites" component={Favorites}/>

  </Router>
);

export default App;

And here is nav.jsx:

import React from 'react';
import {BrowserRouter as NavLink} from 'react-router-dom';

const Nav = () => (

<NavLink exact to="/" activeClassname="active">Search</NavLink>

<NavLink to="/favorites" activeClassname="active">Favorites</NavLink>

);

export default Nav;

When I remove  from app.js it renders, but I don't see what's wrong with the nav.jsx file.

Body:
You're, for some odd reason, aliasing BrowserRouter as NavLink instead of just importing NavLink:

import { BrowserRouter as NavLink } from 'react-router-dom';

Get rid of that and import directly as a name:

import { NavLink } from 'react-router-dom';

Because BrowserRouter expects one React element child, not text, the error is thrown.


问:
How to get a word from an EditText?
I want the user to input a String word by phrase,

"animal" is a null String and I want to get it when the user enters the words after it or before it, I want to get that single word at its current position.

i.e.:

when I enter in my EditText "cat is an animal" the word "cat" will be saved in the list of animals, or "dog is an animal" and the word "dog" is saved, then the TextView says 'change to "ok"'.

```<code>public class MainActivity extends AppCompatActivity {

ArrayList<String> animal_names = new ArrayList<>();
String animal = null;
TextView say;
EditText enter;

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

    say = (TextView) findViewById(R.id.textView);
    enter = (EditText) findViewById(R.id.editText);

    try {
        InputStream input = getAssets().open("animals names.txt");
        InputStreamReader rd = new InputStreamReader(input);
        BufferedReader br = new BufferedReader(rd);
        String line;
        while ((line = br.readLine()) != null) {
            animal_names.add(line);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

}

public void click(View view) {
    String s = enter.getText().toString().trim();
    if (s.equals(animal+" is an animal")){
        say.setText("ok");
        animal_names.add(animal);
    }else if (s.equals("is " + animal + "an animal" )){
        if (animal_names.contains(animal)){
            say.setText("yes");
        }else {
            say.setText("no");
        }
    }
}
</code>```

答:
Unable to understand when you want to perform that action. Anyway what did i understand from your question is you need to add TextWatcher() listner to your EditText and compare your String inside its afterTextChanged() methods. Its look like:

```<code>enter.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                 String s1 = s.toString().trim();
                 if (s1.equals(animal+" is an animal")){
                   say.setText("ok");
                   animal_names.add(animal);
                 }else if (s1.equals("is " + animal + "an animal" )){
                   if (animal_names.contains(animal)){
                      say.setText("yes");
                   }else {
                      say.setText("no");
                   }
                 }
            }
        });
</code>```

----------Updated-----------------

try this inside afterTextChanged() or click of any other Button, add other conditions too if you require.

```<code>if (s.endsWith("is an animal")) {// for "XXX is an animal" condition
            animal_names.add(s.substring(0, s.indexOf("is")).trim());
            say.setText("yes");
    }else if (s.contains("is")&&s.endsWith("an animal")) {// For "is XXX an animal" condition
       say.setText("yes");
       animal_names.add(s.substring(s.lastIndexOf("is")+2, s.indexOf("an animal")).trim());
    }else{
       say.setText("no");
    }
</code>```

Hope it help!!! or update your question if you requirement is something else.

Title: How to get a word from an EditText?

Body:
I want the user to input a String word by phrase,

"animal" is a null String and I want to get it when the user enters the words after it or before it, I want to get that single word at its current position.

i.e.:

when I enter in my EditText "cat is an animal" the word "cat" will be saved in the list of animals, or "dog is an animal" and the word "dog" is saved, then the TextView says 'change to "ok"'.

public class MainActivity extends AppCompatActivity {

ArrayList<String> animal_names = new ArrayList<>();
String animal = null;
TextView say;
EditText enter;

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

    say = (TextView) findViewById(R.id.textView);
    enter = (EditText) findViewById(R.id.editText);

    try {
        InputStream input = getAssets().open("animals names.txt");
        InputStreamReader rd = new InputStreamReader(input);
        BufferedReader br = new BufferedReader(rd);
        String line;
        while ((line = br.readLine()) != null) {
            animal_names.add(line);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

}

public void click(View view) {
    String s = enter.getText().toString().trim();
    if (s.equals(animal+" is an animal")){
        say.setText("ok");
        animal_names.add(animal);
    }else if (s.equals("is " + animal + "an animal" )){
        if (animal_names.contains(animal)){
            say.setText("yes");
        }else {
            say.setText("no");
        }
    }
}

Body:
Unable to understand when you want to perform that action. Anyway what did i understand from your question is you need to add TextWatcher() listner to your EditText and compare your String inside its afterTextChanged() methods. Its look like:

enter.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                 String s1 = s.toString().trim();
                 if (s1.equals(animal+" is an animal")){
                   say.setText("ok");
                   animal_names.add(animal);
                 }else if (s1.equals("is " + animal + "an animal" )){
                   if (animal_names.contains(animal)){
                      say.setText("yes");
                   }else {
                      say.setText("no");
                   }
                 }
            }
        });

----------Updated-----------------

try this inside afterTextChanged() or click of any other Button, add other conditions too if you require.

if (s.endsWith("is an animal")) {// for "XXX is an animal" condition
            animal_names.add(s.substring(0, s.indexOf("is")).trim());
            say.setText("yes");
    }else if (s.contains("is")&&s.endsWith("an animal")) {// For "is XXX an animal" condition
       say.setText("yes");
       animal_names.add(s.substring(s.lastIndexOf("is")+2, s.indexOf("an animal")).trim());
    }else{
       say.setText("no");
    }

Hope it help!!! or update your question if you requirement is something else.


问:
get an array of "val" attributes values from the rows of a table
```<code><table id ='t1'>
<tr val='1'></tr>
<tr val='2'></tr>
<tr val='3'></tr>
<tr val='4'></tr>
<table>
</code>```

how to get from this an array = 1,2,3,4

答:
This should work:</p>

```<code>$.map( $( "table#t1 tr"), function( item) { return $(item).attr("val");})
</code>```

Body: how to get from this an array = 1,2,3,4

Body:
This should work:

$.map( $( "table#t1 tr"), function( item) { return $(item).attr("val");})


问:
Execute a block only when a code has not been executed in 3 seconds
I want to implement a promise in my code to run  angular.bootstrap() in block 2 if 3 seconds has passed and angular.bootstrap() in block 1 has not been done, but only if.

I have two blocks of code:

```<code>// block 1:
Office.initialize = function (reason) {
    $(document).ready(function () {
        angular.bootstrap(document, ['myApp'])
    })
}

// block 2:
$(document).ready(function () {
    angular.bootstrap(document, ['myApp'])
})
</code>```

Does anyone know how to do this?

Edit 1: Just to clarify that it is possible that Office.initialize is never executed (ie, when the app is loaded in Office as an add-in). In this case, I still want to execute angular.bootstrap of block 2 in 3 seconds.

答:
You can use the setTimeout() and clearTimeout() functions in JavaScript.

Function usage:

setTimeout :

```<code>setTimeout(function, time);`
//function is the function to execute
//time is the duration to wait (in milisecods) before executing the function
</code>```

clearTimeout :

```<code>clearTimeout(id);`
//id is the id of the setTimeout block to stop from executing
</code>```

This is how you would implement the functions into your code:

```<code>// block 1:
var wait = setTimeout(myFunction, 3000);
Office.initialize = function (reason) {
  $(document).ready(function () {
      angular.element(document).ready(function () {
          angular.bootstrap(document, ['myApp'])
          clearTimeout(wait);
      })
  })
}

// block 2:
function myFunction() {
  angular.element(document).ready(function () {
      angular.bootstrap(document, ['myApp'])
}
</code>```

Body:
I want to implement a promise in my code to run  angular.bootstrap() in block 2 if 3 seconds has passed and angular.bootstrap() in block 1 has not been done, but only if.

I have two blocks of code:

// block 1:
Office.initialize = function (reason) {
    $(document).ready(function () {
        angular.bootstrap(document, ['myApp'])
    })
}

// block 2:
$(document).ready(function () {
    angular.bootstrap(document, ['myApp'])
})

Does anyone know how to do this?

Edit 1: Just to clarify that it is possible that Office.initialize is never executed (ie, when the app is loaded in Office as an add-in). In this case, I still want to execute angular.bootstrap of block 2 in 3 seconds.

Body:
You can use the setTimeout() and clearTimeout() functions in JavaScript.

Function usage:

setTimeout :

setTimeout(function, time);`
//function is the function to execute
//time is the duration to wait (in milisecods) before executing the function

clearTimeout :

clearTimeout(id);`
//id is the id of the setTimeout block to stop from executing

This is how you would implement the functions into your code:

// block 1:
var wait = setTimeout(myFunction, 3000);
Office.initialize = function (reason) {
  $(document).ready(function () {
      angular.element(document).ready(function () {
          angular.bootstrap(document, ['myApp'])
          clearTimeout(wait);
      })
  })
}

// block 2:
function myFunction() {
  angular.element(document).ready(function () {
      angular.bootstrap(document, ['myApp'])
}


答:
You are using a slim version of jQuery that doesn't include numerous features including animations.

Change .slim to .min in https://code.jquery.com/jquery-3.2.1.slim.js if you want full feature set

```<code><script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</code>```

There is also a  typo in

```<code>$('.lead').hide().fadeIn('slow');
       //^^ missing dot
</code>```

Body:
$(document).ready(function () {
   $('.lead')hide().fadeIn('slow');

});

.lead {
        font-size: 10rem;
        font-weight: bold;
        color: #3fddff;
        text-shadow: 5px 5px 5px #000;

        position: fixed;
        bottom: 0;
        right: 0;
        margin-right: 5rem;
        margin-bottom: 6rem;
        border-bottom: 3px solid #fff;
    }

    .webdev {
        font-size: 3rem;
        font-weight: bold;
        color: #000;
        text-shadow: 3px 3px 3px #aaa;

        position: fixed;
        bottom: 0;
        right: 0;
        margin-right: 25rem;
        margin-bottom: 2rem;
    }

    .lead {
    display: none;
}

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Title Page</title>

    <link type="text/css" rel="stylesheet" href="normalize/normalize.css"/>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

    <link href="styles.css" rel="stylesheet" type="text/css">

    <link href="https://fonts.googleapis.com/css?family=Titillium+Web:400,900" rel="stylesheet">

            portfolio

            about

            contact

            YouTube Channel (comming soon!)

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggleExternalContent" aria-controls="navbarToggleExternalContent" aria-expanded="false" aria-label="Toggle navigation">

        </button>

My Name

Web Developer

Hello,

I'm having trouble getting my fadeIn() to work on my page. I am trying to have my name fade-in once my page is loaded but for some reason that does not happen. I know the file is linked properly because I tested it out with a console.log but the fadeIn() does not work at all. I'm pretty new to jQuery but I thought this was one of the more easier functions to do. Am I overlooking something?

Thank you for your help.

Best,
Edwin

Body:
You are using a slim version of jQuery that doesn't include numerous features including animations.

Change .slim to .min in https://code.jquery.com/jquery-3.2.1.slim.js if you want full feature set

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

There is also a  typo in

$('.lead').hide().fadeIn('slow');
       //^^ missing dot


问:
What is the difference here?
I am learning python and here is a small code that instructions want me to write.

First, def a function called cube that takes an argument called
  number. Don't forget the parentheses and the colon! Make that function
  return the cube of that number (i.e. that number multiplied by itself
  and multiplied by itself once again). Define a second function called
  by_three that takes an argument called number.

if that number is divisible by 3, by_three should call cube(number) and return its result. Otherwise, by_three should return False.

What I did first was;

```<code>def cube(number):
    return number ** 3

def by_three(number):
    if number % 3 == 0:
        cube(number)
        return number
    else:
        return False
</code>```

but apparently in this, by_three(number) returns number itself. so to my understandings, the cube(Number) and return number doesnt work by line order?

this works:

```<code>def cube(number):
    return number ** 3

def by_three(number):
    if number % 3 == 0:
        return cube(number)
    else:
        return False
</code>```

I know why this works, but I dont get why the other one doesnt.

答:
Because you didn't assign the return of the cube() function to a variable. So cube(number) returns a number, then gets forgotten and you just return number which was originally passed into by_three(). If in your first one you did number = cube(number) it would reassign the cubed number to the number variable and it would work.

EDIT for additional info

A simple way to think about it is when passing immutable data types such as integers, floats or strings, after a function evaluates and returns data, that data essentially replaces your function call. So you can imagine:

```<code>def cube(number):
    return number ** 3

def by_three(number):
    if number % 3 == 0:
        9
        return number
    else:
        return False
</code>```

This helps illustrate why nothing happens since 9 just on it's own has no relationship to the VARIABLE number. Granted this isn't valid python code, but you can just imagine the process of what's happening behind the scenes here. So as I stated by reassigning the number, it would be doing this behind the scenes and reassigning number with the cube() returned value of 9:

```<code>def cube(number):
    return number ** 3

def by_three(number):
    if number % 3 == 0:
        number = 9
        return number
    else:
        return False
</code>```

Title: What is the difference here?

Body:
I am learning python and here is a small code that instructions want me to write.

First, def a function called cube that takes an argument called
  number. Don't forget the parentheses and the colon! Make that function
  return the cube of that number (i.e. that number multiplied by itself
  and multiplied by itself once again). Define a second function called
  by_three that takes an argument called number.

if that number is divisible by 3, by_three should call cube(number) and return its result. Otherwise, by_three should return False.

What I did first was;

def cube(number):
    return number ** 3

def by_three(number):
    if number % 3 == 0:
        cube(number)
        return number
    else:
        return False

but apparently in this, by_three(number) returns number itself. so to my understandings, the cube(Number) and return number doesnt work by line order?

this works:

def cube(number):
    return number ** 3

def by_three(number):
    if number % 3 == 0:
        return cube(number)
    else:
        return False

I know why this works, but I dont get why the other one doesnt.

Body:
Because you didn't assign the return of the cube() function to a variable. So cube(number) returns a number, then gets forgotten and you just return number which was originally passed into by_three(). If in your first one you did number = cube(number) it would reassign the cubed number to the number variable and it would work.

EDIT for additional info

A simple way to think about it is when passing immutable data types such as integers, floats or strings, after a function evaluates and returns data, that data essentially replaces your function call. So you can imagine:

def cube(number):
    return number ** 3

def by_three(number):
    if number % 3 == 0:
        9
        return number
    else:
        return False

This helps illustrate why nothing happens since 9 just on it's own has no relationship to the VARIABLE number. Granted this isn't valid python code, but you can just imagine the process of what's happening behind the scenes here. So as I stated by reassigning the number, it would be doing this behind the scenes and reassigning number with the cube() returned value of 9:

def cube(number):
    return number ** 3

def by_three(number):
    if number % 3 == 0:
        number = 9
        return number
    else:
        return False


问:
How to map a different field name in django to mongo field
I ran into this problem where my mongo database has a field "type" that is a reserved word in Python. How do I go about setting it in Django so that Django knows I'm referring to the field Type in mongo, but without running into an error?
Thanks a lot!</p>

```<code># mongo object
payment: {
    user = ObjectId("..."),
    date: ISODate("2013-05-05T23:21:22.802Z"),
    type: "downgrade"
    }

# django
class Payment(models.Model):
    user = models.ForeignKey(..)
    date = models.DateTimeField(default=datetime.datetime.now, null=False)
    type = models.CharField(blank=False, max_length=30) # <== cannot use type
</code>```

答:
If you are using Mongo Engine, db_column won't work for you.

You should specify it using db_field as specified in http://docs.mongoengine.org/guide/defining-documents.html#field-arguments

Your sample would end as:

```<code>class Payment(models.Model):
    user = models.ForeignKey(..)
    date = models.DateTimeField(default=datetime.datetime.now, null=False)
    pay_type = models.CharField(blank=False, max_length=30, db_field ="type")
</code>```

Body:
I ran into this problem where my mongo database has a field "type" that is a reserved word in Python. How do I go about setting it in Django so that Django knows I'm referring to the field Type in mongo, but without running into an error?
Thanks a lot!

# mongo object
payment: {
    user = ObjectId("..."),
    date: ISODate("2013-05-05T23:21:22.802Z"),
    type: "downgrade"
    }

# django
class Payment(models.Model):
    user = models.ForeignKey(..)
    date = models.DateTimeField(default=datetime.datetime.now, null=False)
    type = models.CharField(blank=False, max_length=30) # <== cannot use type

Body:
If you are using Mongo Engine, db_column won't work for you.

You should specify it using db_field as specified in http://docs.mongoengine.org/guide/defining-documents.html#field-arguments

Your sample would end as:

class Payment(models.Model):
    user = models.ForeignKey(..)
    date = models.DateTimeField(default=datetime.datetime.now, null=False)
    pay_type = models.CharField(blank=False, max_length=30, db_field ="type")