问:
Using sunrise/sunset REST API in Android. How to correctly pass the URL with obtained location coordinates?
I am making an Android application which gets the coordinates of the user's location and then uses those coordinates to talk to a REST API provided by -
this website

I am fairly new with JSON parsing and REST API. I have used AsyncTask, Spring and Jackson for it by following this tutorial

My MainActivity.java looks like this -

```<code>package com.gamecodeschool.whereintheworld;

import android.content.Context;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.location.Criteria;
import android.location.Location;

import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import android.os.AsyncTask;

public class MainActivity extends AppCompatActivity implements LocationListener {

    private TextView txtLat;
    private TextView txtLong;
    private TextView txtSource;
    private LocationManager locationManager;
    private String provider;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        new HttpRequestTask().execute();
        setContentView(R.layout.activity_main);
        txtLat = (TextView) findViewById(R.id.txtLat);
        txtLong = (TextView) findViewById(R.id.txtLong);
        txtSource = (TextView) findViewById(R.id.txtSource);

        //Initialize locationManager
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);

        //initialize the location
        if(location != null){
            txtSource.setText("Source = " +provider);
            onLocationChanged(location);
        }

    }
    //start updates when app starts/resumes
    @Override
    protected void onResume() {
        super.onResume();
        new HttpRequestTask().execute();
        locationManager.requestLocationUpdates
                (provider, 500, 1, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }

    @Override
    public void onLocationChanged(Location location) {
        double lat = location.getLatitude();
        double lng = location.getLongitude();
        txtLat.setText(String.valueOf(lat));
        txtLong.setText(String.valueOf(lng));
        txtSource.setText("Source = " + provider);
    }

    public String getCoordinates(Location location)
    {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();

        return ("lat="+latitude+"&lng="+longitude);

    }

    @Override
    public void onStatusChanged(String provider,
                                int status, Bundle extras) {
        txtSource.setText("Source = " + provider);
    }
    @Override
    public void onProviderEnabled(String provider) {

        txtSource.setText("Source = " + provider);
    }
    @Override
    public void onProviderDisabled(String provider) {

        txtSource.setText("Source = " + provider);
    }

    //USER DEFINED CLASS
    private class HttpRequestTask extends AsyncTask<Void, Void, sunrisedata> {

        @Override
        protected sunrisedata doInBackground(Void... params) {
            try {

                final String url = "http://api.sunrise-sunset.org/json?";
                RestTemplate restTemplate = new RestTemplate();
                restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
                sunrisedata greeting = restTemplate.getForObject(url, sunrisedata.class);
                return greeting;
            } catch (Exception e) {
                Log.e("MainActivity", e.getMessage(), e);
            }

            return null;
        }

        @Override
        protected void onPostExecute(sunrisedata greeting) {
            TextView greetingIdText = (TextView) findViewById(R.id.txtSunrise);

            greetingIdText.setText(greeting.getSunrise());

        }

    }

}
</code>```

Here in this part of MainActivity.java

```<code>final String url = "http://api.sunrise-sunset.org/json?";
</code>```

I want to pass the coordinates obtained from this part of the code -

```<code>public void onLocationChanged(Location location) {
        double lat = location.getLatitude();
        double lng = location.getLongitude();
        txtLat.setText(String.valueOf(lat));
        txtLong.setText(String.valueOf(lng));
        txtSource.setText("Source = " + provider);
    }
</code>```

Because according to the REST API docs the GET request URL should be in this format -

```<code>http://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400
</code>```

What is the way in which I can retrieve the latitude and longitude and append it to the URL in the HttpRequestTask class's method -

```<code>protected sunrisedata doInBackground(Void... params)
</code>```

As of now the logcat error looks like this -

```<code>04-03 01:56:35.231 13842-1925/com.gamecodeschool.whereintheworld E/MainActivity: Could not read JSON: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
                                                                                at [Source: buffer(com.android.okio.GzipSource@1713350c).inputStream(); line: 1, column: 11]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
                                                                                at [Source: buffer(com.android.okio.GzipSource@1713350c).inputStream(); line: 1, column: 11]
                                                                                org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
                                                                                at [Source: buffer(com.android.okio.GzipSource@1713350c).inputStream(); line: 1, column: 11]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
                                                                                at [Source: buffer(com.android.okio.GzipSource@1713350c).inputStream(); line: 1, column: 11]
                                                                                at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readInternal(MappingJackson2HttpMessageConverter.java:126)
                                                                                at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:147)
                                                                                at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:76)
                                                                                at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:484)
                                                                                at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:439)
                                                                                at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:237)
                                                                                at com.gamecodeschool.whereintheworld.MainActivity$HttpRequestTask.doInBackground(MainActivity.java:111)
                                                                                at com.gamecodeschool.whereintheworld.MainActivity$HttpRequestTask.doInBackground(MainActivity.java:99)
                                                                                at android.os.AsyncTask$2.call(AsyncTask.java:292)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                                at java.lang.Thread.run(Thread.java:818)
                                                                                Caused by: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
                                                                                at [Source: buffer(com.android.okio.GzipSource@1713350c).inputStream(); line: 1, column: 11]
                                                                                at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1524)
                                                                                at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:557)
                                                                                at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._reportInvalidToken(UTF8StreamJsonParser.java:3094)
                                                                                at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._handleUnexpectedValue(UTF8StreamJsonParser.java:2339)
                                                                                at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._nextTokenNotInObject(UTF8StreamJsonParser.java:817)
                                                                                at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.nextToken(UTF8StreamJsonParser.java:697)
                                                                                at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3031)
                                                                                at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2978)
                                                                                at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2158)
                                                                                at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readInternal(MappingJackson2HttpMessageConverter.java:123)
                                                                                ... 13 more
04-03 01:56:35.232 13842-13842/com.gamecodeschool.whereintheworld D/AndroidRuntime: Shutting down VM
04-03 01:56:35.233 13842-13842/com.gamecodeschool.whereintheworld E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.gamecodeschool.whereintheworld, PID: 13842
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.gamecodeschool.whereintheworld.sunrisedata.getSunrise()' on a null object reference
                                                                                at com.gamecodeschool.whereintheworld.MainActivity$HttpRequestTask.onPostExecute(MainActivity.java:124)
                                                                                at com.gamecodeschool.whereintheworld.MainActivity$HttpRequestTask.onPostExecute(MainActivity.java:99)
                                                                                at android.os.AsyncTask.finish(AsyncTask.java:636)
                                                                                at android.os.AsyncTask.access$500(AsyncTask.java:177)
                                                                                at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5294)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
04-03 01:56:36.027 13842-2035/com.gamecodeschool.whereintheworld E/MainActivity: Could not read JSON: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
                                                                                at [Source: buffer(com.android.okio.GzipSource@3969795b).inputStream(); line: 1, column: 11]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
                                                                                at [Source: buffer(com.android.okio.GzipSource@3969795b).inputStream(); line: 1, column: 11]
                                                                                org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
                                                                                at [Source: buffer(com.android.okio.GzipSource@3969795b).inputStream(); line: 1, column: 11]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
                                                                                at [Source: buffer(com.android.okio.GzipSource@3969795b).inputStream(); line: 1, column: 11]
                                                                                at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readInternal(MappingJackson2HttpMessageConverter.java:126)
                                                                                at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:147)
                                                                                at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:76)
                                                                                at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:484)
                                                                                at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:439)
                                                                                at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:237)
                                                                                at com.gamecodeschool.whereintheworld.MainActivity$HttpRequestTask.doInBackground(MainActivity.java:111)
                                                                                at com.gamecodeschool.whereintheworld.MainActivity$HttpRequestTask.doInBackground(MainActivity.java:99)
                                                                                at android.os.AsyncTask$2.call(AsyncTask.java:292)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                                at java.lang.Thread.run(Thread.java:818)
                                                                                Caused by: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
                                                                                at [Source: buffer(com.android.okio.GzipSource@3969795b).inputStream(); line: 1, column: 11]
                                                                                at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1524)
                                                                                at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:557)
                                                                                at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._reportInvalidToken(UTF8StreamJsonParser.java:3094)
                                                                                at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._handleUnexpectedValue(UTF8StreamJsonParser.java:2339)
                                                                                at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._nextTokenNotInObject(UTF8StreamJsonParser.java:817)
                                                                                at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.nextToken(UTF8StreamJsonParser.java:697)
                                                                                at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3031)
                                                                                at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2978)
                                                                                at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2158)
                                                                                at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readInternal(MappingJackson2HttpMessageConverter.java:123)
                                                                                ... 13 more
</code>```

As far as I figured out this error is coming because the correct URL along with the latitudes and longitudes is not being passed to the website. Obviously the application is also crashing when run on the phone.

Another class which I created by following the tutorial on spring's website is -  sunrisedata.java for storing the obtained JSON response looks like this -

```<code>package com.gamecodeschool.whereintheworld;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown=true)
public class sunrisedata {

    private String results;

    public String getSunrise(){

        return this.results;
    }

}
</code>```

