问:
How to make commands using str array in for loop by Python
I want to do something like this

```<code>CMD_LIST = ['ls -l', 'echo Mama Mia', 'echo bla bla bla']
for i in range(len(CMD_LIST)):
    subprocess.call(CMD_LIST[1])
</code>```

How can i do list of commands in for loop?

答:
CMD_LIST = ['ls -l', 'echo Mama Mia', 'echo bla bla bla']

```<code>for i in range(len(CMD_LIST)):
    subprocess.call(CMD_LIST[i])
</code>```

Did you mean this?

Body:
I want to do something like this

CMD_LIST = ['ls -l', 'echo Mama Mia', 'echo bla bla bla']
for i in range(len(CMD_LIST)):
    subprocess.call(CMD_LIST[1])

How can i do list of commands in for loop?

Body:
CMD_LIST = ['ls -l', 'echo Mama Mia', 'echo bla bla bla']

for i in range(len(CMD_LIST)):
    subprocess.call(CMD_LIST[i])

Did you mean this?


来源: stackexchange

问:
How to set random cookie value using rand function in PHP
How to set random cookie value using rand function in PHP

I don't want to change the value while page refreshed when it once assigned.. until cookie destroy

My code is as follows

```<code><?php
    global $random;
    $random= rand(0, 9999999);
    if(!isset($_COOKIE[$random])) {
        setcookie('user_cookie',$random, time() + (1), "/"); echo $_COOKIE[$random];
    }
    else {
        echo "Cookie '" . $_COOKIE[$random] . "' is set!<br>";
    }
    exit();
?>
</code>```

答:
```<code>if(!isset($_COOKIE['lg'])) {
    setcookie('lg', rand(1,10000), time() + (86400 * 30), "/"); // 86400 = 1 day
}
echo $_COOKIE['lg'];
</code>```

You can check if it is not set then set it.

ContentLicense: CC BY-SA 3.0

Body:
How to set random cookie value using rand function in PHP

I don't want to change the value while page refreshed when it once assigned.. until cookie destroy

My code is as follows

<?php
    global $random;
    $random= rand(0, 9999999);
    if(!isset($_COOKIE[$random])) {
        setcookie('user_cookie',$random, time() + (1), "/"); echo $_COOKIE[$random];
    }
    else {
        echo "Cookie '" . $_COOKIE[$random] . "' is set!
";
    }
    exit();
?>

Body:
if(!isset($_COOKIE['lg'])) {
    setcookie('lg', rand(1,10000), time() + (86400 * 30), "/"); // 86400 = 1 day
}
echo $_COOKIE['lg'];

You can check if it is not set then set it.


问:
Program 'mysql.exe' failed to run: The specified executable is not a valid application
I have problem with mysql command in windows 10. I want to import a file test.sql to test database. I use this command in Windows PowerShell

```<code>.\mysql -u root -p test < test.sql
</code>```

PS return an error with this content

```<code>Program 'mysql.exe' failed to run: The specified executable is not a valid application for this OS platform.At line:1
char:1
+ .\mysql -u root -p
+ ~~~~~~~~~~~~~~~~~~.
At line:1 char:1
+ .\mysql -u root -p
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (:) [], ApplicationFailedException
    + FullyQualifiedErrorId : NativeCommandFailed
</code>```

I tried in windows CMD(also administrate) I get this message This app can't run in your PC

also I find mysql.exe in c/wamp64/bin/mysql/mysql5.7.11/bin
  the size of the app was wierd 0KB.

Is it normal?

what 's the problem?

答:
I installed a new version of mysql using this answer
and it worked in new version of mysql</p>

Body:
I have problem with mysql command in windows 10. I want to import a file test.sql to test database. I use this command in Windows PowerShell

.\mysql -u root -p test < test.sql

PS return an error with this content

Program 'mysql.exe' failed to run: The specified executable is not a valid application for this OS platform.At line:1
char:1
+ .\mysql -u root -p
+ ~~~~~~~~~~~~~~~~~~.
At line:1 char:1
+ .\mysql -u root -p
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (:) [], ApplicationFailedException
    + FullyQualifiedErrorId : NativeCommandFailed

I tried in windows CMD(also administrate) I get this message This app can't run in your PC

also I find mysql.exe in c/wamp64/bin/mysql/mysql5.7.11/bin
  the size of the app was wierd 0KB.

Is it normal?

what 's the problem?


问:
java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
```<code>geocoder = new Geocoder(MapsActivity.this);
                List<Address> addressList = null;

               try {
                    addressList = geocoder.getFromLocation(firstLocationLattiutde, firstLocationlongitude, 5);
                }
                catch (IOException e) {
                    e.printStackTrace();
                }

                Address obj = addressList.get(0);
                add = obj.getAddressLine(0);
                guardAddress.setText(add);
</code>```

but sometime it give error like this

java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference at com.example.fahadaziz.securityapplication.Services.MyService.onLocationChanged

答:
geocoder.getFromLocation() method is returning null.
So before performing any operation on addresslist you must check for null.

```<code>if(addresslist != null)
{
    //go ahead
}
</code>```

Body:
geocoder = new Geocoder(MapsActivity.this);
                List<Address> addressList = null;

               try {
                    addressList = geocoder.getFromLocation(firstLocationLattiutde, firstLocationlongitude, 5);
                }
                catch (IOException e) {
                    e.printStackTrace();
                }

                Address obj = addressList.get(0);
                add = obj.getAddressLine(0);
                guardAddress.setText(add);

but sometime it give error like this

java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference at com.example.fahadaziz.securityapplication.Services.MyService.onLocationChanged

Body:
geocoder.getFromLocation() method is returning null.
So before performing any operation on addresslist you must check for null.

if(addresslist != null)
{
    //go ahead
}


问:
Converting C++ object file from linux .o to Windows .obj
I'm sorry if this sounds crazy. Is there anyway I can convert .o file that I get from g++ compiler to *obj that is compatible with Visual Studio.

This is the reason I am considering doing this conversion.

答: No, there is no way, especially as the .o file was not compiled with a cross-compiler on Linux. In any case, this sounds like a very strange approach to solve a single linking error.</p>

ContentLicense: CC BY-SA 2.5


问:
Regex: How to detect a pattern if an undesired sub pattern comes before the pattern?
I'm new to regex and I'm trying to use Java to detect a sequence of either: lowercase, uppercase, or digits, but not JUST digits separated by periods.
Restriction: No consecutive periods.

The sample String I have is: @@@951.324.1@@@foo1.bar2.123proccess.this.subString

I currently have the following regex: ((\p{Alnum})+\.)+(\p{Alnum})+

I'm trying to have the pattern recognize foo1.bar2.123proccess.this.subString but my regex gives me 951.324.1 since it's a sub-pattern of the pattern I defined.

How would I go about detecting the subString foo1.bar2.123proccess.this.subString

I would imagine the general nature would be: The entire returned String should have at least 1 lowercase or uppercase char, but I'm hopelessly confused on how I would detect that in the String.

答:
```<code>[a-zA-Z\d.]*[a-zA-Z][a-zA-Z\d.]*
</code>```

This can be split into 3 parts:

```<code>[a-zA-Z\d.]* // optional sequence of letters/numbers/dots
[a-zA-Z] // MUST have a letter
[a-zA-Z\d.]* // optional sequence of letters/numbers/dots
</code>```

Basically, "sandwiching" things that are required in optional things.

Try it here: https://regex101.com/r/VT4t2x/1

Body:
[a-zA-Z\d.]*[a-zA-Z][a-zA-Z\d.]*

This can be split into 3 parts:

[a-zA-Z\d.]* // optional sequence of letters/numbers/dots
[a-zA-Z] // MUST have a letter
[a-zA-Z\d.]* // optional sequence of letters/numbers/dots

Basically, "sandwiching" things that are required in optional things.

Try it here: https://regex101.com/r/VT4t2x/1


问:
How can I best handle sessions in my RestController within Spring?
I'm looking for suggestions on how to handle sessions more elegantly than my implementation below.

Basically I've written a BaseController that has a handleSession() routine that does the initial creation and subsequent reads from session data.  This session data is required to store various security information that I don't want to be reading on every hit for obvious performance reasons.  I also don't want to store this on the client, or I would just create a new request to pull the information back to Angular.

CustomerController implements this handleSession() call within each request.  This means I have to put it everywhere.

Is there a more graceful way to handle this?

BaseController.java

```<code>public abstract class BaseController {

    public Logger log = LoggerFactory.getLogger(getClass());

    public void handleSession(HttpSession session) {
        if (session.isNew()) {
            log.info("New session: " + session.getId());
            // TODO: write all session data here?
            session.setAttribute("Parm", "Value");
        } else {
            // TODO: read all session data here?
            log.info("Reused session: " + session.getId() + " Parm is set to: "
                    + session.getAttribute("Parm"));

        }
    }
}
</code>```

CustomerController.java

```<code>@RestController
@RequestMapping("/data/customer")
public class CustomerController extends BaseController {
    @Autowired
    private CustomerRepository customerRepository;

    @RequestMapping("")
    List<Customer> customers(HttpSession session) {
        handleSession(session);
        return customerRepository.getCustomers();
    }

    @RequestMapping("/{company}/{customer}/{division}")
    Customer customer(@PathVariable String company,
            @PathVariable String customer, @PathVariable String division,
            HttpSession session) {
        handleSession(session);
        return customerRepository.getCustomer(company, customer, division);
    }
}
</code>```

答:
Maybe you can get HttpSession information with @Autowired in you Controller. If you pass session information as parameter, there will be chance that you will get security vulnerability finding for your application.

