问:
wondering if there is an efficient way to shorten this code
So my program is going to end up being fairly large and I don't want a whole lot of code that could just be shortened. Here is one instance I am looking for some tips on:

```<code>private void bookComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    string books = null;
    // sets books to the clicked item
    books = bookComboBox.SelectedItem.ToString();
    selectedPictureBox.Visible = true;
    // Loads string to list box and image to selectedPictureBox when programming is selected
    if (books == "Programming")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("programming.png");
        bookListBox.Items.Add("Visual Basic");
        bookListBox.Items.Add("Java");
        bookListBox.Items.Add("C#");
    }
    // Loads string to list box and image to selectedPictureBox when Networking is selected
    else if (books == "Networking")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("networking.png");
        bookListBox.Items.Add("LAN Networks");
        bookListBox.Items.Add("Windows Networking");
        bookListBox.Items.Add("More About Networking");
    }
    // Loads string to list box and image to selectedPictureBox when Web is selected
    else if (books == "Web")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("html.png");
        bookListBox.Items.Add("Web Programming");
        bookListBox.Items.Add("JavaScript");
        bookListBox.Items.Add("ASP");
    }
}
</code>```

The code works fine but I was just hoping to get some tips on shortening this code if necessary, any input is appreciated.

答:
Assuming you can use C# 7's new Tuples:

```<code>private Dictionary<string, (string image, List<string> books)> books = new Dictionary<string, (string image, List<string> books)>
{
    { "Programming", ("programming.png", new List<string> { "Visual Basic", "Java", "C#"} ) },
    { "Networking", ("networking.png", new List<string> {"LAN Networks", "Windows Networking", "More About Networking"}) },
    { "Web", ("html.png", new List<string> {"Web Programming", "Javascript", "ASP"}) }
};

private void bookComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    // sets books to the clicked item
    string book = bookComboBox.SelectedItem.ToString();
    selectedPictureBox.Visible = true;

    if (books.Keys.Contains(book))
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile(books[book].image);
        foreach(var b in books[book].books)
        {
           bookListBox.Items.Add(b);
        }
    }
}
</code>```

But a class is likely even better:

```<code>public class BookGroup
{
    public string ImagePath {get;set;}
    public List<string> Books {get;}

    public BookGroup(string imagePath, params string[] books)
    {
        ImagePath = imagePath;
        Books = new List<string>(books.Length);
        Books.AddRange(books);
    }
}
</code>```

Which isn't all that different to use right now, but it formalizes some things that might make this code easier to work with down the road, and it's possible if you can't use Tuples yet. I might also have a Book class by itself, just for fun, but for now:

```<code>private Dictionary<string, BookGroup> books = new Dictionary<string, BookGroup>
{
    { "Programming", new BookGroup("programming.png", "Visual Basic", "Java", "C#")},
    { "Networking", new BookGroup("networking.png","LAN Networks", "Windows Networking", "More About Networking") },
    { "Web", new BookGroup("html.png", "Web Programming", "Javascript", "ASP") }
};

private void bookComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    // sets books to the clicked item
    string book = bookComboBox.SelectedItem.ToString();
    selectedPictureBox.Visible = true;

    if (books.Keys.Contains(book))
    {
        bookListBox.Items.Clear();
        BookGroup bg = books[book];
        selectedPictureBox.Image = Image.FromFile(bg.ImagePath);
        foreach(var b in bg.Books)
        {
           bookListBox.Items.Add(b);
        }
    }
}
</code>```

Regardless, I'd definitely have a way to load these from a text file... likely a csv, or maybe even a small in-process database, so that I could update this listing without having to recompile or distribute new program code. And, with that in mind, in order to fit this data in a single structure in a single file, I'd likely also repeat the image and type with each book, so that my csv data looks like this:

```
Topic,Image,Title
Programming,programming.png,"Visual Basic"
Programming,programming.png,"Java"
Programming,programming.png,"C#"
Networking,networking.png,"LAN Networks"
Networking,networking.png,"Windows Networking"
Networking,networking.png,"More About Networking"
Web,html.png,"Web Programming"
Web,html.png,"Javascript"
Web,html.png,"ASP"```

That changes the whole character of the code. I'm a bit biased, but I'd likely use this CSV Parser, and again assuming Tuples I'd produce something like this:

```<code>private List<(string Topic, string ImagePath, string Title)> books;

//In the form load code:
books = EasyCSV.FromFile("bookData.csv").Select(b => (b[0], b[1], b[2])).ToList();

//and finally, in the original selectindexchanged method:
private void bookComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    string topic = bookComboBox.SelectedItem.ToString();
    selectedPictureBox.Visible = true;

    var items = books.Where(b => b.Topic == topic).ToArray();
    if(items.Length > 0)
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile(items[0].ImagePath);
        bookListBox.Items.AddRange(items);
    }
}
</code>```

Body:
So my program is going to end up being fairly large and I don't want a whole lot of code that could just be shortened. Here is one instance I am looking for some tips on:

private void bookComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    string books = null;
    // sets books to the clicked item
    books = bookComboBox.SelectedItem.ToString();
    selectedPictureBox.Visible = true;
    // Loads string to list box and image to selectedPictureBox when programming is selected
    if (books == "Programming")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("programming.png");
        bookListBox.Items.Add("Visual Basic");
        bookListBox.Items.Add("Java");
        bookListBox.Items.Add("C#");
    }
    // Loads string to list box and image to selectedPictureBox when Networking is selected
    else if (books == "Networking")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("networking.png");
        bookListBox.Items.Add("LAN Networks");
        bookListBox.Items.Add("Windows Networking");
        bookListBox.Items.Add("More About Networking");
    }
    // Loads string to list box and image to selectedPictureBox when Web is selected
    else if (books == "Web")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("html.png");
        bookListBox.Items.Add("Web Programming");
        bookListBox.Items.Add("JavaScript");
        bookListBox.Items.Add("ASP");
    }
}

The code works fine but I was just hoping to get some tips on shortening this code if necessary, any input is appreciated.

Body:
Assuming you can use C# 7's new Tuples:

private Dictionary<string, (string image, List<string> books)> books = new Dictionary<string, (string image, List<string> books)>
{
    { "Programming", ("programming.png", new List<string> { "Visual Basic", "Java", "C#"} ) },
    { "Networking", ("networking.png", new List<string> {"LAN Networks", "Windows Networking", "More About Networking"}) },
    { "Web", ("html.png", new List<string> {"Web Programming", "Javascript", "ASP"}) }
};

private void bookComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    // sets books to the clicked item
    string book = bookComboBox.SelectedItem.ToString();
    selectedPictureBox.Visible = true;

    if (books.Keys.Contains(book))
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile(books[book].image);
        foreach(var b in books[book].books)
        {
           bookListBox.Items.Add(b);
        }
    }
}

But a class is likely even better:

public class BookGroup
{
    public string ImagePath {get;set;}
    public List<string> Books {get;}

    public BookGroup(string imagePath, params string[] books)
    {
        ImagePath = imagePath;
        Books = new List<string>(books.Length);
        Books.AddRange(books);
    }
}

Which isn't all that different to use right now, but it formalizes some things that might make this code easier to work with down the road, and it's possible if you can't use Tuples yet. I might also have a Book class by itself, just for fun, but for now:

private Dictionary<string, BookGroup> books = new Dictionary<string, BookGroup>
{
    { "Programming", new BookGroup("programming.png", "Visual Basic", "Java", "C#")},
    { "Networking", new BookGroup("networking.png","LAN Networks", "Windows Networking", "More About Networking") },
    { "Web", new BookGroup("html.png", "Web Programming", "Javascript", "ASP") }
};

private void bookComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    // sets books to the clicked item
    string book = bookComboBox.SelectedItem.ToString();
    selectedPictureBox.Visible = true;

    if (books.Keys.Contains(book))
    {
        bookListBox.Items.Clear();
        BookGroup bg = books[book];
        selectedPictureBox.Image = Image.FromFile(bg.ImagePath);
        foreach(var b in bg.Books)
        {
           bookListBox.Items.Add(b);
        }
    }
}

Regardless, I'd definitely have a way to load these from a text file... likely a csv, or maybe even a small in-process database, so that I could update this listing without having to recompile or distribute new program code. And, with that in mind, in order to fit this data in a single structure in a single file, I'd likely also repeat the image and type with each book, so that my csv data looks like this:

Topic,Image,Title
Programming,programming.png,"Visual Basic"
Programming,programming.png,"Java"
Programming,programming.png,"C#"
Networking,networking.png,"LAN Networks"
Networking,networking.png,"Windows Networking"
Networking,networking.png,"More About Networking"
Web,html.png,"Web Programming"
Web,html.png,"Javascript"
Web,html.png,"ASP"

That changes the whole character of the code. I'm a bit biased, but I'd likely use this CSV Parser, and again assuming Tuples I'd produce something like this:

private List<(string Topic, string ImagePath, string Title)> books;

//In the form load code:
books = EasyCSV.FromFile("bookData.csv").Select(b => (b[0], b[1], b[2])).ToList();

//and finally, in the original selectindexchanged method:
private void bookComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    string topic = bookComboBox.SelectedItem.ToString();
    selectedPictureBox.Visible = true;

    var items = books.Where(b => b.Topic == topic).ToArray();
    if(items.Length > 0)
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile(items[0].ImagePath);
        bookListBox.Items.AddRange(items);
    }
}


来源: stackexchange

问:
Spring Batch - Comma separated values - Save in Data Base
I have a file which contains list of values (user IDs)  separated by comma(“,”) as follows.

111, 222, 333, 444, 555, 777  …………

The file contains millions of such records and I wanted to save these values into a single column in a table in  RDBMS.
I tried to use DelimitedLineTokenizer for parsing data.

The issue is that “DelimitedLineTokenizer” considers only one entry in a single line, and rest of the values are ignored.The first entry ("111") is saved and rest of the values in the same line are ignored.If there is a second line , the first element in the second line is saved and rest are ignored.

Is there a way to tokenize all the comma separated values from a single line and save all of them into DB?