Please tell me how to correctly pass the lat and long values obtained in MainActivity class to the url in HttpRequestTask class and I just want to retrieve the sunrise data from JSON and ignore all other fields.

答:
Getting the location of a user happens asynchronously which means you will have to wait until the location is returned to you from the LocationManager before you can make the request to get the sunrise/sunset data.

Right now, you are requesting the sunrise/subset data in onResume() which isn't correct. When you do the request here, it is possible that you won't have the location data yet.

It seems like you will want to fetch the sunrise/sunset data in onLocationChanged(). This method will have the location information you need to add to the url.

Body:
I am making an Android application which gets the coordinates of the user's location and then uses those coordinates to talk to a REST API provided by -
this website

I am fairly new with JSON parsing and REST API. I have used AsyncTask, Spring and Jackson for it by following this tutorial

My MainActivity.java looks like this -

package com.gamecodeschool.whereintheworld;

import android.content.Context;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.location.Criteria;
import android.location.Location;

import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import android.os.AsyncTask;

public class MainActivity extends AppCompatActivity implements LocationListener {

    private TextView txtLat;
    private TextView txtLong;
    private TextView txtSource;
    private LocationManager locationManager;
    private String provider;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        new HttpRequestTask().execute();
        setContentView(R.layout.activity_main);
        txtLat = (TextView) findViewById(R.id.txtLat);
        txtLong = (TextView) findViewById(R.id.txtLong);
        txtSource = (TextView) findViewById(R.id.txtSource);

        //Initialize locationManager
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);

        //initialize the location
        if(location != null){
            txtSource.setText("Source = " +provider);
            onLocationChanged(location);
        }

    }
    //start updates when app starts/resumes
    @Override
    protected void onResume() {
        super.onResume();
        new HttpRequestTask().execute();
        locationManager.requestLocationUpdates
                (provider, 500, 1, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }

    @Override
    public void onLocationChanged(Location location) {
        double lat = location.getLatitude();
        double lng = location.getLongitude();
        txtLat.setText(String.valueOf(lat));
        txtLong.setText(String.valueOf(lng));
        txtSource.setText("Source = " + provider);
    }

    public String getCoordinates(Location location)
    {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();

        return ("lat="+latitude+"&lng="+longitude);

    }

    @Override
    public void onStatusChanged(String provider,
                                int status, Bundle extras) {
        txtSource.setText("Source = " + provider);
    }
    @Override
    public void onProviderEnabled(String provider) {

        txtSource.setText("Source = " + provider);
    }
    @Override
    public void onProviderDisabled(String provider) {

        txtSource.setText("Source = " + provider);
    }

    //USER DEFINED CLASS
    private class HttpRequestTask extends AsyncTask<Void, Void, sunrisedata> {

        @Override
        protected sunrisedata doInBackground(Void... params) {
            try {

                final String url = "http://api.sunrise-sunset.org/json?";
                RestTemplate restTemplate = new RestTemplate();
                restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
                sunrisedata greeting = restTemplate.getForObject(url, sunrisedata.class);
                return greeting;
            } catch (Exception e) {
                Log.e("MainActivity", e.getMessage(), e);
            }

            return null;
        }

        @Override
        protected void onPostExecute(sunrisedata greeting) {
            TextView greetingIdText = (TextView) findViewById(R.id.txtSunrise);

            greetingIdText.setText(greeting.getSunrise());

        }

    }

}

Here in this part of MainActivity.java

final String url = "http://api.sunrise-sunset.org/json?";

I want to pass the coordinates obtained from this part of the code -

public void onLocationChanged(Location location) {
        double lat = location.getLatitude();
        double lng = location.getLongitude();
        txtLat.setText(String.valueOf(lat));
        txtLong.setText(String.valueOf(lng));
        txtSource.setText("Source = " + provider);
    }

Because according to the REST API docs the GET request URL should be in this format -

http://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400

What is the way in which I can retrieve the latitude and longitude and append it to the URL in the HttpRequestTask class's method -

protected sunrisedata doInBackground(Void... params)

As of now the logcat error looks like this -

04-03 01:56:35.231 13842-1925/com.gamecodeschool.whereintheworld E/MainActivity: Could not read JSON: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
                                                                                at [Source: buffer(com.android.okio.GzipSource@1713350c).inputStream(); line: 1, column: 11]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
                                                                                at [Source: buffer(com.android.okio.GzipSource@1713350c).inputStream(); line: 1, column: 11]
                                                                                org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
                                                                                at [Source: buffer(com.android.okio.GzipSource@1713350c).inputStream(); line: 1, column: 11]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
                                                                                at [Source: buffer(com.android.okio.GzipSource@1713350c).inputStream(); line: 1, column: 11]
                                                                                at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readInternal(MappingJackson2HttpMessageConverter.java:126)
                                                                                at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:147)
                                                                                at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:76)
                                                                                at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:484)
                                                                                at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:439)
                                                                                at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:237)
                                                                                at com.gamecodeschool.whereintheworld.MainActivity$HttpRequestTask.doInBackground(MainActivity.java:111)
                                                                                at com.gamecodeschool.whereintheworld.MainActivity$HttpRequestTask.doInBackground(MainActivity.java:99)
                                                                                at android.os.AsyncTask$2.call(AsyncTask.java:292)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                                at java.lang.Thread.run(Thread.java:818)
                                                                                Caused by: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
                                                                                at [Source: buffer(com.android.okio.GzipSource@1713350c).inputStream(); line: 1, column: 11]
                                                                                at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1524)
                                                                                at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:557)
                                                                                at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._reportInvalidToken(UTF8StreamJsonParser.java:3094)
                                                                                at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._handleUnexpectedValue(UTF8StreamJsonParser.java:2339)
                                                                                at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._nextTokenNotInObject(UTF8StreamJsonParser.java:817)
                                                                                at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.nextToken(UTF8StreamJsonParser.java:697)
                                                                                at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3031)
                                                                                at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2978)
                                                                                at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2158)
                                                                                at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readInternal(MappingJackson2HttpMessageConverter.java:123)
                                                                                ... 13 more
04-03 01:56:35.232 13842-13842/com.gamecodeschool.whereintheworld D/AndroidRuntime: Shutting down VM
04-03 01:56:35.233 13842-13842/com.gamecodeschool.whereintheworld E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.gamecodeschool.whereintheworld, PID: 13842
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.gamecodeschool.whereintheworld.sunrisedata.getSunrise()' on a null object reference
                                                                                at com.gamecodeschool.whereintheworld.MainActivity$HttpRequestTask.onPostExecute(MainActivity.java:124)
                                                                                at com.gamecodeschool.whereintheworld.MainActivity$HttpRequestTask.onPostExecute(MainActivity.java:99)
                                                                                at android.os.AsyncTask.finish(AsyncTask.java:636)
                                                                                at android.os.AsyncTask.access$500(AsyncTask.java:177)
                                                                                at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5294)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
04-03 01:56:36.027 13842-2035/com.gamecodeschool.whereintheworld E/MainActivity: Could not read JSON: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
                                                                                at [Source: buffer(com.android.okio.GzipSource@3969795b).inputStream(); line: 1, column: 11]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
                                                                                at [Source: buffer(com.android.okio.GzipSource@3969795b).inputStream(); line: 1, column: 11]
                                                                                org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
                                                                                at [Source: buffer(com.android.okio.GzipSource@3969795b).inputStream(); line: 1, column: 11]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
                                                                                at [Source: buffer(com.android.okio.GzipSource@3969795b).inputStream(); line: 1, column: 11]
                                                                                at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readInternal(MappingJackson2HttpMessageConverter.java:126)
                                                                                at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:147)
                                                                                at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:76)
                                                                                at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:484)
                                                                                at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:439)
                                                                                at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:237)
                                                                                at com.gamecodeschool.whereintheworld.MainActivity$HttpRequestTask.doInBackground(MainActivity.java:111)
                                                                                at com.gamecodeschool.whereintheworld.MainActivity$HttpRequestTask.doInBackground(MainActivity.java:99)
                                                                                at android.os.AsyncTask$2.call(AsyncTask.java:292)
                                                                                at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                                at java.lang.Thread.run(Thread.java:818)
                                                                                Caused by: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Array': was expecting ('true', 'false' or 'null')
                                                                                at [Source: buffer(com.android.okio.GzipSource@3969795b).inputStream(); line: 1, column: 11]
                                                                                at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1524)
                                                                                at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:557)
                                                                                at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._reportInvalidToken(UTF8StreamJsonParser.java:3094)
                                                                                at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._handleUnexpectedValue(UTF8StreamJsonParser.java:2339)
                                                                                at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._nextTokenNotInObject(UTF8StreamJsonParser.java:817)
                                                                                at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.nextToken(UTF8StreamJsonParser.java:697)
                                                                                at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:3031)
                                                                                at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2978)
                                                                                at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2158)
                                                                                at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readInternal(MappingJackson2HttpMessageConverter.java:123)
                                                                                ... 13 more