For this, use the approach below:

```<code>@RestController
@RequestMapping("/data/customer")
public class CustomerController extends BaseController {
    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private HttpSession httpSession;
</code>```

You can remove HttpSession parameter from all your request mapping methods.

Body:
I'm looking for suggestions on how to handle sessions more elegantly than my implementation below.

Basically I've written a BaseController that has a handleSession() routine that does the initial creation and subsequent reads from session data.  This session data is required to store various security information that I don't want to be reading on every hit for obvious performance reasons.  I also don't want to store this on the client, or I would just create a new request to pull the information back to Angular.

CustomerController implements this handleSession() call within each request.  This means I have to put it everywhere.

Is there a more graceful way to handle this?

BaseController.java

public abstract class BaseController {

    public Logger log = LoggerFactory.getLogger(getClass());

    public void handleSession(HttpSession session) {
        if (session.isNew()) {
            log.info("New session: " + session.getId());
            // TODO: write all session data here?
            session.setAttribute("Parm", "Value");
        } else {
            // TODO: read all session data here?
            log.info("Reused session: " + session.getId() + " Parm is set to: "
                    + session.getAttribute("Parm"));

        }
    }
}

CustomerController.java

@RestController
@RequestMapping("/data/customer")
public class CustomerController extends BaseController {
    @Autowired
    private CustomerRepository customerRepository;

    @RequestMapping("")
    List<Customer> customers(HttpSession session) {
        handleSession(session);
        return customerRepository.getCustomers();
    }

    @RequestMapping("/{company}/{customer}/{division}")
    Customer customer(@PathVariable String company,
            @PathVariable String customer, @PathVariable String division,
            HttpSession session) {
        handleSession(session);
        return customerRepository.getCustomer(company, customer, division);
    }
}

Body:
Maybe you can get HttpSession information with @Autowired in you Controller. If you pass session information as parameter, there will be chance that you will get security vulnerability finding for your application.

For this, use the approach below:

@RestController
@RequestMapping("/data/customer")
public class CustomerController extends BaseController {
    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private HttpSession httpSession;

You can remove HttpSession parameter from all your request mapping methods.


答:
```<code><?php
define('COOKIE_KEY', 'COOKIE_KEY');
if (!array_key_exists(COOKIE_KEY, $_COOKIE)) {
    setcookie(COOKIE_KEY, mt_rand(1, 10), time()+3600);
}
</code>```

Title: How to set random cookie value using rand function in PHP


问:
AutoMapper custom mapping
I have these two models

```<code>public class ModelA
{
    public string name { get; set; }
    public string email_address { get; set; }
}

public class ModelB
{
    public string Name { get; set; }
    public string EmailAddress { get; set; }
}
</code>```

and I have this mapping:

```<code>Mapper.Initialize(cfg => cfg.CreateMap<OldStudent, NewStudent>());
var newModel = Mapper.Map<NewStudent>(oldStudent);
</code>```

Well my mapping wont work because email_address and EmailAddress cannot be mapped.

Now I want to create a logic or to insert code where the email_address will turn to EmailAddress so the mapping will work, (in short I want to remove the underscore and make it CamelCase)

I also have too many properties so I dont want to use the manual mapping (.ForMember method by automapper)

Any idea how can I achieve this? Thanks in advance.

答:
Follow the link naming-conventions

and add below lines to config.

```<code>Mapper.Initialize(cfg => {
  cfg.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
  cfg.DestinationMemberNamingConvention = new PascalCaseNamingConvention();
});
</code>```

This would fix the issue.

Title: AutoMapper custom mapping

Body:
I have these two models

public class ModelA
{
    public string name { get; set; }
    public string email_address { get; set; }
}

public class ModelB
{
    public string Name { get; set; }
    public string EmailAddress { get; set; }
}

and I have this mapping:

Mapper.Initialize(cfg => cfg.CreateMap<OldStudent, NewStudent>());
var newModel = Mapper.Map<NewStudent>(oldStudent);

Well my mapping wont work because email_address and EmailAddress cannot be mapped.

Now I want to create a logic or to insert code where the email_address will turn to EmailAddress so the mapping will work, (in short I want to remove the underscore and make it CamelCase)

I also have too many properties so I dont want to use the manual mapping (.ForMember method by automapper)

Any idea how can I achieve this? Thanks in advance.

Body:
Follow the link naming-conventions

and add below lines to config.

Mapper.Initialize(cfg => {
  cfg.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
  cfg.DestinationMemberNamingConvention = new PascalCaseNamingConvention();
});

This would fix the issue.


问:
How a multidimensional array value assignation works in this case?
Why this function does not return an string with the first letter of each word on upper case?</p>

```<code>function titleCase(str) {
     str = str.split(' ');
     for (var i = 0; i < str.length; i++) {
         str[i][0] = str[i][0].toUpperCase();
         console.log(str);
     }
     return str;
}
</code>```

答:
"capitalizeText" method used to covert first character of string to uppercase.

```<code>String.prototype.capitalizeText = String.prototype.capitalizeText || function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
 // return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
}

function titleCase(str) {
     str = str.split(' ');

     for (var i = 0; i < str.length; i++) {
         str[i] = str[i].capitalizeText();
         console.log(str[i]);
     }

     return str.join(" ");
}

$(document).ready(function(){
        $('#divResult b').text(titleCase("testing words"));
});
</code>```

Demo

Body:
Why this function does not return an string with the first letter of each word on upper case?

function titleCase(str) {
     str = str.split(' ');
     for (var i = 0; i < str.length; i++) {
         str[i][0] = str[i][0].toUpperCase();
         console.log(str);
     }
     return str;
}

Body:
"capitalizeText" method used to covert first character of string to uppercase.

String.prototype.capitalizeText = String.prototype.capitalizeText || function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
 // return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
}

function titleCase(str) {
     str = str.split(' ');

     for (var i = 0; i < str.length; i++) {
         str[i] = str[i].capitalizeText();
         console.log(str[i]);
     }

     return str.join(" ");
}

$(document).ready(function(){
        $('#divResult b').text(titleCase("testing words"));
});

Demo


问:
Sharing AMP pages on Google products
If I share an amp page that validates with the AMP validator by the original URL on Google+ users are presented with a redirection warning. Why?

What is the correct way to share AMP pages on Google+? Am I supposed to be sharing the cache URL?

答: This seems to work fine without the redirect now. Not sure if I should blame a bad cache, lag on index, bad fetch...?</p>

Title: Sharing AMP pages on Google products


问:
Count (unique) views Spring boot REST
I'm working on a Spring boot application with RESTful services, JWT based authentication and react as front end.

I want to build in a counter that monitors the unique user requests (e.g. per day) to certain REST endpoints in my RestController and stores the current value to a column in the database.

Specifically I'd like to know how many users clicked on a certain article (api/articles/{id}) per day and bind that value to the entity.

Entity:

```<code>@Data
@Builder
@AllArgsConstructor
@RequiredArgsConstructor
@Entity
@Table(name = "Article")
public class Article{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "message_id", unique = true, nullable = false)
    private Long id;

    @Column(name = "visits")
    private Long visitCounter;

    ...
}
</code>```

Controller:

```<code>@RestController
@RequestMapping("/api/articles")
public class ArticleController {

    private AppUserService userService;
    private ArticleService articleService ;

    @Autowired
    public ArticleController (AppUserService userService, ArticleService articleService ) {
        this.userService = userService;
        this.articleService = articleService;
    }

    @GetMapping(value = "/{id}")
    public ResponseEntity<Article> getArticleById(@PathVariable(value = "id") Long  articleId) {
        Article article = articleService .getArticleById(articleId);
        if(article == null) {
            return ResponseEntity.notFound().build();
        }
         articleService.countVisit(); //???
         return ResponseEntity.ok().body(article);
    }
}

...
</code>```

Any ideas how something like that could be accomplished?

答:
Suppose you have application scoped bean ArticleCountService. The service should have a Map> for counters.

The key is article path (or id or something to identify your article). The value is set of users (e.g. IP addresses to identify unique users you can get from HttpServletRequest). At 23:59:999 you get the map data and create a new empty map.
That's the simplest solution but it could have memory impact.

The mode convenient way is to store something in DB. E.g.
ARTICLE_ID, USER_ID (IP), VISIT_DATE

And once a day aggregate the data (obsolete rows from yesterday could be removed after the calculating.)

Title: Count (unique) views Spring boot REST

Body:
I'm working on a Spring boot application with RESTful services, JWT based authentication and react as front end.

I want to build in a counter that monitors the unique user requests (e.g. per day) to certain REST endpoints in my RestController and stores the current value to a column in the database.

Specifically I'd like to know how many users clicked on a certain article (api/articles/{id}) per day and bind that value to the entity.

Entity:

@Data
@Builder
@AllArgsConstructor
@RequiredArgsConstructor
@Entity
@Table(name = "Article")
public class Article{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "message_id", unique = true, nullable = false)
    private Long id;

    @Column(name = "visits")
    private Long visitCounter;

    ...
}

Controller:

@RestController
@RequestMapping("/api/articles")
public class ArticleController {

    private AppUserService userService;
    private ArticleService articleService ;

    @Autowired
    public ArticleController (AppUserService userService, ArticleService articleService ) {
        this.userService = userService;
        this.articleService = articleService;
    }

    @GetMapping(value = "/{id}")
    public ResponseEntity
 getArticleById(@PathVariable(value = "id") Long  articleId) {
        Article article = articleService .getArticleById(articleId);
        if(article == null) {
            return ResponseEntity.notFound().build();
        }
         articleService.countVisit(); //???
         return ResponseEntity.ok().body(article);
    }
}