The query is a s follows.
INSERT INTO users (id) VALUES (: userid).

I used the following code to parse the file and save it in DB.

```<code>public FlatFileItemReader<User> reader() {

    FlatFileItemReader<User> reader = new FlatFileItemReader<User>();
    DelimitedLineTokenizer reader = new DelimitedLineTokenizer(",");
    reader.setNames(new String[] {“userid”});

    blah…blah….blah….

    reader.setLineMapper(new DefaultLineMapper<User>() {
            {

                setLineTokenizer(reader);
                setFieldSetMapper(new BeanWrapperFieldSetMapper<User>() {
                    {
                        setTargetType(User.class);
                    }
                });
            }
        });
        return reader;
    }

 @Bean
    public UserItemProcessor processor() {
              return new UserItemProcessor();
    }

@Bean
public Job importUserJob(JobCompletionNotificationListener listener) {

        return jobBuilderFactory.get("importUserJob").incrementer(new RunIdIncrementer()).listener(listener)
                .flow(step1()).end().build();
    }

    @Bean
    public Step step1() {

        return stepBuilderFactory.get("step1").<User, User> chunk(5).reader(reader()).processor(processor())
                .writer(writer()).build();
    }
</code>```

答:
Basically, you have two delimiters for target object - comma & new line. So either you writer a custom reader that works on both delimiters or you need to pre process your file to bring it to standard format.

In my opinion, you are better off by pre processing your file to replace all comma with new line character.

You might retain original file as is and create pre processed data in a new temporary file.

You can either do that as a separate spring batch step ( not recommended due to file size ) or if its going to be a scheduled job then probably, in your kick off script.

Replace comma with newline in java

How to break lines at a specific character in Notepad++?

Notepad++ find and replace string with a new-line

Replace comma with new line in a text file using tr in Linux

ContentLicense: CC BY-SA 3.0

Body:
I have a file which contains list of values (user IDs)  separated by comma(“,”) as follows.

111, 222, 333, 444, 555, 777  …………

The file contains millions of such records and I wanted to save these values into a single column in a table in  RDBMS.
I tried to use DelimitedLineTokenizer for parsing data.

The issue is that “DelimitedLineTokenizer” considers only one entry in a single line, and rest of the values are ignored.The first entry ("111") is saved and rest of the values in the same line are ignored.If there is a second line , the first element in the second line is saved and rest are ignored.

Is there a way to tokenize all the comma separated values from a single line and save all of them into DB?

The query is a s follows.
INSERT INTO users (id) VALUES (: userid).

I used the following code to parse the file and save it in DB.

public FlatFileItemReader<User> reader() {

    FlatFileItemReader<User> reader = new FlatFileItemReader<User>();
    DelimitedLineTokenizer reader = new DelimitedLineTokenizer(",");
    reader.setNames(new String[] {“userid”});

    blah…blah….blah….

    reader.setLineMapper(new DefaultLineMapper<User>() {
            {

                setLineTokenizer(reader);
                setFieldSetMapper(new BeanWrapperFieldSetMapper<User>() {
                    {
                        setTargetType(User.class);
                    }
                });
            }
        });
        return reader;
    }

 @Bean
    public UserItemProcessor processor() {
              return new UserItemProcessor();
    }

@Bean
public Job importUserJob(JobCompletionNotificationListener listener) {

        return jobBuilderFactory.get("importUserJob").incrementer(new RunIdIncrementer()).listener(listener)
                .flow(step1()).end().build();
    }

    @Bean
    public Step step1() {

        return stepBuilderFactory.get("step1").<User, User> chunk(5).reader(reader()).processor(processor())
                .writer(writer()).build();
    }


问:
Remove portion of a string after a particular character from the end of the string
I need to remove all characters from a string after a particular character from the end. The below code works when it contains only one #
eg:

```<code>$variable = "8233 Station #2212";
echo trim(substr($variable, 0, strpos($variable, "#")));
</code>```

result: "8233 Station";
But if the string contains more than one # I need to avoid the strings after the last #

```<code> $variable = "8233 Station #2211 #2212";
</code>```

The result i need in the above situation is "8233 Station #2211"

答:
Use strrpos to get position of last matching element

```<code>//$variable = "8233 Station #2212"; //8233 Station
$variable = "8233 Station #2211 #2212";
echo trim(substr($variable, 0, strrpos($variable, "#"))); //8233 Station #2211
</code>```

Body:
I need to remove all characters from a string after a particular character from the end. The below code works when it contains only one #
eg:

$variable = "8233 Station #2212";
echo trim(substr($variable, 0, strpos($variable, "#")));

result: "8233 Station";
But if the string contains more than one # I need to avoid the strings after the last #

 $variable = "8233 Station #2211 #2212";

The result i need in the above situation is "8233 Station #2211"

Body:
Use strrpos to get position of last matching element

//$variable = "8233 Station #2212"; //8233 Station
$variable = "8233 Station #2211 #2212";
echo trim(substr($variable, 0, strrpos($variable, "#"))); //8233 Station #2211


问:
h2o deepwater from docker image in R
I can connect from R to h2o cluster which is running from docker image but there is error appearing:

Version mismatch! H2O is running version 3.11.0.235 but h2o-R package is version 3.11.0.99999 .

I can run many tasks from R but for example i can not run XGB training which I can run with Flow.
I want to create more comprehensive algorithm but I also need R functions to it.

I could not find h2o R package in version 3.11.0.235..
Is there option to use full potential of cluster h2o from R if cluster h2o is running from docker image?

答:
You can set strict_version_check = FALSE in your h2o.init() call and that will get you around the error.  Those versions are close enough that it shouldn't lead to any issues (but technically it could).

Also, that's an older Docker image -- the build number now is 274, so I would also suggest a docker pull, although it's not strictly necessary.  There's more info on the h2oai/deepwater README.

```<code>docker pull opsh2oai/h2o-deepwater
</code>```

Title: h2o deepwater from docker image in R

Body:
You can set strict_version_check = FALSE in your h2o.init() call and that will get you around the error.  Those versions are close enough that it shouldn't lead to any issues (but technically it could).

Also, that's an older Docker image -- the build number now is 274, so I would also suggest a docker pull, although it's not strictly necessary.  There's more info on the h2oai/deepwater README.

docker pull opsh2oai/h2o-deepwater


问:
Which database i have to use to implement the auto-completion of dictionary
I ran across a interview question of implementing a dictionary that can implement the features of auto-completion, auto-correction, spell check etc...

I actually wanted to know which data base i have to use to store all the word like (for location country, city and zip code) .

Please suggest me if there any framework in java with any database or any optimal database that can achieve the solution

Any links that guide me on this are welcome...

答: The simplest solution that can be done is using 'trie'. Its a data structure that represents the characeters at the indexed child node. http://en.wikipedia.org/wiki/Trie Has more info on this. THis need to be done in memory as at the end of each key stroke you are going to modify the set of suggesstions and auto complete list. Also as it is linked to the UI component like dropdown or text field.</p>

ContentLicense: CC BY-SA 2.5


问:
How to center an image inside a list with other elements
I have an unordered list that contains several list elements inside. Also inside is an image element which is to be centered. I tried to center it using the margin: auto; property but since there are list elements on the side, it takes that into account when centering itself. How do I center the image in respect to it's container?

.nav {
  width: 1280px;
  margin: 0 auto;
  font-size: 16px;
  font-weight: 500;
  border: 1px solid black;
}

.nav li {
  float: left;
  vertical-align: top;
  margin: 5px 10px;
}

nav li:first-child {
  margin-left: 75px;
}