As far as I figured out this error is coming because the correct URL along with the latitudes and longitudes is not being passed to the website. Obviously the application is also crashing when run on the phone.

Another class which I created by following the tutorial on spring's website is -  sunrisedata.java for storing the obtained JSON response looks like this -

package com.gamecodeschool.whereintheworld;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown=true)
public class sunrisedata {

    private String results;

    public String getSunrise(){

        return this.results;
    }

}

Please tell me how to correctly pass the lat and long values obtained in MainActivity class to the url in HttpRequestTask class and I just want to retrieve the sunrise data from JSON and ignore all other fields.


来源: stackexchange

问:
rails formatting a json.jbuilder for jquery-ui autocomplete widget
I'm using autocomplete widget of jquery-ui. I found that it sends its parameters as term and it needs a json like this

[{"label": "Client1"},{"label": "Client2"} ]

Instead I am getting

```<code>[{"client":{"label":"Cliente"}}]
</code>```

clients_controller.rb

```<code>def index
  @client = Client.all
  @client = Client.paginate(:page => params[:page])
  if params[:term].present?
    @client = @client.where("client_name LIKE ? ", "%#{params[:term]}%")
  else
    @client = @client.paginate(page: params[:page])
  end

  respond_to do |format|
    format.html
    format.json
  end
end
</code>```

_client.json.jbuilder

```<code>json.client do
  json.label client.client_name
end
</code>```

How can I format a json as I needing it?

答: use json.(@client, :client_name) instead of looping.

ContentLicense: CC BY-SA 3.0

Body:
I'm using autocomplete widget of jquery-ui. I found that it sends its parameters as term and it needs a json like this

[{"label": "Client1"},{"label": "Client2"} ]

Instead I am getting

[{"client":{"label":"Cliente"}}]

clients_controller.rb

def index
  @client = Client.all
  @client = Client.paginate(:page => params[:page])
  if params[:term].present?
    @client = @client.where("client_name LIKE ? ", "%#{params[:term]}%")
  else
    @client = @client.paginate(page: params[:page])
  end

  respond_to do |format|
    format.html
    format.json
  end
end

_client.json.jbuilder

json.client do
  json.label client.client_name
end

How can I format a json as I needing it?


问:
How to stop more than one being removed from an integer?
I know the title may seem fairly confusing, was just unsure on how to ask this...
So, I'm working on a basic sample game (not going to be a complete game or anything), where you can move around and are chased by an enemy character that attacks you. The problem is that when the attack function is called, instead of only removing one heart/hitpoint, they continue to be 'spam removed'. Here's what I'm working with...

```<code>void Enemy::attackPlayer()
{
    if (distance < 50)
    {
        Player::health--;
        return;
    }
}
</code>```

Pretty simple, right? Well the problem is that I need some way of I guess 'sleeping' the single function so that instead of continuing to remove health, it stops after one, then after let's say, 3 seconds, allows another attack to occur.

答:
After taking some of the answers you guys gave me into consideration and messing around with some things by myself, I've came up with a pretty simple solution:

```<code>int Enemy::attackTime = 0;
</code>```

And then...

```<code>void Enemy::attackPlayer()
{
    if (distance > 60)
        return;

    if (time(0) > attackTime)
    {
        attackTime = time(0) + 3;
        Player::health--;
    }
}
</code>```

Body:
I know the title may seem fairly confusing, was just unsure on how to ask this...
So, I'm working on a basic sample game (not going to be a complete game or anything), where you can move around and are chased by an enemy character that attacks you. The problem is that when the attack function is called, instead of only removing one heart/hitpoint, they continue to be 'spam removed'. Here's what I'm working with...

void Enemy::attackPlayer()
{
    if (distance < 50)
    {
        Player::health--;
        return;
    }
}

Pretty simple, right? Well the problem is that I need some way of I guess 'sleeping' the single function so that instead of continuing to remove health, it stops after one, then after let's say, 3 seconds, allows another attack to occur.

Body:
After taking some of the answers you guys gave me into consideration and messing around with some things by myself, I've came up with a pretty simple solution:

int Enemy::attackTime = 0;

And then...

void Enemy::attackPlayer()
{
    if (distance > 60)
        return;

    if (time(0) > attackTime)
    {
        attackTime = time(0) + 3;
        Player::health--;
    }
}


问:
How do I make shelve file empty in python?
I have created a shelve file and inserted a dictionary data. Now I want to cleanup that shelve file to reuse as a clean file.</p>

```<code>import shelve
dict = shelve.open("Sample.db")
# insert some data into sample.db
dict = { "foo" : "bar"}

#Now I want to clean entire shelve file to re-insert the data from begining.
</code>```

答:
none of these really work What I ended up doing was creating a function to handle the file deletion.   </p>

```<code>import shelve
import pyperclip
import sys
import os

mcbShelf = shelve.open('mcb')
command = sys.argv[1].lower()

def remove_files():
    mcbShelf.close()
    os.remove('mcb.dat')
    os.remove('mcb.bak')
    os.remove('mcb.dir')

if command == 'save':
    mcbShelf[sys.argv[2]] = pyperclip.paste()
elif command == 'list':
    pyperclip.copy(", ".join(mcbShelf.keys()))
elif command == 'del':
    remove_files()
else:
    pyperclip.copy(mcbShelf[sys.argv[1]])

mcbShelf.close()
</code>```

Body:
I have created a shelve file and inserted a dictionary data. Now I want to cleanup that shelve file to reuse as a clean file.

import shelve
dict = shelve.open("Sample.db")
# insert some data into sample.db
dict = { "foo" : "bar"}

#Now I want to clean entire shelve file to re-insert the data from begining.

Body:
none of these really work What I ended up doing was creating a function to handle the file deletion.

import shelve
import pyperclip
import sys
import os

mcbShelf = shelve.open('mcb')
command = sys.argv[1].lower()

def remove_files():
    mcbShelf.close()
    os.remove('mcb.dat')
    os.remove('mcb.bak')
    os.remove('mcb.dir')

if command == 'save':
    mcbShelf[sys.argv[2]] = pyperclip.paste()
elif command == 'list':
    pyperclip.copy(", ".join(mcbShelf.keys()))
elif command == 'del':
    remove_files()
else:
    pyperclip.copy(mcbShelf[sys.argv[1]])

mcbShelf.close()


问:
C programming: Sorting Structures with two parameters
I'm Now trying to sort the Last names and Company names. The user has to enter either a last name or company name (only one). this is my code right now:

```<code>struct store {
unsigned long phone_num;
char *first_name;
char *last_name;
char *company_name;
char *email;
};
typedef struct store store;

void findContact(FILE *fp, long fileEnd)
{
/*variables*/
char fName [100];
char lName [100];
char cName [100];
char email [100];

int i, length;
int count = 1;
int size = sizeof(long);
int usize = sizeof(unsigned long);

unsigned long phone;

long nextPosition = 0;
long fNamePosition = 0;
long lNamePosition = 0;
long cNamePosition = 0;
long emailPosition = 0;

store *list;
list = malloc(sizeof(store));

/*Search for Contact position in file*/
fseek(fp, 0, SEEK_SET); /*Seeks to beginning of file*/
do {
    i = count - 1;

    fread(&phone, usize, 1, fp); /*reads phonenumber of contact*/
    fread(&fNamePosition, size , 1, fp);
    fread(&lNamePosition, size, 1, fp);
    fread(&cNamePosition, size, 1, fp);
    fread(&emailPosition, size, 1, fp);
    fread(&nextPosition, size, 1, fp);

    if(fNamePosition != 0) {

        fseek(fp,fNamePosition,SEEK_SET);
        if(lNamePosition == 0) {
          length = cNamePosition - fNamePosition;
        } else {
          length = lNamePosition - fNamePosition;
        }
        fread(fName,sizeof(char),length,fp);
    } else {
        strcpy(fName," ");
    }

    if(lNamePosition != 0) {
        fseek(fp,lNamePosition,SEEK_SET);
        if (cNamePosition == 0) {
          length = emailPosition - lNamePosition;
        } else {
          length = cNamePosition - lNamePosition;
        }
        fread(lName,sizeof(char), length,fp);
    } else {
        strcpy(lName," ");
    }

    if(cNamePosition != 0) {
        fseek(fp,cNamePosition,SEEK_SET);
        length = emailPosition-cNamePosition;
        fread(cName,sizeof(char), length,fp);
    } else {
        strcpy(cName," ");
    }

    fseek(fp,emailPosition,SEEK_SET);
    length = nextPosition - emailPosition;
    fread(email,sizeof(char),length,fp);

    list = realloc(list, count * sizeof(store));

    list[i].phone_num = phone;
    list[i].first_name = (char *) malloc(strlen(fName) + 1);
    strcpy(list[i].first_name, fName);
    list[i].last_name = (char *) malloc(strlen(lName) + 1);
    strcpy(list[i].last_name, lName);
    list[i].company_name = (char *) malloc(strlen(cName) + 1);
    strcpy(list[i].company_name, cName);
    list[i].email = (char *) malloc(strlen(email) + 1);
    strcpy(list[i].email, email);

    count++;

} while (ftell(fp) != fileEnd);

count--;

qsort(list, count, sizeof(store), compareStore);

/*Prints output*/
for(i=0;i<count;i++) {
    printf("First Name: %s\n", list[i].first_name);
    printf("Last Name: %s\n", list[i].last_name);
    printf("Company Name: %s\n", list[i].company_name);
    printf("Phone Number (enter only numbers): %ld\n", list[i].phone_num);
    printf("Email: %s\n", list[i].email);

    free(list[i].first_name);
    free(list[i].last_name);
    free(list[i].company_name);
    free(list[i].email);
}

free(list);
return;
}

int compareStore (const void*a, const void *b)
{
    const store *aa = a;
    const store *bb = b;

    return (strcmp(bb->last_name, aa->last_name));
}
</code>```