...

Any ideas how something like that could be accomplished?


问:
Sql issues when trying to upload using php

I'm trying to upload a video to a folder which is working but, the relevant entry in the DB isn't occurring to match it. Really having trouble seeing what's wrong, as no errors are reported.
</p>

```<code>    session_start();
    require 'db.php';
    $name = $_FILES['video']['name'];
    $uploader = $_SESSION['first_name'].$_SESSION['last_name'];
    $newstring = $_SESSION['last_name'].'_'.$_SESSION['first_name'].'_'.date('ymdhms').".mp4";
    $extension = strtolower(substr($name, strpos($name, '.') + 1));
    $size = $_FILES['video']['size'];
    $max_size = '1073741824';
    $type = $_FILES['video']['type'];
    $id = $_SESSION['id'];
    $date = date('Y-m-D');
    $tmp_name = $_FILES['video']['tmp_name'];

    if(!empty($name)){
        $location = "uploads/";

    if($extension=='mp4'&&$type == 'video/mp4'){
        if($size <= $max_size){
            if(move_uploaded_file($tmp_name, $location.$newstring)){
                $sql = "INSERT INTO videos (file_name, upload_by, date) VALUES
                   ('$newstring', '$id', '$date')";
                mysqli_query($mysqli, $sql);
                require('profile.php');
                $_SESSION['message'] = "Upload Successful!";
                header('Refresh:0; url=profile.php');
            }else{
                $_SESSION['message'] = "File failed to upload";
                header("location: error.php");
            }
</code>```

<p>
I'm not getting a corresponding DB entry. Any help would be really appreciated.
</p>

答:
Try this:</p>

```<code>$sql = "INSERT INTO videos (file_name, upload_by, date) VALUES
                   ('".$newstring."', '".$id."', '".$date."')";
</code>```

Body:
I'm trying to upload a video to a folder which is working but, the relevant entry in the DB isn't occurring to match it. Really having trouble seeing what's wrong, as no errors are reported.

    session_start();
    require 'db.php';
    $name = $_FILES['video']['name'];
    $uploader = $_SESSION['first_name'].$_SESSION['last_name'];
    $newstring = $_SESSION['last_name'].'_'.$_SESSION['first_name'].'_'.date('ymdhms').".mp4";
    $extension = strtolower(substr($name, strpos($name, '.') + 1));
    $size = $_FILES['video']['size'];
    $max_size = '1073741824';
    $type = $_FILES['video']['type'];
    $id = $_SESSION['id'];
    $date = date('Y-m-D');
    $tmp_name = $_FILES['video']['tmp_name'];

    if(!empty($name)){
        $location = "uploads/";

    if($extension=='mp4'&&$type == 'video/mp4'){
        if($size <= $max_size){
            if(move_uploaded_file($tmp_name, $location.$newstring)){
                $sql = "INSERT INTO videos (file_name, upload_by, date) VALUES
                   ('$newstring', '$id', '$date')";
                mysqli_query($mysqli, $sql);
                require('profile.php');
                $_SESSION['message'] = "Upload Successful!";
                header('Refresh:0; url=profile.php');
            }else{
                $_SESSION['message'] = "File failed to upload";
                header("location: error.php");
            }

I'm not getting a corresponding DB entry. Any help would be really appreciated.

Body:
Try this:

$sql = "INSERT INTO videos (file_name, upload_by, date) VALUES
                   ('".$newstring."', '".$id."', '".$date."')";


问:
How can I get the Moment album and all the personal albums in my collectionView?
I'm trying to use the Photos Framework. In my collectionView, I would like to display the poster image of the Camera Roll and Personal albums.

I'm trying to implement the code this way but I still see the same image for each album ... where am I doing wrong?

Here I place my code ... I hope someone can help me

```<code>//USER ALBUM
@property (nonatomic, strong) PHFetchResult *userAlbum;
@property (nonatomic, strong) PHAssetCollection *assetCollection;
@property (nonatomic, strong) PHAsset *asset;

-(void)viewDidLoad {
    [super viewDidLoad];

    PHFetchOptions *userAlbumsOptions = [[PHFetchOptions alloc] init];
    userAlbumsOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];

    self.userAlbum = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum | PHAssetCollectionTypeMoment  subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];

    for (NSInteger i =0; i < self.userAlbum.count; i++) {
        self.assetCollection = [self.userAlbum objectAtIndex:i];
        NSLog(@"%@",[self.assetCollection.localizedTitle uppercaseString]);

        PHFetchResult *fetchResult = [PHAsset fetchKeyAssetsInAssetCollection:self.assetCollection options:nil];
        self.asset = [fetchResult firstObject];
 }
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.userAlbum.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {

        KCCategoryCell *catCell = [collectionView dequeueReusableCellWithReuseIdentifier:categoryCellID forIndexPath:indexPath];

        CGFloat retina = [UIScreen mainScreen].scale;
        CGSize square = CGSizeMake(catCell.albumImage.bounds.size.width * retina, catCell.bounds.size.height * retina);

        [[PHImageManager defaultManager] requestImageForAsset:self.asset targetSize:square  contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                catCell.albumImage.image = result;
        }];

        return catCell;
}
</code>```

答:
The reason to why you're seeing the same image is because you're requesting the same asset for all of your indexes:

```<code>-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {

    KCCategoryCell *catCell = [collectionView dequeueReusableCellWithReuseIdentifier:categoryCellID forIndexPath:indexPath];

    CGFloat retina = [UIScreen mainScreen].scale;
    CGSize square = CGSizeMake(catCell.albumImage.bounds.size.width * retina, catCell.bounds.size.height * retina);

    [[PHImageManager defaultManager] requestImageForAsset:self.asset // <-- Right here
                                               targetSize:square  contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        catCell.albumImage.image = result;
    }];

    return catCell;
}
</code>```

So instead of doing that, do this:

1) Change @property (nonatomic, strong) PHAsset *asset; to @property (nonatomic, strong) PHFetchResult *assets;

2) Instead of doing this:

```<code>PHFetchResult *fetchResult = [PHAsset fetchKeyAssetsInAssetCollection:self.assetCollection options:nil];
self.asset = [fetchResult firstObject];
</code>```

Do this:

```<code>self.assets = [PHAsset fetchKeyAssetsInAssetCollection:self.assetCollection options:nil];
</code>```

3) Lastly, instead of doing this:

```<code>[[PHImageManager defaultManager] requestImageForAsset:self.asset
                                           targetSize:square contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
   catCell.albumImage.image = result;
}];
</code>```

Do this:

```<code>[[PHImageManager defaultManager] requestImageForAsset:self.assets[indexPath.row]
                                           targetSize:square contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
   catCell.albumImage.image = result;
}];
</code>```

To recap:

You're fetching the same image (self.asset) over and over again, for all the cells. So, instead, make a property for all of the assets and fetch the right asset for the right cell.

Body:
I'm trying to use the Photos Framework. In my collectionView, I would like to display the poster image of the Camera Roll and Personal albums.

I'm trying to implement the code this way but I still see the same image for each album ... where am I doing wrong?

Here I place my code ... I hope someone can help me

//USER ALBUM
@property (nonatomic, strong) PHFetchResult *userAlbum;
@property (nonatomic, strong) PHAssetCollection *assetCollection;
@property (nonatomic, strong) PHAsset *asset;

-(void)viewDidLoad {
    [super viewDidLoad];

    PHFetchOptions *userAlbumsOptions = [[PHFetchOptions alloc] init];
    userAlbumsOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];

    self.userAlbum = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum | PHAssetCollectionTypeMoment  subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];

    for (NSInteger i =0; i < self.userAlbum.count; i++) {
        self.assetCollection = [self.userAlbum objectAtIndex:i];
        NSLog(@"%@",[self.assetCollection.localizedTitle uppercaseString]);

        PHFetchResult *fetchResult = [PHAsset fetchKeyAssetsInAssetCollection:self.assetCollection options:nil];
        self.asset = [fetchResult firstObject];
 }
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.userAlbum.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {

        KCCategoryCell *catCell = [collectionView dequeueReusableCellWithReuseIdentifier:categoryCellID forIndexPath:indexPath];

        CGFloat retina = [UIScreen mainScreen].scale;
        CGSize square = CGSizeMake(catCell.albumImage.bounds.size.width * retina, catCell.bounds.size.height * retina);

        [[PHImageManager defaultManager] requestImageForAsset:self.asset targetSize:square  contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                catCell.albumImage.image = result;
        }];

        return catCell;
}

Body:
The reason to why you're seeing the same image is because you're requesting the same asset for all of your indexes:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {

    KCCategoryCell *catCell = [collectionView dequeueReusableCellWithReuseIdentifier:categoryCellID forIndexPath:indexPath];

    CGFloat retina = [UIScreen mainScreen].scale;
    CGSize square = CGSizeMake(catCell.albumImage.bounds.size.width * retina, catCell.bounds.size.height * retina);

    [[PHImageManager defaultManager] requestImageForAsset:self.asset // <-- Right here
                                               targetSize:square  contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        catCell.albumImage.image = result;
    }];

    return catCell;
}

So instead of doing that, do this:

1) Change @property (nonatomic, strong) PHAsset *asset; to @property (nonatomic, strong) PHFetchResult *assets;

2) Instead of doing this:

PHFetchResult *fetchResult = [PHAsset fetchKeyAssetsInAssetCollection:self.assetCollection options:nil];
self.asset = [fetchResult firstObject];

