问:
How to parse CSV with pgloader or PostgreSQL copy when there's a \n (line break) inside double quotes?
I have a csv line like this:

```<code>"aaa"|"bbb"|"ccc"|"dddd
eeeee"
</code>```

I want to import this data using pgloader (http://pgloader.io/) or PostgreSQL COPY (https://www.postgresql.org/docs/9.6/static/sql-copy.html). My issue here is the fact tha according to the CSV standards it's possible to have a line break (\n) inside a quoted field value. But pgloader and also the COPY command treat it like a brand new line of data, instead of one column with line break inside.

```<code>COPY schema.table (
    col_aaa,
    col_bbb,
    col_ccc,
    col_ddd
)
    FROM 'file.csv' WITH DELIMITER '|' ENCODING 'LATIN1' CSV;
</code>```

My COPY command
My pgloader command

```<code>LOAD CSV
FROM 'file.csv'
INTO postgresql://user:password@host:5432/database?schema.table (col_aaa, col_bbb, col_ccc, col_ddd)

WITH
skip header = 0,
fields optionally enclosed by '"',
fields escaped by double-quote,
fields terminated by '|'

SET client_encoding to 'latin1'
BEFORE LOAD DO
    $$ TRUNCATE anac.aerodromos_csv RESTART IDENTITY; $$;
</code>```

I've search a lot from the PostgreSQL docs and also from google.

The only thing that I've found was this: Parsing CSV file with \n in double quoted fields but awk is too slow for a file with more than 1 million lines.

Any hint about how to do it?

My preference is for pgloader, but I can accept the use of sed or perl as regex agent to treat file at a linux shell script.

Any clues about how to do it?

答:
To give you an idea to solve this problem, I am writing this example.

I have just assumed that file will contain only 4 column and will contain only 1 line break. If It isn't the case then you need to change this.

Input File:

```<code>"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"dddd
eeeee"
"aaa"|"bbb"|"cc
c"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"b
bb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"a
aa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"dddd
eeeee"
</code>```

script.pl

```<code>#!/usr/bin/perl
use strict; use warnings; use Data::Dumper;

open ( my $RFH, '<', 'input.io' ) or die ($!);
open ( my $WFH, '>', 'output.o' ) or die ($!);

my $line_break = 0;
my $old_line = '';

while ( my $line = <$RFH> ) {
    chomp($line);
    if ( ! $line_break ){
        my @columns = split( /\|/, $line );
        if ( scalar( @columns ) == 4 && $columns[3] =~ m/"$/ ){
            print $WFH $line."\n";
        }
        else{
            $line_break = 1;
            $old_line = $line;
            next;
        }
    }
    else{
        $line = $old_line . $line;
        $old_line = '';
        $line_break = 0;
        print $WFH $line."\n";
    }
}

close($RFH);
close($WFH);
</code>```

OUTPUT File:

```<code>"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
</code>```

Change this example to your need.
Hope this helps.

Body:
I have a csv line like this:

"aaa"|"bbb"|"ccc"|"dddd
eeeee"

I want to import this data using pgloader (http://pgloader.io/) or PostgreSQL COPY (https://www.postgresql.org/docs/9.6/static/sql-copy.html). My issue here is the fact tha according to the CSV standards it's possible to have a line break (\n) inside a quoted field value. But pgloader and also the COPY command treat it like a brand new line of data, instead of one column with line break inside.

COPY schema.table (
    col_aaa,
    col_bbb,
    col_ccc,
    col_ddd
)
    FROM 'file.csv' WITH DELIMITER '|' ENCODING 'LATIN1' CSV;

My COPY command
My pgloader command

LOAD CSV
FROM 'file.csv'
INTO postgresql://user:password@host:5432/database?schema.table (col_aaa, col_bbb, col_ccc, col_ddd)

WITH
skip header = 0,
fields optionally enclosed by '"',
fields escaped by double-quote,
fields terminated by '|'

SET client_encoding to 'latin1'
BEFORE LOAD DO
    $$ TRUNCATE anac.aerodromos_csv RESTART IDENTITY; $$;

I've search a lot from the PostgreSQL docs and also from google.

The only thing that I've found was this: Parsing CSV file with \n in double quoted fields but awk is too slow for a file with more than 1 million lines.

Any hint about how to do it?

My preference is for pgloader, but I can accept the use of sed or perl as regex agent to treat file at a linux shell script.

Any clues about how to do it?

Body:
To give you an idea to solve this problem, I am writing this example.

I have just assumed that file will contain only 4 column and will contain only 1 line break. If It isn't the case then you need to change this.

Input File:

"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"dddd
eeeee"
"aaa"|"bbb"|"cc
c"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"b
bb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"a
aa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"dddd
eeeee"

script.pl

#!/usr/bin/perl
use strict; use warnings; use Data::Dumper;

open ( my $RFH, '<', 'input.io' ) or die ($!);
open ( my $WFH, '>', 'output.o' ) or die ($!);

my $line_break = 0;
my $old_line = '';

while ( my $line = <$RFH> ) {
    chomp($line);
    if ( ! $line_break ){
        my @columns = split( /\|/, $line );
        if ( scalar( @columns ) == 4 && $columns[3] =~ m/"$/ ){
            print $WFH $line."\n";
        }
        else{
            $line_break = 1;
            $old_line = $line;
            next;
        }
    }
    else{
        $line = $old_line . $line;
        $old_line = '';
        $line_break = 0;
        print $WFH $line."\n";
    }
}

close($RFH);
close($WFH);

OUTPUT File:

"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"
"aaa"|"bbb"|"ccc"|"ddddeeeee"

Change this example to your need.
Hope this helps.


来源: stackexchange

问:
Change default schema for user
```<code>create schema bla;

-- then create table table_name into this schema
</code>```

Then I want change default  schema for user (user is postgres)

I do:  ALTER ROLE postgres SET search_path TO bla; (Query returned successfully with no result).

When I try SELECT * FROM table_name gives error relation "table_name" does not exist

Though SELECT * FROM bla.table_name works fine.

What is wrong in my attempt to change default schema for user?

答:
I think you need to relogin for that. With ALTER USER ... SET you change

Session defaults for run-time configuration variables

Also from ALTER ROLE SET manual:

Role-specific variable settings take effect only at login;

But don't apply changes to current session. If you want immediate change use:

```<code>SET search_path TO bla;
</code>```

It will change path on session level

ContentLicense: CC BY-SA 3.0

Title: Change default schema for user

Body:
create schema bla;

-- then create table table_name into this schema

Then I want change default  schema for user (user is postgres)

I do:  ALTER ROLE postgres SET search_path TO bla; (Query returned successfully with no result).

When I try SELECT * FROM table_name gives error relation "table_name" does not exist

Though SELECT * FROM bla.table_name works fine.

What is wrong in my attempt to change default schema for user?

Body:
I think you need to relogin for that. With ALTER USER ... SET you change

Session defaults for run-time configuration variables

Also from ALTER ROLE SET manual:

Role-specific variable settings take effect only at login;

But don't apply changes to current session. If you want immediate change use:

SET search_path TO bla;

It will change path on session level


问:
Authenticating an user using social identity provider with Azure AD B2C
Assume that a user authenticates a mobile application with Google account using Azure AD B2C. Will Azure create a local account and link the Google login with it?

How does this manage within Azure AD B2C?

答: Azure AD B2C creates a local account and then links it to the social account (Google in this case). If you look in the Azure Portal > Users & Groups, you will see a new user with a username like cpim_@yourtenant.onmicrosoft.com that represents the users that signed in with the social account.</p>


问:
c++ call class's function of another class's function
i hope this makes sense for you, i get confused. let me know if there is a simpler way:</p>

```<code>double A::a(double(b::*bb)())
{
  b.init();
  return (b->*bb)();
}

void A::run();
{
  cout<< a(b.b1);
  cout<< a(b.b2);
}

class A
{
  B b;
  void run();
  double a(double(b::*bb)());
};

class B
{
  void init();
  double b1();
  double b2();
};
</code>```

答:
It doesn't make sense. This makes sense though:

```<code>class B // <- class B definition comes first
{
  void init();
  double b1();
  double b2();
};

class A
{
  B b;
  void run();
  double a(double(B::*bb)()); // <- B instead of b
};

double A::a(double(B::*bb)()) // <- B instead of b
{
  b.init();
  return (b->*bb)();
}

void A::run() // <- you can't put semicolon here
{
  cout<< a(&B::b1); // <- you want to pass the address of a member.
  cout<< a(&B::b2); // <- you want to pass the address of a member.
}
</code>```

Now it makes more sense to me.

ContentLicense: CC BY-SA 2.5

Body:
i hope this makes sense for you, i get confused. let me know if there is a simpler way:

double A::a(double(b::*bb)())
{
  b.init();
  return (b->*bb)();
}

void A::run();
{
  cout<< a(b.b1);
  cout<< a(b.b2);
}

class A
{
  B b;
  void run();
  double a(double(b::*bb)());
};

class B
{
  void init();
  double b1();
  double b2();
};

Body:
It doesn't make sense. This makes sense though:

class B // <- class B definition comes first
{
  void init();
  double b1();
  double b2();
};

class A
{
  B b;
  void run();
  double a(double(B::*bb)()); // <- B instead of b
};

double A::a(double(B::*bb)()) // <- B instead of b
{
  b.init();
  return (b->*bb)();
}

void A::run() // <- you can't put semicolon here
{
  cout<< a(&B::b1); // <- you want to pass the address of a member.
  cout<< a(&B::b2); // <- you want to pass the address of a member.
}

Now it makes more sense to me.


问:
How to set environment variables on compute nodes in an MPI job
I don't understand how the environment is set on compute nodes when running with MPI under a scheduler.

I do:

```<code>mpirun -np 1 --hostfile ./hostfile foo.sh
</code>```

with foo.sh:

```<code>#!/usr/bin/env zsh
echo $LD_LIBRARY_PATH
</code>```

Then I do not recover the LD_LIBRARY_PATH I have got in an interactive shell... What are the initialization files that are executed/sourced at connection with MPI?

note: I am under zsh, and I tried to put things in .zprofile or .zshenv instead of .zshrc, but it doesn't seem to make a change... My LD_LIBRARY_PATH is set in a .profile which is sourced by a .bashrc which is sourced by the .zshrc.

答:
You could specify the number of threads per mpi using end with following command as well.

```<code>env OMP_NUM_THREADS=n PARALLEL=n mpirun -np m program.exe < input.file > output.file &
</code>```

where n and m are the number of threads and number of CPU cores.

Example:

```<code>env OMP_NUM_THREADS=2 PARALLEL=2 mpirun -np 12 program.exe < input.file > output.file &
</code>```

Body:
I don't understand how the environment is set on compute nodes when running with MPI under a scheduler.

I do:

mpirun -np 1 --hostfile ./hostfile foo.sh

with foo.sh:

#!/usr/bin/env zsh
echo $LD_LIBRARY_PATH

Then I do not recover the LD_LIBRARY_PATH I have got in an interactive shell... What are the initialization files that are executed/sourced at connection with MPI?

note: I am under zsh, and I tried to put things in .zprofile or .zshenv instead of .zshrc, but it doesn't seem to make a change... My LD_LIBRARY_PATH is set in a .profile which is sourced by a .bashrc which is sourced by the .zshrc.

Body:
You could specify the number of threads per mpi using end with following command as well.

env OMP_NUM_THREADS=n PARALLEL=n mpirun -np m program.exe < input.file > output.file &

where n and m are the number of threads and number of CPU cores.

Example:

env OMP_NUM_THREADS=2 PARALLEL=2 mpirun -np 12 program.exe < input.file > output.file &


问:
Export variable from within while loop
I want to export a variable from within a loop. I was not able to do it. I am not sure what is missing here.

Any suggestion would be great help

```<code>var="ahs tcs amq tos"

for i in ${var}
do
   ${i}_log="/var/tmp/pmp_${i}_log"
   #export ${i}_log
done
</code>```

答:
An alternative could be to use a single exported associative array instead of multiple variables:

EDIT: oops, this won't work since arrays can't be exported. :\

```<code>var="ahs tcs amq tos"

declare -A logs

for i in ${var}
do
  logs[$i]="/var/tmp/pmp_${i}_log"
done

echo ${logs[@]}
#### export logs
</code>```

Also see Inian's answer for better practices for looping and arrays.

Title: Export variable from within while loop

Body:
I want to export a variable from within a loop. I was not able to do it. I am not sure what is missing here.

Any suggestion would be great help

var="ahs tcs amq tos"

for i in ${var}
do
   ${i}_log="/var/tmp/pmp_${i}_log"
   #export ${i}_log
done

Body:
An alternative could be to use a single exported associative array instead of multiple variables:

EDIT: oops, this won't work since arrays can't be exported. :\

var="ahs tcs amq tos"

declare -A logs

for i in ${var}
do
  logs[$i]="/var/tmp/pmp_${i}_log"
done

echo ${logs[@]}
#### export logs

Also see Inian's answer for better practices for looping and arrays.


问:
How can I find the latest commit from forked repos on github?
For example I find a framework that is not maintained anymore but lots of forks. I want to see the more recent forks only. Network Graph is not available if its large.

答: Github API can list forks, and the default order is newest.


问:
MPI_File_read Error
I am trying to use MPI_File_read to read from an input file. But it is not correctly reading the values. Here is my input file:

```<code>11 3 4 5 2
</code>```

And here is the code i am using to try to read it:

```<code>char *filename = "input/8";
int n;

if (MPI_File_open(comm_2d, filename, MPI_MODE_RDONLY, MPI_INFO_NULL, &f) != MPI_SUCCESS) {
    fprintf(stderr, "Cannot open file %s\n", filename);
    MPI_Abort(comm_2d, FILE_NOT_FOUND);
    MPI_Finalize();
    return 1;
}
MPI_File_seek(f, 0, MPI_SEEK_SET);
MPI_File_read(f, &n, 1, MPI_INT, &status);

cout << "n :" << n << endl;
MPI_File_close(&f);
</code>```

From my understanding this should read the first int "11" from the input.txt. But if gives me a very large number instead.

What am I doing wrong?

答:
I think you can use similar API: MPI_File_write to generate the binary file you wanted easily.

```<code>char *filename = "input/8";
int n;

if (MPI_File_open(comm_2d, filename, MPI_MODE_CREATE| MPI_MODE_RDWR, MPI_INFO_NULL, &f) != MPI_SUCCESS) {
    fprintf(stderr, "Cannot open file %s\n", filename);
    MPI_Abort(comm_2d, FILE_NOT_FOUND);
    MPI_Finalize();
    return 1;
}
MPI_File_seek(f, 0, MPI_SEEK_SET);
int data[10];
data[0]=11;
data[1]=3;data[2]=4;data[3]=5;data[4]=2;
MPI_File_write(f, data, 5, MPI_INT, &status);
MPI_File_close(&f);
</code>```

After you run the above code using 1 process, you can get the binary file using MPI_File_read can read

Title: MPI_File_read Error

Body:
I am trying to use MPI_File_read to read from an input file. But it is not correctly reading the values. Here is my input file:

11 3 4 5 2

And here is the code i am using to try to read it:

char *filename = "input/8";
int n;

if (MPI_File_open(comm_2d, filename, MPI_MODE_RDONLY, MPI_INFO_NULL, &f) != MPI_SUCCESS) {
    fprintf(stderr, "Cannot open file %s\n", filename);
    MPI_Abort(comm_2d, FILE_NOT_FOUND);
    MPI_Finalize();
    return 1;
}
MPI_File_seek(f, 0, MPI_SEEK_SET);
MPI_File_read(f, &n, 1, MPI_INT, &status);

cout << "n :" << n << endl;
MPI_File_close(&f);

From my understanding this should read the first int "11" from the input.txt. But if gives me a very large number instead.

What am I doing wrong?

Body:
I think you can use similar API: MPI_File_write to generate the binary file you wanted easily.

char *filename = "input/8";
int n;

if (MPI_File_open(comm_2d, filename, MPI_MODE_CREATE| MPI_MODE_RDWR, MPI_INFO_NULL, &f) != MPI_SUCCESS) {
    fprintf(stderr, "Cannot open file %s\n", filename);
    MPI_Abort(comm_2d, FILE_NOT_FOUND);
    MPI_Finalize();
    return 1;
}
MPI_File_seek(f, 0, MPI_SEEK_SET);
int data[10];
data[0]=11;
data[1]=3;data[2]=4;data[3]=5;data[4]=2;
MPI_File_write(f, data, 5, MPI_INT, &status);
MPI_File_close(&f);

After you run the above code using 1 process, you can get the binary file using MPI_File_read can read


问:
General suggestions for debugging in R
I get an error when using an R function that I wrote:

```<code>Warning messages:
1: glm.fit: algorithm did not converge
2: glm.fit: algorithm did not converge
</code>```

What I have done:

Step through the function

Adding print to find out at what line the error occurs suggests two functions that should not use glm.fit.  They are window() and save().

My general approaches include adding print and stop commands, and stepping through a function line by line until I can locate the exception.

However, it is not clear to me using those techniques where this error comes from in the code. I am not even certain which functions within the code depend on glm.fit.  How do I go about diagnosing this problem?

答:
At some point, glm.fit is being called. That means one of the functions you call or one of the functions called by those functions is using either glm, glm.fit.

Also, as I mention in my comment above, that is a warning not an error, which makes a big difference. You can't trigger any of R's debugging tools from a warning (with default options before someone tells me I am wrong ;-).

If we change the options to turn warnings into errors then we can start to use R's debugging tools. From ?options we have:

```<code> ‘warn’: sets the handling of warning messages.  If ‘warn’ is
      negative all warnings are ignored.  If ‘warn’ is zero (the
      default) warnings are stored until the top-level function
      returns.  If fewer than 10 warnings were signalled they will
      be printed otherwise a message saying how many (max 50) were
      signalled.  An object called ‘last.warning’ is created and
      can be printed through the function ‘warnings’.  If ‘warn’ is
      one, warnings are printed as they occur.  If ‘warn’ is two or
      larger all warnings are turned into errors.
</code>```

So if you run

```<code>options(warn = 2)
</code>```

then run your code, R will throw an error. At which point, you could run

```<code>traceback()
</code>```

to see the call stack. Here is an example.

```<code>> options(warn = 2)
> foo <- function(x) bar(x + 2)
> bar <- function(y) warning("don't want to use 'y'!")
> foo(1)
Error in bar(x + 2) : (converted from warning) don't want to use 'y'!
> traceback()
7: doWithOneRestart(return(expr), restart)
6: withOneRestart(expr, restarts[[1L]])
5: withRestarts({
       .Internal(.signalCondition(simpleWarning(msg, call), msg,
           call))
       .Internal(.dfltWarn(msg, call))
   }, muffleWarning = function() NULL)
4: .signalSimpleWarning("don't want to use 'y'!", quote(bar(x +
       2)))
3: warning("don't want to use 'y'!")
2: bar(x + 2)
1: foo(1)
</code>```

Here you can ignore the frames marked 4: and higher. We see that foo called bar and that bar generated the warning. That should show you which functions were calling glm.fit.

If you now want to debug this, we can turn to another option to tell R to enter the debugger when it encounters an error, and as we have made warnings errors we will get a debugger when the original warning is triggered. For that you should run:

```<code>options(error = recover)
</code>```

Here is an example:

```<code>> options(error = recover)
> foo(1)
Error in bar(x + 2) : (converted from warning) don't want to use 'y'!

Enter a frame number, or 0 to exit

1: foo(1)
2: bar(x + 2)
3: warning("don't want to use 'y'!")
4: .signalSimpleWarning("don't want to use 'y'!", quote(bar(x + 2)))
5: withRestarts({
6: withOneRestart(expr, restarts[[1]])
7: doWithOneRestart(return(expr), restart)

Selection:
</code>```

You can then step into any of those frames to see what was happening when the warning was thrown.

To reset the above options to their default, enter

```<code>options(error = NULL, warn = 0)
</code>```

As for the specific warning you quote, it is highly likely that you need to allow more iterations in the code. Once you've found out what is calling glm.fit, work out how to pass it the control argument using glm.control - see ?glm.control.

Title: General suggestions for debugging in R

Body:
I get an error when using an R function that I wrote:

Warning messages:
1: glm.fit: algorithm did not converge
2: glm.fit: algorithm did not converge

What I have done:

Step through the function

Adding print to find out at what line the error occurs suggests two functions that should not use glm.fit.  They are window() and save().

My general approaches include adding print and stop commands, and stepping through a function line by line until I can locate the exception.

However, it is not clear to me using those techniques where this error comes from in the code. I am not even certain which functions within the code depend on glm.fit.  How do I go about diagnosing this problem?

Body:
At some point, glm.fit is being called. That means one of the functions you call or one of the functions called by those functions is using either glm, glm.fit.

Also, as I mention in my comment above, that is a warning not an error, which makes a big difference. You can't trigger any of R's debugging tools from a warning (with default options before someone tells me I am wrong ;-).

If we change the options to turn warnings into errors then we can start to use R's debugging tools. From ?options we have:

 ‘warn’: sets the handling of warning messages.  If ‘warn’ is
      negative all warnings are ignored.  If ‘warn’ is zero (the
      default) warnings are stored until the top-level function
      returns.  If fewer than 10 warnings were signalled they will
      be printed otherwise a message saying how many (max 50) were
      signalled.  An object called ‘last.warning’ is created and
      can be printed through the function ‘warnings’.  If ‘warn’ is
      one, warnings are printed as they occur.  If ‘warn’ is two or
      larger all warnings are turned into errors.

So if you run

options(warn = 2)

then run your code, R will throw an error. At which point, you could run

traceback()

to see the call stack. Here is an example.

> options(warn = 2)
> foo <- function(x) bar(x + 2)
> bar <- function(y) warning("don't want to use 'y'!")
> foo(1)
Error in bar(x + 2) : (converted from warning) don't want to use 'y'!
> traceback()
7: doWithOneRestart(return(expr), restart)
6: withOneRestart(expr, restarts[[1L]])
5: withRestarts({
       .Internal(.signalCondition(simpleWarning(msg, call), msg,
           call))
       .Internal(.dfltWarn(msg, call))
   }, muffleWarning = function() NULL)
4: .signalSimpleWarning("don't want to use 'y'!", quote(bar(x +
       2)))
3: warning("don't want to use 'y'!")
2: bar(x + 2)
1: foo(1)

Here you can ignore the frames marked 4: and higher. We see that foo called bar and that bar generated the warning. That should show you which functions were calling glm.fit.

If you now want to debug this, we can turn to another option to tell R to enter the debugger when it encounters an error, and as we have made warnings errors we will get a debugger when the original warning is triggered. For that you should run:

options(error = recover)

Here is an example:

> options(error = recover)
> foo(1)
Error in bar(x + 2) : (converted from warning) don't want to use 'y'!

Enter a frame number, or 0 to exit

1: foo(1)
2: bar(x + 2)
3: warning("don't want to use 'y'!")
4: .signalSimpleWarning("don't want to use 'y'!", quote(bar(x + 2)))
5: withRestarts({
6: withOneRestart(expr, restarts[[1]])
7: doWithOneRestart(return(expr), restart)

Selection:

You can then step into any of those frames to see what was happening when the warning was thrown.

To reset the above options to their default, enter

options(error = NULL, warn = 0)

As for the specific warning you quote, it is highly likely that you need to allow more iterations in the code. Once you've found out what is calling glm.fit, work out how to pass it the control argument using glm.control - see ?glm.control.


问:
How define the img src path in MVC
I have my index.cshtml with a image

And a folder Images inside myApp/Images folder

if i access

http:/localhost/myApp  OR

http:/localhost/myApp/home/

works Ok. But if i use

http:/localhost/myApp/home/index

The page try to look for the image in

http:/localhost/myApp/home/Images/send.png

So how I should define my src.

Aditional note:
Beside the index.cshtml I also have an js file where a hover effect is add it to the image. And have same problem neither of those option work

```<code>$('#u3430_img').hover(
        function () {
            $(this).attr("src", "~/Images/send_hover.png");
        },
        function () {
            $(this).attr("src", "Images/send.png");
        }
);
</code>```

答: in Cshtml page adding ~ is not necessary.Just add /Images/send.png  ...It will come to root and follow hierarchy.</p>

Title: How define the img src path in MVC

Body:
I have my index.cshtml with a image

And a folder Images inside myApp/Images folder

if i access

http:/localhost/myApp  OR

http:/localhost/myApp/home/

works Ok. But if i use

http:/localhost/myApp/home/index

The page try to look for the image in

http:/localhost/myApp/home/Images/send.png

So how I should define my src.

Aditional note:
Beside the index.cshtml I also have an js file where a hover effect is add it to the image. And have same problem neither of those option work

$('#u3430_img').hover(
        function () {
            $(this).attr("src", "~/Images/send_hover.png");
        },
        function () {
            $(this).attr("src", "Images/send.png");
        }
);


问:
ICAL Wrong date in outlook (windows and android) but good in Google Calendar and Iphone ical
Hi There im busy with an i cal calendar.
But he display wrong date:

```<code>BEGIN:VEVENT
SUMMARY:TEST EVENT!
UID:140
STATUS:CONFIRMED
DTSTAMP;TZID=Europe/Amsterdam:20170610T220000Z
DTSTART;TZID=Europe/Amsterdam:20170610T220000Z
DTEND;TZID=Europe/Amsterdam:20170610T220000Z
LAST-MODIFIED:20170608T064314Z
LOCATION:STREET 1 1111 AA CITY
END:VEVENT
END:VCALENDAR
</code>```

This sould be date: 11/06/2017 22:00 (Day time Amsterdam)
In Outlook is the date: 11/06/2017 00:00 (Day time Amsterdam)

This is the rest of my code:

```<code>BEGIN:VCALENDAR
METHOD:PUBLISH
VERSION:2.0
PRODID:-//2017/TEST CALENDAR//EN
BEGIN:VTIMEZONE
TZID:Europe/Amsterdam
BEGIN:STANDARD
DTSTART:20151025T020000
RDATE:20160327T030000
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
TZNAME:Europe/Amsterdam CET
END:STANDARD
BEGIN:STANDARD
DTSTART:20161030T020000
RDATE:20170326T030000
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
TZNAME:Europe/Amsterdam CET
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:20150601T073000
RDATE:20151025T020000
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
TZNAME:Europe/Amsterdam CEST
END:DAYLIGHT
BEGIN:DAYLIGHT
DTSTART:20160327T030000
RDATE:20161030T020000
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
TZNAME:Europe/Amsterdam CEST
END:DAYLIGHT
</code>```

I hope someone can help me out!
Thanks alot!

My php code which generate the Ical is below:

```<code><?php
date_default_timezone_set('Europe/Amsterdam');
$querystr ="
SELECT $wpdb->posts.*
FROM $wpdb->posts, $wpdb->postmeta
WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id
AND ( $wpdb->posts.post_status = 'confirmed'
OR $wpdb->posts.post_status = 'pending'
)
ORDER BY $wpdb->posts.post_date DESC";
$pageposts = $wpdb->get_results($querystr, OBJECT);
?>
<?php
header("Content-Type: text/Calendar");
header("Content-Disposition: inline; filename=TESTAGENDA.ics");
// the iCal date format. Note the Z on the end indicates a UTC timestamp.
define('DATE_ICAL', 'Ymd\THis\Z');
// max line length is 75 chars. New line is \\n
$output = "BEGIN:VCALENDAR\r\n";
$output .= "METHOD:PUBLISH\r\n";
$output .= "VERSION:2.0\r\n";
$output .= "PRODID:-//2017/TEST AGENDA//EN\r\n";

$output .= "BEGIN:VTIMEZONE\r\n";
$output .= "TZID:Europe/Amsterdam\r\n";
$output .= "BEGIN:STANDARD\r\n";
$output .= "DTSTART:20151025T020000\r\n";
$output .= "RDATE:20160327T030000\r\n";
$output .= "TZOFFSETFROM:+0200\r\n";
$output .= "TZOFFSETTO:+0100\r\n";
$output .= "TZNAME:Europe/Amsterdam CET\r\n";
$output .= "END:STANDARD\r\n";
$output .= "BEGIN:STANDARD\r\n";
$output .= "DTSTART:20161030T020000\r\n";
$output .= "RDATE:20170326T030000\r\n";
$output .= "TZOFFSETFROM:+0200\r\n";
$output .= "TZOFFSETTO:+0100\r\n";
$output .= "TZNAME:Europe/Amsterdam CET\r\n";
$output .= "END:STANDARD\r\n";
$output .= "BEGIN:DAYLIGHT\r\n";
$output .= "DTSTART:20150601T073000\r\n";
$output .= "RDATE:20151025T020000\r\n";
$output .= "TZOFFSETFROM:+0100\r\n";
$output .= "TZOFFSETTO:+0200\r\n";
$output .= "TZNAME:Europe/Amsterdam CEST\r\n";
$output .= "END:DAYLIGHT\r\n";
$output .= "BEGIN:DAYLIGHT\r\n";
$output .= "DTSTART:20160327T030000\r\n";
$output .= "RDATE:20161030T020000\r\n";
$output .= "TZOFFSETFROM:+0100\r\n";
$output .= "TZOFFSETTO:+0200\r\n";
$output .= "TZNAME:Europe/Amsterdam CEST\r\n";
$output .= "END:DAYLIGHT\r\n";
$output .= "END:VTIMEZONE\r\n";
?>
<?php if ($pageposts){ ?>
<?php global $post; ?>
<?php foreach ($pageposts as $post): ?>
<?php $postmeta_reservering = get_post_meta( get_the_ID(), 'rtb', true );
if ( ! empty( $postmeta_reservering ) ) {
    $aantalpersonen = $postmeta_reservering['party'];
    $emailadres = $postmeta_reservering['email'];
    $telefoonnr = $postmeta_reservering['phone'];
    $ipadres = $postmeta_reservering['ip'];
}
?>
<?php setup_postdata($post); ?>
<?php if($post->post_status == 'confirmed'){$poststatus = 'CONFIRMED';}else{$poststatus = 'IN-PROCESS';}
$output .= "BEGIN:VEVENT\r\n";
$output .= "SUMMARY:".$post->post_title." Tel.:".$telefoonnr." (".$aantalpersonen." pers.)\r\n";
$output .= "UID:".$post->ID."\r\n";
$output .= "STATUS:".$poststatus."\r\n";
$output .= "DTSTAMP;TZID=Europe/Amsterdam:".date(DATE_ICAL, strtotime($post->post_date))."\r\n";
$output .= "DTSTART;TZID=Europe/Amsterdam:".date(DATE_ICAL, strtotime($post->post_date))."\r\n";
$output .= "DTEND;TZID=Europe/Amsterdam:".date(DATE_ICAL, strtotime($post->post_date))."\r\n";
$output .= "LAST-MODIFIED:".date(DATE_ICAL, strtotime($post->post_modified))."\r\n";
$output .= "LOCATION:STREET 01 1111 AA CITY\r\n";
$output .= "END:VEVENT\r\n";?>
<?php endforeach; ?>
<?php
// close calendar
$output .= "END:VCALENDAR";
// loop over events
echo $output;
?>
<?php }else{ ?>
    <span>No event!</span>
<?php } ?>
</code>```

答:
I have also faced same issue, finally i solved using below method, hope this will help you.

Pass your date to below method, to get global GMT time

```<code>public static Date cvtToGMT(Date myDate){
    TimeZone timeZone = TimeZone.getDefault();
    Date cvtDate = new Date( myDate.getTime() - timeZone.getRawOffset());
    if(timeZone.inDaylightTime(cvtDate)){
        Date dstDate = new Date(cvtDate.getTime() - timeZone.getDSTSavings());
        if ( timeZone.inDaylightTime( dstDate )){
            cvtDate = dstDate;
        }
    }
    return cvtDate;
}
</code>```

Body:
Hi There im busy with an i cal calendar.
But he display wrong date:

BEGIN:VEVENT
SUMMARY:TEST EVENT!
UID:140
STATUS:CONFIRMED
DTSTAMP;TZID=Europe/Amsterdam:20170610T220000Z
DTSTART;TZID=Europe/Amsterdam:20170610T220000Z
DTEND;TZID=Europe/Amsterdam:20170610T220000Z
LAST-MODIFIED:20170608T064314Z
LOCATION:STREET 1 1111 AA CITY
END:VEVENT
END:VCALENDAR

This sould be date: 11/06/2017 22:00 (Day time Amsterdam)
In Outlook is the date: 11/06/2017 00:00 (Day time Amsterdam)

This is the rest of my code:

BEGIN:VCALENDAR
METHOD:PUBLISH
VERSION:2.0
PRODID:-//2017/TEST CALENDAR//EN
BEGIN:VTIMEZONE
TZID:Europe/Amsterdam
BEGIN:STANDARD
DTSTART:20151025T020000
RDATE:20160327T030000
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
TZNAME:Europe/Amsterdam CET
END:STANDARD
BEGIN:STANDARD
DTSTART:20161030T020000
RDATE:20170326T030000
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
TZNAME:Europe/Amsterdam CET
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:20150601T073000
RDATE:20151025T020000
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
TZNAME:Europe/Amsterdam CEST
END:DAYLIGHT
BEGIN:DAYLIGHT
DTSTART:20160327T030000
RDATE:20161030T020000
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
TZNAME:Europe/Amsterdam CEST
END:DAYLIGHT

I hope someone can help me out!
Thanks alot!

My php code which generate the Ical is below:

<?php
date_default_timezone_set('Europe/Amsterdam');
$querystr ="
SELECT $wpdb->posts.*
FROM $wpdb->posts, $wpdb->postmeta
WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id
AND ( $wpdb->posts.post_status = 'confirmed'
OR $wpdb->posts.post_status = 'pending'
)
ORDER BY $wpdb->posts.post_date DESC";
$pageposts = $wpdb->get_results($querystr, OBJECT);
?>
<?php
header("Content-Type: text/Calendar");
header("Content-Disposition: inline; filename=TESTAGENDA.ics");
// the iCal date format. Note the Z on the end indicates a UTC timestamp.
define('DATE_ICAL', 'Ymd\THis\Z');
// max line length is 75 chars. New line is \\n
$output = "BEGIN:VCALENDAR\r\n";
$output .= "METHOD:PUBLISH\r\n";
$output .= "VERSION:2.0\r\n";
$output .= "PRODID:-//2017/TEST AGENDA//EN\r\n";

$output .= "BEGIN:VTIMEZONE\r\n";
$output .= "TZID:Europe/Amsterdam\r\n";
$output .= "BEGIN:STANDARD\r\n";
$output .= "DTSTART:20151025T020000\r\n";
$output .= "RDATE:20160327T030000\r\n";
$output .= "TZOFFSETFROM:+0200\r\n";
$output .= "TZOFFSETTO:+0100\r\n";
$output .= "TZNAME:Europe/Amsterdam CET\r\n";
$output .= "END:STANDARD\r\n";
$output .= "BEGIN:STANDARD\r\n";
$output .= "DTSTART:20161030T020000\r\n";
$output .= "RDATE:20170326T030000\r\n";
$output .= "TZOFFSETFROM:+0200\r\n";
$output .= "TZOFFSETTO:+0100\r\n";
$output .= "TZNAME:Europe/Amsterdam CET\r\n";
$output .= "END:STANDARD\r\n";
$output .= "BEGIN:DAYLIGHT\r\n";
$output .= "DTSTART:20150601T073000\r\n";
$output .= "RDATE:20151025T020000\r\n";
$output .= "TZOFFSETFROM:+0100\r\n";
$output .= "TZOFFSETTO:+0200\r\n";
$output .= "TZNAME:Europe/Amsterdam CEST\r\n";
$output .= "END:DAYLIGHT\r\n";
$output .= "BEGIN:DAYLIGHT\r\n";
$output .= "DTSTART:20160327T030000\r\n";
$output .= "RDATE:20161030T020000\r\n";
$output .= "TZOFFSETFROM:+0100\r\n";
$output .= "TZOFFSETTO:+0200\r\n";
$output .= "TZNAME:Europe/Amsterdam CEST\r\n";
$output .= "END:DAYLIGHT\r\n";
$output .= "END:VTIMEZONE\r\n";
?>
<?php if ($pageposts){ ?>
<?php global $post; ?>
<?php foreach ($pageposts as $post): ?>
<?php $postmeta_reservering = get_post_meta( get_the_ID(), 'rtb', true );
if ( ! empty( $postmeta_reservering ) ) {
    $aantalpersonen = $postmeta_reservering['party'];
    $emailadres = $postmeta_reservering['email'];
    $telefoonnr = $postmeta_reservering['phone'];
    $ipadres = $postmeta_reservering['ip'];
}
?>
<?php setup_postdata($post); ?>
<?php if($post->post_status == 'confirmed'){$poststatus = 'CONFIRMED';}else{$poststatus = 'IN-PROCESS';}
$output .= "BEGIN:VEVENT\r\n";
$output .= "SUMMARY:".$post->post_title." Tel.:".$telefoonnr." (".$aantalpersonen." pers.)\r\n";
$output .= "UID:".$post->ID."\r\n";
$output .= "STATUS:".$poststatus."\r\n";
$output .= "DTSTAMP;TZID=Europe/Amsterdam:".date(DATE_ICAL, strtotime($post->post_date))."\r\n";
$output .= "DTSTART;TZID=Europe/Amsterdam:".date(DATE_ICAL, strtotime($post->post_date))."\r\n";
$output .= "DTEND;TZID=Europe/Amsterdam:".date(DATE_ICAL, strtotime($post->post_date))."\r\n";
$output .= "LAST-MODIFIED:".date(DATE_ICAL, strtotime($post->post_modified))."\r\n";
$output .= "LOCATION:STREET 01 1111 AA CITY\r\n";
$output .= "END:VEVENT\r\n";?>
<?php endforeach; ?>
<?php
// close calendar
$output .= "END:VCALENDAR";
// loop over events
echo $output;
?>
<?php }else{ ?>
    No event!
<?php } ?>

Body:
I have also faced same issue, finally i solved using below method, hope this will help you.

Pass your date to below method, to get global GMT time

public static Date cvtToGMT(Date myDate){
    TimeZone timeZone = TimeZone.getDefault();
    Date cvtDate = new Date( myDate.getTime() - timeZone.getRawOffset());
    if(timeZone.inDaylightTime(cvtDate)){
        Date dstDate = new Date(cvtDate.getTime() - timeZone.getDSTSavings());
        if ( timeZone.inDaylightTime( dstDate )){
            cvtDate = dstDate;
        }
    }
    return cvtDate;
}


问:
Magento 2: Layout Update XML (Admin) Remove & Add Blocks
Quick Note: I have full admin access to M2 but no server access. (Magento EE 2.1.4).

So, I've got a few CMS pages that are using the layout "2 columns with left bar". The sidebar for this layout is a simple menu from a static block.

I'm trying to remove the existing menu and add a static block in its place at the page level.

A quick Google has shown me I can use something like:

```<code><referenceBlock name="advice_centre_leftmenu" remove="true"/>

<referenceContainer name="sidebar">
   <block class="Magento\Cms\Block\Block" name="test">
       <arguments>
            <argument name="block_id" xsi:type="string">test</argument>
       </arguments>
   </block>
</referenceContainer>
</code>```

The issue is that I have no idea what the Container or Block names are. I also don't have the relevant access to get at the PHTML files to find out that way (3rd party dev agency).

In the admin section, the block that contains the menu I'm trying to remove has the identifier "advice_leftmenu" however when I try:

```<code><referenceBlock name="advice_leftmenu" remove="true"/>
</code>```

Nothing happens.

Here is the relevant HTML that's around the sidebar:

```<code><div class="columns">
    <div class="sidebar sidebar-main">
        <div class="widget block block-static-block">
            <div class="left-cms-content">
                ...
            </div>
        </div>
    </div>
</div>
</code>```

I also tried the following to no effect:

```<code><referenceBlock name="sidebar.sidebar-main" remove="true"/>

<referenceBlock name="sidebar-main" remove="true"/>
</code>```

Is there somewhere in the HTML/admin I can look at to find the container/block names?

Am I going to be forced to coerce some time out of the agency to find the names for me?

Update:

I turned on theme hints thanks to a suggestion from @Nolwennig.

I've now managed to add the block using:

```<code><referenceContainer name="sidebar.main">
   <block class="Magento\Cms\Block\Block" name="buyers-menu">
       <arguments>
            <argument name="block_id" xsi:type="string">buyers-menu</argument>
       </arguments>
   </block>
</referenceContainer>
</code>```

However I still can't remove the block, I now know the block id is left_cms_content. I've now also tried:

```<code><referenceBlock name="left_cms_content" remove="true"/>
</code>```

But there's still no effect.

答:
Enable path hints (Enabled Template Path Hints for Storefront) and block hints (Add Block Names to Hints) in the admin interface:

Stores > Configuration > Advanced > Developer > Debug

Body:
Quick Note: I have full admin access to M2 but no server access. (Magento EE 2.1.4).

So, I've got a few CMS pages that are using the layout "2 columns with left bar". The sidebar for this layout is a simple menu from a static block.

I'm trying to remove the existing menu and add a static block in its place at the page level.

A quick Google has shown me I can use something like:

<referenceBlock name="advice_centre_leftmenu" remove="true"/>

<referenceContainer name="sidebar">
   <block class="Magento\Cms\Block\Block" name="test">
       <arguments>
            <argument name="block_id" xsi:type="string">test</argument>
       </arguments>
   </block>
</referenceContainer>

The issue is that I have no idea what the Container or Block names are. I also don't have the relevant access to get at the PHTML files to find out that way (3rd party dev agency).

In the admin section, the block that contains the menu I'm trying to remove has the identifier "advice_leftmenu" however when I try:

<referenceBlock name="advice_leftmenu" remove="true"/>

Nothing happens.

Here is the relevant HTML that's around the sidebar:

                ...

I also tried the following to no effect:

<referenceBlock name="sidebar.sidebar-main" remove="true"/>

<referenceBlock name="sidebar-main" remove="true"/>

Is there somewhere in the HTML/admin I can look at to find the container/block names?

Am I going to be forced to coerce some time out of the agency to find the names for me?

Update:

I turned on theme hints thanks to a suggestion from @Nolwennig.

I've now managed to add the block using:

<referenceContainer name="sidebar.main">
   <block class="Magento\Cms\Block\Block" name="buyers-menu">
       <arguments>
            <argument name="block_id" xsi:type="string">buyers-menu</argument>
       </arguments>
   </block>
</referenceContainer>

However I still can't remove the block, I now know the block id is left_cms_content. I've now also tried:

<referenceBlock name="left_cms_content" remove="true"/>

But there's still no effect.


问:
Logical breakdown for dot net namespace hierarchy
I am looking for a reference/links that give good high level logical breakdown of the dot net namespace.

And if it has some indicators to individual frameworks like what's specific to asp.net, wcf, wpf, wwf etc.

Any links/references/diagrams are highly appreciated.

Update

I found one poster for .net 4.0.

答:
The MSDN Library documentation should be a good start; it contains the entire framework and you can drill down into it as far as you would like to go.

Note: the first link on the page contains all of the class definitions.

ContentLicense: CC BY-SA 4.0


问:
Average a certain column value in MySQL
I have this table structure:

```<code>id | code | rating
1  | 300  |   25
2  | 302  |   35
3  | 100  |   50
4  | 100  |   30
5  | 200  |   40
6  | 103  |   45
</code>```

Here's my query so far:

SELECT code, AVG(rating) FROM table GROUP BY code;

I want to average the rating of all codes greater than 300. I tried setting an IF on the SQL query but it seems it doesn't work. Also tried having two group BYs but it won't work. I want to achieve this result:

```<code>code         |  AVG (rating)
300+ (alias) |  30
100          |  40
200          |  40
103          |  45
</code>```

答:
Use case when in group by:

```<code>select
    case when code >= 300 then '300+' else code end as code,
    avg(rating) as `AVG (rating)`
from yourtable
group by case when code >= 300 then 300 else code end
order by `AVG (rating)`
</code>```

Here is a demo in SQLFiddle.

Note: this will work in MySQL, but as 300+ is string, so more rigorous way should cast code to varchar first:

```<code>select
    case when code >= 300 then '300+' else concat(code, '') end as code,
    avg(rating) as `AVG (rating)`
from yourtable
group by case when code >= 300 then '300+' else concat(code, '') end
order by `AVG (rating)`
</code>```

Title: Average a certain column value in MySQL

Body:
I have this table structure:

id | code | rating
1  | 300  |   25
2  | 302  |   35
3  | 100  |   50
4  | 100  |   30
5  | 200  |   40
6  | 103  |   45

Here's my query so far:

SELECT code, AVG(rating) FROM table GROUP BY code;

I want to average the rating of all codes greater than 300. I tried setting an IF on the SQL query but it seems it doesn't work. Also tried having two group BYs but it won't work. I want to achieve this result:

code         |  AVG (rating)
300+ (alias) |  30
100          |  40
200          |  40
103          |  45

Body:
Use case when in group by:

select
    case when code >= 300 then '300+' else code end as code,
    avg(rating) as `AVG (rating)`
from yourtable
group by case when code >= 300 then 300 else code end
order by `AVG (rating)`

Here is a demo in SQLFiddle.

Note: this will work in MySQL, but as 300+ is string, so more rigorous way should cast code to varchar first:

select
    case when code >= 300 then '300+' else concat(code, '') end as code,
    avg(rating) as `AVG (rating)`
from yourtable
group by case when code >= 300 then '300+' else concat(code, '') end
order by `AVG (rating)`


问:
How to add custom font family in ionic2 app
I want to add new font family from Google fonts in my ionic2 app. I need to change the default font family and add my custom font family. Please help! Thanks</p>

答: Please see this link https://chriztalk.com/using-google-fonts-ionic-2/. It works for me.</p>


问:
How to enable production mode?
I was reading related questions and I found this one, but my question is how can I switch from development to production mode. There are some differences between the modes which are pointed out here.

In the console I can see ....Call enableProdMode() to enable the production mode. However, I'm not sure instance of which type should I call that method on.

Can somebody answer this question?

答:
Go to src/enviroments/enviroments.ts and enable the production mode

```<code>export const environment = {
  production: true
};
</code>```

for Angular 2

Title: How to enable production mode?

Body:
Go to src/enviroments/enviroments.ts and enable the production mode

export const environment = {
  production: true
};

for Angular 2


问:
"NFC tag type not supported" message
I have an app which reads and writes NFC tags. I tested my app on a Galaxy Note 3 and it works fine. But when I test it on a Note 5 and a Galaxy S6, a message pops up that says, "NFC tag type not supported".

Is that the fault of my app or are my tags not support on those devices?

My tag type is ISO 14443A standard.

答:
I confirm that my Samsung S7 with android 7.0 shows the "uncompatible" message but it can properly read mifare tags (just the ID), but only by using NXP specific app.
S7 also supports HCE to emulate cards, but I have yet to find an app which can replicate just the id of a card.</p>

Title: "NFC tag type not supported" message


问:
Revision control locking: Is the jury still out?
When I'm online it seems that everyone has agreed that using the exclusive locking workflow in source control is a Bad Thing. All the new revision control systems I see appear to be built for edit and merge workflows, and many don't even support exclusive locks at all.

However, everyone I work with is of the opinion that exclusive locks are a "must have" for any source control system, and working any other way would be a nightmare. Even recent hires from other companies seem to come in with this idea.

My question isn't who is right. I'm pretty sure what answer I'd get to that. My question is, is there really still any debate over this matter? Is there an honest "pro locking" camp out there that makes a serious case? Is any work being done to advance the art of revision control based around the locking model? Or are locking fans flogging a dead horse?

EDIT:
The answers so far have done a good job of explaining why exclusive locks are a good feature to use occasionally. However, I'm talking about promoting a workflow where exclusive locks are used for everything.

答:
If you're used to exclusive locking, then it's hard to embrace the edit-merge workflow.

Exclusive locking has its benefits, especially for binary files (images, videos, ...) which can't be merged automatically or not at all.

But: the need for exclusive locking always indicates another problem: good communication between people working on the project. Exclusive locking provides a poor replacement: it tells users that someone else is already working on that particular file - something they should know without using a version control system.

Since there are better ways to help with the communication among team members, most (all?) version control systems don't implement exclusive locking anymore or just a reduced version (i.e., locking, but such that those locks are not enforced).

It's not the job of a version control system to help with the communication.

OwnerDisplayName: Stefan


答:
This works on dash and bash (as long as the i's and the path to interpolate them into are reasonable): </p>

```<code>#!/bin/sh
var="a b c d"

for i in $var
do
        export "${i}_log=/var/tmp/pmp_${i}_log"

        #test
        sh -c "echo \$${i}_log"
done
</code>```

Title: Export variable from within while loop

Body:
This works on dash and bash (as long as the i's and the path to interpolate them into are reasonable):

#!/bin/sh
var="a b c d"

for i in $var
do
        export "${i}_log=/var/tmp/pmp_${i}_log"

        #test
        sh -c "echo \$${i}_log"
done


问:
change span text using jquery based on parent element class
I checked through the forum but didn't find the solution for my problem. I am adding a class on an element based on the img src value. If img src contains 'amazon' a class is added to closest li element and based on that li element i'm changing text of a span. Till here everything is fine, after this I want to change the text of span whose parent li element doesn't have that class name. I can't figure out the solution for it. Here is my code.</p>

```<code><script>
jQuery(document).ready(function(){
    var select = 'img[src*="images-amazon.com"]';
    jQuery(select).closest("li").addClass("sac-amazon");

    var cls = jQuery("li.sac-amazon");
    var currency = jQuery("span.woocommerce-Price-currencySymbol");

    if(cls){
        currency.text("US $");
    }else if(!cls){
        currency.text("SG $");
    }

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

答:
Try this (replace 'New Text' with the string of your choice):</p>

```<code>jQuery('ul li').each(function(){
  var t = jQuery(this);
  if(!t.hasClass('sac-amazon')){
    t.text('New text');
  }
});
</code>```

Body:
Try this (replace 'New Text' with the string of your choice):

jQuery('ul li').each(function(){
  var t = jQuery(this);
  if(!t.hasClass('sac-amazon')){
    t.text('New text');
  }
});


问:
Angular2 - Set A Different Color to an element Depending On Value
I am new to Angular2 and was wondering how I go about setting a font color to an element depending on the value.

My scenario is: if the value of the input field is not 100 then I want it red but if it is 100 then I want it green.

I have the following code in place but cant get it working.

XXX.component.css

```<code>.red {
    color: red;
}

.green {
    color: green;
}
</code>```

XXX.component.css

```<code><input mdInput placeholder="Proportion '%'" [(ngModel)]="proportion ">
<p>hello <span ng-class='{red : proportion!= '100', green: proportion === '100'}'>{{proportion}}</span></p>
</code>```

答:
You can also bind the style property.</p>

```<code><span [style.color]="proportion === '100' ? 'green' : 'red'"></span>
</code>```

Body:
I am new to Angular2 and was wondering how I go about setting a font color to an element depending on the value.

My scenario is: if the value of the input field is not 100 then I want it red but if it is 100 then I want it green.

I have the following code in place but cant get it working.

XXX.component.css

.red {
    color: red;
}

.green {
    color: green;
}

XXX.component.css

<input mdInput placeholder="Proportion '%'" [(ngModel)]="proportion ">

hello {{proportion}}

Body:
You can also bind the style property.

<span [style.color]="proportion === '100' ? 'green' : 'red'"></span>


问:
Python logging, how to write info to 2 separate
I'm trying log to different StringIOs. I would've expected that each logger would write to each StringIO that was instantiated and given to. But that's not working, only the first StringIO stores the logged info.
Any suggestions on what I'm missing?

```<code>    import logging
    from StringIO import StringIO
    formatter = logging.Formatter('%(asctime)s %(name)-3s %(levelname)-4s %(message)s')

    log_stream1 = StringIO()
    log1 = logging.getLogger('a')
    log1.setLevel(logging.DEBUG)
    stream_handler1 = logging.StreamHandler(log_stream1)
    stream_handler1.setLevel(logging.INFO)
    stream_handler1.setFormatter(formatter)
    log1.addHandler(stream_handler1)

    log_stream2 = StringIO()
    log2 = logging.getLogger('b')
    log2.setLevel(logging.DEBUG)
    stream_handler2 = logging.StreamHandler(log_stream2)
    stream_handler2.setLevel(logging.INFO)
    stream_handler2.setFormatter(formatter)
    log2.addHandler(stream_handler1)

    log1.info('log1')
    log2.info('log2')
</code>```

output:

```<code>    In [6]: log_stream1.getvalue()
    Out[6]: '2017-06-08 10:05:12,468 a   INFO log1\n2017-06-08 10:05:12,468 b   INFO log2\n'

    In [7]: log_stream2.getvalue()
    Out[7]: ''
</code>```

答:
Change

```<code>log2.addHandler(stream_handler1)
</code>```

To

```<code>log2.addHandler(stream_handler2)
</code>```

Entire code:

```<code>import logging
from StringIO import StringIO
formatter = logging.Formatter('%(asctime)s %(name)-3s %(levelname)-4s %(message)s')

log_stream1 = StringIO()
log1 = logging.getLogger('a')
log1.setLevel(logging.DEBUG)
stream_handler1 = logging.StreamHandler(log_stream1)
stream_handler1.setLevel(logging.INFO)
stream_handler1.setFormatter(formatter)
log1.addHandler(stream_handler1)

log_stream2 = StringIO()
log2 = logging.getLogger('b')
log2.setLevel(logging.DEBUG)
stream_handler2 = logging.StreamHandler(log_stream2)
stream_handler2.setLevel(logging.INFO)
stream_handler2.setFormatter(formatter)
log2.addHandler(stream_handler2)

log1.info('log1')
log2.info('log2')
</code>```

Body:
I'm trying log to different StringIOs. I would've expected that each logger would write to each StringIO that was instantiated and given to. But that's not working, only the first StringIO stores the logged info.
Any suggestions on what I'm missing?

    import logging
    from StringIO import StringIO
    formatter = logging.Formatter('%(asctime)s %(name)-3s %(levelname)-4s %(message)s')

    log_stream1 = StringIO()
    log1 = logging.getLogger('a')
    log1.setLevel(logging.DEBUG)
    stream_handler1 = logging.StreamHandler(log_stream1)
    stream_handler1.setLevel(logging.INFO)
    stream_handler1.setFormatter(formatter)
    log1.addHandler(stream_handler1)

    log_stream2 = StringIO()
    log2 = logging.getLogger('b')
    log2.setLevel(logging.DEBUG)
    stream_handler2 = logging.StreamHandler(log_stream2)
    stream_handler2.setLevel(logging.INFO)
    stream_handler2.setFormatter(formatter)
    log2.addHandler(stream_handler1)

    log1.info('log1')
    log2.info('log2')

output:

    In [6]: log_stream1.getvalue()
    Out[6]: '2017-06-08 10:05:12,468 a   INFO log1\n2017-06-08 10:05:12,468 b   INFO log2\n'

    In [7]: log_stream2.getvalue()
    Out[7]: ''

Body:
Change

log2.addHandler(stream_handler1)

To

log2.addHandler(stream_handler2)

Entire code:

import logging
from StringIO import StringIO
formatter = logging.Formatter('%(asctime)s %(name)-3s %(levelname)-4s %(message)s')

log_stream1 = StringIO()
log1 = logging.getLogger('a')
log1.setLevel(logging.DEBUG)
stream_handler1 = logging.StreamHandler(log_stream1)
stream_handler1.setLevel(logging.INFO)
stream_handler1.setFormatter(formatter)
log1.addHandler(stream_handler1)

log_stream2 = StringIO()
log2 = logging.getLogger('b')
log2.setLevel(logging.DEBUG)
stream_handler2 = logging.StreamHandler(log_stream2)
stream_handler2.setLevel(logging.INFO)
stream_handler2.setFormatter(formatter)
log2.addHandler(stream_handler2)

log1.info('log1')
log2.info('log2')


问:
Iterate Object containing instances of other objects
I am looking for an elegant solution for a specific situation.
I have a JSON file
After I parse it, I get a class object the has fields that are instances of other objects.
the class looks like this:

```<code>public class TaboolaResults {

@SerializedName("session")
@Expose
private String session;

@SerializedName("App-Below-Main-Column-Thumbnails-HP")
@Expose
private AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-2")
@Expose
private AppBelowMainColumnThumbnailsHP2 appBelowMainColumnThumbnailsHP2;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-3")
@Expose
private AppBelowMainColumnThumbnailsHP3 appBelowMainColumnThumbnailsHP3;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-4")
@Expose
private AppBelowMainColumnThumbnailsHP4 appBelowMainColumnThumbnailsHP4;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-5")
@Expose
private AppBelowMainColumnThumbnailsHP5 appBelowMainColumnThumbnailsHP5;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-6")
@Expose
private AppBelowMainColumnThumbnailsHP6 appBelowMainColumnThumbnailsHP6;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-7")
@Expose
private AppBelowMainColumnThumbnailsHP7 appBelowMainColumnThumbnailsHP7;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-8")
@Expose
private AppBelowMainColumnThumbnailsHP8 appBelowMainColumnThumbnailsHP8;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-9")
@Expose
private AppBelowMainColumnThumbnailsHP9 appBelowMainColumnThumbnailsHP9;

public String getSession() {
    return session;
}

public void setSession(String session) {
    this.session = session;
}

public AppBelowMainColumnThumbnailsHP getAppBelowMainColumnThumbnailsHP() {
    return appBelowMainColumnThumbnailsHP;
}

public void setAppBelowMainColumnThumbnailsHP(AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP) {
    this.appBelowMainColumnThumbnailsHP = appBelowMainColumnThumbnailsHP;
}

public AppBelowMainColumnThumbnailsHP2 getAppBelowMainColumnThumbnailsHP2() {
    return appBelowMainColumnThumbnailsHP2;
}

public void setAppBelowMainColumnThumbnailsHP2(AppBelowMainColumnThumbnailsHP2 appBelowMainColumnThumbnailsHP2) {
    this.appBelowMainColumnThumbnailsHP2 = appBelowMainColumnThumbnailsHP2;
}

public AppBelowMainColumnThumbnailsHP3 getAppBelowMainColumnThumbnailsHP3() {
    return appBelowMainColumnThumbnailsHP3;
}

public void setAppBelowMainColumnThumbnailsHP3(AppBelowMainColumnThumbnailsHP3 appBelowMainColumnThumbnailsHP3) {
    this.appBelowMainColumnThumbnailsHP3 = appBelowMainColumnThumbnailsHP3;
}

public AppBelowMainColumnThumbnailsHP4 getAppBelowMainColumnThumbnailsHP4() {
    return appBelowMainColumnThumbnailsHP4;
}

public void setAppBelowMainColumnThumbnailsHP4(AppBelowMainColumnThumbnailsHP4 appBelowMainColumnThumbnailsHP4) {
    this.appBelowMainColumnThumbnailsHP4 = appBelowMainColumnThumbnailsHP4;
}

public AppBelowMainColumnThumbnailsHP5 getAppBelowMainColumnThumbnailsHP5() {
    return appBelowMainColumnThumbnailsHP5;
}

public void setAppBelowMainColumnThumbnailsHP5(AppBelowMainColumnThumbnailsHP5 appBelowMainColumnThumbnailsHP5) {
    this.appBelowMainColumnThumbnailsHP5 = appBelowMainColumnThumbnailsHP5;
}

public AppBelowMainColumnThumbnailsHP6 getAppBelowMainColumnThumbnailsHP6() {
    return appBelowMainColumnThumbnailsHP6;
}

public void setAppBelowMainColumnThumbnailsHP6(AppBelowMainColumnThumbnailsHP6 appBelowMainColumnThumbnailsHP6) {
    this.appBelowMainColumnThumbnailsHP6 = appBelowMainColumnThumbnailsHP6;
}

public AppBelowMainColumnThumbnailsHP7 getAppBelowMainColumnThumbnailsHP7() {
    return appBelowMainColumnThumbnailsHP7;
}

public void setAppBelowMainColumnThumbnailsHP7(AppBelowMainColumnThumbnailsHP7 appBelowMainColumnThumbnailsHP7) {
    this.appBelowMainColumnThumbnailsHP7 = appBelowMainColumnThumbnailsHP7;
}

public AppBelowMainColumnThumbnailsHP8 getAppBelowMainColumnThumbnailsHP8() {
    return appBelowMainColumnThumbnailsHP8;
}

public void setAppBelowMainColumnThumbnailsHP8(AppBelowMainColumnThumbnailsHP8 appBelowMainColumnThumbnailsHP8) {
    this.appBelowMainColumnThumbnailsHP8 = appBelowMainColumnThumbnailsHP8;
}

public AppBelowMainColumnThumbnailsHP9 getAppBelowMainColumnThumbnailsHP9() {
    return appBelowMainColumnThumbnailsHP9;
}

public void setAppBelowMainColumnThumbnailsHP9(AppBelowMainColumnThumbnailsHP9 appBelowMainColumnThumbnailsHP9) {
    this.appBelowMainColumnThumbnailsHP9 = appBelowMainColumnThumbnailsHP9;
}
}
</code>```

A very not elegant way that I achieved what I need is:

```<code> private void extractTaboolaIntoFeed(final TaboolaResults results, final ArrayList<IFlexible> itemResults) {

    int i = 0;
    int currentTaboolaItem = 1;

    if (currentTaboolaItem <= mNumberOfTaboolaItems) {

        AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP = results.getAppBelowMainColumnThumbnailsHP();

        for (; i < itemResults.size(); i++) {

            if (itemResults.get(i) instanceof AbstractItem) {

                AbstractItem abstractItem = (AbstractItem) itemResults.get(i);

                FeedItemType itemType = abstractItem.getItemType();
                if (itemType.equals(FeedItemType.TABOOLA)) {
                    mTaboolaDataSet.add(new TaboolaDataSetItem(abstractItem.getItemId(), appBelowMainColumnThumbnailsHP));
                    currentTaboolaItem++;
                    break;
                }
            }
        }
    }

    if (currentTaboolaItem <= mNumberOfTaboolaItems) {
        AppBelowMainColumnThumbnailsHP2 appBelowMainColumnThumbnailsHP2 = results.getAppBelowMainColumnThumbnailsHP2();

        for (i++; i < itemResults.size(); i++) {
            if (itemResults.get(i) instanceof AbstractItem) {
                AbstractItem abstractItem = (AbstractItem) itemResults.get(i);
                FeedItemType itemType = abstractItem.getItemType();
                if (itemType.equals(FeedItemType.TABOOLA)) {
                    mTaboolaDataSet.add(new TaboolaDataSetItem(abstractItem.getItemId(), appBelowMainColumnThumbnailsHP2));
                    currentTaboolaItem++;
                    break;
                }
            }
        }
    }

    if (currentTaboolaItem <= mNumberOfTaboolaItems) {
        AppBelowMainColumnThumbnailsHP3 appBelowMainColumnThumbnailsHP3 = results.getAppBelowMainColumnThumbnailsHP3();
        for (i++; i < itemResults.size(); i++) {
            if (itemResults.get(i) instanceof AbstractItem) {
                AbstractItem abstractItem = (AbstractItem) itemResults.get(i);
                FeedItemType itemType = abstractItem.getItemType();
                if (itemType.equals(FeedItemType.TABOOLA)) {
                    mTaboolaDataSet.add(new TaboolaDataSetItem(abstractItem.getItemId(), appBelowMainColumnThumbnailsHP3));
                    currentTaboolaItem++;
                    break;
                }
            }
        }
    }

    if (currentTaboolaItem <= mNumberOfTaboolaItems) {
        AppBelowMainColumnThumbnailsHP4 appBelowMainColumnThumbnailsHP4 = results.getAppBelowMainColumnThumbnailsHP4();
        for (i++; i < itemResults.size(); i++) {

            if (itemResults.get(i) instanceof AbstractItem) {

                AbstractItem abstractItem = (AbstractItem) itemResults.get(i);
                FeedItemType itemType = abstractItem.getItemType();
                if (itemType.equals(FeedItemType.TABOOLA)) {
                    mTaboolaDataSet.add(new TaboolaDataSetItem(abstractItem.getItemId(), appBelowMainColumnThumbnailsHP4));
                    currentTaboolaItem++;
                    break;
                }
            }
        }
    }

    if (currentTaboolaItem <= mNumberOfTaboolaItems) {
        AppBelowMainColumnThumbnailsHP5 appBelowMainColumnThumbnailsHP5 = results.getAppBelowMainColumnThumbnailsHP5();
        for (i++; i < itemResults.size(); i++) {

            if (itemResults.get(i) instanceof AbstractItem) {

                AbstractItem abstractItem = (AbstractItem) itemResults.get(i);
                FeedItemType itemType = abstractItem.getItemType();
                if (itemType.equals(FeedItemType.TABOOLA)) {
                    mTaboolaDataSet.add(new TaboolaDataSetItem(abstractItem.getItemId(), appBelowMainColumnThumbnailsHP5));
                    currentTaboolaItem++;
                    break;
                }
            }
        }
    }

    if (currentTaboolaItem <= mNumberOfTaboolaItems) {
        AppBelowMainColumnThumbnailsHP6 appBelowMainColumnThumbnailsHP6 = results.getAppBelowMainColumnThumbnailsHP6();
        for (i++; i < itemResults.size(); i++) {
            if (itemResults.get(i) instanceof AbstractItem) {
                AbstractItem abstractItem = (AbstractItem) itemResults.get(i);
                FeedItemType itemType = abstractItem.getItemType();
                if (itemType.equals(FeedItemType.TABOOLA)) {
                    mTaboolaDataSet.add(new TaboolaDataSetItem(abstractItem.getItemId(), appBelowMainColumnThumbnailsHP6));
                    currentTaboolaItem++;
                    break;
                }
            }
        }
    }

    if (currentTaboolaItem <= mNumberOfTaboolaItems) {
        AppBelowMainColumnThumbnailsHP7 appBelowMainColumnThumbnailsHP7 = results.getAppBelowMainColumnThumbnailsHP7();
        for (i++; i < itemResults.size(); i++) {
            if (itemResults.get(i) instanceof AbstractItem) {
                AbstractItem abstractItem = (AbstractItem) itemResults.get(i);
                FeedItemType itemType = abstractItem.getItemType();
                if (itemType.equals(FeedItemType.TABOOLA)) {
                    mTaboolaDataSet.add(new TaboolaDataSetItem(abstractItem.getItemId(), appBelowMainColumnThumbnailsHP7));
                    currentTaboolaItem++;
                    break;
                }
            }
        }
    }

    if (currentTaboolaItem <= mNumberOfTaboolaItems) {
        AppBelowMainColumnThumbnailsHP8 appBelowMainColumnThumbnailsHP8 = results.getAppBelowMainColumnThumbnailsHP8();
        for (i++; i < itemResults.size(); i++) {
            if (itemResults.get(i) instanceof AbstractItem) {
                AbstractItem abstractItem = (AbstractItem) itemResults.get(i);
                FeedItemType itemType = abstractItem.getItemType();
                if (itemType.equals(FeedItemType.TABOOLA)) {
                    mTaboolaDataSet.add(new TaboolaDataSetItem(abstractItem.getItemId(), appBelowMainColumnThumbnailsHP8));
                    currentTaboolaItem++;
                    break;
                }
            }
        }
    }

    if (currentTaboolaItem <= mNumberOfTaboolaItems) {
        AppBelowMainColumnThumbnailsHP9 appBelowMainColumnThumbnailsHP9 = results.getAppBelowMainColumnThumbnailsHP9();
        for (i++; i < itemResults.size(); i++) {
            if (itemResults.get(i) instanceof AbstractItem) {
                AbstractItem abstractItem = (AbstractItem) itemResults.get(i);
                FeedItemType itemType = abstractItem.getItemType();
                if (itemType.equals(FeedItemType.TABOOLA)) {
                    mTaboolaDataSet.add(new TaboolaDataSetItem(abstractItem.getItemId(), appBelowMainColumnThumbnailsHP9));
                    currentTaboolaItem++;
                    break;
                }
            }
        }
    }
}
</code>```

I'm currently using gson to parse.
The result object containing the instances of the other object are the models received from gson.

Each time I parse the json, the class can contain a different number of objects, according to the response I get from the server.
So the goal is to iterate the fields of the class and check the class results, and check it has result objects or null.

Idily in theory:

Get the class object result, iterate all instance object results, and if object != null, do somethig.

Another possible solution if anybody knows if/how to accomplish it is to configure gson that even though the file contains different objects (objects with a different name), make gson create all objects the same as the equal objects with the same name.

Can anyone advise me a better way to do this?
Thank you

答:
Ended up changing the class to:

```<code>public class TaboolaResults {

@SerializedName("session")
@Expose
private String session;

@SerializedName("App-Below-Main-Column-Thumbnails-HP")
@Expose
private AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-2")
@Expose
private AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP2;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-3")
@Expose
private AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP3;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-4")
@Expose
private AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP4;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-5")
@Expose
private AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP5;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-6")
@Expose
private AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP6;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-7")
@Expose
private AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP7;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-8")
@Expose
private AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP8;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-9")
@Expose
private AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP9;
</code>```

and simply iterate all results like this:

```<code>int currentTaboola = 1;
        for (int i = 0; i < feedItems.size(); i++) {
            if (feedItems.get(i) instanceof TaboolaItem) {
                AbstractItem item = (AbstractItem) feedItems.get(i);
                AppBelowMainColumnThumbnailsHP taboolaResult = mGsonResults.getAppBelowMainColumnThumbnails(currentTaboola);
                mTaboolaDataSet.add(new TaboolaDataSetItem(item.getItemId(), taboolaResult));
                currentTaboola++;
            }
        }
</code>```

Body:
I am looking for an elegant solution for a specific situation.
I have a JSON file
After I parse it, I get a class object the has fields that are instances of other objects.
the class looks like this:

public class TaboolaResults {

@SerializedName("session")
@Expose
private String session;

@SerializedName("App-Below-Main-Column-Thumbnails-HP")
@Expose
private AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-2")
@Expose
private AppBelowMainColumnThumbnailsHP2 appBelowMainColumnThumbnailsHP2;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-3")
@Expose
private AppBelowMainColumnThumbnailsHP3 appBelowMainColumnThumbnailsHP3;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-4")
@Expose
private AppBelowMainColumnThumbnailsHP4 appBelowMainColumnThumbnailsHP4;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-5")
@Expose
private AppBelowMainColumnThumbnailsHP5 appBelowMainColumnThumbnailsHP5;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-6")
@Expose
private AppBelowMainColumnThumbnailsHP6 appBelowMainColumnThumbnailsHP6;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-7")
@Expose
private AppBelowMainColumnThumbnailsHP7 appBelowMainColumnThumbnailsHP7;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-8")
@Expose
private AppBelowMainColumnThumbnailsHP8 appBelowMainColumnThumbnailsHP8;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-9")
@Expose
private AppBelowMainColumnThumbnailsHP9 appBelowMainColumnThumbnailsHP9;

public String getSession() {
    return session;
}

public void setSession(String session) {
    this.session = session;
}

public AppBelowMainColumnThumbnailsHP getAppBelowMainColumnThumbnailsHP() {
    return appBelowMainColumnThumbnailsHP;
}

public void setAppBelowMainColumnThumbnailsHP(AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP) {
    this.appBelowMainColumnThumbnailsHP = appBelowMainColumnThumbnailsHP;
}

public AppBelowMainColumnThumbnailsHP2 getAppBelowMainColumnThumbnailsHP2() {
    return appBelowMainColumnThumbnailsHP2;
}

public void setAppBelowMainColumnThumbnailsHP2(AppBelowMainColumnThumbnailsHP2 appBelowMainColumnThumbnailsHP2) {
    this.appBelowMainColumnThumbnailsHP2 = appBelowMainColumnThumbnailsHP2;
}

public AppBelowMainColumnThumbnailsHP3 getAppBelowMainColumnThumbnailsHP3() {
    return appBelowMainColumnThumbnailsHP3;
}

public void setAppBelowMainColumnThumbnailsHP3(AppBelowMainColumnThumbnailsHP3 appBelowMainColumnThumbnailsHP3) {
    this.appBelowMainColumnThumbnailsHP3 = appBelowMainColumnThumbnailsHP3;
}

public AppBelowMainColumnThumbnailsHP4 getAppBelowMainColumnThumbnailsHP4() {
    return appBelowMainColumnThumbnailsHP4;
}

public void setAppBelowMainColumnThumbnailsHP4(AppBelowMainColumnThumbnailsHP4 appBelowMainColumnThumbnailsHP4) {
    this.appBelowMainColumnThumbnailsHP4 = appBelowMainColumnThumbnailsHP4;
}

public AppBelowMainColumnThumbnailsHP5 getAppBelowMainColumnThumbnailsHP5() {
    return appBelowMainColumnThumbnailsHP5;
}

public void setAppBelowMainColumnThumbnailsHP5(AppBelowMainColumnThumbnailsHP5 appBelowMainColumnThumbnailsHP5) {
    this.appBelowMainColumnThumbnailsHP5 = appBelowMainColumnThumbnailsHP5;
}

public AppBelowMainColumnThumbnailsHP6 getAppBelowMainColumnThumbnailsHP6() {
    return appBelowMainColumnThumbnailsHP6;
}

public void setAppBelowMainColumnThumbnailsHP6(AppBelowMainColumnThumbnailsHP6 appBelowMainColumnThumbnailsHP6) {
    this.appBelowMainColumnThumbnailsHP6 = appBelowMainColumnThumbnailsHP6;
}

public AppBelowMainColumnThumbnailsHP7 getAppBelowMainColumnThumbnailsHP7() {
    return appBelowMainColumnThumbnailsHP7;
}

public void setAppBelowMainColumnThumbnailsHP7(AppBelowMainColumnThumbnailsHP7 appBelowMainColumnThumbnailsHP7) {
    this.appBelowMainColumnThumbnailsHP7 = appBelowMainColumnThumbnailsHP7;
}

public AppBelowMainColumnThumbnailsHP8 getAppBelowMainColumnThumbnailsHP8() {
    return appBelowMainColumnThumbnailsHP8;
}

public void setAppBelowMainColumnThumbnailsHP8(AppBelowMainColumnThumbnailsHP8 appBelowMainColumnThumbnailsHP8) {
    this.appBelowMainColumnThumbnailsHP8 = appBelowMainColumnThumbnailsHP8;
}

public AppBelowMainColumnThumbnailsHP9 getAppBelowMainColumnThumbnailsHP9() {
    return appBelowMainColumnThumbnailsHP9;
}

public void setAppBelowMainColumnThumbnailsHP9(AppBelowMainColumnThumbnailsHP9 appBelowMainColumnThumbnailsHP9) {
    this.appBelowMainColumnThumbnailsHP9 = appBelowMainColumnThumbnailsHP9;
}
}

A very not elegant way that I achieved what I need is:

 private void extractTaboolaIntoFeed(final TaboolaResults results, final ArrayList<IFlexible> itemResults) {

    int i = 0;
    int currentTaboolaItem = 1;

    if (currentTaboolaItem <= mNumberOfTaboolaItems) {

        AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP = results.getAppBelowMainColumnThumbnailsHP();

        for (; i < itemResults.size(); i++) {

            if (itemResults.get(i) instanceof AbstractItem) {

                AbstractItem abstractItem = (AbstractItem) itemResults.get(i);

                FeedItemType itemType = abstractItem.getItemType();
                if (itemType.equals(FeedItemType.TABOOLA)) {
                    mTaboolaDataSet.add(new TaboolaDataSetItem(abstractItem.getItemId(), appBelowMainColumnThumbnailsHP));
                    currentTaboolaItem++;
                    break;
                }
            }
        }
    }

    if (currentTaboolaItem <= mNumberOfTaboolaItems) {
        AppBelowMainColumnThumbnailsHP2 appBelowMainColumnThumbnailsHP2 = results.getAppBelowMainColumnThumbnailsHP2();

        for (i++; i < itemResults.size(); i++) {
            if (itemResults.get(i) instanceof AbstractItem) {
                AbstractItem abstractItem = (AbstractItem) itemResults.get(i);
                FeedItemType itemType = abstractItem.getItemType();
                if (itemType.equals(FeedItemType.TABOOLA)) {
                    mTaboolaDataSet.add(new TaboolaDataSetItem(abstractItem.getItemId(), appBelowMainColumnThumbnailsHP2));
                    currentTaboolaItem++;
                    break;
                }
            }
        }
    }

    if (currentTaboolaItem <= mNumberOfTaboolaItems) {
        AppBelowMainColumnThumbnailsHP3 appBelowMainColumnThumbnailsHP3 = results.getAppBelowMainColumnThumbnailsHP3();
        for (i++; i < itemResults.size(); i++) {
            if (itemResults.get(i) instanceof AbstractItem) {
                AbstractItem abstractItem = (AbstractItem) itemResults.get(i);
                FeedItemType itemType = abstractItem.getItemType();
                if (itemType.equals(FeedItemType.TABOOLA)) {
                    mTaboolaDataSet.add(new TaboolaDataSetItem(abstractItem.getItemId(), appBelowMainColumnThumbnailsHP3));
                    currentTaboolaItem++;
                    break;
                }
            }
        }
    }

    if (currentTaboolaItem <= mNumberOfTaboolaItems) {
        AppBelowMainColumnThumbnailsHP4 appBelowMainColumnThumbnailsHP4 = results.getAppBelowMainColumnThumbnailsHP4();
        for (i++; i < itemResults.size(); i++) {

            if (itemResults.get(i) instanceof AbstractItem) {

                AbstractItem abstractItem = (AbstractItem) itemResults.get(i);
                FeedItemType itemType = abstractItem.getItemType();
                if (itemType.equals(FeedItemType.TABOOLA)) {
                    mTaboolaDataSet.add(new TaboolaDataSetItem(abstractItem.getItemId(), appBelowMainColumnThumbnailsHP4));
                    currentTaboolaItem++;
                    break;
                }
            }
        }
    }

    if (currentTaboolaItem <= mNumberOfTaboolaItems) {
        AppBelowMainColumnThumbnailsHP5 appBelowMainColumnThumbnailsHP5 = results.getAppBelowMainColumnThumbnailsHP5();
        for (i++; i < itemResults.size(); i++) {

            if (itemResults.get(i) instanceof AbstractItem) {

                AbstractItem abstractItem = (AbstractItem) itemResults.get(i);
                FeedItemType itemType = abstractItem.getItemType();
                if (itemType.equals(FeedItemType.TABOOLA)) {
                    mTaboolaDataSet.add(new TaboolaDataSetItem(abstractItem.getItemId(), appBelowMainColumnThumbnailsHP5));
                    currentTaboolaItem++;
                    break;
                }
            }
        }
    }

    if (currentTaboolaItem <= mNumberOfTaboolaItems) {
        AppBelowMainColumnThumbnailsHP6 appBelowMainColumnThumbnailsHP6 = results.getAppBelowMainColumnThumbnailsHP6();
        for (i++; i < itemResults.size(); i++) {
            if (itemResults.get(i) instanceof AbstractItem) {
                AbstractItem abstractItem = (AbstractItem) itemResults.get(i);
                FeedItemType itemType = abstractItem.getItemType();
                if (itemType.equals(FeedItemType.TABOOLA)) {
                    mTaboolaDataSet.add(new TaboolaDataSetItem(abstractItem.getItemId(), appBelowMainColumnThumbnailsHP6));
                    currentTaboolaItem++;
                    break;
                }
            }
        }
    }

    if (currentTaboolaItem <= mNumberOfTaboolaItems) {
        AppBelowMainColumnThumbnailsHP7 appBelowMainColumnThumbnailsHP7 = results.getAppBelowMainColumnThumbnailsHP7();
        for (i++; i < itemResults.size(); i++) {
            if (itemResults.get(i) instanceof AbstractItem) {
                AbstractItem abstractItem = (AbstractItem) itemResults.get(i);
                FeedItemType itemType = abstractItem.getItemType();
                if (itemType.equals(FeedItemType.TABOOLA)) {
                    mTaboolaDataSet.add(new TaboolaDataSetItem(abstractItem.getItemId(), appBelowMainColumnThumbnailsHP7));
                    currentTaboolaItem++;
                    break;
                }
            }
        }
    }

    if (currentTaboolaItem <= mNumberOfTaboolaItems) {
        AppBelowMainColumnThumbnailsHP8 appBelowMainColumnThumbnailsHP8 = results.getAppBelowMainColumnThumbnailsHP8();
        for (i++; i < itemResults.size(); i++) {
            if (itemResults.get(i) instanceof AbstractItem) {
                AbstractItem abstractItem = (AbstractItem) itemResults.get(i);
                FeedItemType itemType = abstractItem.getItemType();
                if (itemType.equals(FeedItemType.TABOOLA)) {
                    mTaboolaDataSet.add(new TaboolaDataSetItem(abstractItem.getItemId(), appBelowMainColumnThumbnailsHP8));
                    currentTaboolaItem++;
                    break;
                }
            }
        }
    }

    if (currentTaboolaItem <= mNumberOfTaboolaItems) {
        AppBelowMainColumnThumbnailsHP9 appBelowMainColumnThumbnailsHP9 = results.getAppBelowMainColumnThumbnailsHP9();
        for (i++; i < itemResults.size(); i++) {
            if (itemResults.get(i) instanceof AbstractItem) {
                AbstractItem abstractItem = (AbstractItem) itemResults.get(i);
                FeedItemType itemType = abstractItem.getItemType();
                if (itemType.equals(FeedItemType.TABOOLA)) {
                    mTaboolaDataSet.add(new TaboolaDataSetItem(abstractItem.getItemId(), appBelowMainColumnThumbnailsHP9));
                    currentTaboolaItem++;
                    break;
                }
            }
        }
    }
}

I'm currently using gson to parse.
The result object containing the instances of the other object are the models received from gson.

Each time I parse the json, the class can contain a different number of objects, according to the response I get from the server.
So the goal is to iterate the fields of the class and check the class results, and check it has result objects or null.

Idily in theory:

Get the class object result, iterate all instance object results, and if object != null, do somethig.

Another possible solution if anybody knows if/how to accomplish it is to configure gson that even though the file contains different objects (objects with a different name), make gson create all objects the same as the equal objects with the same name.

Can anyone advise me a better way to do this?
Thank you

Body:
Ended up changing the class to:

public class TaboolaResults {

@SerializedName("session")
@Expose
private String session;

@SerializedName("App-Below-Main-Column-Thumbnails-HP")
@Expose
private AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-2")
@Expose
private AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP2;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-3")
@Expose
private AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP3;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-4")
@Expose
private AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP4;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-5")
@Expose
private AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP5;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-6")
@Expose
private AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP6;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-7")
@Expose
private AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP7;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-8")
@Expose
private AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP8;

@SerializedName("App-Below-Main-Column-Thumbnails-HP-9")
@Expose
private AppBelowMainColumnThumbnailsHP appBelowMainColumnThumbnailsHP9;

and simply iterate all results like this:

int currentTaboola = 1;
        for (int i = 0; i < feedItems.size(); i++) {
            if (feedItems.get(i) instanceof TaboolaItem) {
                AbstractItem item = (AbstractItem) feedItems.get(i);
                AppBelowMainColumnThumbnailsHP taboolaResult = mGsonResults.getAppBelowMainColumnThumbnails(currentTaboola);
                mTaboolaDataSet.add(new TaboolaDataSetItem(item.getItemId(), taboolaResult));
                currentTaboola++;
            }
        }


问:
Android webview with PDF load
I am loading a page inside the webview

```<code>webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://www.xxxxxxxxx/howtoguide.aspx");
</code>```

then inside the webview I have several function to click event below

```<code>            @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (url.contains("concierge@xxxx.com.sg")) {
                final Intent eIntent = new Intent(
                        android.content.Intent.ACTION_SEND);
                eIntent.setType("plain/text");
                eIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                        new String[]{"xxxxxx"});
                eIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                        "");
                eIntent.putExtra(android.content.Intent.EXTRA_TEXT,
                        "Text to be send");
                startActivity(Intent.createChooser(eIntent,
                        "Send mail..."));

            } else if (url.startsWith("tel:")) {

            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
                startActivity(intent);
                view.reload();

            } else if (url.contains(".pdf")) {
            //Intent intent = new Intent(Intent.ACTION_VIEW);
            //intent.setDataAndType(Uri.parse(url), "application/pdf");
            //try{
            //view.getContext().startActivity(intent);
            //} catch (ActivityNotFoundException e) {
            //user does not have a pdf viewer installed
            //}
            // view.loadUrl("https://docs.google.com/viewer?url=" + url);
               view.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + url);
            } else {
                view.loadUrl(url);
            }
            return true;
        }
</code>```

in this webview there is a click event for PDF. So if I click this the PDF not loading

答:
Please check the below example code for your requirement

```<code>private void init()
{
    WebView webview = (WebView) findViewById(R.id.webview);
    WebSettings settings = webview.getSettings();
    settings.setJavaScriptEnabled(true);
    webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

    MyWebViewClient webViewClient = new MyWebViewClient(this, webview);
    webViewClient.loadUrl(YOUR_URL);
}

private class MyWebViewClient extends WebViewClient
{
    private static final String TAG = "MyWebViewClient";
    private static final String PDF_EXTENSION = ".pdf";
    private static final String PDF_VIEWER_URL = "https://drive.google.com/viewerng/viewer?embedded=true&url=";

    private Context mContext;
    private WebView mWebView;
    private ProgressDialog mProgressDialog;
    private boolean isLoadingPdfUrl;

    public MyWebViewClient(Context context, WebView webView)
    {
        mContext = context;
        mWebView = webView;
        mWebView.setWebViewClient(this);
    }

    public void loadUrl(String url)
    {
        mWebView.stopLoading();

        if (!TextUtils.isEmpty(url))
        {
            isLoadingPdfUrl = isPdfUrl(url);
            if (isLoadingPdfUrl)
            {
                mWebView.clearHistory();
            }

            showProgressDialog();
        }

        mWebView.loadUrl(url);
    }

    @SuppressWarnings("deprecation")
    @Override
    public boolean shouldOverrideUrlLoading(WebView webView, String url)
    {
        return shouldOverrideUrlLoading(url);
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl)
    {
        handleError(errorCode, description.toString(), failingUrl);
    }

    @TargetApi(Build.VERSION_CODES.N)
    @Override
    public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest request)
    {
        final Uri uri = request.getUrl();
        return shouldOverrideUrlLoading(webView, uri.toString());
    }

    @TargetApi(Build.VERSION_CODES.N)
    @Override
    public void onReceivedError(final WebView webView, final WebResourceRequest request, final WebResourceError error)
    {
        final Uri uri = request.getUrl();
        handleError(error.getErrorCode(), error.getDescription().toString(), uri.toString());
    }

    @Override
    public void onPageFinished(final WebView view, final String url)
    {
        Log.i(TAG, "Finished loading. URL : " + url);
        dismissProgressDialog();
    }

    private boolean shouldOverrideUrlLoading(final String url)
    {
        Log.i(TAG, "shouldOverrideUrlLoading() URL : " + url);

        if (url.contains("concierge@xxxx.com.sg"))
        {
            Intent eIntent = new Intent(android.content.Intent.ACTION_SEND);
            eIntent.setType("plain/text");
            eIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"xxxxxx"});
            eIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
            eIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Text to be send");
            startActivity(Intent.createChooser(eIntent, "Send mail..."));
            return true;
        }
        else if (url.startsWith("tel:"))
        {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
            startActivity(intent);
            return true;
        }
        else if (!isLoadingPdfUrl && isPdfUrl(url))
        {
            mWebView.stopLoading();

            final String pdfUrl = PDF_VIEWER_URL + url;

            new Handler().postDelayed(new Runnable()
            {
                @Override
                public void run()
                {
                    loadUrl(pdfUrl);
                }
            }, 300);

            return true;
        }

        return false; // Load url in the webView itself
    }

    private void handleError(final int errorCode, final String description, final String failingUrl)
    {
        Log.e(TAG, "Error : " + errorCode + ", " + description + " URL : " + failingUrl);
    }

    private void showProgressDialog()
    {
        dismissProgressDialog();
        mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
    }

    private void dismissProgressDialog()
    {
        if (mProgressDialog != null && mProgressDialog.isShowing())
        {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    private boolean isPdfUrl(String url)
    {
        if (!TextUtils.isEmpty(url))
        {
            url = url.trim();
            int lastIndex = url.toLowerCase().lastIndexOf(PDF_EXTENSION);
            if (lastIndex != -1)
            {
                return url.substring(lastIndex).equalsIgnoreCase(PDF_EXTENSION);
            }
        }
        return false;
    }
}
</code>```

Checkout the example code for handling redirect urls and open PDF without download, in webview. https://gist.github.com/ashishdas09/014a408f9f37504eb2608d98abf49500

Title: Android webview with PDF load

Body:
I am loading a page inside the webview

webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://www.xxxxxxxxx/howtoguide.aspx");

then inside the webview I have several function to click event below

            @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (url.contains("concierge@xxxx.com.sg")) {
                final Intent eIntent = new Intent(
                        android.content.Intent.ACTION_SEND);
                eIntent.setType("plain/text");
                eIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                        new String[]{"xxxxxx"});
                eIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                        "");
                eIntent.putExtra(android.content.Intent.EXTRA_TEXT,
                        "Text to be send");
                startActivity(Intent.createChooser(eIntent,
                        "Send mail..."));

            } else if (url.startsWith("tel:")) {

            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
                startActivity(intent);
                view.reload();

            } else if (url.contains(".pdf")) {
            //Intent intent = new Intent(Intent.ACTION_VIEW);
            //intent.setDataAndType(Uri.parse(url), "application/pdf");
            //try{
            //view.getContext().startActivity(intent);
            //} catch (ActivityNotFoundException e) {
            //user does not have a pdf viewer installed
            //}
            // view.loadUrl("https://docs.google.com/viewer?url=" + url);
               view.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + url);
            } else {
                view.loadUrl(url);
            }
            return true;
        }

in this webview there is a click event for PDF. So if I click this the PDF not loading

Body:
Please check the below example code for your requirement

private void init()
{
    WebView webview = (WebView) findViewById(R.id.webview);
    WebSettings settings = webview.getSettings();
    settings.setJavaScriptEnabled(true);
    webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

    MyWebViewClient webViewClient = new MyWebViewClient(this, webview);
    webViewClient.loadUrl(YOUR_URL);
}

private class MyWebViewClient extends WebViewClient
{
    private static final String TAG = "MyWebViewClient";
    private static final String PDF_EXTENSION = ".pdf";
    private static final String PDF_VIEWER_URL = "https://drive.google.com/viewerng/viewer?embedded=true&url=";

    private Context mContext;
    private WebView mWebView;
    private ProgressDialog mProgressDialog;
    private boolean isLoadingPdfUrl;

    public MyWebViewClient(Context context, WebView webView)
    {
        mContext = context;
        mWebView = webView;
        mWebView.setWebViewClient(this);
    }

    public void loadUrl(String url)
    {
        mWebView.stopLoading();

        if (!TextUtils.isEmpty(url))
        {
            isLoadingPdfUrl = isPdfUrl(url);
            if (isLoadingPdfUrl)
            {
                mWebView.clearHistory();
            }

            showProgressDialog();
        }

        mWebView.loadUrl(url);
    }

    @SuppressWarnings("deprecation")
    @Override
    public boolean shouldOverrideUrlLoading(WebView webView, String url)
    {
        return shouldOverrideUrlLoading(url);
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl)
    {
        handleError(errorCode, description.toString(), failingUrl);
    }

    @TargetApi(Build.VERSION_CODES.N)
    @Override
    public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest request)
    {
        final Uri uri = request.getUrl();
        return shouldOverrideUrlLoading(webView, uri.toString());
    }

    @TargetApi(Build.VERSION_CODES.N)
    @Override
    public void onReceivedError(final WebView webView, final WebResourceRequest request, final WebResourceError error)
    {
        final Uri uri = request.getUrl();
        handleError(error.getErrorCode(), error.getDescription().toString(), uri.toString());
    }

    @Override
    public void onPageFinished(final WebView view, final String url)
    {
        Log.i(TAG, "Finished loading. URL : " + url);
        dismissProgressDialog();
    }

    private boolean shouldOverrideUrlLoading(final String url)
    {
        Log.i(TAG, "shouldOverrideUrlLoading() URL : " + url);

        if (url.contains("concierge@xxxx.com.sg"))
        {
            Intent eIntent = new Intent(android.content.Intent.ACTION_SEND);
            eIntent.setType("plain/text");
            eIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"xxxxxx"});
            eIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
            eIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Text to be send");
            startActivity(Intent.createChooser(eIntent, "Send mail..."));
            return true;
        }
        else if (url.startsWith("tel:"))
        {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
            startActivity(intent);
            return true;
        }
        else if (!isLoadingPdfUrl && isPdfUrl(url))
        {
            mWebView.stopLoading();

            final String pdfUrl = PDF_VIEWER_URL + url;

            new Handler().postDelayed(new Runnable()
            {
                @Override
                public void run()
                {
                    loadUrl(pdfUrl);
                }
            }, 300);

            return true;
        }

        return false; // Load url in the webView itself
    }

    private void handleError(final int errorCode, final String description, final String failingUrl)
    {
        Log.e(TAG, "Error : " + errorCode + ", " + description + " URL : " + failingUrl);
    }

    private void showProgressDialog()
    {
        dismissProgressDialog();
        mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
    }

    private void dismissProgressDialog()
    {
        if (mProgressDialog != null && mProgressDialog.isShowing())
        {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    private boolean isPdfUrl(String url)
    {
        if (!TextUtils.isEmpty(url))
        {
            url = url.trim();
            int lastIndex = url.toLowerCase().lastIndexOf(PDF_EXTENSION);
            if (lastIndex != -1)
            {
                return url.substring(lastIndex).equalsIgnoreCase(PDF_EXTENSION);
            }
        }
        return false;
    }
}

Checkout the example code for handling redirect urls and open PDF without download, in webview. https://gist.github.com/ashishdas09/014a408f9f37504eb2608d98abf49500