This is my output as of now. It should consider both last name and company name as the same parameters and then sort them:

```<code>First Name: Andre
Last Name: D'Souza
Company Name:
Phone Number (enter only numbers): 6474000964
Email: adsouz03@mail.com
First Name:
Last Name:
Company Name: University of Guelph
Phone Number (enter only numbers): 5192137299
Email: uog@mail.com
First Name: Raf
Last Name:
Company Name: Raffy Taffy
Phone Number (enter only numbers): 1234567
Email: raf@mail.com
</code>```

答:
Your compare function looks wrong. You are passed pointers to two records a and b. These are pointers to your store struct, but you are casting them as store** for some reason, then trying to dereference this as a store*. This has the effect of using the data as pointers, which will certainly cause a segmentation fault.

I suggest:

```<code>int compareStore (const void*a, const void *b)
{
    const store *aa = a;
    const store *bb = b;

    return (strcmp(aa->last_name, bb->last_name));
}
</code>```

Note that strcmp returns exactly the kind of int that qsort is expecting. Just return qsort the value returned by strcmp.

To generalize compareStore to check either Last name or Company name, assume that one of these contains a string, and the other is either NullPtr or a Null string, then the complete solution is:

```<code>int compareStore (const void*a, const void *b)
{
    const store *aa = a;
    const store *bb = b;

    // This MACRO retrieve ptr to last_name or company_name based
    // on whether last_name is a NULL ptr or a null "" string.
    // If last_name is either, use company_name insteadof last_name
    #define getKey(x) ((((x)->last_name==NULL)||((x)->last_name[0]==0)) ? (x)->company_name : (x)->last_name)

    // Use the Macro getKey to point to appropriate sort key for each record
    const char* keyA = getKey(aa);
    const char* keyB = getKey(bb);

    return (strcmp(keyA, keyB));
}
</code>```

Another bug is found in your call to qsort itself, where you pass the size of your list, but you should be passing the size of each record within the list to be sorted:

```<code>qsort (list, count, sizeof(store), compareStore);
</code>```

Body:
I'm Now trying to sort the Last names and Company names. The user has to enter either a last name or company name (only one). this is my code right now:

struct store {
unsigned long phone_num;
char *first_name;
char *last_name;
char *company_name;
char *email;
};
typedef struct store store;

void findContact(FILE *fp, long fileEnd)
{
/*variables*/
char fName [100];
char lName [100];
char cName [100];
char email [100];

int i, length;
int count = 1;
int size = sizeof(long);
int usize = sizeof(unsigned long);

unsigned long phone;

long nextPosition = 0;
long fNamePosition = 0;
long lNamePosition = 0;
long cNamePosition = 0;
long emailPosition = 0;

store *list;
list = malloc(sizeof(store));

/*Search for Contact position in file*/
fseek(fp, 0, SEEK_SET); /*Seeks to beginning of file*/
do {
    i = count - 1;

    fread(&phone, usize, 1, fp); /*reads phonenumber of contact*/
    fread(&fNamePosition, size , 1, fp);
    fread(&lNamePosition, size, 1, fp);
    fread(&cNamePosition, size, 1, fp);
    fread(&emailPosition, size, 1, fp);
    fread(&nextPosition, size, 1, fp);

    if(fNamePosition != 0) {

        fseek(fp,fNamePosition,SEEK_SET);
        if(lNamePosition == 0) {
          length = cNamePosition - fNamePosition;
        } else {
          length = lNamePosition - fNamePosition;
        }
        fread(fName,sizeof(char),length,fp);
    } else {
        strcpy(fName," ");
    }

    if(lNamePosition != 0) {
        fseek(fp,lNamePosition,SEEK_SET);
        if (cNamePosition == 0) {
          length = emailPosition - lNamePosition;
        } else {
          length = cNamePosition - lNamePosition;
        }
        fread(lName,sizeof(char), length,fp);
    } else {
        strcpy(lName," ");
    }

    if(cNamePosition != 0) {
        fseek(fp,cNamePosition,SEEK_SET);
        length = emailPosition-cNamePosition;
        fread(cName,sizeof(char), length,fp);
    } else {
        strcpy(cName," ");
    }

    fseek(fp,emailPosition,SEEK_SET);
    length = nextPosition - emailPosition;
    fread(email,sizeof(char),length,fp);

    list = realloc(list, count * sizeof(store));

    list[i].phone_num = phone;
    list[i].first_name = (char *) malloc(strlen(fName) + 1);
    strcpy(list[i].first_name, fName);
    list[i].last_name = (char *) malloc(strlen(lName) + 1);
    strcpy(list[i].last_name, lName);
    list[i].company_name = (char *) malloc(strlen(cName) + 1);
    strcpy(list[i].company_name, cName);
    list[i].email = (char *) malloc(strlen(email) + 1);
    strcpy(list[i].email, email);

    count++;

} while (ftell(fp) != fileEnd);

count--;

qsort(list, count, sizeof(store), compareStore);

/*Prints output*/
for(i=0;i<count;i++) {
    printf("First Name: %s\n", list[i].first_name);
    printf("Last Name: %s\n", list[i].last_name);
    printf("Company Name: %s\n", list[i].company_name);
    printf("Phone Number (enter only numbers): %ld\n", list[i].phone_num);
    printf("Email: %s\n", list[i].email);

    free(list[i].first_name);
    free(list[i].last_name);
    free(list[i].company_name);
    free(list[i].email);
}

free(list);
return;
}

int compareStore (const void*a, const void *b)
{
    const store *aa = a;
    const store *bb = b;

    return (strcmp(bb->last_name, aa->last_name));
}

This is my output as of now. It should consider both last name and company name as the same parameters and then sort them:

First Name: Andre
Last Name: D'Souza
Company Name:
Phone Number (enter only numbers): 6474000964
Email: adsouz03@mail.com
First Name:
Last Name:
Company Name: University of Guelph
Phone Number (enter only numbers): 5192137299
Email: uog@mail.com
First Name: Raf
Last Name:
Company Name: Raffy Taffy
Phone Number (enter only numbers): 1234567
Email: raf@mail.com

Body:
Your compare function looks wrong. You are passed pointers to two records a and b. These are pointers to your store struct, but you are casting them as store** for some reason, then trying to dereference this as a store*. This has the effect of using the data as pointers, which will certainly cause a segmentation fault.

I suggest:

int compareStore (const void*a, const void *b)
{
    const store *aa = a;
    const store *bb = b;

    return (strcmp(aa->last_name, bb->last_name));
}

Note that strcmp returns exactly the kind of int that qsort is expecting. Just return qsort the value returned by strcmp.

To generalize compareStore to check either Last name or Company name, assume that one of these contains a string, and the other is either NullPtr or a Null string, then the complete solution is:

int compareStore (const void*a, const void *b)
{
    const store *aa = a;
    const store *bb = b;

    // This MACRO retrieve ptr to last_name or company_name based
    // on whether last_name is a NULL ptr or a null "" string.
    // If last_name is either, use company_name insteadof last_name
    #define getKey(x) ((((x)->last_name==NULL)||((x)->last_name[0]==0)) ? (x)->company_name : (x)->last_name)

    // Use the Macro getKey to point to appropriate sort key for each record
    const char* keyA = getKey(aa);
    const char* keyB = getKey(bb);

    return (strcmp(keyA, keyB));
}

Another bug is found in your call to qsort itself, where you pass the size of your list, but you should be passing the size of each record within the list to be sorted:

qsort (list, count, sizeof(store), compareStore);


问:
How do I calculate the area of a 2d polygon?
Assuming a series of points in 2d space that do not self-intersect, what is an efficient method of determining the area of the resulting polygon?

As a side note, this is not homework and I am not looking for code.  I am looking for a description I can use to implement my own method.  I have my ideas about pulling a sequence of triangles from the list of points, but I know there are a bunch of edge cases regarding convex and concave polygons that I probably won't catch.

答:
I'm going to give a few simple functions for calculating area of 2d polygon. This works for both convex and concave polygons.
  we simply divide the polygon into many sub-triangles.