Do this:

self.assets = [PHAsset fetchKeyAssetsInAssetCollection:self.assetCollection options:nil];

3) Lastly, instead of doing this:

[[PHImageManager defaultManager] requestImageForAsset:self.asset
                                           targetSize:square contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
   catCell.albumImage.image = result;
}];

Do this:

[[PHImageManager defaultManager] requestImageForAsset:self.assets[indexPath.row]
                                           targetSize:square contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
   catCell.albumImage.image = result;
}];

To recap:

You're fetching the same image (self.asset) over and over again, for all the cells. So, instead, make a property for all of the assets and fetch the right asset for the right cell.


问:
what is wrong with this code of login validate form using php
In this code login page is going to validate form and if password is correct then its working correct but if not then its not working else code why?
Here is code

```<code><?php
    if(isset($_POST['submit']))
    {
        $user=$_POST['user'];
        $password=$_POST['password'];
        $query="select * from users where user='$user' and password='$password'";
        $run=mysqli_query($con,$query);
        if(mysqli_num_rows($run)>0){
            $row=mysqli_fetch_array($run);
            $u_name=$row['user'];
            $u_password=$row['password'];
            if($user==$u_name && $password==$u_password){
                if(isset($_POST['remember'])){
                    setcookie('user',$user,time()+60*60*7);
                    setcookie('password',$password,time()+60*60*7);
                }
                session_start();
                $_SESSION['user']=$user;
                echo "<script> window.location.assign('../index.php'); </script>";
                exit();
            }
            else{
                echo "<script> alert('incorrect user name or password')</script>";
                echo "<script> window.location.assign('login.php'); </script>";
            }
        }
    }
?>
</code>```

if condition  part is working correctly but not else condition  part .help me please.

答:
The answer of your question is because you have the alert js inside the if statement where it will be executed only if there is more than 0 rows returned.

Please hash your users passwords.
Please use prepared statements to use with users input on DB query.
Echoing JS like that aint cool but its up to you if you want use it.

Body:
In this code login page is going to validate form and if password is correct then its working correct but if not then its not working else code why?
Here is code

<?php
    if(isset($_POST['submit']))
    {
        $user=$_POST['user'];
        $password=$_POST['password'];
        $query="select * from users where user='$user' and password='$password'";
        $run=mysqli_query($con,$query);
        if(mysqli_num_rows($run)>0){
            $row=mysqli_fetch_array($run);
            $u_name=$row['user'];
            $u_password=$row['password'];
            if($user==$u_name && $password==$u_password){
                if(isset($_POST['remember'])){
                    setcookie('user',$user,time()+60*60*7);
                    setcookie('password',$password,time()+60*60*7);
                }
                session_start();
                $_SESSION['user']=$user;
                echo "";
                exit();
            }
            else{
                echo "";
                echo "";
            }
        }
    }
?>

if condition  part is working correctly but not else condition  part .help me please.


问:
Public SSL certificate Error
We have done the setup for JIRA with Jenkins. From Jira side, it displayed Jenkins job but from Jenkins side not able to connect Jira. SSL certificate issue is getting displayed

Requirement:  Jenkins integration with Jira.

1)      Jenkins should be integrated with Jira

2)      update tickets automatically when a job is built successfully or failed.

3)      Create bug in Jira if test failed

Done Till Now.

1)       Created code to run the test using mvn and SVN

2)      Integrated SVN to Jenkins [working fine]

3)      Install Jira plugin, JiraTestResultReporter, Jiraissueupdater

Please help me to get public SSL certificate

答:
Try these steps!

Step 1 : Get root certificate of https://www.google.com

Open https://www.google.com in a chrome browser.

Select Inspect from context menu(right clicking on page) and navigate to security tab

Click on view certificates

Click on top most certificate on hierarchy and confirm it is tailed with Root CA phrase.

drag and drop that image which you saw written certificate on desktop.

Thats it! you got your root certificate!

Step 2 : install certificate to your java cacerts

please verify you have system variable JAVA_HOME declared and you will perform these steps on that jre cacerts only!

Navigate to cacerts by JAVA_HOME/jre/lib/security/cacerts

Download and install keytool explorer it is available for all platforms

open cacerts in that tool and import cetificate by "import trusted certificate" button.

Save your changes (you may come across issue if it is mac and you do not have write access!)

Step 3 : Restart jenkins

You should not get ssl handshake problem now onwards.

Title: Public SSL certificate Error


问:
Iterate in jquery to get values of input text
I have three rows of which I want to get the values of all the text by looping them all, so I tried something like this.

```<code>var collection = $(".vendorDaterow");
collection.each(function() {});
</code>```

But while debugging i didn't find the value in any of the property.

Below is my html

```<code><tr>
  <td>
    <div class="row noPadding vendorForm">
      <div class="vendorDaterow">
        <div class="vendorName" id="dvVendorNameData">
          <label>SP Vender Name</label><span><input type="text" name="nmVendorData" id="txtVendorName" /></span>
        </div>
        <div class="vendorFromDate">
          <label>From Date</label><span class="datepicker"><input type="text" name="spFromDate" id="spFromDate" class="dateClass" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
        </div>
        <div class="vendorToDate">
          <label>To Date</label><span class="datepicker"><input type="text" name="spToDate" id="spToDate" class="dateClass1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
        </div>
      </div>
      <div class="add">
        <i class="fa fa-plus" aria-hidden="true"></i>
      </div>
      <i class="max"><label>(Maximum 5 Vendors)</label></i>
    </div>
  </td>
</tr>
</code>```

What should I do to get the values of the input text of all the element

答:
The following snippet prints only the input value when it changes. We use the selector $(".vendorDaterow") and the delegation event on the input that have changed.

