问:
ASP.NET MVC 3.0 Razor, load View from anywhere out of the box?
Is it true that it is possible to load View from anywhere without
implementation of custom VirtualPathProvider in MVC 3.0?

If it is true how to do it?

Basically it is not a problem to implement custom VirtualPathProvider which would load the
View from anywhere but my implementation working only in MVC 2.0 and not working wih MVC 3.0, fore some reason method GetFile newer called for not existed views in MVC 3.0 and in that case I am getting "Server Error in '/' Application."

I followed the same code for my custom VirtualPathProvider from here: http://buildstarted.com/2010/09/28/mvc-3-razor-view-engine-without-a-controller/

UPDATE 1

OK i did fix my problem with my custom VirtualPathProvider after i put registration of my custom VirtualPathProvider provider first line in the Application_Start()

```<code>    protected void Application_Start()
    {
        //Should be first line before routes and areas registration.
        HostingEnvironment.RegisterVirtualPathProvider(new MyVirtualPathProvider());

        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }
</code>```

When registration of custom VirtualPathProvider in Global.asax.cs folowing after AreaRegistration.RegisterAllAreas(); or RegisterRoutes(RouteTable.Routes); method method override VirtualFile GetFile(string virtualPath) wont work for "virtual Views".

UPDATE 2

does it means that the classes RazorView and RazorViewEngineRender is the answer?

UPDATE 3

If i have string representation of my razor view which does not exists in the file system (e.g i store razor views in database) how may i render it using this kind of approach http://buildstarted.com/2010/09/28/mvc-3-razor-view-engine-without-a-controller/

For example string representation of my View looks like this:

```<code>"@{
    ViewBag.Title = ""About Us"";
}

<h2>About</h2>
<p>
     Put content here.
</p>"
</code>```

UPDATE 4

Now i see, to be able to use @Html.<something> custom TemplateBase should be implemented.
The sample of implementation of HtmlTemplateBase<T> could be fount here http://www.fidelitydesign.net/?p=239, but it won't work with RazorEngine v2, i am successfully getting template compiled, then after assembly loaded method public override void Execute() won't be executed i am getting an error: The method or operation is not implemented (stacktrace: http://tinypic.com/r/dcow4/7)

To make “public override T Model” happened i did change declaration of “public TModel Model” to “public virtual TModel Model” in “public abstract class TemplateBase : TemplateBase, ITemplate”. May be there is some another changes should be done? Or something in HtmlTemplateBase<T> should be done another way?

答:
Don't be confused by Ben's (@BuildStarted) sample code in his article.  He is detailing how to use an early version of the Razor ViewEngine to render templates without using a controller action.  The intention was to be able to render templates in a generic fashion, rather than as specific page views. (This is what has evolved into our RazorEngine templating framework @ http://razorengine.codeplex.com).

The VirtualPathProvider is still a core part of ASP.NET.  There appears to be a general confusion about MVC 3's DependencyResolver being a replacement of a VirtualPathProvider but this is not the case, you still require a provider to be able to access content on a virtual path (which incidentally, all paths in ASP.NET are virtual).

Reverting my original answer, you should be able to achieve what you want purely through subclassing the RazorViewEngine and using that to create your views.

Have a look at this topic: http://coderjournal.com/2009/05/creating-your-first-mvc-viewengine/

Body:
Is it true that it is possible to load View from anywhere without
implementation of custom VirtualPathProvider in MVC 3.0?

If it is true how to do it?

Basically it is not a problem to implement custom VirtualPathProvider which would load the
View from anywhere but my implementation working only in MVC 2.0 and not working wih MVC 3.0, fore some reason method GetFile newer called for not existed views in MVC 3.0 and in that case I am getting "Server Error in '/' Application."

I followed the same code for my custom VirtualPathProvider from here: http://buildstarted.com/2010/09/28/mvc-3-razor-view-engine-without-a-controller/

UPDATE 1

OK i did fix my problem with my custom VirtualPathProvider after i put registration of my custom VirtualPathProvider provider first line in the Application_Start()

    protected void Application_Start()
    {
        //Should be first line before routes and areas registration.
        HostingEnvironment.RegisterVirtualPathProvider(new MyVirtualPathProvider());

        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

When registration of custom VirtualPathProvider in Global.asax.cs folowing after AreaRegistration.RegisterAllAreas(); or RegisterRoutes(RouteTable.Routes); method method override VirtualFile GetFile(string virtualPath) wont work for "virtual Views".

UPDATE 2

does it means that the classes RazorView and RazorViewEngineRender is the answer?

UPDATE 3

If i have string representation of my razor view which does not exists in the file system (e.g i store razor views in database) how may i render it using this kind of approach http://buildstarted.com/2010/09/28/mvc-3-razor-view-engine-without-a-controller/

For example string representation of my View looks like this:

"@{
    ViewBag.Title = ""About Us"";
}

About

     Put content here.

"

UPDATE 4

Now i see, to be able to use @Html.<something> custom TemplateBase should be implemented.
The sample of implementation of HtmlTemplateBase<T> could be fount here http://www.fidelitydesign.net/?p=239, but it won't work with RazorEngine v2, i am successfully getting template compiled, then after assembly loaded method public override void Execute() won't be executed i am getting an error: The method or operation is not implemented (stacktrace: http://tinypic.com/r/dcow4/7)

To make “public override T Model” happened i did change declaration of “public TModel Model” to “public virtual TModel Model” in “public abstract class TemplateBase : TemplateBase, ITemplate”. May be there is some another changes should be done? Or something in HtmlTemplateBase<T> should be done another way?


来源: stackexchange

问:
Required to Declare Primary Keys on Junction Table?
In a junction table made up of only foreign keys (e.g. ShopSupplier in the example below), must we also declare those columns as primary keys in the DDL create statement? If yes, what would be the point of doing so? I would argue that these are NOT primary keys in the example below

```<code>CREATE TABLE Shop
(
    ShopID TEXT PRIMARY KEY UNIQUE,
    ShopName TEXT
);

CREATE TABLE Supplier
(
    SupplierID TEXT PRIMARY KEY UNIQUE,
    SupplierName TEXT
);

CREATE TABLE ShopSupplier
(
    ShopID TEXT,
    SupplierID TEXT,
    FOREIGN KEY(ShopID) REFERENCES Shop(ShopID),
    FOREIGN KEY(SupplierID) REFERENCES Supplier(SupplierID)
);
</code>```

The question again: Should I also declare PRIMARY KEY(ShopID, SupplierID) for the ShopSupplier table. If so, why? I would argue that there should be no primary key for that table.

答:
Both columns are foreign key, because they are referencing to other tables. In the case that only single connection between specific rows of Shopand Supplier may exit, you can use a unique constraint or create a combined primary key:

```<code>CREATE TABLE ShopSupplier(
  ShopID TEXT,
  SupplierID TEXT,
  PRIMARY KEY(ShopID, SupplierID),
  FOREIGN KEY(ShopID) REFERENCES Shop(ShopID),
  FOREIGN KEY(SupplierID) REFERENCES Supplier(SupplierID));
</code>```

Then, both columns are foreign keys and belonging to the primary key.

In general setting the columns of a (pure) junction table as primary key isn't necessary. You may use it as a constraint to prohibit duplicates.

ContentLicense: CC BY-SA 3.0

Body:
In a junction table made up of only foreign keys (e.g. ShopSupplier in the example below), must we also declare those columns as primary keys in the DDL create statement? If yes, what would be the point of doing so? I would argue that these are NOT primary keys in the example below

CREATE TABLE Shop
(
    ShopID TEXT PRIMARY KEY UNIQUE,
    ShopName TEXT
);

CREATE TABLE Supplier
(
    SupplierID TEXT PRIMARY KEY UNIQUE,
    SupplierName TEXT
);

CREATE TABLE ShopSupplier
(
    ShopID TEXT,
    SupplierID TEXT,
    FOREIGN KEY(ShopID) REFERENCES Shop(ShopID),
    FOREIGN KEY(SupplierID) REFERENCES Supplier(SupplierID)
);

The question again: Should I also declare PRIMARY KEY(ShopID, SupplierID) for the ShopSupplier table. If so, why? I would argue that there should be no primary key for that table.

Body:
Both columns are foreign key, because they are referencing to other tables. In the case that only single connection between specific rows of Shopand Supplier may exit, you can use a unique constraint or create a combined primary key:

CREATE TABLE ShopSupplier(
  ShopID TEXT,
  SupplierID TEXT,
  PRIMARY KEY(ShopID, SupplierID),
  FOREIGN KEY(ShopID) REFERENCES Shop(ShopID),
  FOREIGN KEY(SupplierID) REFERENCES Supplier(SupplierID));

Then, both columns are foreign keys and belonging to the primary key.

In general setting the columns of a (pure) junction table as primary key isn't necessary. You may use it as a constraint to prohibit duplicates.


问:
When having a UIView scroll up with the keyboard, it seems to jump on every single textField awkwardly, not sure how to fix it
Here's a gif of what's happening:

Here's the functions:

```<code>func getKeyboardHeight(_ notification:Notification) -> CGFloat {
    let userInfo = notification.userInfo
    let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
    return keyboardSize.cgRectValue.height
}

func keyboardWillShow(_ notification:Notification) {
    view.frame.origin.y = -getKeyboardHeight(notification)
}

func keyboardWillHide(_ notification:Notification) {
    view.frame.origin.y = 0
}

func subscribeToKeyBoardNotifications(){
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil)
}
</code>```

It works perfectly on the first text input tap, however if I tap on the one below it, the view kind of "jumps" up and goes back into where it should be, which is very visually jarring.

I also tried checking if view.frame.origin.y == 0, to adjust the origin of y, but that didn't work, as the origin for the first textbox is -4, and the second is -92 (doesn't really make sense to me tbh), and I want to use this in different views and not hardcode the origin.y for each potentinal input box.