.nav img {
  display: block;
  margin: auto;
  height: 21px;
  width: 24px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="nav">
  <ul class="clearfix">
    <li>Home</li>
    <li>Moments</li>
    <li>Notifications</li>
    <li>Messages</li>
    <img src="assets/image/twitter-icon.png" alt="Twitter Icon">
  </ul>
</nav></code>```

答:
Put your img element into li and do some changes in your css like below snippet:

.nav ul {
  width: 800px;
  margin: 0 auto;
  font-size: 16px;
  font-weight: 500;
  border: 1px solid black;
  padding: 0;
  list-style-type: none;
  text-align: center;
}

.nav li {
  display: inline-block;
  vertical-align: middle;
  margin: 5px 10px;
}

.nav img {
  display: block;
  margin: auto;
}

.nav ul:before,
.nav ul:after {
  content: "";
  display: table;
}

.nav ul:after {
  clear: both;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--html-->
<nav class="nav">
  <ul class="clearfix">
    <li>Home</li>
    <li>Moments</li>
    <li>Notifications</li>
    <li>Messages</li>
    <li><img src="//login.create.net/images/icons/user/twitter_30x30.png" alt="Twitter Icon"></li>
  </ul>
</nav></code>```

Body:
I have an unordered list that contains several list elements inside. Also inside is an image element which is to be centered. I tried to center it using the margin: auto; property but since there are list elements on the side, it takes that into account when centering itself. How do I center the image in respect to it's container?

.nav {
  width: 1280px;
  margin: 0 auto;
  font-size: 16px;
  font-weight: 500;
  border: 1px solid black;
}

.nav li {
  float: left;
  vertical-align: top;
  margin: 5px 10px;
}

nav li:first-child {
  margin-left: 75px;
}

.nav img {
  display: block;
  margin: auto;
  height: 21px;
  width: 24px;
}

Home

Moments

Notifications

Messages

Body:
Put your img element into li and do some changes in your css like below snippet:

.nav ul {
  width: 800px;
  margin: 0 auto;
  font-size: 16px;
  font-weight: 500;
  border: 1px solid black;
  padding: 0;
  list-style-type: none;
  text-align: center;
}

.nav li {
  display: inline-block;
  vertical-align: middle;
  margin: 5px 10px;
}

.nav img {
  display: block;
  margin: auto;
}

.nav ul:before,
.nav ul:after {
  content: "";
  display: table;
}

.nav ul:after {
  clear: both;
}

<!--html-->
<nav class="nav">
  <ul class="clearfix">
    <li>Home</li>
    <li>Moments</li>
    <li>Notifications</li>
    <li>Messages</li>
    <li><img src="//login.create.net/images/icons/user/twitter_30x30.png" alt="Twitter Icon"></li>
  </ul>
</nav>


问:
Why does this only work with a return statement here?
I just started to teach myself java with no prior programming experience and I just completed the functional programming course in Udacity. While making a Tic Tac Toe game as the final project, I am required to program a function that checks for a winner or tie. The game is represented as a 2d array and everything else is already given; my only job is code the checkGameWinner function. I've completed the code and gotten it to work; but in the interest of fully understanding Java, I want to ask the following:

```<code>    public String checkGameWinner(char [][]grid){
    String result = "None";
    //Student code goes here ...

    if(grid[1][1]=='x' && grid[1][0]=='x'&& grid[1][2]=='x'){
        result = "X wins";
    }
    else if(grid[1][1]=='x' && grid[0][1]=='x'&& grid[2][1]=='x'){
        result = "X wins";
    }
    else if(grid[1][1]=='x' && grid[0][0]=='x' && grid[2][2]=='x'){
        result = "X wins";
    }
    else if(grid[1][1]=='x' && grid[0][2]=='x' && grid[2][0]=='x'){
        result = "X wins";
    }
    else if(grid[0][0]=='x' && grid[1][0]=='x' && grid[2][0]=='x'){
        result = "X wins";
    }
    else if(grid[2][0]=='x' && grid[2][1]=='x' && grid[2][2]=='x'){
        result = "X wins";
    }
    else if(grid[0][2]=='x' && grid[1][2]=='x' && grid[2][2]=='x'){
        result = "X wins";
    }
    else if(grid[0][0]=='x' && grid[0][1]=='x' && grid[0][2]=='x'){
        result = "X wins";
    }

    else if(grid[1][1]=='o' && grid[1][0]=='o'&& grid[1][2]=='o'){
        result = "O wins";
    }
    else if(grid[1][1]=='o' && grid[0][1]=='o'&& grid[2][1]=='o'){
        result = "O wins";
    }
    else if(grid[1][1]=='o' && grid[0][0]=='o' && grid[2][2]=='o'){
        result = "O wins";
    }
    else if(grid[1][1]=='o' && grid[0][2]=='o' && grid[2][0]=='o'){
        result = "O wins";
    }
    else if(grid[0][0]=='o' && grid[1][0]=='o' && grid[2][0]=='o'){
        result = "O wins";
    }
    else if(grid[2][0]=='o' && grid[2][1]=='o' && grid[2][2]=='o'){
        result = "O wins";
    }
    else if(grid[0][2]=='o' && grid[1][2]=='o' && grid[2][2]=='o'){
        result = "O wins";
    }
    else if(grid[0][0]=='o' && grid[0][1]=='o' && grid[0][2]=='o'){
        result = "O wins";
    }

    else {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (grid[i][j] == '-') {
                    result = "None";
                    return result;
                } else {
                    result = "Tie";
                }
            }
        }
    }

    return result;
}
</code>```

My logic was that I would first check for all of the 16 different winning combinations, then check if any of the cells in the array were empty using a for loop(which if they were the function returns "None" and the game proceeds). Finally, if there are no winning combinations and no empty spaces, the game is a tie and I left that as the last statement. I found that in order for the above code to work as intended, I needed to include an additional return statement immediately after the if statement in the double for loop(the one checking for empty spaces). If this return was not added, the game would end and be declared a Tie at incorrect moments, even when empty spaces were available. My question is why is this return necessary? If the boolean value of the if statement under the for loop is true(i.e. there are ANY empty spaces), then shouldn't the variable "result" be updated as "none" and the following else statement skipped, therefore exiting the for loop, and then going to the final return at the end of the code?. I've read that generally you don't want more than one return in any one function, but I'm not sure how true this is. I hope this was understandable and if anyone has any insight or help they can give this beginning programmer would be very appreciative. Thank you. P.S. Empty spaces are represented by the '-' character.

答:
Working on the same udacity course I had a very similar experience trying to figure out where to place the final 'if' statement evaluating for a tie in order for the program to step through the function correctly; and I ran into the same issue of it not working if I didn't also have the very last 'return' statement in there. Thanks for all the discussion on ending the for loops better. I finally came up with this method for evaluating for a tie.</p>

```<code>public String checkGameWinner(char[][] grid) {
    String result = "None";
    char[] letter = {'x', 'o'};
    String[] otherResults = {"X Wins", "O Wins", "Tie"};
    int isTie = 0;

    //checks for win on both diagonals
    for (int i = 0; i < letter.length; i++) {
        if (grid[0][0] == letter[i] && grid[1][1] == letter[i] && grid[2][2] == letter[i]) {
            return otherResults[i];
        }
        if (grid[0][2] == letter[i] && grid[1][1] == letter[i] && grid[2][0] == letter[i]) {
            return otherResults[i];
        }
        for (int j = 0; j < grid.length; j++) {
            //Checks for win on rows
            if (grid[0][j] == letter[i] && grid[1][j] == letter[i] && grid[2][j] == letter[i]) {
                return otherResults[i];
            }
            //Checks for win on columns
            if (grid[j][0] == letter[i] && grid[j][1] == letter[i] && grid[j][2] == letter[i]) {
                return otherResults[i];
            }
        }
    }
    // checks for tie or draw
    for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid.length; j++) {
            if (grid[i][j] == 'x' || grid[i][j] == 'o') {
                isTie = isTie + 1;
            }
        }
    }
    if (isTie == 9){
        return otherResults [2];
    }
    return result;
}
</code>```

Body:
I just started to teach myself java with no prior programming experience and I just completed the functional programming course in Udacity. While making a Tic Tac Toe game as the final project, I am required to program a function that checks for a winner or tie. The game is represented as a 2d array and everything else is already given; my only job is code the checkGameWinner function. I've completed the code and gotten it to work; but in the interest of fully understanding Java, I want to ask the following:

    public String checkGameWinner(char [][]grid){
    String result = "None";
    //Student code goes here ...

    if(grid[1][1]=='x' && grid[1][0]=='x'&& grid[1][2]=='x'){
        result = "X wins";
    }
    else if(grid[1][1]=='x' && grid[0][1]=='x'&& grid[2][1]=='x'){
        result = "X wins";
    }
    else if(grid[1][1]=='x' && grid[0][0]=='x' && grid[2][2]=='x'){
        result = "X wins";
    }
    else if(grid[1][1]=='x' && grid[0][2]=='x' && grid[2][0]=='x'){
        result = "X wins";
    }
    else if(grid[0][0]=='x' && grid[1][0]=='x' && grid[2][0]=='x'){
        result = "X wins";
    }
    else if(grid[2][0]=='x' && grid[2][1]=='x' && grid[2][2]=='x'){
        result = "X wins";
    }
    else if(grid[0][2]=='x' && grid[1][2]=='x' && grid[2][2]=='x'){
        result = "X wins";
    }
    else if(grid[0][0]=='x' && grid[0][1]=='x' && grid[0][2]=='x'){
        result = "X wins";
    }

    else if(grid[1][1]=='o' && grid[1][0]=='o'&& grid[1][2]=='o'){
        result = "O wins";
    }
    else if(grid[1][1]=='o' && grid[0][1]=='o'&& grid[2][1]=='o'){
        result = "O wins";
    }
    else if(grid[1][1]=='o' && grid[0][0]=='o' && grid[2][2]=='o'){
        result = "O wins";
    }
    else if(grid[1][1]=='o' && grid[0][2]=='o' && grid[2][0]=='o'){
        result = "O wins";
    }
    else if(grid[0][0]=='o' && grid[1][0]=='o' && grid[2][0]=='o'){
        result = "O wins";
    }
    else if(grid[2][0]=='o' && grid[2][1]=='o' && grid[2][2]=='o'){
        result = "O wins";
    }
    else if(grid[0][2]=='o' && grid[1][2]=='o' && grid[2][2]=='o'){
        result = "O wins";
    }
    else if(grid[0][0]=='o' && grid[0][1]=='o' && grid[0][2]=='o'){
        result = "O wins";
    }

    else {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (grid[i][j] == '-') {
                    result = "None";
                    return result;
                } else {
                    result = "Tie";
                }
            }
        }
    }

    return result;
}

My logic was that I would first check for all of the 16 different winning combinations, then check if any of the cells in the array were empty using a for loop(which if they were the function returns "None" and the game proceeds). Finally, if there are no winning combinations and no empty spaces, the game is a tie and I left that as the last statement. I found that in order for the above code to work as intended, I needed to include an additional return statement immediately after the if statement in the double for loop(the one checking for empty spaces). If this return was not added, the game would end and be declared a Tie at incorrect moments, even when empty spaces were available. My question is why is this return necessary? If the boolean value of the if statement under the for loop is true(i.e. there are ANY empty spaces), then shouldn't the variable "result" be updated as "none" and the following else statement skipped, therefore exiting the for loop, and then going to the final return at the end of the code?. I've read that generally you don't want more than one return in any one function, but I'm not sure how true this is. I hope this was understandable and if anyone has any insight or help they can give this beginning programmer would be very appreciative. Thank you. P.S. Empty spaces are represented by the '-' character.

Body:
Working on the same udacity course I had a very similar experience trying to figure out where to place the final 'if' statement evaluating for a tie in order for the program to step through the function correctly; and I ran into the same issue of it not working if I didn't also have the very last 'return' statement in there. Thanks for all the discussion on ending the for loops better. I finally came up with this method for evaluating for a tie.