$(".vendorDaterow").on('change', 'input', function(){
    var text = $(this).val();
    console.log(text);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td>
                                <div class="row noPadding vendorForm">
                                    <div class="vendorDaterow">
                                        <div class="vendorName" id="dvVendorNameData">
                                            <label>SP Vender Name</label><span><input type="text" name="nmVendorData" id="txtVendorName" /></span>
                                        </div>
                                        <div class="vendorFromDate">
                                            <label>From Date</label><span class="datepicker"><input type="text" name="spFromDate" id="spFromDate" class="dateClass" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                                        </div>
                                        <div class="vendorToDate">
                                            <label>To Date</label><span class="datepicker"><input type="text" name="spToDate" id="spToDate" class="dateClass1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                                        </div>
                                    </div>
                                    <div class="add">
                                        <i class="fa fa-plus" aria-hidden="true"></i>
                                    </div>
                                    <i class="max"><label>(Maximum 5 Vendors)</label></i>
                                </div>
                            </td>
                        </tr></code>```

The snippet below prints all the input values after a change. After a change in an input, each() will loop over all the input elements inside the class vendorDaterow and get their values.

var save;
$(".vendorDaterow input").on("change",function(){
save = []
$(".vendorDaterow input").each(function(){
  var text = $(this).val();
  if(text){
    save.push(text);
  }
})
console.log(save);
})

//console.log($(".vendorDaterow").html())```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
    <td>
        <div class="row noPadding vendorForm">
            <div class="vendorDaterow">
                <div class="vendorName" id="dvVendorNameData">
                    <label>SP Vender Name</label><span><input type="text" name="nmVendorData" id="txtVendorName" /></span>
                </div>
                <div class="vendorFromDate">
                    <label>From Date</label><span class="datepicker"><input type="text" name="spFromDate" id="spFromDate" class="dateClass" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                </div>
                <div class="vendorToDate">
                    <label>To Date</label><span class="datepicker"><input type="text" name="spToDate" id="spToDate" class="dateClass1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                </div>
            </div>
            <div class="add">
                <i class="fa fa-plus" aria-hidden="true"></i>
            </div>
            <i class="max"><label>(Maximum 5 Vendors)</label></i>
        </div>
    </td></code>```

Body:
I have three rows of which I want to get the values of all the text by looping them all, so I tried something like this.

var collection = $(".vendorDaterow");
collection.each(function() {});

But while debugging i didn't find the value in any of the property.

Below is my html

          SP Vender Name<input type="text" name="nmVendorData" id="txtVendorName" />

          From Date<input type="text" name="spFromDate" id="spFromDate" class="dateClass" />

          To Date<input type="text" name="spToDate" id="spToDate" class="dateClass1" />

      (Maximum 5 Vendors)

What should I do to get the values of the input text of all the element

Body:
The following snippet prints only the input value when it changes. We use the selector $(".vendorDaterow") and the delegation event on the input that have changed.

$(".vendorDaterow").on('change', 'input', function(){
    var text = $(this).val();
    console.log(text);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td>
                                <div class="row noPadding vendorForm">
                                    <div class="vendorDaterow">
                                        <div class="vendorName" id="dvVendorNameData">
                                            <label>SP Vender Name</label><span><input type="text" name="nmVendorData" id="txtVendorName" /></span>
                                        </div>
                                        <div class="vendorFromDate">
                                            <label>From Date</label><span class="datepicker"><input type="text" name="spFromDate" id="spFromDate" class="dateClass" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                                        </div>
                                        <div class="vendorToDate">
                                            <label>To Date</label><span class="datepicker"><input type="text" name="spToDate" id="spToDate" class="dateClass1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                                        </div>
                                    </div>
                                    <div class="add">
                                        <i class="fa fa-plus" aria-hidden="true"></i>
                                    </div>
                                    <i class="max"><label>(Maximum 5 Vendors)</label></i>
                                </div>
                            </td>
                        </tr>

The snippet below prints all the input values after a change. After a change in an input, each() will loop over all the input elements inside the class vendorDaterow and get their values.

var save;
$(".vendorDaterow input").on("change",function(){
save = []
$(".vendorDaterow input").each(function(){
  var text = $(this).val();
  if(text){
    save.push(text);
  }
})
console.log(save);
})

//console.log($(".vendorDaterow").html())

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
    <td>
        <div class="row noPadding vendorForm">
            <div class="vendorDaterow">
                <div class="vendorName" id="dvVendorNameData">
                    <label>SP Vender Name</label><span><input type="text" name="nmVendorData" id="txtVendorName" /></span>
                </div>
                <div class="vendorFromDate">
                    <label>From Date</label><span class="datepicker"><input type="text" name="spFromDate" id="spFromDate" class="dateClass" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                </div>
                <div class="vendorToDate">
                    <label>To Date</label><span class="datepicker"><input type="text" name="spToDate" id="spToDate" class="dateClass1" /><i class="fa fa-calendar" aria-hidden="true"></i></span>
                </div>
            </div>
            <div class="add">
                <i class="fa fa-plus" aria-hidden="true"></i>
            </div>
            <i class="max"><label>(Maximum 5 Vendors)</label></i>
        </div>
    </td>


问:
How to calculate accurate distance travelled by the user using google maps?
I am having two doubts because today only i started doing projects on google maps my first doubt is

How to calculate distance traveled by user when using google maps ?

like how taxi app is calculating the distance, now let me explain my problem in depth regarding this question i have checkin and check out button in map when user click the checkin button i will take that exact lat and long of that user when user checkout i will fetch the lat and long from where he checked out, after i will send this source latlong and destination latlong to google api this will return the kilometer. But what i need is wherever he traveled he may traveled extra bit of kilometer i need to calculate that also how can i do that.

My second doubt is my google maps taking long time to plot the blue mark  in my map it shows searching for gps in notification bar how can i achieve this ?

Below is my complete Code

VisitTravel.java

```<code>public class VisitTravel extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
  GoogleApiClient.OnConnectionFailedListener,
  LocationListener {
    private List < LatLng > obj;
    private GoogleMap mGoogleMap;
    private Double latitue, longtitue, Start_lat, Start_long;
    private SupportMapFragment mapFrag;
    private LocationRequest mLocationRequest;
    private GoogleApiClient mGoogleApiClient;
    private Location mLastLocation;
    private ImageView cancel_bottomsheet;
    protected static final int REQUEST_CHECK_SETTINGS = 0x1;

    private Bundle bundle;
    private ProgressDialog progressDialog;
    private String Checkin, parsedDistance, duration, JsonResponse;
    private VisitDAO visitDAO;
    private Long primaryID;
    private ArrayList < LatLng > points;
    private Integer id, flag, incidentid, userid;
    private TextView heading, duration_textview, dot_source, destination, distance;
    private PowerManager.WakeLock wakeLock;
    private BottomSheetBehavior bottomSheetBehavior;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_visit_travel);
      // Obtain the SupportMapFragment and get notified when the map is ready to be used.
      mapFrag = (SupportMapFragment) getSupportFragmentManager()
        .findFragmentById(R.id.map);
      mapFrag.getMapAsync(this);
      InternetCheck internetCheck = new InternetCheck();
      boolean check = internetCheck.isNetworkAvailable(VisitTravel.this);
      if (!check) {
        showAlertDialog();
      } else {
        createLocationRequest();
        buildGoogleApiClient();
        Settingsapi();
        progressDialog = new ProgressDialog(VisitTravel.this);
        //  polylineOptions = new PolylineOptions();
        cancel_bottomsheet = (ImageView) findViewById(R.id.cancel);
        heading = (TextView) findViewById(R.id.heading);
        dot_source = (TextView) findViewById(R.id.dot_source);
        distance = (TextView) findViewById(R.id.distance);
        duration_textview = (TextView) findViewById(R.id.duration);
        destination = (TextView) findViewById(R.id.destination);
        progressDialog.setMessage("Fetching Location Updates");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.show();
        View bottomSheet = findViewById(R.id.bottom_sheet);
        LoginDAO loginobj = new LoginDAO(this);
        userid = loginobj.getUserID();
        bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
        cancel_bottomsheet.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
          }
        });
        bundle = getIntent().getExtras();
        if (bundle != null) {
          flag = bundle.getInt("flag");
          latitue = bundle.getDouble("destination_lat");
          longtitue = bundle.getDouble("destination_long");
          incidentid = bundle.getInt("incidentid");
          if (flag == 1) {

          } else {
            //  time = bundle.getString("checkin");
            id = bundle.getInt("id");
            incidentid = bundle.getInt("incidentid");
            Start_lat = bundle.getDouble("lat");
            Checkin = bundle.getString("checkin");
            Start_long = bundle.getDouble("long");
            String address = bundle.getString("startaddress");
            String distance = bundle.getString("estimateddistance");
            setBottomSheet(address, distance);
          }
        }
        obj = new ArrayList < > ();
        final FloatingActionButton startfab = (FloatingActionButton) findViewById(R.id.start);
        final FloatingActionButton stopfab = (FloatingActionButton) findViewById(R.id.stopfab);
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
          "WakelockTag");
        wakeLock.acquire();
        visitDAO = new VisitDAO(getApplicationContext());
        if (flag == 2) {
          startfab.setVisibility(View.INVISIBLE);
        }
        startfab.setBackgroundResource(R.drawable.ic_play_circle_outline_black_24dp);
        final SharedPreferences preferences = getSharedPreferences("lat_long", Context.MODE_PRIVATE);
        startfab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              if (mLastLocation != null) {
                String checkin_to_server = dateFormat.format(new Date());
                Date date = null;
                try {
                  date = dateFormat.parse(checkin_to_server);
                } catch (ParseException e) {
                  e.printStackTrace();
                }

                String checkin_view = dateview.format(date);
                double startinglat = mLastLocation.getLatitude();
                double startinglong = mLastLocation.getLongitude();
                //        String addres=address(startinglat,startinglong);
                String jsonresponse = null;
                try {
                  jsonresponse = new GetDistance().execute(startinglat, startinglong, 12.951601, 80.184641).get();
                } catch (InterruptedException e) {
                  e.printStackTrace();
                } catch (ExecutionException e) {
                  e.printStackTrace();
                }
                ParserTask parserTask = new ParserTask();
                if (jsonresponse != null) {
                  Log.d("responsejson", jsonresponse);
                  parserTask.execute(jsonresponse);
                }
                JSONObject jsonObject = null;
                try {
                  jsonObject = new JSONObject(jsonresponse);
                } catch (JSONException e) {
                  e.printStackTrace();
                }

                //Here il save the userlocation in db
              } catch (JSONException e) {
                e.printStackTrace();
              }
            } else {
              Toast.makeText(getApplicationContext(), "Please Wait Till We Recieve Location Updates", Toast.LENGTH_SHORT).show();

            }

          }
        });
      stopfab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          if (mLastLocation != null) {
            double lat = mLastLocation.getLatitude();
            double longt = mLastLocation.getLongitude();
            String startlat = preferences.getString("startlat", "");
            Log.d("startlat", startlat);
            String startlong = preferences.getString("startlong", "");
            // Calculating distance
            String distance = getKilometer(Double.valueOf(startlat), Double.valueOf(startlong), lat, longt);
            Intent intent = new Intent(VisitTravel.this, IncidentView.class);
            setResult(RESULT_OK, intent);
            finish();
          } else {
            Toast.makeText(getApplicationContext(), "Please Wait Fetching Location", Toast.LENGTH_SHORT).show();
          }
        }
      });
    }
  }

@Override
public void onStart() {
  super.onStart();
  Log.d("start", "onStart fired ..............");
  mGoogleApiClient.connect();
}

private void showAlertDialog() {
  AlertDialog.Builder builder = new AlertDialog.Builder(VisitTravel.this);
  builder.setTitle("Network Connectivity")
    .setMessage("Please Check Your Network Connectivity")
    .setCancelable(false)
    .setNegativeButton("Close", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int id) {
        Intent intent = new Intent(getApplicationContext(), IncidentView.class);
        setResult(RESULT_OK, intent);
        finish();
      }
    });
  AlertDialog alert = builder.create();
  alert.show();
}

@Override
public void onPause() {
  super.onPause();
  //  progressDialog.dismiss();
  if (wakeLock.isHeld()) {
    wakeLock.release();
  }
  //stop location updates when Activity is no longer active
  if (mGoogleApiClient.isConnected()) {
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    mGoogleApiClient.disconnect();
  }
}

@Override
public void onMapReady(GoogleMap googleMap) {
  mGoogleMap = googleMap;
  mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
  map_marker_End(12.951601, 80.184641, "Destination");
  if (flag == 2) {
    map_marker_start(Start_lat, Start_long, Checkin);
  }
  //Initialize Google Play Services
  if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (ContextCompat.checkSelfPermission(this,
        android.Manifest.permission.ACCESS_FINE_LOCATION) ==
      PackageManager.PERMISSION_GRANTED) {
      //Location Permission already granted
      createLocationRequest();
      buildGoogleApiClient();
      mGoogleMap.setMyLocationEnabled(true);
    } else {
      //Request Location Permission
      checkLocationPermission();
    }
  } else {
    buildGoogleApiClient();
    mGoogleMap.setMyLocationEnabled(true);
  }

}

protected synchronized void buildGoogleApiClient() {

  mGoogleApiClient = new GoogleApiClient.Builder(this)
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .addApi(LocationServices.API)
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .build();
  mGoogleApiClient.connect();

}