答:
My suggestion is to add the content(only the content which needs to scroll) you wants to be scrolled up when the keyboard appears into a UIScrollView and set it's bottom constraint to BottomLayoutGuid. the get a outlet to the controller. And in storyBoard's relevant UIViewController set the 'AdjustScrollViewInsets' in AttributeInspector property to Unchecked</p>

```<code>@IBOutlet weak var scrollViewBottomCons     : NSLayoutConstraint!
let scrollViewBottomConsNormalValue         : CGFloat!              = 50                    // assuming its storyboard value is 50

func keyboardWillShow(_ notification:Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if scrollViewBottomCons.constant == scrollViewBottomConsNormalValue {
            self.scrollViewBottomCons.constant                      = keyboardSize.height
            self.navigationController?.isNavigationBarHidden        = true                  // assuming its current state is true
        }
    }
}

func keyboardWillHide(_ notification:Notification) {
    if let _ = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if scrollViewBottomCons.constant != scrollViewBottomConsRealValue {
            self.scrollViewBottomCons.constant                      = scrollViewBottomConsRealValue
            self.navigationController?.isNavigationBarHidden        = true                  // assuming its current state is true
        }
    }
}
</code>```

Body:
Here's a gif of what's happening:

Here's the functions:

func getKeyboardHeight(_ notification:Notification) -> CGFloat {
    let userInfo = notification.userInfo
    let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
    return keyboardSize.cgRectValue.height
}

func keyboardWillShow(_ notification:Notification) {
    view.frame.origin.y = -getKeyboardHeight(notification)
}

func keyboardWillHide(_ notification:Notification) {
    view.frame.origin.y = 0
}

func subscribeToKeyBoardNotifications(){
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil)
}

It works perfectly on the first text input tap, however if I tap on the one below it, the view kind of "jumps" up and goes back into where it should be, which is very visually jarring.

I also tried checking if view.frame.origin.y == 0, to adjust the origin of y, but that didn't work, as the origin for the first textbox is -4, and the second is -92 (doesn't really make sense to me tbh), and I want to use this in different views and not hardcode the origin.y for each potentinal input box.

Body:
My suggestion is to add the content(only the content which needs to scroll) you wants to be scrolled up when the keyboard appears into a UIScrollView and set it's bottom constraint to BottomLayoutGuid. the get a outlet to the controller. And in storyBoard's relevant UIViewController set the 'AdjustScrollViewInsets' in AttributeInspector property to Unchecked

@IBOutlet weak var scrollViewBottomCons     : NSLayoutConstraint!
let scrollViewBottomConsNormalValue         : CGFloat!              = 50                    // assuming its storyboard value is 50

func keyboardWillShow(_ notification:Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if scrollViewBottomCons.constant == scrollViewBottomConsNormalValue {
            self.scrollViewBottomCons.constant                      = keyboardSize.height
            self.navigationController?.isNavigationBarHidden        = true                  // assuming its current state is true
        }
    }
}

func keyboardWillHide(_ notification:Notification) {
    if let _ = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if scrollViewBottomCons.constant != scrollViewBottomConsRealValue {
            self.scrollViewBottomCons.constant                      = scrollViewBottomConsRealValue
            self.navigationController?.isNavigationBarHidden        = true                  // assuming its current state is true
        }
    }
}


问:
Spring Security - always redirect to failure-url
I'm trying to use Spring Security in my application, but after every successful registration, when it comes to sign in I meet a problem. Spring redirects me to failureUrl. I feel tired of looking for my mistake. Could you show me the proper way? I'd really appreciate. There's code with security config:

```<code>@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private RegisterService registerService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers(
                        "/registration",
                        "/js/**",
                        "/css/**",
                        "/img/**",
                        "/webjars/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error")
                .permitAll()
                .and()
                .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login");
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(registerService).passwordEncoder(passwordEncoder());
    }

}
</code>```

And service responible for signing up and in

```<code>@Service
public class RegisterService implements UserDetailsService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private UserRepository userRepository;

    public User save(UserDto userDto){
        User user = new User();
        user.setLogin(userDto.getLogin());
        user.setFirstName(userDto.getFirstName());
        user.setLastName(userDto.getLastName());
        user.setEmail(userDto.getEmail());
        user.setPassword(passwordEncoder.encode(userDto.getPassword()));
        user.setRole("ROLE_USER");
        return userRepository.save(user);
    }

    public User findByEmail(String email){
        return userRepository.findByEmail(email);
    }

    public User findByLogin(String login){
        return userRepository.findByLogin(login);
    }

    @Override
    public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
        User user = userRepository.findByLogin(login);
        if(user == null){
            throw new UsernameNotFoundException("Invalid username or password.");
        }

        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(user.getRole()));

        return new org.springframework.security.core.userdetails.User(
                user.getLogin(), user.getPassword(), authorities);
    }

}
</code>```

答:
Try adding a defaultSuccessUrl in your configuration:

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {
http
        .csrf().disable()
        .authorizeRequests()
        .antMatchers(
                "/registration",
                "/js/**",
                "/css/**",
                "/img/**",
                "/webjars/**").permitAll()
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .loginPage("/login")
        .failureUrl("/login?error")
        .defaultSuccessUrl("/")
        .permitAll()
        .and()
        .logout()
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login");
}
</code>```

I also think calling permitAll() for the formLogin is redundant as this is the default but this shouldn't be a problem.

Body:
I'm trying to use Spring Security in my application, but after every successful registration, when it comes to sign in I meet a problem. Spring redirects me to failureUrl. I feel tired of looking for my mistake. Could you show me the proper way? I'd really appreciate. There's code with security config:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private RegisterService registerService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers(
                        "/registration",
                        "/js/**",
                        "/css/**",
                        "/img/**",
                        "/webjars/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .failureUrl("/login?error")
                .permitAll()
                .and()
                .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login");
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(registerService).passwordEncoder(passwordEncoder());
    }

}

And service responible for signing up and in

@Service
public class RegisterService implements UserDetailsService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private UserRepository userRepository;

    public User save(UserDto userDto){
        User user = new User();
        user.setLogin(userDto.getLogin());
        user.setFirstName(userDto.getFirstName());
        user.setLastName(userDto.getLastName());
        user.setEmail(userDto.getEmail());
        user.setPassword(passwordEncoder.encode(userDto.getPassword()));
        user.setRole("ROLE_USER");
        return userRepository.save(user);
    }

    public User findByEmail(String email){
        return userRepository.findByEmail(email);
    }

    public User findByLogin(String login){
        return userRepository.findByLogin(login);
    }

    @Override
    public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
        User user = userRepository.findByLogin(login);
        if(user == null){
            throw new UsernameNotFoundException("Invalid username or password.");
        }

        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(user.getRole()));

        return new org.springframework.security.core.userdetails.User(
                user.getLogin(), user.getPassword(), authorities);
    }

}

Body:
Try adding a defaultSuccessUrl in your configuration:

@Override
protected void configure(HttpSecurity http) throws Exception {
http
        .csrf().disable()
        .authorizeRequests()
        .antMatchers(
                "/registration",
                "/js/**",
                "/css/**",
                "/img/**",
                "/webjars/**").permitAll()
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .loginPage("/login")
        .failureUrl("/login?error")
        .defaultSuccessUrl("/")
        .permitAll()
        .and()
        .logout()
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login");
}

I also think calling permitAll() for the formLogin is redundant as this is the default but this shouldn't be a problem.


问:
How to Print Alphabet sequentially in PHP?
I have an array variable $arr = array('A','B','C','D');

```<code>$number = 5; (This is dynamic)
</code>```

My new array value should be

```<code>$arr = array('A','B','C','D','E','F','G','H','I');
</code>```

If

```<code>$number = 3;
</code>```

Output should be:

```<code>$arr = array('A','B','C','D','E','F','G');
</code>```

If $number variable will come more than 22 then print array from A to Z and with AA, AB, AC.. etc.

How to do that in PHP code?

答:
```<code>$output = array();
$arr = array(A,B,C,D,E);
$data = range('F','Z');
$num = 4;