public String checkGameWinner(char[][] grid) {
    String result = "None";
    char[] letter = {'x', 'o'};
    String[] otherResults = {"X Wins", "O Wins", "Tie"};
    int isTie = 0;

    //checks for win on both diagonals
    for (int i = 0; i < letter.length; i++) {
        if (grid[0][0] == letter[i] && grid[1][1] == letter[i] && grid[2][2] == letter[i]) {
            return otherResults[i];
        }
        if (grid[0][2] == letter[i] && grid[1][1] == letter[i] && grid[2][0] == letter[i]) {
            return otherResults[i];
        }
        for (int j = 0; j < grid.length; j++) {
            //Checks for win on rows
            if (grid[0][j] == letter[i] && grid[1][j] == letter[i] && grid[2][j] == letter[i]) {
                return otherResults[i];
            }
            //Checks for win on columns
            if (grid[j][0] == letter[i] && grid[j][1] == letter[i] && grid[j][2] == letter[i]) {
                return otherResults[i];
            }
        }
    }
    // checks for tie or draw
    for (int i = 0; i < grid.length; i++) {
        for (int j = 0; j < grid.length; j++) {
            if (grid[i][j] == 'x' || grid[i][j] == 'o') {
                isTie = isTie + 1;
            }
        }
    }
    if (isTie == 9){
        return otherResults [2];
    }
    return result;
}


问:
Create parameters for sub-process jbpm
I have the following figure:

Escalate to next level is a sub-process which needs a lot of variables, however the parent process doesn't need them and in fact the PerapareParameters task should generate them and pass it to the process. How can I do that in a way that doesn't require me to map them in the data items for the process. I'm using the eclipse plugin. Thanks in advance :)

答: To pass variables in sub-process you have to perform variable mapping. I cant see any other way to pass variables. </p>

Title: Create parameters for sub-process jbpm


问:
Slow git rev-list when iterating git commit history over time intervals
I wrote a tool that uses git rev-list -n1 --before=X to iterate a Git commit history using fixed time intervals, so that I see the last revision for every year, month, etc.

The problem is that rev-list kicks off a new revision walk on every call, and it takes longer the father back I go. Here are some samples from the Linux kernel source.

```<code>$ time git rev-list -n1 --before="Jan 1 2016" HEAD
a889331d759453fa7f424330f75ae4e2b9e02db4

real    0m1.395s
user    0m1.367s
sys 0m0.024s

$ time git rev-list -n1 --before="Jan 1 2015" HEAD
5b5e76218fbdbb71a01d5480f289ead624232876

real    0m2.349s
user    0m2.306s
sys 0m0.036s

$ time git rev-list -n1 --before="Jan 1 2005" HEAD

real    0m5.556s
user    0m5.435s
sys 0m0.105s
</code>```

If I want to call rev-list in a loop over N decreasing dates, that loop runs N walks that take longer on every iteration. The docs talk about bit-maps and object traversal strategies to speed up the history, but I am having trouble understanding them. I tried git repack -ab followed by git rev-list --use-bitmap-index, but that didn't improve results.

My only requirement is that given any position for HEAD, I can accurately pinpoint the first revision that appears before the date given to --before, following paths to ancestors if needed.

What is the best way to make rev-list faster for this use case?

答:
Repeatedly scanning a list to select successive elements is O(N^2).  Doesn't much matter how efficient the scan is, that N^2 is going to bite.

Generate one list with commit id and date, then strip what you don't want and generate your real log messages from the selected sha's. That's three passes total, not N.

```<code>git log --first-parent --pretty=%H\ %cd --date=short \
| awk '$2$3 != last { last=$2$3; print $1}' 'FS=[- ]' \
| git log --no-walk --stdin
</code>```

That took fifteen seconds cold-cache on the linux repo, with a spinny-things hdd, listing 147 commits.  A rerun took less than a second.

edit: subbing in --date-order for --first-parent to consider all paths took 25.1 seconds cold-cache, 7.9 seconds hot, to list 782 commits.

Body:
I wrote a tool that uses git rev-list -n1 --before=X to iterate a Git commit history using fixed time intervals, so that I see the last revision for every year, month, etc.

The problem is that rev-list kicks off a new revision walk on every call, and it takes longer the father back I go. Here are some samples from the Linux kernel source.

$ time git rev-list -n1 --before="Jan 1 2016" HEAD
a889331d759453fa7f424330f75ae4e2b9e02db4

real    0m1.395s
user    0m1.367s
sys 0m0.024s

$ time git rev-list -n1 --before="Jan 1 2015" HEAD
5b5e76218fbdbb71a01d5480f289ead624232876

real    0m2.349s
user    0m2.306s
sys 0m0.036s

$ time git rev-list -n1 --before="Jan 1 2005" HEAD

real    0m5.556s
user    0m5.435s
sys 0m0.105s

If I want to call rev-list in a loop over N decreasing dates, that loop runs N walks that take longer on every iteration. The docs talk about bit-maps and object traversal strategies to speed up the history, but I am having trouble understanding them. I tried git repack -ab followed by git rev-list --use-bitmap-index, but that didn't improve results.

My only requirement is that given any position for HEAD, I can accurately pinpoint the first revision that appears before the date given to --before, following paths to ancestors if needed.

What is the best way to make rev-list faster for this use case?

Body:
Repeatedly scanning a list to select successive elements is O(N^2).  Doesn't much matter how efficient the scan is, that N^2 is going to bite.

Generate one list with commit id and date, then strip what you don't want and generate your real log messages from the selected sha's. That's three passes total, not N.

git log --first-parent --pretty=%H\ %cd --date=short \
| awk '$2$3 != last { last=$2$3; print $1}' 'FS=[- ]' \
| git log --no-walk --stdin

That took fifteen seconds cold-cache on the linux repo, with a spinny-things hdd, listing 147 commits.  A rerun took less than a second.

edit: subbing in --date-order for --first-parent to consider all paths took 25.1 seconds cold-cache, 7.9 seconds hot, to list 782 commits.


问:
VS Code + CMake : cmake.build not found
I have CMake working perfectly fine with Visual Studio 2015. I wanted to try VS Code with C++ and CMake extensions, but when I try to call the build command (configured to F7 by default with the CMake extension for VSCode), I only get the message:

```<code>command 'cmake.build' not found
</code>```

Is it trying to tell me it can't find CMake ? Because Cmake is installed and working so... I also tried changing in the settings to the full path to cmake with no success. I installed both CMake and CMake Tools from Extensions. Also the toolbar for CMake doesn't appear on the blue VSCode toolbar as shown in CMake Tools extension doc.

答:
try this:

create a new copy of "mingw32-make.exe".

rename the copy to "make.exe".

restart your vscode.

Title: VS Code + CMake : cmake.build not found

Body:
I have CMake working perfectly fine with Visual Studio 2015. I wanted to try VS Code with C++ and CMake extensions, but when I try to call the build command (configured to F7 by default with the CMake extension for VSCode), I only get the message:

command 'cmake.build' not found

Is it trying to tell me it can't find CMake ? Because Cmake is installed and working so... I also tried changing in the settings to the full path to cmake with no success. I installed both CMake and CMake Tools from Extensions. Also the toolbar for CMake doesn't appear on the blue VSCode toolbar as shown in CMake Tools extension doc.


问:
Rails 3 Routing Resources with Variable Namespace
Is it possible to have a variable namespace? I have restful resources like the following:

```<code>resources :articles
resources :persons
</code>```

But I need to scope these inside a variable namespace, such that it responds to URLs of the form:

```<code>':edition/:controller/:action/:id'
</code>```

for example:

/foobar/article/edit/123 or /bazbam/person/edit/345

for each of the resources. Is this possible with the resources method, or must I hand-craft these? I will not know the possible values for :edition ahead of time; these get looked up in a before_filter in my ApplicationController.

Is this all I need to do?

```<code>scope ':edition' do
  resources :articles
  resources :matches
  resources :teams
end
</code>```

UPDATE: When using the scope directive above, I get routes like I want:

```<code>    articles GET    /:edition/articles(.:format)          {:action=>"index", :controller=>"articles"}
             POST   /:edition/articles(.:format)          {:action=>"create", :controller=>"articles"}
 new_article GET    /:edition/articles/new(.:format)      {:action=>"new", :controller=>"articles"}
edit_article GET    /:edition/articles/:id/edit(.:format) {:action=>"edit", :controller=>"articles"}
     article GET    /:edition/articles/:id(.:format)      {:action=>"show", :controller=>"articles"}
             PUT    /:edition/articles/:id(.:format)      {:action=>"update", :controller=>"articles"}
             DELETE /:edition/articles/:id(.:format)      {:action=>"destroy", :controller=>"articles"}
     matches GET    /:edition/matches(.:format)           {:action=>"index", :controller=>"matches"}
             POST   /:edition/matches(.:format)           {:action=>"create", :controller=>"matches"}
   new_match GET    /:edition/matches/new(.:format)       {:action=>"new", :controller=>"matches"}
  edit_match GET    /:edition/matches/:id/edit(.:format)  {:action=>"edit", :controller=>"matches"}
       match GET    /:edition/matches/:id(.:format)       {:action=>"show", :controller=>"matches"}
             PUT    /:edition/matches/:id(.:format)       {:action=>"update", :controller=>"matches"}
             DELETE /:edition/matches/:id(.:format)       {:action=>"destroy", :controller=>"matches"}
       teams GET    /:edition/teams(.:format)             {:action=>"index", :controller=>"teams"}
             POST   /:edition/teams(.:format)             {:action=>"create", :controller=>"teams"}
    new_team GET    /:edition/teams/new(.:format)         {:action=>"new", :controller=>"teams"}
   edit_team GET    /:edition/teams/:id/edit(.:format)    {:action=>"edit", :controller=>"teams"}
        team GET    /:edition/teams/:id(.:format)         {:action=>"show", :controller=>"teams"}
             PUT    /:edition/teams/:id(.:format)         {:action=>"update", :controller=>"teams"}
             DELETE /:edition/teams/:id(.:format)         {:action=>"destroy", :controller=>"teams"}
</code>```

I'm now able to reference :edition in my ApplicationController:

```<code>class ApplicationController < ActionController::Base
  protect_from_forgery

  before_filter :authenticate_user!
  before_filter :get_edition

  def get_edition
    @edition = Edition.first(:conditions => { :FriendlyName => params[:edition] } )
  end

end
</code>```

Now I just want to make sure this is the best way to accomplish this.

答:
Actually, you can just do the following :

```<code>my_var = "persons"
resources my_var.to_sym
</code>```

The to_sym method on a string changes it to a symbol

Body:
Is it possible to have a variable namespace? I have restful resources like the following:

resources :articles
resources :persons

But I need to scope these inside a variable namespace, such that it responds to URLs of the form:

':edition/:controller/:action/:id'

for example:

/foobar/article/edit/123 or /bazbam/person/edit/345

for each of the resources. Is this possible with the resources method, or must I hand-craft these? I will not know the possible values for :edition ahead of time; these get looked up in a before_filter in my ApplicationController.

Is this all I need to do?

scope ':edition' do
  resources :articles
  resources :matches
  resources :teams
end

UPDATE: When using the scope directive above, I get routes like I want:

    articles GET    /:edition/articles(.:format)          {:action=>"index", :controller=>"articles"}
             POST   /:edition/articles(.:format)          {:action=>"create", :controller=>"articles"}
 new_article GET    /:edition/articles/new(.:format)      {:action=>"new", :controller=>"articles"}
edit_article GET    /:edition/articles/:id/edit(.:format) {:action=>"edit", :controller=>"articles"}
     article GET    /:edition/articles/:id(.:format)      {:action=>"show", :controller=>"articles"}
             PUT    /:edition/articles/:id(.:format)      {:action=>"update", :controller=>"articles"}
             DELETE /:edition/articles/:id(.:format)      {:action=>"destroy", :controller=>"articles"}
     matches GET    /:edition/matches(.:format)           {:action=>"index", :controller=>"matches"}
             POST   /:edition/matches(.:format)           {:action=>"create", :controller=>"matches"}
   new_match GET    /:edition/matches/new(.:format)       {:action=>"new", :controller=>"matches"}
  edit_match GET    /:edition/matches/:id/edit(.:format)  {:action=>"edit", :controller=>"matches"}
       match GET    /:edition/matches/:id(.:format)       {:action=>"show", :controller=>"matches"}
             PUT    /:edition/matches/:id(.:format)       {:action=>"update", :controller=>"matches"}
             DELETE /:edition/matches/:id(.:format)       {:action=>"destroy", :controller=>"matches"}
       teams GET    /:edition/teams(.:format)             {:action=>"index", :controller=>"teams"}
             POST   /:edition/teams(.:format)             {:action=>"create", :controller=>"teams"}
    new_team GET    /:edition/teams/new(.:format)         {:action=>"new", :controller=>"teams"}
   edit_team GET    /:edition/teams/:id/edit(.:format)    {:action=>"edit", :controller=>"teams"}
        team GET    /:edition/teams/:id(.:format)         {:action=>"show", :controller=>"teams"}
             PUT    /:edition/teams/:id(.:format)         {:action=>"update", :controller=>"teams"}
             DELETE /:edition/teams/:id(.:format)         {:action=>"destroy", :controller=>"teams"}

I'm now able to reference :edition in my ApplicationController:

class ApplicationController < ActionController::Base
  protect_from_forgery

  before_filter :authenticate_user!
  before_filter :get_edition

  def get_edition
    @edition = Edition.first(:conditions => { :FriendlyName => params[:edition] } )
  end

end

Now I just want to make sure this is the best way to accomplish this.

Body:
Actually, you can just do the following :

my_var = "persons"
resources my_var.to_sym

The to_sym method on a string changes it to a symbol


问:
cakephp 3 using for login another model than users auth
I'm trying to make a login from another model and I have an error.

This is my code for Student Model

```<code> var $name= 'Student';

public $components = array(
    'Session',
    'Auth' => array(
        'loginAction' => array(
            'controller' => 'students',
            'action' => 'login',
            'plugin' => 'students'
        ),
        'authError' => 'Did you really think you are allowed to see that?',
        'authenticate' => array(
            'Form' => array(
                'fields' => array(
                    'username' => 'username', //Default is 'username' in the userModel
                    'password' => 'password'  //Default is 'password' in the userModel
                )
            )
        )
    )
);
</code>```

StudentsController looks like

```<code>public function beforeFilter(Event $event) {
    parent::beforeFilter($event);
    $this->Auth->allow('login');
}

public function login() {

    if($this->Session->check('Auth.Student')){
        $this->redirect(array('action' => 'login'));
    }

    if ($this->request->is('post')) {
        if ($this->Auth->login()) {
            $this->Session->setFlash(__('Welcome, '. $this->Auth->student('username')));
            $this->redirect($this->Auth->redirectUrl());
        } else {
            $this->Session->setFlash(__('Invalid username or password'));
        }
    }
}
</code>```

And the AppController is

```<code> public function initialize()
{
    parent::initialize();

    $this->loadComponent('RequestHandler');
    $this->loadComponent('Flash');
}

  public $components = array(
    'Session',
    'Auth' => array(
        'loginRedirect' => array('controller' => 'students', 'action' => 'login'),
        'loginAction' => array('controller' => 'students', 'action' => 'login'),

    ));

 public function beforeFilter(Event $event) {

    $this->Auth->authenticate=array (
        'loginAction' => [
            'controller' => 'Students',
            'action' => 'login',
            'plugin' => false,
        ],
        'Basic' => ['userModel' => 'Students'],
        'Form' => ['userModel' => 'Students']
    );

}
</code>```

And I have the following error

Component class SessionComponent could not be found.

How can I fix it?

答:
Session was deprecated in cakePHP 3, How you are doing is for cake2. In cake 3 you can use RequestHandeler like,

```<code>    $this->loadComponent('RequestHandler');
</code>```

OR

```<code>   public $components = array(
       'RequestHandler'
   );
then use,
$this->request->Session()->read/write/delete/destroy();
</code>```

Hope this will work for you :).

Body:
I'm trying to make a login from another model and I have an error.

This is my code for Student Model

 var $name= 'Student';

public $components = array(
    'Session',
    'Auth' => array(
        'loginAction' => array(
            'controller' => 'students',
            'action' => 'login',
            'plugin' => 'students'
        ),
        'authError' => 'Did you really think you are allowed to see that?',
        'authenticate' => array(
            'Form' => array(
                'fields' => array(
                    'username' => 'username', //Default is 'username' in the userModel
                    'password' => 'password'  //Default is 'password' in the userModel
                )
            )
        )
    )
);

StudentsController looks like

public function beforeFilter(Event $event) {
    parent::beforeFilter($event);
    $this->Auth->allow('login');
}

public function login() {

    if($this->Session->check('Auth.Student')){
        $this->redirect(array('action' => 'login'));
    }

    if ($this->request->is('post')) {
        if ($this->Auth->login()) {
            $this->Session->setFlash(__('Welcome, '. $this->Auth->student('username')));
            $this->redirect($this->Auth->redirectUrl());
        } else {
            $this->Session->setFlash(__('Invalid username or password'));
        }
    }
}

And the AppController is

 public function initialize()
{
    parent::initialize();

    $this->loadComponent('RequestHandler');
    $this->loadComponent('Flash');
}

  public $components = array(
    'Session',
    'Auth' => array(
        'loginRedirect' => array('controller' => 'students', 'action' => 'login'),
        'loginAction' => array('controller' => 'students', 'action' => 'login'),

    ));

 public function beforeFilter(Event $event) {

    $this->Auth->authenticate=array (
        'loginAction' => [
            'controller' => 'Students',
            'action' => 'login',
            'plugin' => false,
        ],
        'Basic' => ['userModel' => 'Students'],
        'Form' => ['userModel' => 'Students']
    );

}

And I have the following error

Component class SessionComponent could not be found.

How can I fix it?

Body:
Session was deprecated in cakePHP 3, How you are doing is for cake2. In cake 3 you can use RequestHandeler like,

    $this->loadComponent('RequestHandler');

OR

   public $components = array(
       'RequestHandler'
   );
then use,
$this->request->Session()->read/write/delete/destroy();

Hope this will work for you :).


问:
ASP.NET Authentication "Remember Me" CheckBox not staying checked
I am having problems with my login page. It pulls through the Username correctly from the cookie, however the CheckBox for Remember Me does not become checked when I view the page, even though the code for setting it on the Page_Load is being executed.

LoggedIn event for setting the cookies

```<code>    protected void lLogin_LoggedIn(object sender, EventArgs e)
    {
        // If Remember me then set an appropriate cookie
        if (lLogin.RememberMeSet)
        {
            HttpCookie loginCookie = new HttpCookie("loginCookie");
            Response.Cookies.Remove("loginCookie");
            Response.Cookies.Add(loginCookie);
            loginCookie.Values.Add("username", lLogin.UserName.ToString());
            DateTime dtExpiry = DateTime.Now.AddDays(15);
            Response.Cookies["loginCookie"].Expires = dtExpiry;
        }

        // Set a cookie to expire after 1 second
        else
        {
            HttpCookie loginCookie = new HttpCookie("loginCookie");
            Response.Cookies.Remove("loginCookie");
            Response.Cookies.Add(loginCookie);
            loginCookie.Values.Add("username", lLogin.UserName.ToString());
            DateTime dtExpiry = DateTime.Now.AddSeconds(1); //you can add years and months too here
            Response.Cookies["loginCookie"].Expires = dtExpiry;
        }
    }
</code>```

Page_Load event for Login page

```<code>    protected void Page_Load(object sender, EventArgs e)
    {
        // Get username field to set focus
        TextBox txtUserName = (TextBox)lLogin.FindControl("UserName");

        if (!IsPostBack)
        {
            // For resetting the login url so that it doesn't have a return value in the URL
            if (Request.QueryString["ReturnURL"] != null)
            {
                Response.Redirect("~/Login.aspx", true);
            }

            if (Request.IsAuthenticated)
            {
                Response.Redirect("~/Main/Home.aspx", true);
            }

            // If login cookie exists pull username
            if (Request.Cookies["loginCookie"] != null)
            {
                HttpCookie loginCookie = Request.Cookies["loginCookie"];
                lLogin.UserName = loginCookie.Values["username"].ToString();
                CheckBox cb = (CheckBox)lLogin.FindControl("RememberMe");
                // This is being Executed which is why I am puzzled
                cb.Checked = true;
            }
        }

        this.SetFocus(txtUserName);
    }
</code>```

My Web.Config  contains the following information as well as a MachineKey, Is this correct?