```<code>//don't forget to include cmath for abs function
struct Point{
  double x;
  double y;
}
// cross_product
double cp(Point a, Point b){ //returns cross product
  return a.x*b.y-a.y*b.x;
}

double area(Point * vertices, int n){  //n is number of sides
  double sum=0.0;
  for(i=0; i<n; i++){
    sum+=cp(vertices[i], vertices[(i+1)%n]); //%n is for last triangle
  }
  return abs(sum)/2.0;
}
</code>```

OwnerDisplayName: Jason Z

LastEditorDisplayName: MattK

Body:
I'm going to give a few simple functions for calculating area of 2d polygon. This works for both convex and concave polygons.
  we simply divide the polygon into many sub-triangles.

//don't forget to include cmath for abs function
struct Point{
  double x;
  double y;
}
// cross_product
double cp(Point a, Point b){ //returns cross product
  return a.x*b.y-a.y*b.x;
}

double area(Point * vertices, int n){  //n is number of sides
  double sum=0.0;
  for(i=0; i<n; i++){
    sum+=cp(vertices[i], vertices[(i+1)%n]); //%n is for last triangle
  }
  return abs(sum)/2.0;
}

ContentLicense: CC BY-SA 4.0


问:
Polynomial time and exponential time
Could someone explain the difference between polynomial-time, non-polynomial-time, and exponential-time algorithms?

For example, if an algorithm takes O(n^2) time, then which category is it in?

答:
Check this out.

Exponential is worse than polynomial.

O(n^2) falls into the quadratic category, which is a type of polynomial (the special case of the exponent being equal to 2) and better than  exponential.

Exponential is much worse than polynomial.  Look at how the functions grow

```<code>n    = 10    |     100   |      1000

n^2  = 100   |   10000   |   1000000

k^n  = k^10  |   k^100   |    k^1000
</code>```

k^1000 is exceptionally huge unless k is smaller than something like 1.1. Like, something like every particle in the universe would have to do 100 billion billion billion operations per second for trillions of billions of billions of years to get that done.

I didn't calculate it out, but ITS THAT BIG.

Title: Polynomial time and exponential time

Body:
Check this out.

Exponential is worse than polynomial.

O(n^2) falls into the quadratic category, which is a type of polynomial (the special case of the exponent being equal to 2) and better than  exponential.

Exponential is much worse than polynomial.  Look at how the functions grow

n    = 10    |     100   |      1000

n^2  = 100   |   10000   |   1000000

k^n  = k^10  |   k^100   |    k^1000

k^1000 is exceptionally huge unless k is smaller than something like 1.1. Like, something like every particle in the universe would have to do 100 billion billion billion operations per second for trillions of billions of billions of years to get that done.

I didn't calculate it out, but ITS THAT BIG.


问:
hover not working with a background image
I have a website with a background image but when I add a css navigation  bar the hover tag doesn't work. the hover element works with out the back ground image but when i add the background image it dosent

here's my code

html

```<code><!DOCTYPE html>
<html>
<head>
    <title>Cool</title>
    <link href="stylesheet.css" "type= "text/css" rel= "stylesheet">
    <link rel="icon" type="image/png" href="icon2.jpg"/>
</head>
<body>
    <div id="background-image">
    <div id="background-overlay">
    <h1>Cool</h1>
            <h2>Vertical Navigation Bar</h2>

            <ul>
            <li><a href="#home">Home</a></li>
            <li><a href="#news">News</a></li>
            <li><a href="#contact">Contact</a></li>
            <li><a href="#about">About</a></li>
            </ul>

            <p>hi</p>
    </div>
    </div>
</body>
</html>
</code>```

CSS

```<code>*{
z-index:-8;
}
body{
margin:0px;
}
#backround-image{
background-image:url("background.jpg");
background-size:cover;
background-position:center center;
position:relative;
top: 0;
bottom :0;
height: 100vh;
z-index: -10;
}
#backround-overlay{
position: absolute;
background-color: rgba(0,0,0,0.5);
top: 0;
bottom: 0;
height: 100%;
width: 100%;
z-index:-9;
}
h1{
text-align:center;
font-family:arial black;

}
l{
float:left;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 200px;
background-color: #f1f1f1;
}

li a {
display: block;
color: #000;
padding: 8px 16px;
text-decoration: none;
}

/* Change the link color on hover */
li a:hover{
background-color: red;
color: black;
}
</code>```

thanks for any help

Thomas

答: If you remove position: relative; from background-image the issue is resolved and doesn't cause any weirdness. At the moment this appears to be unnecessary styling.</p>

Body:
I have a website with a background image but when I add a css navigation  bar the hover tag doesn't work. the hover element works with out the back ground image but when i add the background image it dosent

here's my code

html

<!DOCTYPE html>

    <title>Cool</title>
    <link href="stylesheet.css" "type= "text/css" rel= "stylesheet">
    <link rel="icon" type="image/png" href="icon2.jpg"/>

Cool

Vertical Navigation Bar

Home

News

Contact

About

hi

CSS

*{
z-index:-8;
}
body{
margin:0px;
}
#backround-image{
background-image:url("background.jpg");
background-size:cover;
background-position:center center;
position:relative;
top: 0;
bottom :0;
height: 100vh;
z-index: -10;
}
#backround-overlay{
position: absolute;
background-color: rgba(0,0,0,0.5);
top: 0;
bottom: 0;
height: 100%;
width: 100%;
z-index:-9;
}
h1{
text-align:center;
font-family:arial black;

}
l{
float:left;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 200px;
background-color: #f1f1f1;
}

li a {
display: block;
color: #000;
padding: 8px 16px;
text-decoration: none;
}

/* Change the link color on hover */
li a:hover{
background-color: red;
color: black;
}

thanks for any help

Thomas


问:
Specifying a Perl 6 class in a variable
I have a bunch of Perl 6 tests that start off with some basic tests where I put the class name to test in a variable the use that variable throughout the test:

```<code>my $package = 'Some::Class';
use-ok $package;

my $class = ::($package);
can-ok $class, 'new';
</code>```

I hadn't paid attention to this for a bit, but it no longer works because classes are lexically loaded now:

No such symbol 'Some::Class'

It's not a hard fix. Load the module without use-ok and in the scope where I want ::($package):

```<code>use Some::Class;

...
</code>```

The other solutions (discounting an ugly EVAL perhaps) have the issue I'm trying to avoid.