protected void createLocationRequest() {
  mLocationRequest = new LocationRequest();
  mLocationRequest.setInterval(1000 * 10);
  mLocationRequest.setFastestInterval(1000 * 5);
  mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

@Override
public void onConnected(Bundle bundle) {

  startLocationUpdates();
}

protected void startLocationUpdates() {
  if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    // TODO: Consider calling
    Toast.makeText(this, "LocationNotUpdated", Toast.LENGTH_SHORT).show();
    ActivityCompat.requestPermissions(VisitTravel.this,
      new String[] {
        android.Manifest.permission
          .ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION
      },
      20);

  } else {
    if (mGoogleApiClient.isConnected()) {
      LocationServices.FusedLocationApi.requestLocationUpdates(
        mGoogleApiClient, mLocationRequest, this);
      Log.d("Loc", "Location update started ..............: ");
      //       Toast.makeText(this, "LocationUpdatedStart", Toast.LENGTH_SHORT).show();
    }
  }
}

@Override
public void onConnectionSuspended(int i) {}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

public void map_marker_start(Double lat, Double longt, String title) {
  MarkerOptions markerOptions = new MarkerOptions();
  LatLng latLng = new LatLng(lat, longt);
  Log.d("lat", String.valueOf(latLng.longitude));
  markerOptions.position(latLng);
  markerOptions.title(title);
  markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
  mGoogleMap.addMarker(markerOptions).showInfoWindow();

}

public void map_marker_End(Double lat, Double longt, String title) {
  final MarkerOptions markerOptions_end = new MarkerOptions();
  LatLng latLng = new LatLng(lat, longt);
  Log.d("lat", String.valueOf(latLng.longitude));
  markerOptions_end.position(latLng);
  markerOptions_end.title(title);
  markerOptions_end.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
  mGoogleMap.addMarker(markerOptions_end).showInfoWindow();
  mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
    @Override
    public boolean onMarkerClick(Marker marker) {
      String title = marker.getTitle();
      if (title.equals("Destination")) {
        dot_source.setText("\u2022");
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
        heading.setText("TEST");
        duration_textview.setText("Duration:" + " " + duration);
        return true;
      } else {
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
        return true;

      }

    }
  });

}

@Override
public void onLocationChanged(Location location) {
  mLastLocation = location;
  PolylineOptions polylineOptions = new PolylineOptions();
  Log.d("location", mLastLocation.toString());
  LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
  obj.add(latLng);
  polylineOptions.addAll(obj);
  polylineOptions.width(9);
  polylineOptions.color(Color.parseColor("#2196f3"));
  mGoogleMap.addPolyline(polylineOptions);
  progressDialog.dismiss();
  mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
  CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
    latLng, 12);
  mGoogleMap.animateCamera(cameraUpdate);
}

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

private void checkLocationPermission() {
  if (ContextCompat.checkSelfPermission(VisitTravel.this, android.Manifest.permission.ACCESS_FINE_LOCATION) !=
    PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(this,
        android.Manifest.permission.ACCESS_FINE_LOCATION)) {

      // Show an explanation to the user *asynchronously* -- don't block
      // this thread waiting for the user's response! After the user
      // sees the explanation, try again to request the permission.
      new AlertDialog.Builder(this)
        .setTitle("Location Permission Needed")
        .setMessage("This app needs the Location permission, please accept to use location functionality")
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialogInterface, int i) {
            //Prompt the user once explanation has been shown
            ActivityCompat.requestPermissions(VisitTravel.this,
              new String[] {
                android.Manifest.permission.ACCESS_FINE_LOCATION
              },
              MY_PERMISSIONS_REQUEST_LOCATION);
          }
        })
        .create()
        .show();

    } else {
      // No explanation needed, we can request the permission.
      ActivityCompat.requestPermissions(this,
        new String[] {
          android.Manifest.permission.ACCESS_FINE_LOCATION
        },
        MY_PERMISSIONS_REQUEST_LOCATION);
    }
  }
}

@Override
public void onRequestPermissionsResult(int requestCode,
  String permissions[], int[] grantResults) {
  switch (requestCode) {
    case MY_PERMISSIONS_REQUEST_LOCATION:
      {
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0 &&
          grantResults[0] == PackageManager.PERMISSION_GRANTED) {

          // permission was granted, yay! Do the
          // location-related task you need to do.
          if (ContextCompat.checkSelfPermission(this,
              android.Manifest.permission.ACCESS_FINE_LOCATION) ==
            PackageManager.PERMISSION_GRANTED) {

            if (mGoogleApiClient == null) {
              buildGoogleApiClient();
            }
            createLocationRequest();
            ///  buildGoogleApiClient();
            //  Settingsapi();
            mGoogleMap.setMyLocationEnabled(true);
          }

        } else {

          // permission denied, boo! Disable the
          // functionality that depends on this permission.
          Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
        }
        return;
      }

      // other 'case' lines to check for other
      // permissions this app might request
  }
}

public String getKilometer(final double lat1, final double lon1, final double lat2, final double lon2) {
  Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
      try {
        URL url = new URL("http://maps.googleapis.com/maps/api/directions/json?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric&mode=driving");
        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        InputStream in = new BufferedInputStream(conn.getInputStream());
        StringBuilder buffer = new StringBuilder();
        BufferedReader reader = null;
        reader = new BufferedReader(new InputStreamReader( in ));
        String inputLine;
        while ((inputLine = reader.readLine()) != null)
          buffer.append(inputLine + "\n");
        if (buffer.length() == 0) {
          // Stream was empty. No point in parsing.
          Log.e("empty", "empty");
        }
        JsonResponse = buffer.toString();
        Log.d("response", JsonResponse);
        JSONObject jsonObject = new JSONObject(JsonResponse);
        JSONArray array = jsonObject.getJSONArray("routes");
        JSONObject routes = array.getJSONObject(0);
        JSONArray legs = routes.getJSONArray("legs");
        JSONObject steps = legs.getJSONObject(0);
        JSONObject distance = steps.getJSONObject("distance");
        parsedDistance = distance.getString("text");

      } catch (ProtocolException e) {
        e.printStackTrace();
      } catch (MalformedURLException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
  });
  thread.start();
  try {
    thread.join();
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
  return parsedDistance;
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  switch (requestCode) {
    // Check for the integer request code originally supplied to startResolutionForResult().
    case REQUEST_CHECK_SETTINGS:
      switch (resultCode) {
        case Activity.RESULT_OK:
          startLocationUpdates();
          break;
        case Activity.RESULT_CANCELED:
          Intent intent = new Intent(this, Incident.class);
          startActivity(intent);
          break;
      }
      break;
  }
}

@Override
protected void onStop() {
  super.onStop();
  if (wakeLock.isHeld()) {
    wakeLock.release();
  }

}