```<code>    <authentication mode="Forms">
  <forms loginUrl="Login.aspx" protection="All" timeout="60000" name="HRKCO" slidingExpiration="true" />
</authentication>
    <sessionState mode="InProc"  cookieless="UseCookies" timeout="30"/>
</code>```

EDIT

I solved this problem by using:

```<code>lLogin.RememberMeSet = true;
</code>```

I assumed this would be the same as finding the RememberMe CheckBox and setting the checked state but obviously it was not. Just thought I would share this if anyone else was having similar problems.

答:
The Solution to my problem was the way in which I was setting the checkbox in the Page_Load Event.

Solution

```<code>// If login cookie exists pull username
    if (Request.Cookies["loginCookie"] != null)
    {
        HttpCookie loginCookie = Request.Cookies["loginCookie"];
        lLogin.UserName = loginCookie.Values["username"].ToString();
        lLogin.RememberMeSet = true;
    }
</code>```

Body:
I am having problems with my login page. It pulls through the Username correctly from the cookie, however the CheckBox for Remember Me does not become checked when I view the page, even though the code for setting it on the Page_Load is being executed.

LoggedIn event for setting the cookies

    protected void lLogin_LoggedIn(object sender, EventArgs e)
    {
        // If Remember me then set an appropriate cookie
        if (lLogin.RememberMeSet)
        {
            HttpCookie loginCookie = new HttpCookie("loginCookie");
            Response.Cookies.Remove("loginCookie");
            Response.Cookies.Add(loginCookie);
            loginCookie.Values.Add("username", lLogin.UserName.ToString());
            DateTime dtExpiry = DateTime.Now.AddDays(15);
            Response.Cookies["loginCookie"].Expires = dtExpiry;
        }

        // Set a cookie to expire after 1 second
        else
        {
            HttpCookie loginCookie = new HttpCookie("loginCookie");
            Response.Cookies.Remove("loginCookie");
            Response.Cookies.Add(loginCookie);
            loginCookie.Values.Add("username", lLogin.UserName.ToString());
            DateTime dtExpiry = DateTime.Now.AddSeconds(1); //you can add years and months too here
            Response.Cookies["loginCookie"].Expires = dtExpiry;
        }
    }

Page_Load event for Login page

    protected void Page_Load(object sender, EventArgs e)
    {
        // Get username field to set focus
        TextBox txtUserName = (TextBox)lLogin.FindControl("UserName");

        if (!IsPostBack)
        {
            // For resetting the login url so that it doesn't have a return value in the URL
            if (Request.QueryString["ReturnURL"] != null)
            {
                Response.Redirect("~/Login.aspx", true);
            }

            if (Request.IsAuthenticated)
            {
                Response.Redirect("~/Main/Home.aspx", true);
            }

            // If login cookie exists pull username
            if (Request.Cookies["loginCookie"] != null)
            {
                HttpCookie loginCookie = Request.Cookies["loginCookie"];
                lLogin.UserName = loginCookie.Values["username"].ToString();
                CheckBox cb = (CheckBox)lLogin.FindControl("RememberMe");
                // This is being Executed which is why I am puzzled
                cb.Checked = true;
            }
        }

        this.SetFocus(txtUserName);
    }

My Web.Config  contains the following information as well as a MachineKey, Is this correct?

    <authentication mode="Forms">
  <forms loginUrl="Login.aspx" protection="All" timeout="60000" name="HRKCO" slidingExpiration="true" />
</authentication>
    <sessionState mode="InProc"  cookieless="UseCookies" timeout="30"/>

EDIT

I solved this problem by using:

lLogin.RememberMeSet = true;

I assumed this would be the same as finding the RememberMe CheckBox and setting the checked state but obviously it was not. Just thought I would share this if anyone else was having similar problems.

Body:
The Solution to my problem was the way in which I was setting the checkbox in the Page_Load Event.

Solution

// If login cookie exists pull username
    if (Request.Cookies["loginCookie"] != null)
    {
        HttpCookie loginCookie = Request.Cookies["loginCookie"];
        lLogin.UserName = loginCookie.Values["username"].ToString();
        lLogin.RememberMeSet = true;
    }


问:
ios - How to hidden YTPlayerView Youtube logo
One day, the YouTube logo appears like a picture.
Vanish together when disappears.
Touch the image to reappear.
If you touch the logo, there is a problem with YouTube.
I want to hide the logo.
We looked at the parameter at the youtube developer site.
It is useless to apply a variable called modestbranding.
I want to hide the logo.

It's my code

```<code>NSDictionary *dicPlayerVars = @{@"autohide":@1,
                                @"playsinline":@1,
                                @"showinfo":@0,
                                @"rel":@0,
                                @"color":@"white",
                                @"modestbranding":@1,};

[self.viewVideo loadWithVideoId:strVideoId playerVars:dicPlayerVars];
</code>```

答:
modestbranding

This parameter lets you use a YouTube player that does not show a YouTube logo. Set the parameter value to 1 to prevent the YouTube logo from displaying in the control bar.

You can add ?modestbranding=1 to your url. That will remove the logo.

You can find other options on the Google Developers website.

Body:
One day, the YouTube logo appears like a picture.
Vanish together when disappears.
Touch the image to reappear.
If you touch the logo, there is a problem with YouTube.
I want to hide the logo.
We looked at the parameter at the youtube developer site.
It is useless to apply a variable called modestbranding.
I want to hide the logo.

It's my code

NSDictionary *dicPlayerVars = @{@"autohide":@1,
                                @"playsinline":@1,
                                @"showinfo":@0,
                                @"rel":@0,
                                @"color":@"white",
                                @"modestbranding":@1,};

[self.viewVideo loadWithVideoId:strVideoId playerVars:dicPlayerVars];


答:
You can use display:inline-block to get it.

```<code>.nav img {
  display: inline-block; /*Add this*/
  vertical-align: middle; /*Add this*/
  height: 21px;
  width: 24px;
}

.nav li {
  display:inline-block; /*Add this*/
  vertical-align: middle; /*Add this*/
  margin: 5px 10px;
}

.nav {
  text-align:center; /*Add this*/
}
</code>```

.nav {
  width: 1280px;
  margin: 0 auto;
  font-size: 16px;
  font-weight: 500;
  border: 1px solid black;
  text-align:center;
}

.nav li {
  display:inline-block;
  vertical-align: middle;
  margin: 5px 10px;
}

nav li:first-child {
  margin-left: 75px;
}