if($num < 22){
    $output = array_merge($arr,array_slice($data, 0, $num));
}else{
     // Write ur format here..
    // $output = array('AA','AB',......,'AZ');
}

echo '```';
print_r($output);
</code>```

Body:
I have an array variable $arr = array('A','B','C','D');

$number = 5; (This is dynamic)

My new array value should be

$arr = array('A','B','C','D','E','F','G','H','I');

If

$number = 3;

Output should be:

$arr = array('A','B','C','D','E','F','G');

If $number variable will come more than 22 then print array from A to Z and with AA, AB, AC.. etc.

How to do that in PHP code?

Body:
$output = array();
$arr = array(A,B,C,D,E);
$data = range('F','Z');
$num = 4;

if($num < 22){
    $output = array_merge($arr,array_slice($data, 0, $num));
}else{
     // Write ur format here..
    // $output = array('AA','AB',......,'AZ');
}

echo '<pre>';
print_r($output);


问:
Using Kylin without HDFS and HBase
is it possible to connect Apache Kylin without other databases like Hbase (plus HDFS) in general? So you can store raw data and the cube metadata somewhere else? </p>

答:
To use Kylin ,HDFS is mandatatory .Raw data as well as Cube data both will be stored in HDFS.

If you want to support other nosql datastore like cassandra ,you can consider other framework ,FiloDB

Title: Using Kylin without HDFS and HBase


问:
Scalable Contains method for LINQ against a SQL backend
I'm looking for an elegant way to execute a Contains() statement in a scalable way. Please allow me to give some background before I come to the actual question.

The IN statement

In Entity Framework and LINQ to SQL the Contains statement is translated as a SQL IN statement. For instance, from this statement:

var ids = Enumerable.Range(1,10);
var courses = Courses.Where(c => ids.Contains(c.CourseID)).ToList();
```
<p>Entity Framework will generate</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
    [Extent1].[CourseID] AS [CourseID],
    [Extent1].[Title] AS [Title],
    [Extent1].[Credits] AS [Credits],
    [Extent1].[DepartmentID] AS [DepartmentID]
    FROM [dbo].[Course] AS [Extent1]
    WHERE [Extent1].[CourseID] IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
</code>```

Unfortunately, the In statement is not scalable. As per MSDN:

Including an extremely large number of values (many thousands) in an IN clause can consume resources and return errors 8623 or 8632

which has to do with running out of resources or exceeding expression limits.

But before these errors occur, the IN statement becomes increasingly slow with growing numbers of items. I can't find documentation about its growth rate, but it performs well up to a few thousands of items, but beyond that it gets dramatically slow. (Based on SQL Server experiences).

Scalable

We can't always avoid this statement. A JOIN with the source data in stead would generally perform much better, but that's only possible when the source data is in the same context. Here I'm dealing with data coming from a client in a disconnected scenario. So I have been looking for a scalable solution. A satisfactory approach turned out to be cutting the operation into chunks:

```<code>var courses = ids.ToChunks(1000)
                 .Select(chunk => Courses.Where(c => chunk.Contains(c.CourseID)))
                 .SelectMany(x => x).ToList();
</code>```

(where ToChunks is this little extension method).

This executes the query in chunks of 1000 that all perform well enough. With e.g. 5000 items, 5 queries will run that together are likely to be faster than one query with 5000 items.

But not DRY

But of course I don't want to scatter this construct all over my code. I am looking for an extension method by which any IQueryable<T> can be transformed into a chunky executing statement. Ideally something like this:

```<code>var courses = Courses.Where(c => ids.Contains(c.CourseID))
              .AsChunky(1000)
              .ToList();
</code>```

But maybe this

```<code>var courses = Courses.ChunkyContains(c => c.CourseID, ids, 1000)
              .ToList();
</code>```

I've given the latter solution a first shot:

```<code>public static IEnumerable<TEntity> ChunkyContains<TEntity, TContains>(
    this IQueryable<TEntity> query,
    Expression<Func<TEntity,TContains>> match,
    IEnumerable<TContains> containList,
    int chunkSize = 500)
{
    return containList.ToChunks(chunkSize)
               .Select (chunk => query.Where(x => chunk.Contains(match)))
               .SelectMany(x => x);
}
</code>```

Obviously, the part x => chunk.Contains(match) doesn't compile. But I don't know how to manipulate the match expression into a Contains expression.

Maybe someone can help me make this solution work. And of course I'm open to other approaches to make this statement scalable.

答:
Using a stored procedure with a table valued parameter could also work well. You in effect write a joint In  the stored procedure between your table / view and the table valued parameter.

https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/table-valued-parameters

Body:
I'm looking for an elegant way to execute a Contains() statement in a scalable way. Please allow me to give some background before I come to the actual question.

The IN statement

In Entity Framework and LINQ to SQL the Contains statement is translated as a SQL IN statement. For instance, from this statement:

var ids = Enumerable.Range(1,10);
var courses = Courses.Where(c => ids.Contains(c.CourseID)).ToList();

Entity Framework will generate

SELECT
    [Extent1].[CourseID] AS [CourseID],
    [Extent1].[Title] AS [Title],
    [Extent1].[Credits] AS [Credits],
    [Extent1].[DepartmentID] AS [DepartmentID]
    FROM [dbo].[Course] AS [Extent1]
    WHERE [Extent1].[CourseID] IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

Unfortunately, the In statement is not scalable. As per MSDN:

Including an extremely large number of values (many thousands) in an IN clause can consume resources and return errors 8623 or 8632

which has to do with running out of resources or exceeding expression limits.

But before these errors occur, the IN statement becomes increasingly slow with growing numbers of items. I can't find documentation about its growth rate, but it performs well up to a few thousands of items, but beyond that it gets dramatically slow. (Based on SQL Server experiences).

Scalable

We can't always avoid this statement. A JOIN with the source data in stead would generally perform much better, but that's only possible when the source data is in the same context. Here I'm dealing with data coming from a client in a disconnected scenario. So I have been looking for a scalable solution. A satisfactory approach turned out to be cutting the operation into chunks:

var courses = ids.ToChunks(1000)
                 .Select(chunk => Courses.Where(c => chunk.Contains(c.CourseID)))
                 .SelectMany(x => x).ToList();

(where ToChunks is this little extension method).

This executes the query in chunks of 1000 that all perform well enough. With e.g. 5000 items, 5 queries will run that together are likely to be faster than one query with 5000 items.

But not DRY

But of course I don't want to scatter this construct all over my code. I am looking for an extension method by which any IQueryable<T> can be transformed into a chunky executing statement. Ideally something like this:

var courses = Courses.Where(c => ids.Contains(c.CourseID))
              .AsChunky(1000)
              .ToList();

But maybe this

var courses = Courses.ChunkyContains(c => c.CourseID, ids, 1000)
              .ToList();

I've given the latter solution a first shot:

public static IEnumerable<TEntity> ChunkyContains<TEntity, TContains>(
    this IQueryable<TEntity> query,
    Expression<Func<TEntity,TContains>> match,
    IEnumerable<TContains> containList,
    int chunkSize = 500)
{
    return containList.ToChunks(chunkSize)
               .Select (chunk => query.Where(x => chunk.Contains(match)))
               .SelectMany(x => x);
}

Obviously, the part x => chunk.Contains(match) doesn't compile. But I don't know how to manipulate the match expression into a Contains expression.

Maybe someone can help me make this solution work. And of course I'm open to other approaches to make this statement scalable.


问:
ElementToBeClickable 'not working'
```<code>IWebDriver driver = new RemoteWebDriver(uri, dc);
WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0,0,60));
driver.Navigate().GoToUrl("https://google.com/ncr");
string xpath = "//*[@id=\"lst-ib\"]";  // the google search text box
IWebElement element = driver.FindElement(By.XPath(xpath));
//wait.Until(ExpectedConditions.ElementToBeClickable(element));
element.Click();
element.SendKeys("some text");
</code>```

The above code, works as is. However, if I uncomment the wait.Until then the browser opens, but no text is sent. It seems to 'stop' at the wait.Until. No idea what I am doing wrong. It is not a problem for the current use case, but would be nice to know how to do it correctly for future uses.

EDIT:
After doing a little searching and testing, I found the following code works specifically for RemoteWebDriver.

```<code>IWebDriver driver = new RemoteWebDriver(uri, dc);
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(60);
IWebElement element = driver.FindElement(By.Name(name));
</code>```

It works when the "name" exists in the DOM, and throws an exception when I modify "name" to something not in the DOM, as would be expected.
Thanks @DebanjanB for sending me in the right direction.

答:
can you please try the below code. Its working fine.

```<code>public static void search() throws Throwable
    {
        WebElement SearchBox = driver.findElement(By.xpath(".//*[@id='ctl00_PlaceHolderSearchArea_SmallSearchInputBox1_csr_sbox']"));
        SearchBox.clear();
        SearchBox.sendKeys("Text");
        driver.manage().timeouts().implicitlyWait(8000, TimeUnit.SECONDS);
        WebElement SearchLink=driver.findElement(By.xpath(".//*[@id='ctl00_PlaceHolderSearchArea_SmallSearchInputBox1_csr_SearchLink']"));
        SearchLink.click();
        driver.manage().timeouts().implicitlyWait(10000, TimeUnit.SECONDS);
        driver.navigate().back();
    }