@Override
public void onBackPressed() {
  super.onBackPressed();
  Intent intent = new Intent(this, IncidentView.class);
  if (mGoogleApiClient.isConnected()) {
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    mGoogleApiClient.disconnect();
  }
  intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
  setResult(RESULT_OK, intent);
  finish();
}
}
</code>```

Searched alot and not getting proper way to start with? Any help would really valuable.

--Thanks!

答:
This worked for me:

Capture the latitude and longitude at regular intervals and store. Calculate and sum the distance between each stored value.

Body:
I am having two doubts because today only i started doing projects on google maps my first doubt is

How to calculate distance traveled by user when using google maps ?

like how taxi app is calculating the distance, now let me explain my problem in depth regarding this question i have checkin and check out button in map when user click the checkin button i will take that exact lat and long of that user when user checkout i will fetch the lat and long from where he checked out, after i will send this source latlong and destination latlong to google api this will return the kilometer. But what i need is wherever he traveled he may traveled extra bit of kilometer i need to calculate that also how can i do that.

My second doubt is my google maps taking long time to plot the blue mark  in my map it shows searching for gps in notification bar how can i achieve this ?

Below is my complete Code

VisitTravel.java

public class VisitTravel extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
  GoogleApiClient.OnConnectionFailedListener,
  LocationListener {
    private List < LatLng > obj;
    private GoogleMap mGoogleMap;
    private Double latitue, longtitue, Start_lat, Start_long;
    private SupportMapFragment mapFrag;
    private LocationRequest mLocationRequest;
    private GoogleApiClient mGoogleApiClient;
    private Location mLastLocation;
    private ImageView cancel_bottomsheet;
    protected static final int REQUEST_CHECK_SETTINGS = 0x1;

    private Bundle bundle;
    private ProgressDialog progressDialog;
    private String Checkin, parsedDistance, duration, JsonResponse;
    private VisitDAO visitDAO;
    private Long primaryID;
    private ArrayList < LatLng > points;
    private Integer id, flag, incidentid, userid;
    private TextView heading, duration_textview, dot_source, destination, distance;
    private PowerManager.WakeLock wakeLock;
    private BottomSheetBehavior bottomSheetBehavior;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_visit_travel);
      // Obtain the SupportMapFragment and get notified when the map is ready to be used.
      mapFrag = (SupportMapFragment) getSupportFragmentManager()
        .findFragmentById(R.id.map);
      mapFrag.getMapAsync(this);
      InternetCheck internetCheck = new InternetCheck();
      boolean check = internetCheck.isNetworkAvailable(VisitTravel.this);
      if (!check) {
        showAlertDialog();
      } else {
        createLocationRequest();
        buildGoogleApiClient();
        Settingsapi();
        progressDialog = new ProgressDialog(VisitTravel.this);
        //  polylineOptions = new PolylineOptions();
        cancel_bottomsheet = (ImageView) findViewById(R.id.cancel);
        heading = (TextView) findViewById(R.id.heading);
        dot_source = (TextView) findViewById(R.id.dot_source);
        distance = (TextView) findViewById(R.id.distance);
        duration_textview = (TextView) findViewById(R.id.duration);
        destination = (TextView) findViewById(R.id.destination);
        progressDialog.setMessage("Fetching Location Updates");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.show();
        View bottomSheet = findViewById(R.id.bottom_sheet);
        LoginDAO loginobj = new LoginDAO(this);
        userid = loginobj.getUserID();
        bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
        cancel_bottomsheet.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
          }
        });
        bundle = getIntent().getExtras();
        if (bundle != null) {
          flag = bundle.getInt("flag");
          latitue = bundle.getDouble("destination_lat");
          longtitue = bundle.getDouble("destination_long");
          incidentid = bundle.getInt("incidentid");
          if (flag == 1) {

          } else {
            //  time = bundle.getString("checkin");
            id = bundle.getInt("id");
            incidentid = bundle.getInt("incidentid");
            Start_lat = bundle.getDouble("lat");
            Checkin = bundle.getString("checkin");
            Start_long = bundle.getDouble("long");
            String address = bundle.getString("startaddress");
            String distance = bundle.getString("estimateddistance");
            setBottomSheet(address, distance);
          }
        }
        obj = new ArrayList < > ();
        final FloatingActionButton startfab = (FloatingActionButton) findViewById(R.id.start);
        final FloatingActionButton stopfab = (FloatingActionButton) findViewById(R.id.stopfab);
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
          "WakelockTag");
        wakeLock.acquire();
        visitDAO = new VisitDAO(getApplicationContext());
        if (flag == 2) {
          startfab.setVisibility(View.INVISIBLE);
        }
        startfab.setBackgroundResource(R.drawable.ic_play_circle_outline_black_24dp);
        final SharedPreferences preferences = getSharedPreferences("lat_long", Context.MODE_PRIVATE);
        startfab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              if (mLastLocation != null) {
                String checkin_to_server = dateFormat.format(new Date());
                Date date = null;
                try {
                  date = dateFormat.parse(checkin_to_server);
                } catch (ParseException e) {
                  e.printStackTrace();
                }

                String checkin_view = dateview.format(date);
                double startinglat = mLastLocation.getLatitude();
                double startinglong = mLastLocation.getLongitude();
                //        String addres=address(startinglat,startinglong);
                String jsonresponse = null;
                try {
                  jsonresponse = new GetDistance().execute(startinglat, startinglong, 12.951601, 80.184641).get();
                } catch (InterruptedException e) {
                  e.printStackTrace();
                } catch (ExecutionException e) {
                  e.printStackTrace();
                }
                ParserTask parserTask = new ParserTask();
                if (jsonresponse != null) {
                  Log.d("responsejson", jsonresponse);
                  parserTask.execute(jsonresponse);
                }
                JSONObject jsonObject = null;
                try {
                  jsonObject = new JSONObject(jsonresponse);
                } catch (JSONException e) {
                  e.printStackTrace();
                }

                //Here il save the userlocation in db
              } catch (JSONException e) {
                e.printStackTrace();
              }
            } else {
              Toast.makeText(getApplicationContext(), "Please Wait Till We Recieve Location Updates", Toast.LENGTH_SHORT).show();

            }

          }
        });
      stopfab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          if (mLastLocation != null) {
            double lat = mLastLocation.getLatitude();
            double longt = mLastLocation.getLongitude();
            String startlat = preferences.getString("startlat", "");
            Log.d("startlat", startlat);
            String startlong = preferences.getString("startlong", "");
            // Calculating distance
            String distance = getKilometer(Double.valueOf(startlat), Double.valueOf(startlong), lat, longt);
            Intent intent = new Intent(VisitTravel.this, IncidentView.class);
            setResult(RESULT_OK, intent);
            finish();
          } else {
            Toast.makeText(getApplicationContext(), "Please Wait Fetching Location", Toast.LENGTH_SHORT).show();
          }
        }
      });
    }
  }

@Override
public void onStart() {
  super.onStart();
  Log.d("start", "onStart fired ..............");
  mGoogleApiClient.connect();
}

private void showAlertDialog() {
  AlertDialog.Builder builder = new AlertDialog.Builder(VisitTravel.this);
  builder.setTitle("Network Connectivity")
    .setMessage("Please Check Your Network Connectivity")
    .setCancelable(false)
    .setNegativeButton("Close", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int id) {
        Intent intent = new Intent(getApplicationContext(), IncidentView.class);
        setResult(RESULT_OK, intent);
        finish();
      }
    });
  AlertDialog alert = builder.create();
  alert.show();
}

@Override
public void onPause() {
  super.onPause();
  //  progressDialog.dismiss();
  if (wakeLock.isHeld()) {
    wakeLock.release();
  }
  //stop location updates when Activity is no longer active
  if (mGoogleApiClient.isConnected()) {
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    mGoogleApiClient.disconnect();
  }
}

@Override
public void onMapReady(GoogleMap googleMap) {
  mGoogleMap = googleMap;
  mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
  map_marker_End(12.951601, 80.184641, "Destination");
  if (flag == 2) {
    map_marker_start(Start_lat, Start_long, Checkin);
  }
  //Initialize Google Play Services
  if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (ContextCompat.checkSelfPermission(this,
        android.Manifest.permission.ACCESS_FINE_LOCATION) ==
      PackageManager.PERMISSION_GRANTED) {
      //Location Permission already granted
      createLocationRequest();
      buildGoogleApiClient();
      mGoogleMap.setMyLocationEnabled(true);
    } else {
      //Request Location Permission
      checkLocationPermission();
    }
  } else {
    buildGoogleApiClient();
    mGoogleMap.setMyLocationEnabled(true);
  }

}

protected synchronized void buildGoogleApiClient() {

  mGoogleApiClient = new GoogleApiClient.Builder(this)
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .addApi(LocationServices.API)
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .build();
  mGoogleApiClient.connect();

}

protected void createLocationRequest() {
  mLocationRequest = new LocationRequest();
  mLocationRequest.setInterval(1000 * 10);
  mLocationRequest.setFastestInterval(1000 * 5);
  mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

@Override
public void onConnected(Bundle bundle) {

  startLocationUpdates();
}

protected void startLocationUpdates() {
  if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    // TODO: Consider calling
    Toast.makeText(this, "LocationNotUpdated", Toast.LENGTH_SHORT).show();
    ActivityCompat.requestPermissions(VisitTravel.this,
      new String[] {
        android.Manifest.permission
          .ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION
      },
      20);

  } else {
    if (mGoogleApiClient.isConnected()) {
      LocationServices.FusedLocationApi.requestLocationUpdates(
        mGoogleApiClient, mLocationRequest, this);
      Log.d("Loc", "Location update started ..............: ");
      //       Toast.makeText(this, "LocationUpdatedStart", Toast.LENGTH_SHORT).show();
    }
  }
}

@Override
public void onConnectionSuspended(int i) {}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

public void map_marker_start(Double lat, Double longt, String title) {
  MarkerOptions markerOptions = new MarkerOptions();
  LatLng latLng = new LatLng(lat, longt);
  Log.d("lat", String.valueOf(latLng.longitude));
  markerOptions.position(latLng);
  markerOptions.title(title);
  markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
  mGoogleMap.addMarker(markerOptions).showInfoWindow();

}

public void map_marker_End(Double lat, Double longt, String title) {
  final MarkerOptions markerOptions_end = new MarkerOptions();
  LatLng latLng = new LatLng(lat, longt);
  Log.d("lat", String.valueOf(latLng.longitude));
  markerOptions_end.position(latLng);
  markerOptions_end.title(title);
  markerOptions_end.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
  mGoogleMap.addMarker(markerOptions_end).showInfoWindow();
  mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
    @Override
    public boolean onMarkerClick(Marker marker) {
      String title = marker.getTitle();
      if (title.equals("Destination")) {
        dot_source.setText("\u2022");
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
        heading.setText("TEST");
        duration_textview.setText("Duration:" + " " + duration);
        return true;
      } else {
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
        return true;

      }

    }
  });

}

@Override
public void onLocationChanged(Location location) {
  mLastLocation = location;
  PolylineOptions polylineOptions = new PolylineOptions();
  Log.d("location", mLastLocation.toString());
  LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
  obj.add(latLng);
  polylineOptions.addAll(obj);
  polylineOptions.width(9);
  polylineOptions.color(Color.parseColor("#2196f3"));
  mGoogleMap.addPolyline(polylineOptions);
  progressDialog.dismiss();
  mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
  CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
    latLng, 12);
  mGoogleMap.animateCamera(cameraUpdate);
}

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

private void checkLocationPermission() {
  if (ContextCompat.checkSelfPermission(VisitTravel.this, android.Manifest.permission.ACCESS_FINE_LOCATION) !=
    PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(this,
        android.Manifest.permission.ACCESS_FINE_LOCATION)) {

      // Show an explanation to the user *asynchronously* -- don't block
      // this thread waiting for the user's response! After the user
      // sees the explanation, try again to request the permission.
      new AlertDialog.Builder(this)
        .setTitle("Location Permission Needed")
        .setMessage("This app needs the Location permission, please accept to use location functionality")
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialogInterface, int i) {
            //Prompt the user once explanation has been shown
            ActivityCompat.requestPermissions(VisitTravel.this,
              new String[] {
                android.Manifest.permission.ACCESS_FINE_LOCATION
              },
              MY_PERMISSIONS_REQUEST_LOCATION);
          }
        })
        .create()
        .show();

    } else {
      // No explanation needed, we can request the permission.
      ActivityCompat.requestPermissions(this,
        new String[] {
          android.Manifest.permission.ACCESS_FINE_LOCATION
        },
        MY_PERMISSIONS_REQUEST_LOCATION);
    }
  }
}

@Override
public void onRequestPermissionsResult(int requestCode,
  String permissions[], int[] grantResults) {
  switch (requestCode) {
    case MY_PERMISSIONS_REQUEST_LOCATION:
      {
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0 &&
          grantResults[0] == PackageManager.PERMISSION_GRANTED) {

          // permission was granted, yay! Do the
          // location-related task you need to do.
          if (ContextCompat.checkSelfPermission(this,
              android.Manifest.permission.ACCESS_FINE_LOCATION) ==
            PackageManager.PERMISSION_GRANTED) {

            if (mGoogleApiClient == null) {
              buildGoogleApiClient();
            }
            createLocationRequest();
            ///  buildGoogleApiClient();
            //  Settingsapi();
            mGoogleMap.setMyLocationEnabled(true);
          }

        } else {

          // permission denied, boo! Disable the
          // functionality that depends on this permission.
          Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
        }
        return;
      }

      // other 'case' lines to check for other
      // permissions this app might request
  }
}

public String getKilometer(final double lat1, final double lon1, final double lat2, final double lon2) {
  Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
      try {
        URL url = new URL("http://maps.googleapis.com/maps/api/directions/json?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric&mode=driving");
        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        InputStream in = new BufferedInputStream(conn.getInputStream());
        StringBuilder buffer = new StringBuilder();
        BufferedReader reader = null;
        reader = new BufferedReader(new InputStreamReader( in ));
        String inputLine;
        while ((inputLine = reader.readLine()) != null)
          buffer.append(inputLine + "\n");
        if (buffer.length() == 0) {
          // Stream was empty. No point in parsing.
          Log.e("empty", "empty");
        }
        JsonResponse = buffer.toString();
        Log.d("response", JsonResponse);
        JSONObject jsonObject = new JSONObject(JsonResponse);
        JSONArray array = jsonObject.getJSONArray("routes");
        JSONObject routes = array.getJSONObject(0);
        JSONArray legs = routes.getJSONArray("legs");
        JSONObject steps = legs.getJSONObject(0);
        JSONObject distance = steps.getJSONObject("distance");
        parsedDistance = distance.getString("text");

      } catch (ProtocolException e) {
        e.printStackTrace();
      } catch (MalformedURLException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
  });
  thread.start();
  try {
    thread.join();
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
  return parsedDistance;
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  switch (requestCode) {
    // Check for the integer request code originally supplied to startResolutionForResult().
    case REQUEST_CHECK_SETTINGS:
      switch (resultCode) {
        case Activity.RESULT_OK:
          startLocationUpdates();
          break;
        case Activity.RESULT_CANCELED:
          Intent intent = new Intent(this, Incident.class);
          startActivity(intent);
          break;
      }
      break;
  }
}

@Override
protected void onStop() {
  super.onStop();
  if (wakeLock.isHeld()) {
    wakeLock.release();
  }

}

@Override
public void onBackPressed() {
  super.onBackPressed();
  Intent intent = new Intent(this, IncidentView.class);
  if (mGoogleApiClient.isConnected()) {
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    mGoogleApiClient.disconnect();
  }
  intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
  setResult(RESULT_OK, intent);
  finish();
}
}

Searched alot and not getting proper way to start with? Any help would really valuable.

--Thanks!


问:
pgadmin4- missing csv option
I have problem. After upgrade my server I have too change pgAdmin to version 4 v2.0, and now I can't change the separator ext.
I don't have option to change csv.
My options :

In manual they have option to change csv.

Do you have any idea ?

答: The options you mentioned are committed recently in the code base and will be available in next public release of pgAdmin4, I would suggest you try these options when the new version is available.</p>

Title: pgadmin4- missing csv option


问:
Many to many database
This is probably basic stuff, but I really made my homework looking it up. I still can´t find the solution.

I have a users db, a movies db, and a ratings db. Ratings has a movie_id, user_id and grade.

```<code>class Rating < ActiveRecord::Base

  attr_accessible :grade

  belongs_to :user
  belongs_to :movie