But, I don't particularly like that since the name shows up twice in the file. I've particularly liked my formerly-working idiom that I carried over from Perl 5. If I wanted to change a class name, it only showed up once in the file. I could easily generate boilerplate tests (although, it's not that much harder for the fix).

Is there a way I can get back to the ideal I wanted? (Although I figure lexical loading in the next version will get in the way again).

答:
To sum up the problem: You want to load modules using a symbol instead of hardcoding it.
Using a constant should do this for you:

```<code>constant some-module = 'Some::Module';
use ::(some-module);
</code>```

You can also load the module at runtime using require, which would allow runtime computed values:

```<code>my $some-module = 'Some::Module';
require ::($some-module);
::($some-module).foo
</code>```

It would make sense to do this after trying a use-ok.

For extra credit, you may find the techniques in this article useful.
http://rakudo.org/2017/03/18/lexical-require-upgrade-info/

Title: Specifying a Perl 6 class in a variable

Body:
I have a bunch of Perl 6 tests that start off with some basic tests where I put the class name to test in a variable the use that variable throughout the test:

my $package = 'Some::Class';
use-ok $package;

my $class = ::($package);
can-ok $class, 'new';

I hadn't paid attention to this for a bit, but it no longer works because classes are lexically loaded now:

No such symbol 'Some::Class'

It's not a hard fix. Load the module without use-ok and in the scope where I want ::($package):

use Some::Class;

...

The other solutions (discounting an ugly EVAL perhaps) have the issue I'm trying to avoid.

But, I don't particularly like that since the name shows up twice in the file. I've particularly liked my formerly-working idiom that I carried over from Perl 5. If I wanted to change a class name, it only showed up once in the file. I could easily generate boilerplate tests (although, it's not that much harder for the fix).

Is there a way I can get back to the ideal I wanted? (Although I figure lexical loading in the next version will get in the way again).

Body:
To sum up the problem: You want to load modules using a symbol instead of hardcoding it.
Using a constant should do this for you:

constant some-module = 'Some::Module';
use ::(some-module);

You can also load the module at runtime using require, which would allow runtime computed values:

my $some-module = 'Some::Module';
require ::($some-module);
::($some-module).foo

It would make sense to do this after trying a use-ok.

For extra credit, you may find the techniques in this article useful.
http://rakudo.org/2017/03/18/lexical-require-upgrade-info/


问:
Why isn't my unordered lists not being positioned beside the centered image?
I'm trying to put my two lists beside the image that is centered in the middle one on each side but the two lists have to be centered and not all the way right or left.

Thanks in advance.
*Please fullscreen the html snippet.

div.main p {
  color: white;
  font-size: 20px;
  font-family: Arial, Helvetica, sans-serif;
  text-align: center;
}

div.main h1 {
  color: white;
  font-family: Arial, Helvetica, sans-serif;
  font-weight: bold;
  text-decoration: underline;
  text-align: center;
  font-size: 36px;
}

div.material {
  float: left;
}

div.material h2 {
  color: white;
  font-size: 20px;
  font-family: Arial, Helvetica, sans-serif;
  font-weight: bold;
  text-decoration: underline;
}

div.list li {
  color: white;
  font-size: 16px;
  font-family: Arial, Helvetica, sans-serif;
  text-align: left;
  list-style-type: none;
}

div.materialy {
  float: right;
}

div.materialy h2 {
  color: white;
  font-size: 20px;
  font-family: Arial, Helvetica, sans-serif;
  font-weight: bold;
  text-decoration: underline;
}

div.listy li {
  color: white;
  font-size: 16px;
  font-family: Arial, Helvetica, sans-serif;
  list-style-type: none;
  text-align: right;
}

div.method p {
  color: white;
  font-size: 20px;
  font-family: Arial, Helvetica, sans-serif;
  text-align: center;
  text-decoration: underline;
  font-weight: bold;
}

div.method li {
  color: white;
  font-size: 16px;
  font-family: Arial, Helvetica, sans-serif;
  text-align: center;
  list-style-type: none;
  line-height: 40px;
}

div.skill li {
  font-weight: bold;
  font-style: italic;
  font-size: 18px;
}

div.skill p {
  font-style: italic;
  text-decoration: none;
  font-size: 16px;
  color: #F00;
}

div.image img {
  display: block;
  margin: 0 auto;
}

body {
  background-color: blue;
}

div.nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  font: Arial, Helvetica, sans-serif black;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 18px;
  border-radius: 5px;
  border-bottom: solid black;
  border-top: solid black;
  border-left: solid black;
  border-right: solid black;
  background: #09F;
  /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(#09F, #9FF);
  /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(#09F, #9FF);
  /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(#09F, #9FF);
  /* For Firefox 3.6 to 15 */
  background: linear-gradient(#09F, #9FF);
  /* Standard syntax (must be last) */
}

div.nav li {
  float: left;
}

div.nav li a {
  display: block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

div.nav li a:hover {
  background-color: #0FC;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<link href="style4.css" type="text/css" rel="stylesheet" />

<head>
  <title>Tips</title>
</head>
<div class="nav">
  <ul>
    <li>Home
    </li>
    <li>Tips
    </li>
    <li>Learn
    </li>
    <li>Contact
    </li>
  </ul>
</div>

<body>
  <div class="main">
    <h1>Welcome to the tips page!</h1>
    <p>
      <br>Artists typically use great techniques to make their art more professional looking and it also helps them improve their skills at drawing.
      <br>They use different types of mediums, tools, and art supplies to enhance the looks of their artwork.</p>
  </div>
  <div class="material">
    <h2>Materials for a beginner or newbie:</h2>
  </div>
  <div class="image">
    </br>
    </br>
    </br>
    <div class="list">
      <ul>
        <li>HB #2 Pencil</li>
        <li>Clean white vinyl eraser</li>
        <li>White printer paper</li>
        <li>Good lighting or desk lamp</li>
      </ul>
    </div>
    <img src="person-drawing.jpg" height="296" width="395"></div>
  <div class="materialy">
    <h2>Materials for the advanced:</h2>
    <div class="listy">
      <ul>
        <li>Staedtler Design/Drafting Pencil Set</li>
        <li>Clean white vinyl eraser</li>
        <li>Gum eraser</li>
        <li>Kneaded eraser</li>
        <li>White printer paper</li>
        <li>Good lighting or desk lamp</li>
        <li>Blending sticks</li>
        <li>0.5/0.7 mechanical pencils</li>
        <li>0.5/0.7 mechanical pencil lead</li>
        <li>Fine tip liner marker</li>
        <li>Adjustable drafting table</li>
      </ul>
    </div>
  </div>
  </br>
  <div class="method">
    <p>Here are some good methods and techniques to practice drawing skills:</p>
    <ul>
      <div class="skill">
        <li>Drawing is a skill</li>
        <p>*Drawing isn't some magical activity that people are born with! It can be taught and learnt from also, anyone can be skilled at drawing!</p>
      </div>
      <li>Drawing or sketching lightly</li>
      <li>Observe your artwork while drawing regularly</li>
      <li>Look for basic shapes</li>
      <li>Take your time</li>
      <li>Use guidelines/structure to form the foundation of the drawing</li>
      <li>Use resources if needed</li>
      <li>Be consistent</li>
      <li>Relax and have fun</li>
      <li>Keep practicing constantly</li>
    </ul>
  </div>
</body>

</html></code>```

答:
Here is the rewritten code:
     https://jsfiddle.net/vsjka9r7/

```<code><div class="nav">
<ul>
    <li><a href="home.html">Home</a></li>
    <li><a href="">Tips</a></li>
    <li><a href="index.html">Learn</a></li>
    <li><a href="contacts.html">Contact</a></li>
</ul>
</div>
<div class="main">
<h1>Welcome to the tips page!</h1>
<p><br>
    Artists typically use great techniques to make their art more professional looking and it also helps them improve their skills at drawing.
<br>
    They use different types of mediums, tools, and art supplies to enhance the looks of their artwork.
</p>
</div>
<div class="centerContentController">
<div class="leftList">
    <div class="material">
        <h2>Materials for a beginner or newbie:</h2>
    </div>
    <br>
    <br>
    <br>
    <div class="list">
        <ul>
            <li>HB #2 Pencil</li>
            <li>Clean white vinyl eraser</li>
            <li>White printer paper</li>
            <li>Good lighting or desk lamp</li>
        </ul>
    </div>
</div>
<img src="person-drawing.jpg" height="296" width="395" class="materialsImg">
 <div class="rightList">
    <div class="materialy">
        <h2>Materials for the advanced:</h2>
            <div class="listy">
                <ul>
                    <li>Staedtler Design/Drafting Pencil Set</li>
                    <li>Clean white vinyl eraser</li>
                    <li>Gum eraser</li>
                    <li>Kneaded eraser</li>
                    <li>White printer paper</li>
                    <li>Good lighting or desk lamp</li>
                    <li>Blending sticks</li>
                    <li>0.5/0.7 mechanical pencils</li>
                    <li>0.5/0.7 mechanical pencil lead</li>
                    <li>Fine tip liner marker</li>
                    <li>Adjustable drafting table</li>
                </ul>
            </div>
    </div>
    <br>
 </div>
 </div>
 <div class="bottomContent">
<div class="method">
    <p>Here are some good methods and techniques to practice drawing skills:
</p>
        <ul>
          <div class="skill">
              <li>Drawing is a skill</li>
              <p>*Drawing isn't some magical activity that people are born with! It can be taught and learnt from also, anyone can be skilled at drawing!</p>
          </div>
          <li>Drawing or sketching lightly</li>
          <li>Observe your artwork while drawing regularly</li>
          <li>Look for basic shapes</li>
          <li>Take your time</li>
          <li>Use guidelines/structure to form the foundation of the drawing</li>
          <li>Use resources if needed</li>
          <li>Be consistent</li>
          <li>Relax and have fun</li>
          <li>Keep practicing constantly</li>
        </ul>
</div>
</code>```

Does that work for ya?
If not I am here to help :)

What I changed:
I simply created a div container to contain the image and the two unordered list.
I then created a div for each of the unordered list and floated them to the right/left. For the center image I positioned it in the center.

Body:
I'm trying to put my two lists beside the image that is centered in the middle one on each side but the two lists have to be centered and not all the way right or left.

Thanks in advance.
*Please fullscreen the html snippet.

div.main p {
  color: white;
  font-size: 20px;
  font-family: Arial, Helvetica, sans-serif;
  text-align: center;
}

div.main h1 {
  color: white;
  font-family: Arial, Helvetica, sans-serif;
  font-weight: bold;
  text-decoration: underline;
  text-align: center;
  font-size: 36px;
}

div.material {
  float: left;
}

div.material h2 {
  color: white;
  font-size: 20px;
  font-family: Arial, Helvetica, sans-serif;
  font-weight: bold;
  text-decoration: underline;
}

div.list li {
  color: white;
  font-size: 16px;
  font-family: Arial, Helvetica, sans-serif;
  text-align: left;
  list-style-type: none;
}

div.materialy {
  float: right;
}

div.materialy h2 {
  color: white;
  font-size: 20px;
  font-family: Arial, Helvetica, sans-serif;
  font-weight: bold;
  text-decoration: underline;
}

div.listy li {
  color: white;
  font-size: 16px;
  font-family: Arial, Helvetica, sans-serif;
  list-style-type: none;
  text-align: right;
}

div.method p {
  color: white;
  font-size: 20px;
  font-family: Arial, Helvetica, sans-serif;
  text-align: center;
  text-decoration: underline;
  font-weight: bold;
}

div.method li {
  color: white;
  font-size: 16px;
  font-family: Arial, Helvetica, sans-serif;
  text-align: center;
  list-style-type: none;
  line-height: 40px;
}

div.skill li {
  font-weight: bold;
  font-style: italic;
  font-size: 18px;
}

div.skill p {
  font-style: italic;
  text-decoration: none;
  font-size: 16px;
  color: #F00;
}

div.image img {
  display: block;
  margin: 0 auto;
}

body {
  background-color: blue;
}

div.nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  font: Arial, Helvetica, sans-serif black;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 18px;
  border-radius: 5px;
  border-bottom: solid black;
  border-top: solid black;
  border-left: solid black;
  border-right: solid black;
  background: #09F;
  /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(#09F, #9FF);
  /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(#09F, #9FF);
  /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(#09F, #9FF);
  /* For Firefox 3.6 to 15 */
  background: linear-gradient(#09F, #9FF);
  /* Standard syntax (must be last) */
}

div.nav li {
  float: left;
}

div.nav li a {
  display: block;
  color: black;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

div.nav li a:hover {
  background-color: #0FC;
}

<!DOCTYPE html>

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

  <title>Tips</title>

Home

Tips

Learn

Contact

Welcome to the tips page!

Artists typically use great techniques to make their art more professional looking and it also helps them improve their skills at drawing.

They use different types of mediums, tools, and art supplies to enhance the looks of their artwork.

Materials for a beginner or newbie:

HB #2 Pencil

Clean white vinyl eraser

White printer paper

Good lighting or desk lamp

Materials for the advanced:

Staedtler Design/Drafting Pencil Set

Clean white vinyl eraser

Gum eraser

Kneaded eraser

White printer paper

Good lighting or desk lamp

Blending sticks

0.5/0.7 mechanical pencils

0.5/0.7 mechanical pencil lead

Fine tip liner marker

Adjustable drafting table

Here are some good methods and techniques to practice drawing skills:

Drawing is a skill

*Drawing isn't some magical activity that people are born with! It can be taught and learnt from also, anyone can be skilled at drawing!

Drawing or sketching lightly

Observe your artwork while drawing regularly

Look for basic shapes

Take your time

Use guidelines/structure to form the foundation of the drawing

Use resources if needed

Be consistent

Relax and have fun

Keep practicing constantly

Body:
Here is the rewritten code:
     https://jsfiddle.net/vsjka9r7/

<div class="nav">
<ul>
    <li><a href="home.html">Home</a></li>
    <li><a href="">Tips</a></li>
    <li><a href="index.html">Learn</a></li>
    <li><a href="contacts.html">Contact</a></li>
</ul>
</div>
<div class="main">
<h1>Welcome to the tips page!</h1>
<p><br>
    Artists typically use great techniques to make their art more professional looking and it also helps them improve their skills at drawing.
<br>
    They use different types of mediums, tools, and art supplies to enhance the looks of their artwork.
</p>
</div>
<div class="centerContentController">
<div class="leftList">
    <div class="material">
        <h2>Materials for a beginner or newbie:</h2>
    </div>
    <br>
    <br>
    <br>
    <div class="list">
        <ul>
            <li>HB #2 Pencil</li>
            <li>Clean white vinyl eraser</li>
            <li>White printer paper</li>
            <li>Good lighting or desk lamp</li>
        </ul>
    </div>
</div>
<img src="person-drawing.jpg" height="296" width="395" class="materialsImg">
 <div class="rightList">
    <div class="materialy">
        <h2>Materials for the advanced:</h2>
            <div class="listy">
                <ul>
                    <li>Staedtler Design/Drafting Pencil Set</li>
                    <li>Clean white vinyl eraser</li>
                    <li>Gum eraser</li>
                    <li>Kneaded eraser</li>
                    <li>White printer paper</li>
                    <li>Good lighting or desk lamp</li>
                    <li>Blending sticks</li>
                    <li>0.5/0.7 mechanical pencils</li>
                    <li>0.5/0.7 mechanical pencil lead</li>
                    <li>Fine tip liner marker</li>
                    <li>Adjustable drafting table</li>
                </ul>
            </div>
    </div>
    <br>
 </div>
 </div>
 <div class="bottomContent">
<div class="method">
    <p>Here are some good methods and techniques to practice drawing skills:
</p>
        <ul>
          <div class="skill">
              <li>Drawing is a skill</li>
              <p>*Drawing isn't some magical activity that people are born with! It can be taught and learnt from also, anyone can be skilled at drawing!</p>
          </div>
          <li>Drawing or sketching lightly</li>
          <li>Observe your artwork while drawing regularly</li>
          <li>Look for basic shapes</li>
          <li>Take your time</li>
          <li>Use guidelines/structure to form the foundation of the drawing</li>
          <li>Use resources if needed</li>
          <li>Be consistent</li>
          <li>Relax and have fun</li>
          <li>Keep practicing constantly</li>
        </ul>
</div>

Does that work for ya?
If not I am here to help :)

What I changed:
I simply created a div container to contain the image and the two unordered list.
I then created a div for each of the unordered list and floated them to the right/left. For the center image I positioned it in the center.


问:
How to generate a unique fake email with a custom domain with faker?
I have a laravel application that requires the registered users must use their company email (custom domain).

So how i can i achieve that with faker generators to test it with my model factories ?

答:
You can use a simple trick with php's preg_replace function:

preg_replace('/@example\..*/', '@domain.com', $faker->unique()->safeEmail)

so your laravel model factory might looks like this:

```<code>$factory->define(App\User::class, function (Faker\Generator $faker) {
    static $password;
    return [
        'name' => $faker->name,
        'email' => preg_replace('/@example\..*/', '@domain.com', $faker->unique()->safeEmail),
        'password' => $password ?: $password = bcrypt('secret'),
        'avatar' => $faker->imageUrl,
        'remember_token' => str_random(10),
    ];
});
</code>```

Body:
You can use a simple trick with php's preg_replace function:

preg_replace('/@example\..*/', '@domain.com', $faker->unique()->safeEmail)

so your laravel model factory might looks like this:

$factory->define(App\User::class, function (Faker\Generator $faker) {
    static $password;
    return [
        'name' => $faker->name,
        'email' => preg_replace('/@example\..*/', '@domain.com', $faker->unique()->safeEmail),
        'password' => $password ?: $password = bcrypt('secret'),
        'avatar' => $faker->imageUrl,
        'remember_token' => str_random(10),
    ];
});


问:
How does Javac work for multiple files, directories, classes and source?
I'm trying to figure out how javac works with regard to stuff like sourcepath, classpath and prebuilt classes etc. I'm trying to read the documentation, but can't really make sense of it.

I've tried to think of some sample cases below.

If I'm compiling a single file onlyfile.java which has no dependencies, which has 2 classes A and B , and class A uses class B , does class B need to be defined/declared before A ? Or is javac smart and does multiple passes or something like that ?

root.java uses another class in a file file2.java located in the same folder. If I execute javac root.java , how does javac know to search the folder for the class file and if not found , for source file instead ?

How does the above work if the file2 is located in a subdirectory ?

EDIT:
I read somewhere that import is just a way to cut down on typing rather than "loading" anything like in python.
Suppose that I'm building only 1 java file which uses multiple other classes, and that these class files already exist. Without import, the a.b.c.d part of the class object already tells me where to search for the class file, then why a cp option ?

答:
For first two options try with javac *.java

Duplicate of Compiling Multiple Classes (Console) in Java


问:
Animate google maps polyline from a set of points like in animaps
I have a set or array of points (lat, lon) which represent a vehicle route or path. I want to play those points in something looks like a flash (but using javascript and google maps api), like in this page:

http://www.animaps.com/pb/161960002/1805/Piraeus_Line

or like in google maps's page:

https://www.youtube.com/watch?v=iec4fVTuNCE

I have been looking for the many tutorials but nothing gives a straight forward solution.

The problem of animaps is that I should always embed it as an iframe in my website, while I need to make this dynamic because I have positions retrieved from database.

答:
First use the
Directions Service
 to get the directions from your from > to positions.

Then create a polyline for that direction, to the polyline you can add symbols that you can animate along it's path by updating their offset.

var map;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var polyline, symbol;

function initialize() {

  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var mapOptions = {
    zoom: 7,
    center: chicago,
    styles: [{
      "elementType": "geometry",
      "stylers": [{
        "color": "#212121"
      }]
    }, {
      "elementType": "labels.icon",
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "elementType": "labels.text.fill",
      "stylers": [{
        "color": "#757575"
      }]
    }, {
      "elementType": "labels.text.stroke",
      "stylers": [{
        "color": "#212121"
      }]
    }, {
      "featureType": "administrative",
      "elementType": "geometry",
      "stylers": [{
        "color": "#757575"
      }, {
        "visibility": "off"
      }]
    }, {
      "featureType": "administrative.country",
      "elementType": "labels.text.fill",
      "stylers": [{
        "color": "#9e9e9e"
      }]
    }, {
      "featureType": "administrative.land_parcel",
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "featureType": "administrative.locality",
      "elementType": "labels.text.fill",
      "stylers": [{
        "color": "#bdbdbd"
      }]
    }, {
      "featureType": "administrative.neighborhood",
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "featureType": "poi",
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "featureType": "poi",
      "elementType": "labels.text",
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "featureType": "poi",
      "elementType": "labels.text.fill",
      "stylers": [{
        "color": "#757575"
      }]
    }, {
      "featureType": "poi.park",
      "elementType": "geometry",
      "stylers": [{
        "color": "#181818"
      }]
    }, {
      "featureType": "poi.park",
      "elementType": "labels.text.fill",
      "stylers": [{
        "color": "#616161"
      }]
    }, {
      "featureType": "poi.park",
      "elementType": "labels.text.stroke",
      "stylers": [{
        "color": "#1b1b1b"
      }]
    }, {
      "featureType": "road",
      "elementType": "geometry.fill",
      "stylers": [{
        "color": "#2c2c2c"
      }]
    }, {
      "featureType": "road",
      "elementType": "labels",
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "featureType": "road",
      "elementType": "labels.icon",
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "featureType": "road",
      "elementType": "labels.text.fill",
      "stylers": [{
        "color": "#8a8a8a"
      }]
    }, {
      "featureType": "road.arterial",
      "elementType": "geometry",
      "stylers": [{
        "color": "#373737"
      }]
    }, {
      "featureType": "road.highway",
      "elementType": "geometry",
      "stylers": [{
        "color": "#3c3c3c"
      }]
    }, {
      "featureType": "road.highway.controlled_access",
      "elementType": "geometry",
      "stylers": [{
        "color": "#4e4e4e"
      }]
    }, {
      "featureType": "road.local",
      "elementType": "labels.text.fill",
      "stylers": [{
        "color": "#616161"
      }]
    }, {
      "featureType": "transit",
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "featureType": "transit",
      "elementType": "labels.text.fill",
      "stylers": [{
        "color": "#757575"
      }]
    }, {
      "featureType": "water",
      "elementType": "geometry",
      "stylers": [{
        "color": "#000000"
      }]
    }, {
      "featureType": "water",
      "elementType": "labels.text",
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "featureType": "water",
      "elementType": "labels.text.fill",
      "stylers": [{
        "color": "#3d3d3d"
      }]
    }]
  }
  map = new google.maps.Map(document.getElementById('map'), mapOptions);
  directionsDisplay.setMap(map);

  calcRoute();

}

function calcRoute() {
  var request = {
    origin: 'chicago, il',
    destination: 'peoria, il',
    travelMode: 'DRIVING'
  };
  directionsService.route(request, function(response, status) {
    if (status == 'OK') {
      createPath(response);
    }
  });
}

function createPath(response) {

  symbol = {
    path: google.maps.SymbolPath.CIRCLE,
    scale: 6,
    strokeColor: '#fff'
  };

  polyline = new google.maps.Polyline({
    path: [],
    strokeColor: '#e91e63',
    strokeWeight: 3,
    icons: [{
      icon: symbol,
      offset: '0%'
    }]
  });

  var bounds = new google.maps.LatLngBounds();

  var legs = response.routes[0].legs;
  for (i = 0; i < legs.length; i++) {
    var steps = legs[i].steps;
    for (j = 0; j < steps.length; j++) {
      var nextSegment = steps[j].path;
      for (k = 0; k < nextSegment.length; k++) {
        polyline.getPath().push(nextSegment[k]);
        bounds.extend(nextSegment[k]);
      }
    }
  }

  polyline.setMap(map);
  map.setCenter(bounds.getCenter());

  animateCircle(polyline);
}

function animateCircle(line) {
  var count = 0;
  var icons = line.get('icons');
  window.setInterval(function() {
    count = (count + 1) % 200;
    icons[0].offset = (count / 2) + '%';
    line.set('icons', icons);
  }, 20);
}

google.maps.event.addDomListener(window, 'load', initialize);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#map {
  height: 200px;
  width: 100%;
}</code>```

```

Body:
First use the
Directions Service
 to get the directions from your from > to positions.

Then create a polyline for that direction, to the polyline you can add symbols that you can animate along it's path by updating their offset.

var map;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var polyline, symbol;

function initialize() {

  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var mapOptions = {
    zoom: 7,
    center: chicago,
    styles: [{
      "elementType": "geometry",
      "stylers": [{
        "color": "#212121"
      }]
    }, {
      "elementType": "labels.icon",
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "elementType": "labels.text.fill",
      "stylers": [{
        "color": "#757575"
      }]
    }, {
      "elementType": "labels.text.stroke",
      "stylers": [{
        "color": "#212121"
      }]
    }, {
      "featureType": "administrative",
      "elementType": "geometry",
      "stylers": [{
        "color": "#757575"
      }, {
        "visibility": "off"
      }]
    }, {
      "featureType": "administrative.country",
      "elementType": "labels.text.fill",
      "stylers": [{
        "color": "#9e9e9e"
      }]
    }, {
      "featureType": "administrative.land_parcel",
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "featureType": "administrative.locality",
      "elementType": "labels.text.fill",
      "stylers": [{
        "color": "#bdbdbd"
      }]
    }, {
      "featureType": "administrative.neighborhood",
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "featureType": "poi",
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "featureType": "poi",
      "elementType": "labels.text",
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "featureType": "poi",
      "elementType": "labels.text.fill",
      "stylers": [{
        "color": "#757575"
      }]
    }, {
      "featureType": "poi.park",
      "elementType": "geometry",
      "stylers": [{
        "color": "#181818"
      }]
    }, {
      "featureType": "poi.park",
      "elementType": "labels.text.fill",
      "stylers": [{
        "color": "#616161"
      }]
    }, {
      "featureType": "poi.park",
      "elementType": "labels.text.stroke",
      "stylers": [{
        "color": "#1b1b1b"
      }]
    }, {
      "featureType": "road",
      "elementType": "geometry.fill",
      "stylers": [{
        "color": "#2c2c2c"
      }]
    }, {
      "featureType": "road",
      "elementType": "labels",
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "featureType": "road",
      "elementType": "labels.icon",
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "featureType": "road",
      "elementType": "labels.text.fill",
      "stylers": [{
        "color": "#8a8a8a"
      }]
    }, {
      "featureType": "road.arterial",
      "elementType": "geometry",
      "stylers": [{
        "color": "#373737"
      }]
    }, {
      "featureType": "road.highway",
      "elementType": "geometry",
      "stylers": [{
        "color": "#3c3c3c"
      }]
    }, {
      "featureType": "road.highway.controlled_access",
      "elementType": "geometry",
      "stylers": [{
        "color": "#4e4e4e"
      }]
    }, {
      "featureType": "road.local",
      "elementType": "labels.text.fill",
      "stylers": [{
        "color": "#616161"
      }]
    }, {
      "featureType": "transit",
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "featureType": "transit",
      "elementType": "labels.text.fill",
      "stylers": [{
        "color": "#757575"
      }]
    }, {
      "featureType": "water",
      "elementType": "geometry",
      "stylers": [{
        "color": "#000000"
      }]
    }, {
      "featureType": "water",
      "elementType": "labels.text",
      "stylers": [{
        "visibility": "off"
      }]
    }, {
      "featureType": "water",
      "elementType": "labels.text.fill",
      "stylers": [{
        "color": "#3d3d3d"
      }]
    }]
  }
  map = new google.maps.Map(document.getElementById('map'), mapOptions);
  directionsDisplay.setMap(map);

  calcRoute();

}

function calcRoute() {
  var request = {
    origin: 'chicago, il',
    destination: 'peoria, il',
    travelMode: 'DRIVING'
  };
  directionsService.route(request, function(response, status) {
    if (status == 'OK') {
      createPath(response);
    }
  });
}

function createPath(response) {

  symbol = {
    path: google.maps.SymbolPath.CIRCLE,
    scale: 6,
    strokeColor: '#fff'
  };

  polyline = new google.maps.Polyline({
    path: [],
    strokeColor: '#e91e63',
    strokeWeight: 3,
    icons: [{
      icon: symbol,
      offset: '0%'
    }]
  });

  var bounds = new google.maps.LatLngBounds();

  var legs = response.routes[0].legs;
  for (i = 0; i < legs.length; i++) {
    var steps = legs[i].steps;
    for (j = 0; j < steps.length; j++) {
      var nextSegment = steps[j].path;
      for (k = 0; k < nextSegment.length; k++) {
        polyline.getPath().push(nextSegment[k]);
        bounds.extend(nextSegment[k]);
      }
    }
  }

  polyline.setMap(map);
  map.setCenter(bounds.getCenter());

  animateCircle(polyline);
}

function animateCircle(line) {
  var count = 0;
  var icons = line.get('icons');
  window.setInterval(function() {
    count = (count + 1) % 200;
    icons[0].offset = (count / 2) + '%';
    line.set('icons', icons);
  }, 20);
}

google.maps.event.addDomListener(window, 'load', initialize);

#map {
  height: 200px;
  width: 100%;
}

<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC9d3jaUX6Qdr0Uzvq6fQXVmZ1PBuHEVAQ"></script>