</code>```

do let me know in case you face any challenges

Title: ElementToBeClickable 'not working'

Body:
IWebDriver driver = new RemoteWebDriver(uri, dc);
WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0,0,60));
driver.Navigate().GoToUrl("https://google.com/ncr");
string xpath = "//*[@id=\"lst-ib\"]";  // the google search text box
IWebElement element = driver.FindElement(By.XPath(xpath));
//wait.Until(ExpectedConditions.ElementToBeClickable(element));
element.Click();
element.SendKeys("some text");

The above code, works as is. However, if I uncomment the wait.Until then the browser opens, but no text is sent. It seems to 'stop' at the wait.Until. No idea what I am doing wrong. It is not a problem for the current use case, but would be nice to know how to do it correctly for future uses.

EDIT:
After doing a little searching and testing, I found the following code works specifically for RemoteWebDriver.

IWebDriver driver = new RemoteWebDriver(uri, dc);
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(60);
IWebElement element = driver.FindElement(By.Name(name));

It works when the "name" exists in the DOM, and throws an exception when I modify "name" to something not in the DOM, as would be expected.
Thanks @DebanjanB for sending me in the right direction.

Body:
can you please try the below code. Its working fine.

public static void search() throws Throwable
    {
        WebElement SearchBox = driver.findElement(By.xpath(".//*[@id='ctl00_PlaceHolderSearchArea_SmallSearchInputBox1_csr_sbox']"));
        SearchBox.clear();
        SearchBox.sendKeys("Text");
        driver.manage().timeouts().implicitlyWait(8000, TimeUnit.SECONDS);
        WebElement SearchLink=driver.findElement(By.xpath(".//*[@id='ctl00_PlaceHolderSearchArea_SmallSearchInputBox1_csr_SearchLink']"));
        SearchLink.click();
        driver.manage().timeouts().implicitlyWait(10000, TimeUnit.SECONDS);
        driver.navigate().back();
    }

do let me know in case you face any challenges


问:
iOS 11 Logo and title in NavigationBar
I have been searching and trying for days but since it's a new thing there's not much information available (or I can't find them).

Anyway, I am trying to get use of new NavBar features in iOS 11 but I want to put both a logo and a large title (of each ViewController) in my NavBar. Something like the screenshot below:

How is it possible to implement this?

Side Hint:

For same app in iOS 10 I set the logo to show instead of titleView in NavBar but now in newer version we want to add the Title too.

Thanks in advance

答:
Without your code sample it's hard to say what goes wrong for you, but this just works:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    if #available(iOS 11, *) {
        navigationController?.navigationBar.prefersLargeTitles = true
        navigationItem.largeTitleDisplayMode = .always
        title = "Your title"
    }

    let titleImageView = NavigationImageView()
    titleImageView.image = UIImage(named: "yourImageName")
    navigationItem.titleView = titleImageView
}
</code>```

EDIT: To set custom size for your title view you can subclass your UIView (UIImageView) and override sizeThatFits

```<code>class NavigationImageView: UIImageView {
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        return CGSize(width: 50, height: 50)
    }
}
</code>```

Title: iOS 11 Logo and title in NavigationBar

Body:
Without your code sample it's hard to say what goes wrong for you, but this just works:

override func viewDidLoad() {
    super.viewDidLoad()

    if #available(iOS 11, *) {
        navigationController?.navigationBar.prefersLargeTitles = true
        navigationItem.largeTitleDisplayMode = .always
        title = "Your title"
    }

    let titleImageView = NavigationImageView()
    titleImageView.image = UIImage(named: "yourImageName")
    navigationItem.titleView = titleImageView
}

EDIT: To set custom size for your title view you can subclass your UIView (UIImageView) and override sizeThatFits

class NavigationImageView: UIImageView {
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        return CGSize(width: 50, height: 50)
    }
}


问:
Selenium/java-xpath for xlink:href attribute
I tried to locate use element with attribute value '#aaa' for below snippet

```<code><svg>
    <use xlink:href='#aaa'></use>
</svg>
</code>```

I was able to locate using css selector use[* |href='#aaa'] . But I require it in xpath. I tried below xpath but it is not working

```<code>(//*[name()='use'])[ * ='#aaa' or @href='#aaa']
</code>```

Note :I need to use the value '#aaa' to differentiate from other elements.

Could anyone please help to construct this xpath.

答:
lookout, if someone needs contains.. </p>

```<code>"//*[name()='use'][contains(@*='#aaa')]"
</code>```

Body:
I tried to locate use element with attribute value '#aaa' for below snippet

<svg>
    <use xlink:href='#aaa'></use>
</svg>

I was able to locate using css selector use[* |href='#aaa'] . But I require it in xpath. I tried below xpath but it is not working