end

class User < ActiveRecord::Base

  has_many :ratings, :dependent => :destroy
  has_many :movies, :through => :ratings
...

class Movie < ActiveRecord::Base

  has_many :ratings, :dependent => :destroy
  has_many :users, :through => :ratings
...
</code>```

But I can´t create a rating with both movie_id and user_id

```<code>rails c test
Loading test environment (Rails 3.0.3)
@movie=Factory(:movie)
 #<Movie id: 1, title: "Rocky 20", link: "#", created_at: "2011-01-22 21:04:42", updated_at: "2011-01-22 21:04:42">
 @user=Factory(:user)
 #<User id: 1, name: "lola", email: "lola@gmail.com", created_at: "2011-01-22 21:04:48", updated_at: "2011-01-22 21:04:48", encrypted_password: "c306a696138fa08c543ada3a3b4fd92067e9941743b7558e891...", salt: "f82c6abaccec17e2866d50150ad200181eb4bc8e0204249f171...", admin: false>
>> @user.ratings.create(:grade=> 4, :movie_id =>@movie.id)
=> #<Rating id: 1, grade: 4, user_id: nil, movie_id: nil, created_at: "2011-01-22 21:04:55", updated_at: "2011-01-22 21:04:55">
</code>```

that "movie_id: nil" is what is killing me...

then of course me tests are not passing:
@user.rating.create(grade => 5, :movie_id => @movie.id) has no movie_id
@movie.rating.create(grade => 5, :user_id => @user.id) has no user_id

any hints?

Thanks!!

答:
The code you're showing here should absolutely work IMO. Which leaves me guessing that it's something you aren't showing here. A couple of things I'd try:

Use the regular console for a change

Don't use Factories (maybe it's them?), create actual entries instead

I've tried your example and here's what I got:

```<code>> m = Movie.create :title => "Foo"
=> #<Movie id: 1, title: "Foo", created_at: …>

> u = User.create :name => "Marc"
=> #<User id: 1, name: "Marc", created_at: …>

> u.ratings.create :grade => 4, :movie_id => m.id
=> #<Rating id: 1, grade: 4, user_id: 1, movie_id: 1, created_at: …>
> m.ratings.create :grade => 3, :user_id => u.id
=> #<Rating id: 2, grade: 3, user_id: 1, movie_id: 1, created_at: …>
</code>```

Which you can also use like this, as you might know:

```<code>> m.ratings.create :grade => 3, :user => u
=> #<Rating id: 3, grade: 3, user_id: 1, movie_id: 1, created_at: …>
</code>```

Title: Many to many database

Body:
This is probably basic stuff, but I really made my homework looking it up. I still can´t find the solution.

I have a users db, a movies db, and a ratings db. Ratings has a movie_id, user_id and grade.

class Rating < ActiveRecord::Base

  attr_accessible :grade

  belongs_to :user
  belongs_to :movie
end

class User < ActiveRecord::Base

  has_many :ratings, :dependent => :destroy
  has_many :movies, :through => :ratings
...

class Movie < ActiveRecord::Base

  has_many :ratings, :dependent => :destroy
  has_many :users, :through => :ratings
...

But I can´t create a rating with both movie_id and user_id

rails c test
Loading test environment (Rails 3.0.3)
@movie=Factory(:movie)
 #<Movie id: 1, title: "Rocky 20", link: "#", created_at: "2011-01-22 21:04:42", updated_at: "2011-01-22 21:04:42">
 @user=Factory(:user)
 #<User id: 1, name: "lola", email: "lola@gmail.com", created_at: "2011-01-22 21:04:48", updated_at: "2011-01-22 21:04:48", encrypted_password: "c306a696138fa08c543ada3a3b4fd92067e9941743b7558e891...", salt: "f82c6abaccec17e2866d50150ad200181eb4bc8e0204249f171...", admin: false>
>> @user.ratings.create(:grade=> 4, :movie_id =>@movie.id)
=> #<Rating id: 1, grade: 4, user_id: nil, movie_id: nil, created_at: "2011-01-22 21:04:55", updated_at: "2011-01-22 21:04:55">

that "movie_id: nil" is what is killing me...

then of course me tests are not passing:
@user.rating.create(grade => 5, :movie_id => @movie.id) has no movie_id
@movie.rating.create(grade => 5, :user_id => @user.id) has no user_id

any hints?

Thanks!!

Body:
The code you're showing here should absolutely work IMO. Which leaves me guessing that it's something you aren't showing here. A couple of things I'd try:

Use the regular console for a change

Don't use Factories (maybe it's them?), create actual entries instead

I've tried your example and here's what I got:

> m = Movie.create :title => "Foo"
=> #<Movie id: 1, title: "Foo", created_at: …>

> u = User.create :name => "Marc"
=> #<User id: 1, name: "Marc", created_at: …>

> u.ratings.create :grade => 4, :movie_id => m.id
=> #<Rating id: 1, grade: 4, user_id: 1, movie_id: 1, created_at: …>
> m.ratings.create :grade => 3, :user_id => u.id
=> #<Rating id: 2, grade: 3, user_id: 1, movie_id: 1, created_at: …>

Which you can also use like this, as you might know:

> m.ratings.create :grade => 3, :user => u
=> #<Rating id: 3, grade: 3, user_id: 1, movie_id: 1, created_at: …>