.nav img {
  display: inline-block;
  vertical-align: middle;
  height: 21px;
  width: 24px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="nav">
  <ul class="clearfix">
    <li>Home</li>
    <li>Moments</li>
    <li>Notifications</li>
    <li>Messages</li>
    <img src="http://lorempixel.com/200/200/" alt="Twitter Icon">
  </ul>
</nav></code>```

Title: How to center an image inside a list with other elements

Body:
You can use display:inline-block to get it.

.nav img {
  display: inline-block; /*Add this*/
  vertical-align: middle; /*Add this*/
  height: 21px;
  width: 24px;
}

.nav li {
  display:inline-block; /*Add this*/
  vertical-align: middle; /*Add this*/
  margin: 5px 10px;
}

.nav {
  text-align:center; /*Add this*/
}

.nav {
  width: 1280px;
  margin: 0 auto;
  font-size: 16px;
  font-weight: 500;
  border: 1px solid black;
  text-align:center;
}

.nav li {
  display:inline-block;
  vertical-align: middle;
  margin: 5px 10px;
}

nav li:first-child {
  margin-left: 75px;
}

.nav img {
  display: inline-block;
  vertical-align: middle;
  height: 21px;
  width: 24px;
}

<nav class="nav">
  <ul class="clearfix">
    <li>Home</li>
    <li>Moments</li>
    <li>Notifications</li>
    <li>Messages</li>
    <img src="http://lorempixel.com/200/200/" alt="Twitter Icon">
  </ul>
</nav>


问:
Java Swing drawing PlayButton for a basic music player
Maybe my case it's a simple confusion of ideas. How do draw a button like this using Shape?

I don't mind the rounded corners, heres my aproach for a round corner button.

```<code>import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;

import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.JComponent;
import javax.swing.plaf.basic.BasicButtonUI;

public class PlayButtonUI extends BasicButtonUI{

    protected Shape shape;

    @Override
    protected void installDefaults(AbstractButton b) {
        super.installDefaults(b);
        b.setOpaque(false);//removes that annoying default background
    }

    @Override public void paint(Graphics g, JComponent c) {
        Graphics2D g2 = (Graphics2D)g;
        AbstractButton b = (AbstractButton) c;
        ButtonModel model = b.getModel();
        drawButtonShape(b);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);//smoth borders
        if(model.isArmed()) {
            g2.setColor(Color.RED);//color when button is pressed
        }else{
            g2.setColor(Color.GREEN);//default button color
        }
        g2.fill(shape);//aplying color
        super.paint(g2, c);
    }

    private void drawButtonShape(JComponent c) {
        //button shape is drawn here, 16 are the border radius
        shape = new RoundRectangle2D.Float(0, 0, c.getWidth()-1, c.getHeight()-1,16, 16);
    }

}
</code>```

I don't really know how to draw anything at all, this class was a result from a chaotic example that i found somewhere, and then simplified by myself until it just worked, i left some comments for the important lines.

I've been looking for a while, and found this example in oracle docs.
https://docs.oracle.com/javase/tutorial/2d/geometry/arbitrary.html

I don't really know how to convert Graphics2D to Shape, please tell me if i'm taking the wrong way.

答:
So, I've spent the better of the day banging my head against this problem, trying to do a whole bunch of trig magic ... I can't even do simple card tricks :P

Then I realised, there are other tricks I could do...

```<code>import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.GeneralPath;
import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.plaf.basic.BasicButtonUI;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                JButton btn = new JButton();
                btn.setUI(new PlayButtonUI());
                frame.add(btn);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class PlayButtonUI extends BasicButtonUI {

        @Override
        public Dimension getPreferredSize(JComponent c) {
            return new Dimension(200, 200);
        }

        @Override
        public void paint(Graphics g, JComponent c) {
            Graphics2D g2 = (Graphics2D) g;
            AbstractButton b = (AbstractButton) c;
            ButtonModel model = b.getModel();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);//smoth borders
            if (model.isArmed()) {
                g2.setColor(Color.BLACK);//color when button is pressed
            } else {
                g2.setColor(Color.GRAY);//default button color
            }

            float thinkness = Math.min(c.getWidth(), c.getHeight()) * 0.1f;

            Shape shape = shapeFor(c, thinkness);
            g2.setStroke(new BasicStroke(thinkness, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
            g2.fill(shape);//aplying color
            g2.draw(shape);

            super.paint(g2, c);
        }

        private Shape shapeFor(JComponent c, float thickness) {
            GeneralPath gp = new GeneralPath();

            double width = c.getWidth();
            double height = c.getHeight();
            double vPos = height / 2.0;
            double hPos = width - thickness;

            gp.moveTo(0.0 + thickness, 0.0 + thickness);
            gp.lineTo(hPos, vPos);
            gp.lineTo(0.0 + thickness, height - thickness);
            gp.closePath();

            return gp;
        }

    }
}
</code>```

So, this is a slight "cheat".  What this actually does is uses the properties of the Stroke to generate rounded edges, rather than trying to use curveTo or compound shapes

Have a look at Stroking and Filling Graphics Primitives for more details

ContentLicense: CC BY-SA 4.0

Body:
Maybe my case it's a simple confusion of ideas. How do draw a button like this using Shape?

I don't mind the rounded corners, heres my aproach for a round corner button.

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;

import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.JComponent;
import javax.swing.plaf.basic.BasicButtonUI;

public class PlayButtonUI extends BasicButtonUI{

    protected Shape shape;

    @Override
    protected void installDefaults(AbstractButton b) {
        super.installDefaults(b);
        b.setOpaque(false);//removes that annoying default background
    }

    @Override public void paint(Graphics g, JComponent c) {
        Graphics2D g2 = (Graphics2D)g;
        AbstractButton b = (AbstractButton) c;
        ButtonModel model = b.getModel();
        drawButtonShape(b);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);//smoth borders
        if(model.isArmed()) {
            g2.setColor(Color.RED);//color when button is pressed
        }else{
            g2.setColor(Color.GREEN);//default button color
        }
        g2.fill(shape);//aplying color
        super.paint(g2, c);
    }

    private void drawButtonShape(JComponent c) {
        //button shape is drawn here, 16 are the border radius
        shape = new RoundRectangle2D.Float(0, 0, c.getWidth()-1, c.getHeight()-1,16, 16);
    }

}

I don't really know how to draw anything at all, this class was a result from a chaotic example that i found somewhere, and then simplified by myself until it just worked, i left some comments for the important lines.

I've been looking for a while, and found this example in oracle docs.
https://docs.oracle.com/javase/tutorial/2d/geometry/arbitrary.html

I don't really know how to convert Graphics2D to Shape, please tell me if i'm taking the wrong way.

Body:
So, I've spent the better of the day banging my head against this problem, trying to do a whole bunch of trig magic ... I can't even do simple card tricks :P

Then I realised, there are other tricks I could do...

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.GeneralPath;
import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.plaf.basic.BasicButtonUI;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                JButton btn = new JButton();
                btn.setUI(new PlayButtonUI());
                frame.add(btn);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class PlayButtonUI extends BasicButtonUI {

        @Override
        public Dimension getPreferredSize(JComponent c) {
            return new Dimension(200, 200);
        }

        @Override
        public void paint(Graphics g, JComponent c) {
            Graphics2D g2 = (Graphics2D) g;
            AbstractButton b = (AbstractButton) c;
            ButtonModel model = b.getModel();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);//smoth borders
            if (model.isArmed()) {
                g2.setColor(Color.BLACK);//color when button is pressed
            } else {
                g2.setColor(Color.GRAY);//default button color
            }

            float thinkness = Math.min(c.getWidth(), c.getHeight()) * 0.1f;

            Shape shape = shapeFor(c, thinkness);
            g2.setStroke(new BasicStroke(thinkness, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
            g2.fill(shape);//aplying color
            g2.draw(shape);

            super.paint(g2, c);
        }

        private Shape shapeFor(JComponent c, float thickness) {
            GeneralPath gp = new GeneralPath();

            double width = c.getWidth();
            double height = c.getHeight();
            double vPos = height / 2.0;
            double hPos = width - thickness;

            gp.moveTo(0.0 + thickness, 0.0 + thickness);
            gp.lineTo(hPos, vPos);
            gp.lineTo(0.0 + thickness, height - thickness);
            gp.closePath();

            return gp;
        }

    }
}

So, this is a slight "cheat".  What this actually does is uses the properties of the Stroke to generate rounded edges, rather than trying to use curveTo or compound shapes

Have a look at Stroking and Filling Graphics Primitives for more details


答:
It can also be done with substr() which extract the string from a string and strrpos() which return last occurrence of a character, try like below:

```<code><?php
$variable = "8233 Station #2211 #2212";
echo substr($variable, 0, strrpos($variable, "#"));
</code>```

check the output here: https://eval.in/813032

Title: Remove portion of a string after a particular character from the end of the string

Body:
I need to remove all characters from a string after a particular character from the end. The below code works when it contains only one #
eg:

$variable = "8233 Station #2212";
echo trim(substr($variable, 0, strpos($variable, "#")));

result: "8233 Station";
But if the string contains more than one # I need to avoid the strings after the last #

 $variable = "8233 Station #2211 #2212";

The result i need in the above situation is "8233 Station #2211"

Body:
It can also be done with substr() which extract the string from a string and strrpos() which return last occurrence of a character, try like below:

<?php
$variable = "8233 Station #2211 #2212";
echo substr($variable, 0, strrpos($variable, "#"));

check the output here: https://eval.in/813032


问:
How to copy all rows from one SQL Server table to a table on a different SQL Server
I have a database in SQL Server 2008 and the same database (backup) in SQL Server 2016. All the schema and tables are exactly the same.

I need to copy all rows from a table in SQL Server 2008 to the same table in SQL Server 2016. How to achieve this?

答:
If it's a 1-time extract only, I'd not bother setting up a linked server, but instead I would use the Export Data functionality in SQL Server Management Studio.

To do this, right-click the Source Database in SSMS, then select "Tasks" -> "Export Data". You can use the wizard to specify exactly what you want to export (I.e. one or more tables, or even data using a query), specify the target, and select whether you want to run the package or save it for later use.


问:
Issue in getting Current Location with GPS_PROVIDER and NETWORK_PROVIDER
I trying to get current location in my android application. But, every time I am getting my Location as null. I have done as below :

```<code>private void getLocation() {
    try {
        if (ActivityCompat.checkSelfPermission((Activity) mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission((Activity) mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Constant.displayLogE(">> PErmission >> ", ">> not granted");
            return;
        } else {
            mLocationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);
            // getting GPS status
            boolean isGPSEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            // getting network status
            boolean isNetworkEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                if (isNetworkEnabled) {
                    mLocationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            0,
                            0, this);
                    if (mLocationManager != null) {

                        mLocation = mLocationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (mLocation != null) {
                            mCurrentLatitude = mLocation.getLatitude();
                            mCurrentLongitude = mLocation.getLongitude();
                            loadFilterListData();
                        }
                    }
                } else if (isGPSEnabled) {
                    if (mLocation == null) {
                        mLocationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                0,
                                0, this);
                        if (mLocationManager != null) {
                            mLocation = mLocationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (mLocation != null) {
                                mCurrentLatitude = mLocation.getLatitude();
                                mCurrentLongitude = mLocation.getLongitude();
                                loadFilterListData();
                            }
                        }
                    }
                }
                if (mLocation == null) {
                    Constant.displayToast(mContext, "Location not fetched. Please, try again.");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}
</code>```

I don't know the solution for this as i am checking for both NETWORK_PROVIDER as well as GPS_PROVIDER. But, getting mLocation as null every time.

I have given necessary permissions in my Manifest file also.

What might be the issue ?

Thanks.

答:
as JayDeep Patel referenced me for the Answer,

I have used fused google api , to get the accurate location inside my onConnected() method as below : (got success :))

pls. check it out : its really works :

```<code>private void getLocation() {
    try {
        if (ActivityCompat.checkSelfPermission((Activity) mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission((Activity) mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Constant.displayLogE(">> PErmission >> ", ">> not granted");
            return;
        } else {
            mLocationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);
            // getting GPS status
            boolean isGPSEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            // getting network status
            boolean isNetworkEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                if (isNetworkEnabled) {
                    mLocationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            0,
                            0, this);
                    if (mLocationManager != null) {

                        mLocation = mLocationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (mLocation != null) {
                            mCurrentLatitude = mLocation.getLatitude();
                            mCurrentLongitude = mLocation.getLongitude();
                            loadFilterListData();
                        } else {
                            mCurrentLatitude = mLastLocation.getLatitude();
                            mCurrentLongitude = mLastLocation.getLongitude();
                            loadFilterListData();
                        }
                    }
                } else if (isGPSEnabled) {
                    if (mLocation == null) {
                        mLocationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                0,
                                0, this);
                        if (mLocationManager != null) {
                            mLocation = mLocationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (mLocation != null) {
                                mCurrentLatitude = mLocation.getLatitude();
                                mCurrentLongitude = mLocation.getLongitude();
                                loadFilterListData();
                            } else {
                                mCurrentLatitude = mLastLocation.getLatitude();
                                mCurrentLongitude = mLastLocation.getLongitude();
                                loadFilterListData();
                            }
                        }
                    }
                }
                if (mLastLocation == null) {
                    Constant.displayToast(mContext, "Location not fetched. Please, try again.");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}
</code>```

and below is my onConnected() method :

```<code>@Override
public void onConnected(@Nullable Bundle bundle) {
    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (mLastLocation != null) {
        // here we go you can see current lat long.
        Log.e(TAG, "onConnected: " + String.valueOf(mLastLocation.getLatitude()) + ":" + String.valueOf(mLastLocation.getLongitude()));
    }
}
</code>```

Body:
I trying to get current location in my android application. But, every time I am getting my Location as null. I have done as below :

private void getLocation() {
    try {
        if (ActivityCompat.checkSelfPermission((Activity) mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission((Activity) mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Constant.displayLogE(">> PErmission >> ", ">> not granted");
            return;
        } else {
            mLocationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);
            // getting GPS status
            boolean isGPSEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            // getting network status
            boolean isNetworkEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                if (isNetworkEnabled) {
                    mLocationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            0,
                            0, this);
                    if (mLocationManager != null) {

                        mLocation = mLocationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (mLocation != null) {
                            mCurrentLatitude = mLocation.getLatitude();
                            mCurrentLongitude = mLocation.getLongitude();
                            loadFilterListData();
                        }
                    }
                } else if (isGPSEnabled) {
                    if (mLocation == null) {
                        mLocationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                0,
                                0, this);
                        if (mLocationManager != null) {
                            mLocation = mLocationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (mLocation != null) {
                                mCurrentLatitude = mLocation.getLatitude();
                                mCurrentLongitude = mLocation.getLongitude();
                                loadFilterListData();
                            }
                        }
                    }
                }
                if (mLocation == null) {
                    Constant.displayToast(mContext, "Location not fetched. Please, try again.");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

I don't know the solution for this as i am checking for both NETWORK_PROVIDER as well as GPS_PROVIDER. But, getting mLocation as null every time.

I have given necessary permissions in my Manifest file also.

What might be the issue ?

Thanks.

Body:
as JayDeep Patel referenced me for the Answer,

I have used fused google api , to get the accurate location inside my onConnected() method as below : (got success :))

pls. check it out : its really works :

private void getLocation() {
    try {
        if (ActivityCompat.checkSelfPermission((Activity) mContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission((Activity) mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Constant.displayLogE(">> PErmission >> ", ">> not granted");
            return;
        } else {
            mLocationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);
            // getting GPS status
            boolean isGPSEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            // getting network status
            boolean isNetworkEnabled = mLocationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                if (isNetworkEnabled) {
                    mLocationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            0,
                            0, this);
                    if (mLocationManager != null) {

                        mLocation = mLocationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (mLocation != null) {
                            mCurrentLatitude = mLocation.getLatitude();
                            mCurrentLongitude = mLocation.getLongitude();
                            loadFilterListData();
                        } else {
                            mCurrentLatitude = mLastLocation.getLatitude();
                            mCurrentLongitude = mLastLocation.getLongitude();
                            loadFilterListData();
                        }
                    }
                } else if (isGPSEnabled) {
                    if (mLocation == null) {
                        mLocationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                0,
                                0, this);
                        if (mLocationManager != null) {
                            mLocation = mLocationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (mLocation != null) {
                                mCurrentLatitude = mLocation.getLatitude();
                                mCurrentLongitude = mLocation.getLongitude();
                                loadFilterListData();
                            } else {
                                mCurrentLatitude = mLastLocation.getLatitude();
                                mCurrentLongitude = mLastLocation.getLongitude();
                                loadFilterListData();
                            }
                        }
                    }
                }
                if (mLastLocation == null) {
                    Constant.displayToast(mContext, "Location not fetched. Please, try again.");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

and below is my onConnected() method :

@Override
public void onConnected(@Nullable Bundle bundle) {
    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (mLastLocation != null) {
        // here we go you can see current lat long.
        Log.e(TAG, "onConnected: " + String.valueOf(mLastLocation.getLatitude()) + ":" + String.valueOf(mLastLocation.getLongitude()));
    }
}


答:
Use strrpos instead of strpos

strpos — Find the position of the first occurrence of a substring in a string

strrpos — Find the position of the last occurrence of a substring in a string

```<code>$variable = "8233 Station #2212 #2212";
echo trim(substr($variable, 0, strrpos($variable, "#")));
</code>```

Body:
Use strrpos instead of strpos

strpos — Find the position of the first occurrence of a substring in a string

strrpos — Find the position of the last occurrence of a substring in a string

$variable = "8233 Station #2212 #2212";
echo trim(substr($variable, 0, strrpos($variable, "#")));


问:
Android Studio WebView Youtube Video BlackScreen
I want to play a video in the WebView but somehow I get an blackscreen on the video but I can hear the sound of it. Would be really glad if someone can help me</p>

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

WebView displayYoutubeVideo;
TextView button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String frameVideo = "<html><body>Video From YouTube<br><iframe
    width=\"560\" height=\"315\"
    src=\"https://www.youtube.com/embed/WtO3_tF8niU\" frameborder=\"0\"
    allowfullscreen></iframe></body></html>";

    WebView displayYoutubeVideo = (WebView) findViewById(R.id.youtube_view);

    displayYoutubeVideo.getSettings().setUserAgentString("Mozilla/5.0
           (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0");

    displayYoutubeVideo.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }
    });
    WebSettings webSettings = displayYoutubeVideo.getSettings();
    webSettings.setJavaScriptEnabled(true);
    displayYoutubeVideo.loadData(frameVideo, "text/html", "utf-8");
}
}
</code>```

答: I guess you might be missing android:hardwareAccelerated="true" in the permissions of your activity in the manifest file. Since you are playing a flash video this should work out to make the WebView flash enabled. This is something that I encountered and the resolution was to add this permission.

Body:
I want to play a video in the WebView but somehow I get an blackscreen on the video but I can hear the sound of it. Would be really glad if someone can help me

public class MainActivity extends AppCompatActivity {

WebView displayYoutubeVideo;
TextView button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String frameVideo = "Video From YouTube
";

    WebView displayYoutubeVideo = (WebView) findViewById(R.id.youtube_view);

    displayYoutubeVideo.getSettings().setUserAgentString("Mozilla/5.0
           (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0");

    displayYoutubeVideo.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }
    });
    WebSettings webSettings = displayYoutubeVideo.getSettings();
    webSettings.setJavaScriptEnabled(true);
    displayYoutubeVideo.loadData(frameVideo, "text/html", "utf-8");
}
}


问:
Object of class GuzzleHttp\Psr7\Request could not be converted to string
I've got an issue for laravel 5.4 when I trying to using guzzleHttp. here is my code.

```<code>use GuzzleHttp\Client;
$url = 'http://example.com';
$client = new Client();

$parameter = ['query' => ['name' => 'xxx', 'address' => 'yyy'], 'headers' => [ 'User-Agent' => 'xxxx', 'exceptions' => false, 'timeout' => 10 ]];
$res = $client->request('GET', $url, $parameter);

if ($res->getStatusCode() == 200)
{
 $json = (string)$res->getBody();
 return $json;
}
</code>```

and I've got this error on log:
Error Exception: Object of class GuzzleHttp\Psr7\Request could not be converted to string

what is wrong with my code? please kindly help me.
fyi, this error not always happen. sometimes it show this error, sometimes success.

thank you

答:
Try this.....    </p>

```<code>    try {
        $parameter = ['query' => ['name' => 'xxx', 'address' => 'yyy'], 'headers' => [ 'User-Agent' => 'xxxx', 'exceptions' => false, 'timeout' => 10 ]];
        $res = $client->request('GET', $url, $parameter);

        if ($res->getStatusCode() == 200)
          {
             return $res->getBody()->getContents();
          }
    }catch(Exception $e){
        echo 'Caught exception: ',  $e->getMessage();
    }
</code>```

Body:
I've got an issue for laravel 5.4 when I trying to using guzzleHttp. here is my code.

use GuzzleHttp\Client;
$url = 'http://example.com';
$client = new Client();

$parameter = ['query' => ['name' => 'xxx', 'address' => 'yyy'], 'headers' => [ 'User-Agent' => 'xxxx', 'exceptions' => false, 'timeout' => 10 ]];
$res = $client->request('GET', $url, $parameter);

if ($res->getStatusCode() == 200)
{
 $json = (string)$res->getBody();
 return $json;
}

and I've got this error on log:
Error Exception: Object of class GuzzleHttp\Psr7\Request could not be converted to string

what is wrong with my code? please kindly help me.
fyi, this error not always happen. sometimes it show this error, sometimes success.

thank you

Body:
Try this.....

    try {
        $parameter = ['query' => ['name' => 'xxx', 'address' => 'yyy'], 'headers' => [ 'User-Agent' => 'xxxx', 'exceptions' => false, 'timeout' => 10 ]];
        $res = $client->request('GET', $url, $parameter);

        if ($res->getStatusCode() == 200)
          {
             return $res->getBody()->getContents();
          }
    }catch(Exception $e){
        echo 'Caught exception: ',  $e->getMessage();
    }


问:
MS Access: How to disable Form autosave and create Save button
I understand that inputting data in a form in MS Access automatically updates the fields in the table. However, how do I disable this feature and instead allow a user to click a "Save" button at the end to update the records? Have been reading online that I need VBA etc. that I have no experience with.</p>

答:
This can only be done in code.

You need to set a module level boolean variable to control saving (auto vs manual) and set its value to True when the save button is clicked.

```<code>Private mIsUserUpdate As Boolean 'Flag

'Cancel Auto Save
Private Sub Form_BeforeUpdate(Cancel As Integer)
    If Not mIsUserUpdate Then Cancel = True
End Sub

'Manual Save
Private Sub YourButtonName_Click()

    '...
    'Do work
    '...

    mIsUserUpdate = True 'OK to save
    DoCmd.RunCommand acCmdSaveRecord
    mIsUserUpdate = False 'Revert
End Sub
</code>```

Body:
This can only be done in code.

You need to set a module level boolean variable to control saving (auto vs manual) and set its value to True when the save button is clicked.

Private mIsUserUpdate As Boolean 'Flag

'Cancel Auto Save
Private Sub Form_BeforeUpdate(Cancel As Integer)
    If Not mIsUserUpdate Then Cancel = True
End Sub

'Manual Save
Private Sub YourButtonName_Click()

    '...
    'Do work
    '...

    mIsUserUpdate = True 'OK to save
    DoCmd.RunCommand acCmdSaveRecord
    mIsUserUpdate = False 'Revert
End Sub