(//*[name()='use'])[ * ='#aaa' or @href='#aaa']

Note :I need to use the value '#aaa' to differentiate from other elements.

Could anyone please help to construct this xpath.

Body:
lookout, if someone needs contains..

"//*[name()='use'][contains(@*='#aaa')]"


问:
Swift - How to dismiss all of view controllers to go back to root
I want a my app can go to a first view controller when every time users want it.

So I want to create a function to dismiss all the view controllers, regardless of whether it is pushed in navigation controllers or presented modally or opened anything methods.

I tried various ways, but I failed to dismiss all the view controllers certainly.
Is there an easy way?

答:
If you are using Navigation you can use first one
or if you are presenting modally you can second one:

For Navigation

```<code>self.navigationController?.popToRootViewController(animated: true)
</code>```

For Presenting modally

```<code>self.view.window!.rootViewController?.dismissViewControllerAnimated(false, completion: nil)
</code>```

Body:
If you are using Navigation you can use first one
or if you are presenting modally you can second one:

For Navigation

self.navigationController?.popToRootViewController(animated: true)

For Presenting modally

self.view.window!.rootViewController?.dismissViewControllerAnimated(false, completion: nil)

ContentLicense: CC BY-SA 4.0


问:
Making sticky javascript
I have a javascript form where I am using innerHTML to set some text.

When the form submits that information is lost.Is there anyway I can make it "sticky".I was thinking a cookie but that's about all I know.

Thanks

```<code><form "action="" name="myform">
<input type="text" name='name">
<div id="theName"></div>
</form>
</code>```

Quick example I am capturing the name and need the div to show the name after the form submits.

答:
Are you setting the "value" attribute of the input tags to something or blank? you can just remove (remove the attribute itself) that so that the last value set will be used (true only for non-password type inputs. also, haven't tried it in all browsers.).

Or better yet, you can use serverside script like (PHP, ASP, RUBY, etc) to set the attribute value to the previously submitted.

```<code><form method="post">
<input type="text" name="txtinput" id="txtinput" value="<?php echo $_POST['txtinput']?>"/>
<input type="submit" value="submit">
</form>
</code>```

doing it in js only is much more complicated and unreliable since your going to use cookies.

PS: I'm assuming your not using XHR(AJAX) to submit your forms since XHR's don't refresh pages or re-initializes inputs unless you told them to.

ContentLicense: CC BY-SA 2.5

Title: Making sticky javascript

Body:
I have a javascript form where I am using innerHTML to set some text.

When the form submits that information is lost.Is there anyway I can make it "sticky".I was thinking a cookie but that's about all I know.

Thanks

<form "action="" name="myform">
<input type="text" name='name">

</form>

Quick example I am capturing the name and need the div to show the name after the form submits.

Body:
Are you setting the "value" attribute of the input tags to something or blank? you can just remove (remove the attribute itself) that so that the last value set will be used (true only for non-password type inputs. also, haven't tried it in all browsers.).

Or better yet, you can use serverside script like (PHP, ASP, RUBY, etc) to set the attribute value to the previously submitted.

<form method="post">
<input type="text" name="txtinput" id="txtinput" value="<?php echo $_POST['txtinput']?>"/>
<input type="submit" value="submit">
</form>

doing it in js only is much more complicated and unreliable since your going to use cookies.

PS: I'm assuming your not using XHR(AJAX) to submit your forms since XHR's don't refresh pages or re-initializes inputs unless you told them to.


问:
get one method variable to other method in the same class and show in the route - Laravel 5.2
I have a controller. There have two function. Now i want to get variable(It is random string) value from one function to another function and print this value into the Route(url).

Controller:

```<code>class PrizeCalculateController extends Controller
{
      public function calculatePrize($id, $randomStr=0)
    {
        $randomStr = str_random(5);
        return view('pages.pageWaiting', ['res' => $res, 'randomStr' => $randomStr]);
    }

    public function showPrizePage($id, $randomStr=0)
    {
        //get random string from calculatePrize function
        $getStr = PrizeCalculateController::calculatePrize($randomStr);
        return view('pages.prizesDetails', ['res' => $id, 'getStr' => $getStr]);
    }
}
</code>```

I have tried to get random string from calculatePrize function to showPrizePage function this way:

```<code>$getStr = PrizeCalculateController::calculatePrize($randomStr);
</code>```

And if i dd($getStr) then i get null. Now how can i get this variable from calculatePrize function to showPrizePage function.

Want to make route:

```<code>Route::get('/prize/{getStr}','PrizeCalculateController@showPrizePage');
</code>```

答:
You should try this:</p>

```<code>use Illuminate\Http\Request;
use Session;

    public function calculatePrize($id, $randomStr=0)
        {
            $randomStr = str_random(5);
            Session::set('randomString', $randomStr);
            return view('pages.pageWaiting', ['res' => $res, 'randomStr' => $randomStr]);
        }

        public function showPrizePage($id,$randomStr=0)
        {
            if(Session::has('randomString')) {
                $randomStr = Session::get('randomString');
            } else {
              $randomStr = 0;
            }

            $getStr = PrizeCalculateController::calculatePrize($randomStr);
            return view('pages.prizesDetails', ['res' => $id, 'getStr' => $getStr]);
        }
</code>```

Body:
I have a controller. There have two function. Now i want to get variable(It is random string) value from one function to another function and print this value into the Route(url).

Controller:

class PrizeCalculateController extends Controller
{
      public function calculatePrize($id, $randomStr=0)
    {
        $randomStr = str_random(5);
        return view('pages.pageWaiting', ['res' => $res, 'randomStr' => $randomStr]);
    }

    public function showPrizePage($id, $randomStr=0)
    {
        //get random string from calculatePrize function
        $getStr = PrizeCalculateController::calculatePrize($randomStr);
        return view('pages.prizesDetails', ['res' => $id, 'getStr' => $getStr]);
    }
}

I have tried to get random string from calculatePrize function to showPrizePage function this way:

$getStr = PrizeCalculateController::calculatePrize($randomStr);

And if i dd($getStr) then i get null. Now how can i get this variable from calculatePrize function to showPrizePage function.

Want to make route:

Route::get('/prize/{getStr}','PrizeCalculateController@showPrizePage');

Body:
You should try this:

use Illuminate\Http\Request;
use Session;

    public function calculatePrize($id, $randomStr=0)
        {
            $randomStr = str_random(5);
            Session::set('randomString', $randomStr);
            return view('pages.pageWaiting', ['res' => $res, 'randomStr' => $randomStr]);
        }

        public function showPrizePage($id,$randomStr=0)
        {
            if(Session::has('randomString')) {
                $randomStr = Session::get('randomString');
            } else {
              $randomStr = 0;
            }

            $getStr = PrizeCalculateController::calculatePrize($randomStr);
            return view('pages.prizesDetails', ['res' => $id, 'getStr' => $getStr]);
        }


问:
Google Sheets removing leading spaces query results
My sheet is pulling data from another sheet with:

```<code>=QUERY('WHERE TO SEND STUDENTS'!A:D, "select B,C,D where A<>'' order by D",1)
</code>```

Some of the contents of D has a leading space which causes it to be at the top of the column. Is there a way to remove this leading space and then sort the column D?

答:
I suggest to trim only column D and combine columns with array { }:

=arrayformula( query( { A:C, TRIM(D:D) },
"select Col2, Col3, Col4 where Col2 <> '' order by Col4", 1 ) )

Body:
My sheet is pulling data from another sheet with:

=QUERY('WHERE TO SEND STUDENTS'!A:D, "select B,C,D where A<>'' order by D",1)

Some of the contents of D has a leading space which causes it to be at the top of the column. Is there a way to remove this leading space and then sort the column D?


问:
Link FLTK with g++
In order to try out FLTK, I have the following file structure:

```<code>project
|--main.cc
|--include
|  |--FL
|  |  |--all FLTK header files
|--lib
|  |--libfltk.a
|  |--other fltk libraries
</code>```

With the following content in main.cc:

```<code>#include <FL/Fl.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Window.H>

int main()
{
    Fl_Window window(200, 200, "Window title");
    Fl_Box box(0,0,200,200,"Hello, World!");
    window.show();
    return Fl::run();
}
</code>```

Now when I run:

```<code>g++ -std=c++11 -c -o main.o main.cc -I include
g++ -std=c++11 -o main.exe main.o -L lib -lfltk
</code>```

I get a whole bunch of errors after the second call to g++:

```<code>lib/libfltk.a(Fl.o):Fl.cxx:(.text$_ZL13image_to_iconPK12Fl_RGB_Imagebii+0xf3): undefined reference to `CreateDIBSection@24'
lib/libfltk.a(Fl.o):Fl.cxx:(.text$_ZL13image_to_iconPK12Fl_RGB_Imagebii+0x1cf): undefined reference to `DeleteObject@4'
lib/libfltk.a(Fl.o):Fl.cxx:(.text$_ZL13image_to_iconPK12Fl_RGB_Imagebii+0x258): undefined reference to `CreateBitmap@20'
lib/libfltk.a(Fl.o):Fl.cxx:(.text$_ZL13image_to_iconPK12Fl_RGB_Imagebii+0x2a6): undefined reference to `DeleteObject@4'
lib/libfltk.a(Fl.o):Fl.cxx:(.text$_ZL13image_to_iconPK12Fl_RGB_Imagebii+0x2b1): undefined reference to `DeleteObject@4'
lib/libfltk.a(Fl.o):Fl.cxx:(.text$__tcf_1+0x5b): undefined reference to `OleUninitialize@0'
lib/libfltk.a(Fl.o):Fl.cxx:(.text$__tcf_1+0x83): undefined reference to `RestoreDC@8'
etc ...
</code>```

The result is the same when I try to link the other FLTK libraries. Can anyone help me with that?

I use gcc from Windows, with MingW.

答: To solve this sort of problems is necessary to take help from fltk-config script. Therefore, it is enought to add line fltk-config --ldflags to compiler to avoid linker errors. Be sure to use "`" symbol around this command since this is the script and its should be executed.

Title: Link FLTK with g++

Body:
In order to try out FLTK, I have the following file structure:

project
|--main.cc
|--include
|  |--FL
|  |  |--all FLTK header files
|--lib
|  |--libfltk.a
|  |--other fltk libraries

With the following content in main.cc:

#include <FL/Fl.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Window.H>

int main()
{
    Fl_Window window(200, 200, "Window title");
    Fl_Box box(0,0,200,200,"Hello, World!");
    window.show();
    return Fl::run();
}

Now when I run:

g++ -std=c++11 -c -o main.o main.cc -I include
g++ -std=c++11 -o main.exe main.o -L lib -lfltk

I get a whole bunch of errors after the second call to g++:

lib/libfltk.a(Fl.o):Fl.cxx:(.text$_ZL13image_to_iconPK12Fl_RGB_Imagebii+0xf3): undefined reference to `CreateDIBSection@24'
lib/libfltk.a(Fl.o):Fl.cxx:(.text$_ZL13image_to_iconPK12Fl_RGB_Imagebii+0x1cf): undefined reference to `DeleteObject@4'
lib/libfltk.a(Fl.o):Fl.cxx:(.text$_ZL13image_to_iconPK12Fl_RGB_Imagebii+0x258): undefined reference to `CreateBitmap@20'
lib/libfltk.a(Fl.o):Fl.cxx:(.text$_ZL13image_to_iconPK12Fl_RGB_Imagebii+0x2a6): undefined reference to `DeleteObject@4'
lib/libfltk.a(Fl.o):Fl.cxx:(.text$_ZL13image_to_iconPK12Fl_RGB_Imagebii+0x2b1): undefined reference to `DeleteObject@4'
lib/libfltk.a(Fl.o):Fl.cxx:(.text$__tcf_1+0x5b): undefined reference to `OleUninitialize@0'
lib/libfltk.a(Fl.o):Fl.cxx:(.text$__tcf_1+0x83): undefined reference to `RestoreDC@8'
etc ...

The result is the same when I try to link the other FLTK libraries. Can anyone help me with that?

I use gcc from Windows, with MingW.


答:
You can increment letters by incrementing it, then store it that array itself. This will print two letter sequence also ie., AA, AB ...</p>

```<code>$arr = array('A','B','C','D');
$item = end($arr) ;
$i = 0 ;
while( $i++ < $number ) {
    $arr[] = ++$item  ;
}
print_r($arr) ;
</code>```

Title: How to Print Alphabet sequentially in PHP?

Body:
You can increment letters by incrementing it, then store it that array itself. This will print two letter sequence also ie., AA, AB ...

$arr = array('A','B','C','D');
$item = end($arr) ;
$i = 0 ;
while( $i++ < $number ) {
    $arr[] = ++$item  ;
}
print_r($arr) ;


问:
Binding List of user controls to flipview?
I am planning to implement horizontal list of user controls, which i want to add it to the flip view during runtime, I tried the following code:

```<code><FlipView Grid.Row="2" Name="SlideFlipView"
              ItemsSource="{x:Bind SlideViews}"
              SelectionChanged="SlideFlipView_SelectionChanged"
              Background="AliceBlue">
        <FlipView.ItemTemplate>
            <DataTemplate>
                <Frame Name="MenuDetailFrame" SourcePageType="{Binding}"/>
            </DataTemplate>
        </FlipView.ItemTemplate>
</FlipView>
</code>```

Class looks like the following code:

```<code> public sealed partial class MenuDetailPage : Page
 {
    private List<object> SlideViews;

    public MenuDetailPage()
    {
        this.InitializeComponent();
        LoadInitials();
    }

    private void LoadInitials()
    {
        SlideViews = new List<object>
        {
            typeof(TopImageBottomTextControl),
            typeof(TopTextBottomImageControl)
        };
    }
 }
</code>```

but the user control doesn't appear in the flip when I run the program. Let me know if I am missing something here

答:
According to the "Frame Class":

SourcePageType can be set in XAML, using string-to-type conversion that's interpreted using XAML namespace mappings, but that's rarely done. It's a better practice to have code at the app level that tracks activation and whether a suspended app is resuming, which then uses Frame.Navigate to set the current page.

For your requirement, you could bind the user control object to the Content of Frame.

```<code>private void LoadInitials()
{
    SlideViews = new List<object>
 {
    new TopImageBottomTextControl(),
    new TopImageBottomTextControl()
 };
}
</code>```

Usage

```<code><FlipView Name="SlideFlipView"
          ItemsSource="{x:Bind SlideViews}"
          SelectionChanged="SlideFlipView_SelectionChanged"
          Background="AliceBlue">
    <FlipView.ItemTemplate>
        <DataTemplate>
            <Frame Name="MenuDetailFram"  Content="{Binding}" />
        </DataTemplate>
    </FlipView.ItemTemplate>
</FlipView>
</code>```

Body:
I am planning to implement horizontal list of user controls, which i want to add it to the flip view during runtime, I tried the following code:

<FlipView Grid.Row="2" Name="SlideFlipView"
              ItemsSource="{x:Bind SlideViews}"
              SelectionChanged="SlideFlipView_SelectionChanged"
              Background="AliceBlue">
        <FlipView.ItemTemplate>
            <DataTemplate>
                <Frame Name="MenuDetailFrame" SourcePageType="{Binding}"/>
            </DataTemplate>
        </FlipView.ItemTemplate>
</FlipView>

Class looks like the following code:

 public sealed partial class MenuDetailPage : Page
 {
    private List<object> SlideViews;

    public MenuDetailPage()
    {
        this.InitializeComponent();
        LoadInitials();
    }

    private void LoadInitials()
    {
        SlideViews = new List<object>
        {
            typeof(TopImageBottomTextControl),
            typeof(TopTextBottomImageControl)
        };
    }
 }

but the user control doesn't appear in the flip when I run the program. Let me know if I am missing something here

Body:
According to the "Frame Class":

SourcePageType can be set in XAML, using string-to-type conversion that's interpreted using XAML namespace mappings, but that's rarely done. It's a better practice to have code at the app level that tracks activation and whether a suspended app is resuming, which then uses Frame.Navigate to set the current page.

For your requirement, you could bind the user control object to the Content of Frame.

private void LoadInitials()
{
    SlideViews = new List<object>
 {
    new TopImageBottomTextControl(),
    new TopImageBottomTextControl()
 };
}

Usage

<FlipView Name="SlideFlipView"
          ItemsSource="{x:Bind SlideViews}"
          SelectionChanged="SlideFlipView_SelectionChanged"
          Background="AliceBlue">
    <FlipView.ItemTemplate>
        <DataTemplate>
            <Frame Name="MenuDetailFram"  Content="{Binding}" />
        </DataTemplate>
    </FlipView.ItemTemplate>
</FlipView>


问:
What is wrong with using 'Not In' in this SQL query?
I have table called BST as shown below:

Here N is value of node of Binary Tree and P is its Parent node. I have to write a query that will determine if a node is a Root Node, Leaf Node or Inner Node. I wrote below SQL query for this:

```<code>select N,
case
when P is null then 'Root'
when N in (select distinct P from BST) then 'Inner'
when N not in (select distinct P from BST) then 'Leaf'
end as type
from BST
</code>```

However, this is not giving me desired result as last condition for 'Leaf' in Case statement doesn't satisfy for leaf node. I am getting below output in this case:

I have a workaround for now as below query which is giving me expected output:

```<code>select N,
case
when P is null then 'Root'
when N in (select distinct P from BST) then 'Inner'
else 'Leaf'
end as type
from BST
</code>```

Expected Output:

But I can't figure out what's wrong with the first one. Could someone explain me this?

答:
Write where notExists instead of not in so that it will not consider nulls

select N,

case

when P is null then 'Root'

when N in (select distinct P from BST) then 'Inner'

when N not exists (select * from BST as t2 where t2.N=t1.N)
then 'Leaf'

end as type
from BST as t1

Body:
I have table called BST as shown below:

Here N is value of node of Binary Tree and P is its Parent node. I have to write a query that will determine if a node is a Root Node, Leaf Node or Inner Node. I wrote below SQL query for this:

select N,
case
when P is null then 'Root'
when N in (select distinct P from BST) then 'Inner'
when N not in (select distinct P from BST) then 'Leaf'
end as type
from BST

However, this is not giving me desired result as last condition for 'Leaf' in Case statement doesn't satisfy for leaf node. I am getting below output in this case:

I have a workaround for now as below query which is giving me expected output:

select N,
case
when P is null then 'Root'
when N in (select distinct P from BST) then 'Inner'
else 'Leaf'
end as type
from BST

Expected Output:

But I can't figure out what's wrong with the first one. Could someone explain me this?


问:
How can I make a function treat a whole sentence like one parameter?
How should I pass a sentence to function and make it behave like one parameter.

Example:

```<code>function Test ()
{
  echo $1
}
body="This the test"
Test $body
</code>```

I want output like this=> "This the test"  because of spaces it will print me Test only. What specific characters should i put to make whole sentence like one parameter. Thanks in advance.

答:
Use the special parameter which includes all positional parameters and quote it. If you quote the input argument as you show in your question, your existing function should have worked, though.</p>

```<code>Test () { echo "$@"; }
</code>```

Body:
How should I pass a sentence to function and make it behave like one parameter.

Example:

function Test ()
{
  echo $1
}
body="This the test"
Test $body

I want output like this=> "This the test"  because of spaces it will print me Test only. What specific characters should i put to make whole sentence like one parameter. Thanks in advance.

Body:
Use the special parameter which includes all positional parameters and quote it. If you quote the input argument as you show in your question, your existing function should have worked, though.

Test () { echo "$@"; }


答:
If you look at the WebElement represented as Search Box on Google Home Page, the element is as follows :

```<code><input class="gsfi" id="lst-ib" maxlength="2048" name="q" autocomplete="off" title="Search" type="text" value="" aria-label="Search" aria-haspopup="false" role="combobox" aria-autocomplete="list" dir="ltr" spellcheck="false" style="border: none; padding: 0px; margin: 0px; height: auto; width: 100%; background: url("data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw%3D%3D") transparent; position: absolute; z-index: 6; left: 0px; outline: none;">
</code>```

A couple of things about the Search Box :

It's an <input> tag which will accept only text

An <input> tag won't have any onClick() event associated with it like the <button> or  tags.

So a proper clause for ExpectedConditions can be ElementIsVisible instead of ElementToBeClickable.

ElementIsVisible clause will ensure that the an element is present on the DOM of a page and visible.

Visibility means that the element is not only displayed but also has a height and width that is greater than 0.

Update :

As you mentioned that you are getting the same result, so I will make some simple tweaks to your code and write the equivalent code as :

```<code>WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0,0,10));
IWebElement element = wait.Until(ExpectedConditions.ElementIsVisible(By.Name("q")));
element.SendKeys("some text");
</code>```

Title: ElementToBeClickable 'not working'

Body:
IWebDriver driver = new RemoteWebDriver(uri, dc);
WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0,0,60));
driver.Navigate().GoToUrl("https://google.com/ncr");
string xpath = "//*[@id=\"lst-ib\"]";  // the google search text box
IWebElement element = driver.FindElement(By.XPath(xpath));
//wait.Until(ExpectedConditions.ElementToBeClickable(element));
element.Click();
element.SendKeys("some text");

The above code, works as is. However, if I uncomment the wait.Until then the browser opens, but no text is sent. It seems to 'stop' at the wait.Until. No idea what I am doing wrong. It is not a problem for the current use case, but would be nice to know how to do it correctly for future uses.

EDIT:
After doing a little searching and testing, I found the following code works specifically for RemoteWebDriver.

IWebDriver driver = new RemoteWebDriver(uri, dc);
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(60);
IWebElement element = driver.FindElement(By.Name(name));

It works when the "name" exists in the DOM, and throws an exception when I modify "name" to something not in the DOM, as would be expected.
Thanks @DebanjanB for sending me in the right direction.

Body:
If you look at the WebElement represented as Search Box on Google Home Page, the element is as follows :

<input class="gsfi" id="lst-ib" maxlength="2048" name="q" autocomplete="off" title="Search" type="text" value="" aria-label="Search" aria-haspopup="false" role="combobox" aria-autocomplete="list" dir="ltr" spellcheck="false" style="border: none; padding: 0px; margin: 0px; height: auto; width: 100%; background: url(&quot;data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw%3D%3D&quot;) transparent; position: absolute; z-index: 6; left: 0px; outline: none;">

A couple of things about the Search Box :

It's an <input> tag which will accept only text

An <input> tag won't have any onClick() event associated with it like the <button> or <a> tags.

So a proper clause for ExpectedConditions can be ElementIsVisible instead of ElementToBeClickable.

ElementIsVisible clause will ensure that the an element is present on the DOM of a page and visible.

Visibility means that the element is not only displayed but also has a height and width that is greater than 0.

Update :

As you mentioned that you are getting the same result, so I will make some simple tweaks to your code and write the equivalent code as :

WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0,0,10));
IWebElement element = wait.Until(ExpectedConditions.ElementIsVisible(By.Name("q")));
element.SendKeys("some text");


问:
How to update array state in react native?
I am trying to update only one element in an array state but i am not sure of how to do it.

State

```<code>constructor(props) {
    super(props);
    this.state = {
        markers: [],
    };
}
</code>```

Setting the state

```<code> setCurrentLocation() {
    var root = this;
    root.setState({
        markers: [
            ...root.state.markers,
            {
                coordinate: {
                    latitude: parseFloat(root.state.currentLat),
                    longitude: parseFloat(root.state.currentLon)
                },
                key: root.state.currentLat,
                image: pinCurrentLocation

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

If i want to change the key in the fourth element of marker, how do i do that?

Thanks

答:
Try this using create function</p>

```<code>onEditComparatorClicked(i) {
   let editableComparatorIndexes = [...this.state.markers];
   editableComparatorIndexes[i] = 1;
   this.setState({editableComparatorIndexes});
}
</code>```

Body:
I am trying to update only one element in an array state but i am not sure of how to do it.

State

constructor(props) {
    super(props);
    this.state = {
        markers: [],
    };
}

Setting the state

 setCurrentLocation() {
    var root = this;
    root.setState({
        markers: [
            ...root.state.markers,
            {
                coordinate: {
                    latitude: parseFloat(root.state.currentLat),
                    longitude: parseFloat(root.state.currentLon)
                },
                key: root.state.currentLat,
                image: pinCurrentLocation

            },
        ],
    });
}

If i want to change the key in the fourth element of marker, how do i do that?

Thanks

Body:
Try this using create function

onEditComparatorClicked(i) {
   let editableComparatorIndexes = [...this.state.markers];
   editableComparatorIndexes[i] = 1;
   this.setState({editableComparatorIndexes});
}


问:
Add Google Maps API V2 in a fragment
I'm trying to show the map from the Google Maps API V2 in fragment. I tried with the SupportMapFragment, but I can't get the expected output.
Also I'm a beginner on this platform! What I really want is just a way to put a map from the Google Maps API V2 for Android in a fragment. Please share your ideas and references.

Thanks in Advance !

答:
Here is my code.

Create project in google map concole and generate api key.

and then add dependency to build.gradle(app level).

```<code>compile 'com.google.android.gms:play-services-maps:10.2.1'
compile 'com.google.android.gms:play-services-location:10.2.1'
compile 'com.google.android.gms:play-services-places:10.2.1'
</code>```

remember to add permissions in Android.manifest

```<code><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-feature android:name="android.hardware.location.gps" android:required="true"/>
</code>```

create activity_main.xml

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="MergeRootFrame">

    <fragment
        class="com.googlelocationmapdemo.FragmentLocation"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</FrameLayout>
</code>```

nothing to call from MainActivity.class

Create fragment_location.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearMap"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/map"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
</code>```

Create FragmentLocation.class

```<code>public class FragmentLocation extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener {

    public static final String TAG = FragmentLocation.class.getSimpleName();
    public static final int REQUEST_CODE_FOR_PERMISSIONS = 1;
    GoogleApiClient mGoogleApiClient;
    LatLng mLatLng;
    GoogleMap mGoogleMap;
    Marker mCurrLocationMarker;
    private LinearLayout linearMap;
    Location mLastLocation;
    LocationManager locationManager;
    boolean statusOfGPS;
    private Dialog mDialogGPS;
    View view;
    LocationRequest mLocationRequest;
    SupportMapFragment mFragment;
   FragmentManager fragmentManager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        view=inflater.inflate(R.layout.fragment_location,container,false);
        fragmentManager=getChildFragmentManager();
        mFragment = (SupportMapFragment)fragmentManager.findFragmentById(R.id.map);
        mFragment.getMapAsync(this);
        if (!isGooglePlayServicesAvailable()) {
            Toast.makeText(getActivity(), "play services not available", Toast.LENGTH_SHORT).show();
        }
        locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        return view;
    }

    @Override
    public void onConnected(Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000); //5 seconds
        mLocationRequest.setFastestInterval(2000); //3 seconds
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
    }

    @Override
    public void onLocationChanged(Location location) {
        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }
        mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(mLatLng);
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(mLatLng));
        // Zoom in the Google Map
        mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (getActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED &&
                    getActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {
                buildGoogleApiClient();
                mGoogleMap.setMyLocationEnabled(true);

            } else {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION
                                , Manifest.permission.ACCESS_FINE_LOCATION},
                        REQUEST_CODE_FOR_PERMISSIONS);
            }
        } else {
            buildGoogleApiClient();
            mGoogleMap.setMyLocationEnabled(true);
        }

        //show dialog when click on location top-right side located on map.
        mGoogleMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
            @Override
            public boolean onMyLocationButtonClick() {
                statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                if (!statusOfGPS) {
                    turnOnGps();
                } else {
                    getCurrentLocation(mLastLocation);
                }
                return false;
            }
        });
    }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            GooglePlayServicesUtil.getErrorDialog(status, getActivity(), 0).show();
            return false;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_FOR_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (getActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED &&
                            getActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                                    == PackageManager.PERMISSION_GRANTED) {
                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mGoogleMap.setMyLocationEnabled(true);
                    }

                } else {
                    if (!(shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_COARSE_LOCATION)) && (!(shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)))) {
                        Snackbar snackbar = Snackbar.make(linearMap, "Never asked"
                                , Snackbar.LENGTH_INDEFINITE);
                        snackbar.setAction("Allow", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Intent intent = new Intent();
                                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
                                intent.setData(uri);
                                startActivity(intent);
                            }
                        });
                        snackbar.show();
                    }
                }
                break;
        }
    }

    private void getCurrentLocation(Location location) {

        mLastLocation = location;

        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }
        if (locationManager != null) {
            if (ContextCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                mLastLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);//getting last location
            }
            if (mLastLocation != null) {
                if (mGoogleMap != null) {
                    Log.d("activity", "LOC by Network");
                    mLatLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
                    MarkerOptions markerOptions = new MarkerOptions();
                    markerOptions.position(mLatLng);
                    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
                    mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
                    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(mLatLng));
                    mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
                }
            }
        }
    }

    private void turnOnGps() {
        if (mGoogleMap != null) {
            mGoogleMap.clear();
        }
        statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);//getting status of gps whether gps is on or off.
        mDialogGPS = new Dialog(getActivity(), R.style.MyDialogTheme);
        mDialogGPS.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mDialogGPS.setContentView(R.layout.dialog_turnongps);
        TextView txtCancel = (TextView) mDialogGPS.findViewById(R.id.txtCancel);
        TextView txtOK = (TextView) mDialogGPS.findViewById(R.id.txtSetting);

        ImageView imgLocation = (ImageView) mDialogGPS.findViewById(R.id.imgLocation);

        imgLocation.setImageResource(R.drawable.ic_location_my);

        txtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDialogGPS.dismiss();
                //finish();
                if (!statusOfGPS) {
                    getCurrentLocationByDefault();
                } else {
                    getCurrentLocation(mLastLocation);
                }
            }
        });

        txtOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //It is use to redirect to setting->location to turn on gps when press ok.
                startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                mDialogGPS.dismiss();
                if (!statusOfGPS) {
                    getCurrentLocationByDefault();
                } else {
                    getCurrentLocation(mLastLocation);
                }
            }
        });
        mDialogGPS.show();
    }

    private void getCurrentLocationByDefault() {
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        if (mGoogleMap != null) {
            LatLng xFrom1 = new LatLng(0.0, 0.0);
            mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(xFrom1, (float) 0.0));

            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(xFrom1);
            markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_taxi));
            mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
        } else {
            Log.i("MainActivity", "getCurrentLocationByDefault else");
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (mDialogGPS != null) {
            if (mDialogGPS.isShowing()) {
                mDialogGPS.dismiss();
            }
        }
        if (!statusOfGPS) {
            turnOnGps();
        } else {
            getCurrentLocation(mLastLocation);
        }

    }
    protected synchronized void buildGoogleApiClient() {
        if (mGoogleApiClient != null) {
            mGoogleApiClient = null;
        }
        mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }
}
</code>```

create dailog_gps.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="20dp"
    android:orientation="vertical">

    <LinearLayout

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/txtPhoneNumber"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Use Location?"
            android:textColor="@android:color/black"
          android:textSize="16sp"
            />

    </LinearLayout>

    <LinearLayout
        android:layout_marginTop="15dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="This app wants to change your \ndevice settings:"
            android:textSize="14sp" />

    </LinearLayout>

    <LinearLayout
        android:layout_marginTop="10dp"
        android:weightSum="2"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/imgLocation"
            android:layout_weight="1"
            android:layout_gravity="top"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Use GPS, Wi-Fi and mobile \nnetwork for location"
            android:layout_marginLeft="20dp"
            android:textSize="12sp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:orientation="horizontal"
        android:layout_marginTop="20dp">

        <TextView
            android:id="@+id/txtCancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="NO"
            android:layout_marginRight="30dp"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/txtSetting"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="YES"
            android:layout_marginRight="30dp"
            android:textSize="16sp" />

    </LinearLayout>
</LinearLayout>
</code>```

Hope this will help you :-)

Title: Add Google Maps API V2 in a fragment

Body:
Here is my code.

Create project in google map concole and generate api key.

and then add dependency to build.gradle(app level).

compile 'com.google.android.gms:play-services-maps:10.2.1'
compile 'com.google.android.gms:play-services-location:10.2.1'
compile 'com.google.android.gms:play-services-places:10.2.1'

remember to add permissions in Android.manifest

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-feature android:name="android.hardware.location.gps" android:required="true"/>

create activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="MergeRootFrame">

    <fragment
        class="com.googlelocationmapdemo.FragmentLocation"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</FrameLayout>

nothing to call from MainActivity.class

Create fragment_location.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearMap"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/map"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

Create FragmentLocation.class

public class FragmentLocation extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener {

    public static final String TAG = FragmentLocation.class.getSimpleName();
    public static final int REQUEST_CODE_FOR_PERMISSIONS = 1;
    GoogleApiClient mGoogleApiClient;
    LatLng mLatLng;
    GoogleMap mGoogleMap;
    Marker mCurrLocationMarker;
    private LinearLayout linearMap;
    Location mLastLocation;
    LocationManager locationManager;
    boolean statusOfGPS;
    private Dialog mDialogGPS;
    View view;
    LocationRequest mLocationRequest;
    SupportMapFragment mFragment;
   FragmentManager fragmentManager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        view=inflater.inflate(R.layout.fragment_location,container,false);
        fragmentManager=getChildFragmentManager();
        mFragment = (SupportMapFragment)fragmentManager.findFragmentById(R.id.map);
        mFragment.getMapAsync(this);
        if (!isGooglePlayServicesAvailable()) {
            Toast.makeText(getActivity(), "play services not available", Toast.LENGTH_SHORT).show();
        }
        locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        return view;
    }

    @Override
    public void onConnected(Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000); //5 seconds
        mLocationRequest.setFastestInterval(2000); //3 seconds
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(getActivity(),
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
    }

    @Override
    public void onLocationChanged(Location location) {
        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }
        mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(mLatLng);
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(mLatLng));
        // Zoom in the Google Map
        mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (getActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED &&
                    getActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {
                buildGoogleApiClient();
                mGoogleMap.setMyLocationEnabled(true);

            } else {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION
                                , Manifest.permission.ACCESS_FINE_LOCATION},
                        REQUEST_CODE_FOR_PERMISSIONS);
            }
        } else {
            buildGoogleApiClient();
            mGoogleMap.setMyLocationEnabled(true);
        }

        //show dialog when click on location top-right side located on map.
        mGoogleMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
            @Override
            public boolean onMyLocationButtonClick() {
                statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                if (!statusOfGPS) {
                    turnOnGps();
                } else {
                    getCurrentLocation(mLastLocation);
                }
                return false;
            }
        });
    }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            GooglePlayServicesUtil.getErrorDialog(status, getActivity(), 0).show();
            return false;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_FOR_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (getActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED &&
                            getActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                                    == PackageManager.PERMISSION_GRANTED) {
                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mGoogleMap.setMyLocationEnabled(true);
                    }

                } else {
                    if (!(shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_COARSE_LOCATION)) && (!(shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)))) {
                        Snackbar snackbar = Snackbar.make(linearMap, "Never asked"
                                , Snackbar.LENGTH_INDEFINITE);
                        snackbar.setAction("Allow", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Intent intent = new Intent();
                                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
                                intent.setData(uri);
                                startActivity(intent);
                            }
                        });
                        snackbar.show();
                    }
                }
                break;
        }
    }

    private void getCurrentLocation(Location location) {

        mLastLocation = location;

        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }
        if (locationManager != null) {
            if (ContextCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                mLastLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);//getting last location
            }
            if (mLastLocation != null) {
                if (mGoogleMap != null) {
                    Log.d("activity", "LOC by Network");
                    mLatLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
                    MarkerOptions markerOptions = new MarkerOptions();
                    markerOptions.position(mLatLng);
                    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
                    mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
                    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(mLatLng));
                    mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
                }
            }
        }
    }

    private void turnOnGps() {
        if (mGoogleMap != null) {
            mGoogleMap.clear();
        }
        statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);//getting status of gps whether gps is on or off.
        mDialogGPS = new Dialog(getActivity(), R.style.MyDialogTheme);
        mDialogGPS.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mDialogGPS.setContentView(R.layout.dialog_turnongps);
        TextView txtCancel = (TextView) mDialogGPS.findViewById(R.id.txtCancel);
        TextView txtOK = (TextView) mDialogGPS.findViewById(R.id.txtSetting);

        ImageView imgLocation = (ImageView) mDialogGPS.findViewById(R.id.imgLocation);

        imgLocation.setImageResource(R.drawable.ic_location_my);

        txtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDialogGPS.dismiss();
                //finish();
                if (!statusOfGPS) {
                    getCurrentLocationByDefault();
                } else {
                    getCurrentLocation(mLastLocation);
                }
            }
        });

        txtOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //It is use to redirect to setting->location to turn on gps when press ok.
                startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                mDialogGPS.dismiss();
                if (!statusOfGPS) {
                    getCurrentLocationByDefault();
                } else {
                    getCurrentLocation(mLastLocation);
                }
            }
        });
        mDialogGPS.show();
    }

    private void getCurrentLocationByDefault() {
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        if (mGoogleMap != null) {
            LatLng xFrom1 = new LatLng(0.0, 0.0);
            mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(xFrom1, (float) 0.0));

            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(xFrom1);
            markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_taxi));
            mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
        } else {
            Log.i("MainActivity", "getCurrentLocationByDefault else");
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        statusOfGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (mDialogGPS != null) {
            if (mDialogGPS.isShowing()) {
                mDialogGPS.dismiss();
            }
        }
        if (!statusOfGPS) {
            turnOnGps();
        } else {
            getCurrentLocation(mLastLocation);
        }

    }
    protected synchronized void buildGoogleApiClient() {
        if (mGoogleApiClient != null) {
            mGoogleApiClient = null;
        }
        mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }
}

create dailog_gps.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="20dp"
    android:orientation="vertical">

    <LinearLayout

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/txtPhoneNumber"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Use Location?"
            android:textColor="@android:color/black"
          android:textSize="16sp"
            />

    </LinearLayout>

    <LinearLayout
        android:layout_marginTop="15dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="This app wants to change your \ndevice settings:"
            android:textSize="14sp" />

    </LinearLayout>

    <LinearLayout
        android:layout_marginTop="10dp"
        android:weightSum="2"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/imgLocation"
            android:layout_weight="1"
            android:layout_gravity="top"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Use GPS, Wi-Fi and mobile \nnetwork for location"
            android:layout_marginLeft="20dp"
            android:textSize="12sp" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:orientation="horizontal"
        android:layout_marginTop="20dp">

        <TextView
            android:id="@+id/txtCancel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="NO"
            android:layout_marginRight="30dp"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/txtSetting"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="YES"
            android:layout_marginRight="30dp"
            android:textSize="16sp" />

    </LinearLayout>
</LinearLayout>

Hope this will help you :-)