问:
How can I prevent a library from masking functions
A typical situation is the following:

```<code>library(dplyr)
library(xgboost)
</code>```

When I import the library xgboost, the function slice of dplyr is masked, and I have to write dplyr::slice even though I never use xgboost::slice explicitly.

The obvious solution to the problem is to import xgboost before dplyr. But it is crazy to import all libraries which can affect the functions of dplyr in advance. Moreover this problem often happens when I use caret library. Namely train function imports automatically required libraries and some functions are masked at the time.

It is possible to prevent some functions from being masked?

Is it possible to mask "the masking function" (e.g. xgboost::slice) with an early imported function (e.g. dplyr::slice)?

Notes

I am NOT asking how to disable warning message.

I am NOT asking how to use the masked functions.

答:
The solution is to manage your namespace like it is common to do in other languages. You can selectively import dplyr functions:

```<code>select <- dplyr::select
</code>```

For convenience you can also import the whole package and selectively reimport functions from previously attached packages:

```<code>library("dplyr")
filter <- stats::filter
</code>```

R has a great module system and attaching whole namespaces is especially handy for interactive use. It does requires a bit of manual adjusting if the preferences of the package authors do not match yours.

Note that in packages and long-term maintenance scripts you should privilege selective imports, in part because it is hard to predict new exported functions in future releases. Having several packages imported in bulk might give rise to unexpected masking over time.

More generally a good rule is to rely on a single attached package and selectively import the rest. To this end the tidyverse package might be handy if you're a heavy tidyverse user because it provides a single import point for several packages.

Finally it seems from your question that you think that the order of attached packages might have side effects inside other packages. This is nothing to worry about because all packages have their own contexts. The import scheme will only affect your script.

Body:
A typical situation is the following:

library(dplyr)
library(xgboost)

When I import the library xgboost, the function slice of dplyr is masked, and I have to write dplyr::slice even though I never use xgboost::slice explicitly.

The obvious solution to the problem is to import xgboost before dplyr. But it is crazy to import all libraries which can affect the functions of dplyr in advance. Moreover this problem often happens when I use caret library. Namely train function imports automatically required libraries and some functions are masked at the time.

It is possible to prevent some functions from being masked?

Is it possible to mask "the masking function" (e.g. xgboost::slice) with an early imported function (e.g. dplyr::slice)?

Notes

I am NOT asking how to disable warning message.

I am NOT asking how to use the masked functions.

Body:
The solution is to manage your namespace like it is common to do in other languages. You can selectively import dplyr functions:

select <- dplyr::select

For convenience you can also import the whole package and selectively reimport functions from previously attached packages:

library("dplyr")
filter <- stats::filter

R has a great module system and attaching whole namespaces is especially handy for interactive use. It does requires a bit of manual adjusting if the preferences of the package authors do not match yours.

Note that in packages and long-term maintenance scripts you should privilege selective imports, in part because it is hard to predict new exported functions in future releases. Having several packages imported in bulk might give rise to unexpected masking over time.

More generally a good rule is to rely on a single attached package and selectively import the rest. To this end the tidyverse package might be handy if you're a heavy tidyverse user because it provides a single import point for several packages.

Finally it seems from your question that you think that the order of attached packages might have side effects inside other packages. This is nothing to worry about because all packages have their own contexts. The import scheme will only affect your script.


来源: stackexchange

问:
What is wrong with the data that I am trying to send to matplotlib?
I have the following script:

```<code>import pandas
from collections import Counter
import matplotlib.pyplot as plt

while True:
    data = [int(x) for x in raw_input("Enter the list containing the data: ").split()]
    letter_counts = Counter(data)
    df = pandas.DataFrame.from_dict(letter_counts, orient="index")
    df.plot(kind="bar")
    plt.show()
</code>```

When I either type or copy and paste a series or numbers, for instance,

```<code> 1 4 5 6 3
</code>```

the script works perfectly and shows me the histogram. However, when I paste numbers from the output I get from a different terminal window, for instance:

```<code>  13 13 16 16 16 16 9 9 9 9 9 15 15 15 15 20 20 20 20 20 22 22 22 22 13
  13 13 13 12 12 12 12 12 16 16 16 16 15 15 15 15 15 15 15 15 15 15 15
  15 15 22 22 22 22 22 15 15 15 15 13 13 13 13 13 18 18 18 18 10 10 10
  10 12 12 12 12 12 10 10 10 10 20 20 20 20 20 15 15 15 15 15 15 15 15
  17 17 17 17 17 13
</code>```

The first time I enter the data, it works perfectly; however, when I enter it the second time, it doesn't do anything and then I have to hit enter again. It shows me the plot, but when I close it, it gives me the following error:

```<code>> Enter the list containing the data: Traceback (most recent call last):
> File "make_histo.py", line 9, in <module>
>     df.plot(kind="bar")   File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py",
> line 2627, in __call__
>     sort_columns=sort_columns, **kwds)   File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py",
> line 1869, in plot_frame
>     **kwds)   File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py",
> line 1694, in _plot
>     plot_obj.generate()   File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py",
> line 243, in generate
>     self._compute_plot_data()   File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py",
> line 352, in _compute_plot_data
>     'plot'.format(numeric_data.__class__.__name__))
TypeError: Empty 'DataFrame': no numeric data to plot
</code>```

What am I doing wrong?

答:
I don't quite get the behavior you described: when I copy-paste the block of numbers from your question I get embedded line breaks and this causes raw_input() to get called multiple times.

A possible workaround for that problem is to make the program treat an empty line as end-of-input: the following very simple code accepts a copy-paste of your block of numbers OK on my system (Windows, Python 2.7):

```<code>while True:
    print ("Enter the list containing the data: ")
    lines = []
    while True:
        line = raw_input()
        if (line):
            lines.append(line.lstrip().strip())
        else:
            break
    data = []
    for line in lines:
        for x in line.split():
            data.append(int(x))
    print data
</code>```

Hope this may be helpful.

ContentLicense: CC BY-SA 3.0

Body:
I have the following script:

import pandas
from collections import Counter
import matplotlib.pyplot as plt

while True:
    data = [int(x) for x in raw_input("Enter the list containing the data: ").split()]
    letter_counts = Counter(data)
    df = pandas.DataFrame.from_dict(letter_counts, orient="index")
    df.plot(kind="bar")
    plt.show()

When I either type or copy and paste a series or numbers, for instance,

 1 4 5 6 3

the script works perfectly and shows me the histogram. However, when I paste numbers from the output I get from a different terminal window, for instance:

  13 13 16 16 16 16 9 9 9 9 9 15 15 15 15 20 20 20 20 20 22 22 22 22 13
  13 13 13 12 12 12 12 12 16 16 16 16 15 15 15 15 15 15 15 15 15 15 15
  15 15 22 22 22 22 22 15 15 15 15 13 13 13 13 13 18 18 18 18 10 10 10
  10 12 12 12 12 12 10 10 10 10 20 20 20 20 20 15 15 15 15 15 15 15 15
  17 17 17 17 17 13

The first time I enter the data, it works perfectly; however, when I enter it the second time, it doesn't do anything and then I have to hit enter again. It shows me the plot, but when I close it, it gives me the following error:

> Enter the list containing the data: Traceback (most recent call last):
> File "make_histo.py", line 9, in <module>
>     df.plot(kind="bar")   File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py",
> line 2627, in __call__
>     sort_columns=sort_columns, **kwds)   File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py",
> line 1869, in plot_frame
>     **kwds)   File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py",
> line 1694, in _plot
>     plot_obj.generate()   File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py",
> line 243, in generate
>     self._compute_plot_data()   File "/usr/local/lib/python2.7/dist-packages/pandas/plotting/_core.py",
> line 352, in _compute_plot_data
>     'plot'.format(numeric_data.__class__.__name__))
TypeError: Empty 'DataFrame': no numeric data to plot

What am I doing wrong?

Body:
I don't quite get the behavior you described: when I copy-paste the block of numbers from your question I get embedded line breaks and this causes raw_input() to get called multiple times.

A possible workaround for that problem is to make the program treat an empty line as end-of-input: the following very simple code accepts a copy-paste of your block of numbers OK on my system (Windows, Python 2.7):

while True:
    print ("Enter the list containing the data: ")
    lines = []
    while True:
        line = raw_input()
        if (line):
            lines.append(line.lstrip().strip())
        else:
            break
    data = []
    for line in lines:
        for x in line.split():
            data.append(int(x))
    print data

Hope this may be helpful.


问:
Does await new Task(async () => Actually halt execution until finished?
I guess I'm not really understanding the await command in c#. I thought that using await would allow a method to continue processing and would would work in a separate thread and return a value once it completed however, I have the following code:

```<code>public async Task<DatabaseActionResult> BackupToAzureAsync(DatabaseSchedule schedule)
{
    try
    {
        foreach (var o in myObjects)
        {
                await new Task(async () =>
                {
                    try
                    {
                        //Do some stuff.
                    }
                    catch (Exception e)
                    {
                        throw; //Should this throw the exception to the functions Try/Catch block so it can log it to the event viewer?
                    }
                }
            }
        }
    catch (Exception e)
    {
        //Log exception to event viewer and return a DatabaseActionResult object
    }
}
</code>```

However, the foreach() executes, waits for the task to complete, and then only after completion, continues to the next. If I remove the await statement, then it runs the task for every loop iteration simultaneously but the Try/Catch block doesn't throw the exception up the stack. Instead it just stop the service entirely as if it were a service unhandled exception.

How can I either get the new task to run once for each for/each loop without waiting for the previous one to complete, or how can I get the try/catch block to throw the exception up the stack so it can get caught and processed in the method's try/catch block?

Thanks!

FOLLOW-UP:

Would this work and still maintain the Try/Catch stack?

```<code>foreach (var t in tables)
{
    try
    {
        var tableTasks = new List<Task>
        {
            new Task(async () =>
                {
                    try
                    {
                        //Do stuff
                    }
                    catch (DataError e)
                    {
                        throw e;
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
            )
        };
    }
    catch (Exception e)
    {
        return new DatabaseActionResult();
    }
}
</code>```

答:
I guess I'm not really understanding the await command in c#.

That's correct. Do some research before you ask a question. There are many StackOverflow questions, articles, videos, tutorial and books that explain how this works.

I thought that using await would allow a method to continue processing and would would work in a separate thread and return a value once it completed

That is 100% absolutely wrong, so stop thinking all of that right now.

However, the foreach() executes, waits for the task to complete,

An asynchronous wait -- await -- waits for a task to complete. That's why its called "await".

It is asynchronous because if the task is not complete then await returns to the caller and does other work on this thread until the task is complete, at which time the work that follows the await is scheduled to execute.

Make sure you understand that await is an operator on tasks. It is not a calling convention on calls.  Any expression of awaitable type can be awaited; don't fall into the trap of believing that await makes a call asynchronous.  The called method is already asynchronous; the task that is returned is the thing that is awaited.

How can I either get the new task to run once for each for/each loop without waiting for the previous one to complete

Don't await the task.  Await means "I cannot proceed until this task is complete."

If your desired workflow is "create one task per object and asynchronously wait for all of them to finish", that's await Task.WhenAll(tasks).  So create a sequence of tasks -- either using your loop to build up a list, or a Select to create a sequence -- and then await all of them at once.

Note that exception handling in a WhenAll situation is a little bit unusual.  Read the documentation carefully and understand it before you write the code.

Body:
I guess I'm not really understanding the await command in c#. I thought that using await would allow a method to continue processing and would would work in a separate thread and return a value once it completed however, I have the following code:

public async Task<DatabaseActionResult> BackupToAzureAsync(DatabaseSchedule schedule)
{
    try
    {
        foreach (var o in myObjects)
        {
                await new Task(async () =>
                {
                    try
                    {
                        //Do some stuff.
                    }
                    catch (Exception e)
                    {
                        throw; //Should this throw the exception to the functions Try/Catch block so it can log it to the event viewer?
                    }
                }
            }
        }
    catch (Exception e)
    {
        //Log exception to event viewer and return a DatabaseActionResult object
    }
}

However, the foreach() executes, waits for the task to complete, and then only after completion, continues to the next. If I remove the await statement, then it runs the task for every loop iteration simultaneously but the Try/Catch block doesn't throw the exception up the stack. Instead it just stop the service entirely as if it were a service unhandled exception.

How can I either get the new task to run once for each for/each loop without waiting for the previous one to complete, or how can I get the try/catch block to throw the exception up the stack so it can get caught and processed in the method's try/catch block?

Thanks!

FOLLOW-UP:

Would this work and still maintain the Try/Catch stack?

foreach (var t in tables)
{
    try
    {
        var tableTasks = new List<Task>
        {
            new Task(async () =>
                {
                    try
                    {
                        //Do stuff
                    }
                    catch (DataError e)
                    {
                        throw e;
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
            )
        };
    }
    catch (Exception e)
    {
        return new DatabaseActionResult();
    }
}


问:
DNS not working in PHP (but does in general)
The following script:

```<code><?php
 $dnsrecs = dns_get_record('google.com'); foreach($dnsrecs as $dnsrec){ foreach($dnsrec as $label=>$val){ echo $label.':'. $val . '<br>'; } }

  echo file_get_contents('https://google.com');

?>
</code>```

Gives back a list of DNS records, but ends up failing on the file_get_contents, although phpinfo() says:

```<code>allow_url_fopen On  On
allow_url_include   Off
</code>```

With the following error:

PHP message: PHP Warning:  file_get_contents(https://google.com): failed to open stream: php_network_getaddresses: getaddrinfo failed: No address associated with hostname in /var/www/a.php on line 5" while reading response header from upstream, client: 152.66.34.10, server: xxx, request: "GET /a.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php-fpm-www.sock:", host: "xxx"

DNS resolution on the server works, with the same user as nginx is running:

```<code># sudo -u www-data host google.com
google.com has address 216.58.212.142
google.com has IPv6 address 2a00:1450:400e:800::200e
google.com mail is handled by 50 alt4.aspmx.l.google.com.
google.com mail is handled by 10 aspmx.l.google.com.
google.com mail is handled by 30 alt2.aspmx.l.google.com.
google.com mail is handled by 40 alt3.aspmx.l.google.com.
google.com mail is handled by 20 alt1.aspmx.l.google.com.
</code>```

My PHP version is recent:

```<code># php --version
PHP 5.5.9-1ubuntu4.21 (cli) (built: Feb  9 2017 20:54:58)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
    with Zend OPcache v7.0.3, Copyright (c) 1999-2014, by Zend Technologies
</code>```

I am running it via php5-fpm, and it seems to be related to that, because sudo -u www-data php a.php works correctly.

My php.ini file is here: http://pastebin.com/qZePJdT5
And my phpinfo is here: http://pastebin.com/cAWuu8wr

Thanks.

答: Rebooting server (linux) and changing nothing else fixed this.</p>

Body:
The following script:

<?php
 $dnsrecs = dns_get_record('google.com'); foreach($dnsrecs as $dnsrec){ foreach($dnsrec as $label=>$val){ echo $label.':'. $val . '
'; } }

  echo file_get_contents('https://google.com');

?>

Gives back a list of DNS records, but ends up failing on the file_get_contents, although phpinfo() says:

allow_url_fopen On  On
allow_url_include   Off

With the following error:

PHP message: PHP Warning:  file_get_contents(https://google.com): failed to open stream: php_network_getaddresses: getaddrinfo failed: No address associated with hostname in /var/www/a.php on line 5" while reading response header from upstream, client: 152.66.34.10, server: xxx, request: "GET /a.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php-fpm-www.sock:", host: "xxx"

DNS resolution on the server works, with the same user as nginx is running:

# sudo -u www-data host google.com
google.com has address 216.58.212.142
google.com has IPv6 address 2a00:1450:400e:800::200e
google.com mail is handled by 50 alt4.aspmx.l.google.com.
google.com mail is handled by 10 aspmx.l.google.com.
google.com mail is handled by 30 alt2.aspmx.l.google.com.
google.com mail is handled by 40 alt3.aspmx.l.google.com.
google.com mail is handled by 20 alt1.aspmx.l.google.com.

My PHP version is recent:

# php --version
PHP 5.5.9-1ubuntu4.21 (cli) (built: Feb  9 2017 20:54:58)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
    with Zend OPcache v7.0.3, Copyright (c) 1999-2014, by Zend Technologies

I am running it via php5-fpm, and it seems to be related to that, because sudo -u www-data php a.php works correctly.

My php.ini file is here: http://pastebin.com/qZePJdT5
And my phpinfo is here: http://pastebin.com/cAWuu8wr

Thanks.


问:
Javascript file not including inside html page
I'm trying to use JQuery inside a ASP.NET MVC practice project but the site.js file not working or including inside html page. If I write JQuery code inside script tag in html then it's working fine, Even I have included some other files like Bootstrap and site.css that also working only problem with site.js file.

Site.js

```<code>$(document).ready(function () {
    alert("Hello 1");
});

$(window).load(function () {
    alert("Hello 2");
});
</code>```

_Layout.cshtml

Including snippet

```<code><script src="~/lib/jquery/dist/jquery.min.js" type="text/javascript"></script>
<script src="~/js/site.js" type="text/javascript"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js" type="text/javascript"></script>
</code>```

答:
Drag and drop the site.js file from the solution explorer into the view, it should add the correct path. If that doesn't work try to put this:

```<code>(function($) {
    $(document).ready(function () {
        alert("Hello 1");
    });

    $(window).load(function () {
        alert("Hello 2");
    });
})(jQuery);
</code>```

I'm not sure how does the (function($){//code})(jQuery); works, but in the past solved my problem.

Body:
I'm trying to use JQuery inside a ASP.NET MVC practice project but the site.js file not working or including inside html page. If I write JQuery code inside script tag in html then it's working fine, Even I have included some other files like Bootstrap and site.css that also working only problem with site.js file.

Site.js

$(document).ready(function () {
    alert("Hello 1");
});

$(window).load(function () {
    alert("Hello 2");
});

_Layout.cshtml

Including snippet

Body:
Drag and drop the site.js file from the solution explorer into the view, it should add the correct path. If that doesn't work try to put this:

(function($) {
    $(document).ready(function () {
        alert("Hello 1");
    });

    $(window).load(function () {
        alert("Hello 2");
    });
})(jQuery);

I'm not sure how does the (function($){//code})(jQuery); works, but in the past solved my problem.


问:
iOS - UISearchBar dynamic search results doesn't work when typed quickly (swift)
What I want is a searchbar that updates the tableview with usernames as every character is entered into the searchbar by the user. When the user deletes (backspaces) all the characters in the searchbar, ie the searchbar is empty, I want the tableview to be display no usernames and be empty.

I have a semi functioning UISearchbar that searches for usernames (Parse backend). It works fine when I type character by character in the searchbar slowly.

However, when I type quickly, the search results are a bit off - it shows me usernames from characters that were previously entered. For eg: if I enter 'nik' quickly it still shows me usernames with 'ni' in them. Also, when I backspace quickly until there are no characters in the searchbar, it still shows me certain usernames.

Again, it works fine when I enter characters in slowly, but I feel like it isn't very efficient. I have tried all sorts of things but nothing has worked well so far. I have added the relevant code below, let me know if you need more information.

```<code>    // called when keyboard search button pressed
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

    let searchString = searchBar.text;

    if (searchString != "") {
        //do load users
        loadUsers(searchText: searchString!);
        print("called from searchBarSearchButtonClicked");
    }

}

// called when cancel button pressed
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {

    searchBar.text = "";

    //hide tableview maybe?!
    //searchTableView.isHidden = true;

}

func updateSearchResults(for searchController: UISearchController) {
    let searchString: String = (searchController.searchBar.text)!;

    /*if (searchString == "" && !searchActive) {
        searchResults.removeAll(keepingCapacity: false);
        searchTableView.reloadData();
        print("test");
    }*/

    if (searchString != "" && !self.searchActive) {
        loadUsers(searchText: searchString);
        print("called from updateResults");
    }

    if (searchString == "") {
        searchResults.removeAll(keepingCapacity: false);
        searchTableView.reloadData();
        print("test");
    }
}

func loadUsers(searchText: String ) {

    if(searchText != "") {

        let usernameQuery = PFUser.query();
        //usernameQuery?.whereKey("username", equalTo: searchText);
        usernameQuery?.whereKey("username", contains: searchText.lowercased());

        let fbUsername = PFUser.query();
        fbUsername?.whereKey("username", contains: searchText);

        let firstnameQuery = PFUser.query();
        //firstnameQuery?.whereKey("last_name", equalTo: searchText)
        firstnameQuery?.whereKey("last_name", contains: searchText);

        let lastnameQuery = PFUser.query();
        //lastnameQuery?.whereKey("first_name", equalTo: searchText);
        lastnameQuery?.whereKey("first_name", contains: searchText);

        let query = PFQuery.orQuery(withSubqueries: [usernameQuery!,fbUsername!, firstnameQuery!, lastnameQuery!]);

        searchActive = true;

        query.findObjectsInBackground { (objects, error) in

            if error != nil {

                print("There was an error getting userlist");

            }

            else {

                if let object = objects {

                    self.searchResults.removeAll(keepingCapacity: false);

                    for object in objects! {

                        let user = object.object(forKey: "username") as! String;
                        self.searchResults.append(user);

                    }

                    //self.searchTableView.reloadData();

                    DispatchQueue.main.async {

                     self.searchTableView.reloadData();

                     //self.userSearchController.searchBar.resignFirstResponder();

                     }

                }

            }

            self.searchActive = false;

        }
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if(userSearchController.isActive) {

        print(searchResults.count);
        return searchResults.count;

    }

    return 0;
}

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath);

    if(self.userSearchController.isActive && searchResults.count > indexPath.row) {

        print(searchResults[indexPath.row]);
        cell.textLabel?.text = searchResults[indexPath.row];

    }

    return cell;

}

/*
public func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
    return true;
}

public func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
    return true;
}

func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {

        //loadUsers(searchText: (searchBar.text)!);
} */

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    if (searchBar.text != "" ) {
        NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(loadUsers(searchText:)), object: searchBar.text! as String);

        perform(#selector(loadUsers(searchText:)), with: searchBar.text! as String, afterDelay: 0.50);

        print("called from textDidChange");

    }
    if (searchBar.text == "") {

        searchResults.removeAll(keepingCapacity: false);
        searchTableView.reloadData();
        print("test2");
    }

}
</code>```

答:
I solved this problem by using Timer. The code below waits for one second before calling your function. If a text change occurs in that one second it will invalidate the previous scheduled timer and only do the second one. You can check this by printing the search text in your function.</p>

```<code>var timer: Timer?

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        timer?.invalidate() //cancels out previous Timers
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(myFunctionThatDoesServerSearch), userInfo: nil, repeats: false)
    }
</code>```

Body:
What I want is a searchbar that updates the tableview with usernames as every character is entered into the searchbar by the user. When the user deletes (backspaces) all the characters in the searchbar, ie the searchbar is empty, I want the tableview to be display no usernames and be empty.

I have a semi functioning UISearchbar that searches for usernames (Parse backend). It works fine when I type character by character in the searchbar slowly.

However, when I type quickly, the search results are a bit off - it shows me usernames from characters that were previously entered. For eg: if I enter 'nik' quickly it still shows me usernames with 'ni' in them. Also, when I backspace quickly until there are no characters in the searchbar, it still shows me certain usernames.

Again, it works fine when I enter characters in slowly, but I feel like it isn't very efficient. I have tried all sorts of things but nothing has worked well so far. I have added the relevant code below, let me know if you need more information.

    // called when keyboard search button pressed
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

    let searchString = searchBar.text;

    if (searchString != "") {
        //do load users
        loadUsers(searchText: searchString!);
        print("called from searchBarSearchButtonClicked");
    }

}

// called when cancel button pressed
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {

    searchBar.text = "";

    //hide tableview maybe?!
    //searchTableView.isHidden = true;

}

func updateSearchResults(for searchController: UISearchController) {
    let searchString: String = (searchController.searchBar.text)!;

    /*if (searchString == "" && !searchActive) {
        searchResults.removeAll(keepingCapacity: false);
        searchTableView.reloadData();
        print("test");
    }*/

    if (searchString != "" && !self.searchActive) {
        loadUsers(searchText: searchString);
        print("called from updateResults");
    }

    if (searchString == "") {
        searchResults.removeAll(keepingCapacity: false);
        searchTableView.reloadData();
        print("test");
    }
}

func loadUsers(searchText: String ) {

    if(searchText != "") {

        let usernameQuery = PFUser.query();
        //usernameQuery?.whereKey("username", equalTo: searchText);
        usernameQuery?.whereKey("username", contains: searchText.lowercased());

        let fbUsername = PFUser.query();
        fbUsername?.whereKey("username", contains: searchText);

        let firstnameQuery = PFUser.query();
        //firstnameQuery?.whereKey("last_name", equalTo: searchText)
        firstnameQuery?.whereKey("last_name", contains: searchText);

        let lastnameQuery = PFUser.query();
        //lastnameQuery?.whereKey("first_name", equalTo: searchText);
        lastnameQuery?.whereKey("first_name", contains: searchText);

        let query = PFQuery.orQuery(withSubqueries: [usernameQuery!,fbUsername!, firstnameQuery!, lastnameQuery!]);

        searchActive = true;

        query.findObjectsInBackground { (objects, error) in

            if error != nil {

                print("There was an error getting userlist");

            }

            else {

                if let object = objects {

                    self.searchResults.removeAll(keepingCapacity: false);

                    for object in objects! {

                        let user = object.object(forKey: "username") as! String;
                        self.searchResults.append(user);

                    }

                    //self.searchTableView.reloadData();

                    DispatchQueue.main.async {

                     self.searchTableView.reloadData();

                     //self.userSearchController.searchBar.resignFirstResponder();

                     }

                }

            }

            self.searchActive = false;

        }
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if(userSearchController.isActive) {

        print(searchResults.count);
        return searchResults.count;

    }

    return 0;
}

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath);

    if(self.userSearchController.isActive && searchResults.count > indexPath.row) {

        print(searchResults[indexPath.row]);
        cell.textLabel?.text = searchResults[indexPath.row];

    }

    return cell;

}

/*
public func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
    return true;
}

public func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
    return true;
}

func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {

        //loadUsers(searchText: (searchBar.text)!);
} */

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    if (searchBar.text != "" ) {
        NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(loadUsers(searchText:)), object: searchBar.text! as String);

        perform(#selector(loadUsers(searchText:)), with: searchBar.text! as String, afterDelay: 0.50);

        print("called from textDidChange");

    }
    if (searchBar.text == "") {

        searchResults.removeAll(keepingCapacity: false);
        searchTableView.reloadData();
        print("test2");
    }

}

Body:
I solved this problem by using Timer. The code below waits for one second before calling your function. If a text change occurs in that one second it will invalidate the previous scheduled timer and only do the second one. You can check this by printing the search text in your function.

var timer: Timer?

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        timer?.invalidate() //cancels out previous Timers
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(myFunctionThatDoesServerSearch), userInfo: nil, repeats: false)
    }


问:
(R, dplyr) select multiple columns starts with same string and summarise mean (90% CI) by group
I am new to tidyverse, conceptually I would like to calculate mean and 90% CI of all columns starts with "ab", grouped by "case". Tried many ways but none seem to work, my actual data has many columns so explicitly list them out is not an option.

test data below

```<code>library(tidyverse)

dat <- tibble(case= c("case1", "case1", "case2", "case2", "case3"),
              abc = c(1, 2, 3, 1, 2),
              abe = c(1, 3, 2, 3, 4),
              bca = c(1, 6, 3, 8, 9))
</code>```

below code is what i would like to do conceptually, but doesn't work, obviously

```<code>dat %>% group_by(`case`) %>%
  summarise(mean=mean(select(starts_with("ab"))),
            qt=quantile(select(starts_with("ab"), prob=c(0.05, 0.95))))
</code>```

what I would like to get is something like below

```<code>case abc_mean abe_mean abc_lb abc_ub abe_lb abe_ub

  <chr>    <dbl>    <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
1 case1      1.5      2.0   1.05   1.95   1.10   2.90
2 case2      2.0      2.5   1.10   2.90   2.05   2.95
3 case3      2.0      4.0   2.00   2.00   4.00   4.00
</code>```

答:
You were very close, just move that select before the summarise. We then use summarise_all, and specify the appropriate functions within funs.

```<code>dat %>%
    group_by(case) %>%
    select(starts_with('ab')) %>%
    summarise_all(funs('mean' = mean, 'ub' = quantile(., .95), 'lb' = quantile(., .05)))

# # A tibble: 3 x 7
#    case abc_mean abe_mean abc_ub abe_ub abc_lb abe_lb
#   <chr>    <dbl>    <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
# 1 case1      1.5      2.0   1.95   2.90   1.05   1.10
# 2 case2      2.0      2.5   2.90   2.95   1.10   2.05
# 3 case3      2.0      4.0   2.00   4.00   2.00   4.00
</code>```

We use summarise_all instead of summarise because we wish to perform the same operations on multiple columns. It requires far less typing to use summarise_all instead of a summarise call in which we specify each column and each operation separately.

Body:
I am new to tidyverse, conceptually I would like to calculate mean and 90% CI of all columns starts with "ab", grouped by "case". Tried many ways but none seem to work, my actual data has many columns so explicitly list them out is not an option.

test data below

library(tidyverse)

dat <- tibble(case= c("case1", "case1", "case2", "case2", "case3"),
              abc = c(1, 2, 3, 1, 2),
              abe = c(1, 3, 2, 3, 4),
              bca = c(1, 6, 3, 8, 9))

below code is what i would like to do conceptually, but doesn't work, obviously

dat %>% group_by(`case`) %>%
  summarise(mean=mean(select(starts_with("ab"))),
            qt=quantile(select(starts_with("ab"), prob=c(0.05, 0.95))))

what I would like to get is something like below

case abc_mean abe_mean abc_lb abc_ub abe_lb abe_ub

  <chr>    <dbl>    <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
1 case1      1.5      2.0   1.05   1.95   1.10   2.90
2 case2      2.0      2.5   1.10   2.90   2.05   2.95
3 case3      2.0      4.0   2.00   2.00   4.00   4.00

Body:
You were very close, just move that select before the summarise. We then use summarise_all, and specify the appropriate functions within funs.

dat %>%
    group_by(case) %>%
    select(starts_with('ab')) %>%
    summarise_all(funs('mean' = mean, 'ub' = quantile(., .95), 'lb' = quantile(., .05)))

# # A tibble: 3 x 7
#    case abc_mean abe_mean abc_ub abe_ub abc_lb abe_lb
#   <chr>    <dbl>    <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
# 1 case1      1.5      2.0   1.95   2.90   1.05   1.10
# 2 case2      2.0      2.5   2.90   2.95   1.10   2.05
# 3 case3      2.0      4.0   2.00   4.00   2.00   4.00

We use summarise_all instead of summarise because we wish to perform the same operations on multiple columns. It requires far less typing to use summarise_all instead of a summarise call in which we specify each column and each operation separately.


问:
C}++ How to display a vector of objects for the user in a certain format
Okay so, I've been beating myself up over this and I don't think include all of my code in this post to find an answer. Part of my problem is I don't really know how to word the question.

So say I have a vector of objects called inventory that takes objects from my Item class. and I make a function: inventory.addItem(itemObject)

So I can successfully add items just by using the inventory.push_back(itemObject)
function.

When I display the vector I can iterate through it and print out to the console

```<code>iterator->itemObject.getItemName()
</code>```

But my main goal is to print out that I have multiple of the same objects and print out one of the getItemName and then an integer value of how many of the objects with equal getItemName values and print out that value next to it:

For example:

```<code>Item hammer("Hammer");
Item sword("Sword");

inventory.addItem(hammer);
inventory.addItem(hammer);
inventory.addItem(hammer);
inventory.addItem(sword);
</code>```

And if I use my inventory.displayInventory() function which all I do is iterate through each object, and access the object's getItemName() function and have it be outputted giving me:

```<code>"Hammer"
"Hammer"
"Hammer"
"Sword"
</code>```

My goal is to have in my inventory.displayInventory() function:

```<code>"Hammer" (3)
"Sword" (1)
</code>```

Does anyone have any Idea how I can manipulate my for loop iteration to help with this? Or does this sound like a bad idea through and through and I should just stick with them printing separate?

Thanks for any advice!

答:
You can use a map to do this:

```<code>std::map<std::string, int> items;
for(Item const& item : inventory) {
    items[item.getItemName()]++;
}

for(auto const& pair : items) {
    std::cout << pair.first << ": (" << pair.second << ")" << std::endl;
}
</code>```

If you need the calculation to be more specific than just Item Names, that's possible too, though you need to make sure your Item class overloads operator< and operator==, since std::map requires that its keys be sortable. If you've done that, though, then the code is slightly simpler:

```<code>std::map<Item, int> items;
for(Item const& item : inventory) {
    items[item]++;
}

for(auto const& pair : items) {
    std::cout << pair.first.getItemName() << ": (" << pair.second << ")" << std::endl;
}
</code>```

Body:
Okay so, I've been beating myself up over this and I don't think include all of my code in this post to find an answer. Part of my problem is I don't really know how to word the question.

So say I have a vector of objects called inventory that takes objects from my Item class. and I make a function: inventory.addItem(itemObject)

So I can successfully add items just by using the inventory.push_back(itemObject)
function.

When I display the vector I can iterate through it and print out to the console

iterator->itemObject.getItemName()

But my main goal is to print out that I have multiple of the same objects and print out one of the getItemName and then an integer value of how many of the objects with equal getItemName values and print out that value next to it:

For example:

Item hammer("Hammer");
Item sword("Sword");

inventory.addItem(hammer);
inventory.addItem(hammer);
inventory.addItem(hammer);
inventory.addItem(sword);

And if I use my inventory.displayInventory() function which all I do is iterate through each object, and access the object's getItemName() function and have it be outputted giving me:

"Hammer"
"Hammer"
"Hammer"
"Sword"

My goal is to have in my inventory.displayInventory() function:

"Hammer" (3)
"Sword" (1)

Does anyone have any Idea how I can manipulate my for loop iteration to help with this? Or does this sound like a bad idea through and through and I should just stick with them printing separate?

Thanks for any advice!

Body:
You can use a map to do this:

std::map<std::string, int> items;
for(Item const& item : inventory) {
    items[item.getItemName()]++;
}

for(auto const& pair : items) {
    std::cout << pair.first << ": (" << pair.second << ")" << std::endl;
}

If you need the calculation to be more specific than just Item Names, that's possible too, though you need to make sure your Item class overloads operator< and operator==, since std::map requires that its keys be sortable. If you've done that, though, then the code is slightly simpler:

std::map<Item, int> items;
for(Item const& item : inventory) {
    items[item]++;
}

for(auto const& pair : items) {
    std::cout << pair.first.getItemName() << ": (" << pair.second << ")" << std::endl;
}


问:
pass a context to another class and change a TextView of an activity
I want to change a TextView from another, non-activity class. I see the answer here How to update a TextView of an activity from another class in the adapost's post, but I don't know how to properly pass a context to "ClassB".

In Main class, I tried ClassB obj = new ClassB(this); and ClassB obj = new ClassB(getApplicationContext());. But every time, TextView txtView = (TextView)findViewById(R.id.text); returns NullPointerException.

I am sure that I do it aftersetContentView, I can acheive this textView from Main class.

How to pass the context to make it work?

答:
The problem was the Id resource. When the TextView's Id was set to @+id/text, the object returned NullPointerException. When I created Id xml resource, added an item <item type="id" name="tv_zero" /> and in the activity xml android:id="@id/tv_zero" Application worked fine.
I called it in the main by ClassB ObjOne = new ClassB(this); and ObjOne.Update();


问:
Waterline - Postgres - DataTypes
I am having difficulties with Waterline models and creating the Postgres tables related to those models.

No matter what I do to create a varchar(n) in the table through a model, it converts the attribute to text. And bigint also is being converted to integer!

Should I change the ORM?

Is there a way to do that?

答:
You can do a more pleasant approach, using Waterline to "RUD" in "CRUD" but not to "C" - create! This because Waterline can be very "bad" at creating intermediary tables, primary keys (composite keys) and etc. So what I do today is this:

Compose a full .sql file archive to create indexes and tables.

Create the database once. (Alter if needed).

Declare all the tables as models. Just insert the type, primary key (if it is a single one) and lifecycle callbacks.

Make sure that config/models.js is set to migrate : safe.

Conclusion: I can insert, read and delete rows with Waterline, but I don't trust it (performance-wise) to create my tables. Sequelize on the other hand is a much more mature ORM and can be used if you need it. For me the hybrid waterline + SQL is sufficient.

EDIT: My models dont have any aggregation (like my_pets: { model: pet} ), just row names and types, as simple as possible.

Title: Waterline - Postgres - DataTypes


问:
Node translation > client > node > json > node > client
I am not so good in node, need your help a little bit.

I want to make my node to be  'translator'. What does it mean?

I found something like this:
How to forward a request to other endpoint in node.js

I want send through ajax request to my node server, then this server should send request to json and received data display in browser.

How can i change it to receive responses and throw it to browser?

```<code>var express = require('express');
var fs = require('fs');
var path = require('path');
var http = require('http');
var https = require('https');
var app = express();

var HTTP_PORT = 3000;

// Create an HTTP service
http.createServer(app).listen(HTTP_PORT,function() {
  console.log('Listening HTTP on port ' + HTTP_PORT);
});

//endpoint for tracking
app.get('/track', function(req, res) {

  sendRequestToOtherEndPoint(req);

  processRequest(req);
  res.setHeader('Content-Type', 'application/json');
  res.send('Req OK');
});

function processRequest(req){
    console.log("request processed");
}

function sendRequestToOtherEndPoint(req){
    //magic here :)
}
</code>```

I spend a lot of time on it and don't have ideas.

My ajax request:

```<code><script type="text/javascript">
$(document).ready(function() {
    $("#testbutton").click(function() {
        $.ajax({
url: '',
            dataType: 'json',
            success: function(data) {
                $("#results").append('works');
                alert(data);
            },
             error: function() {
                $("#results").append("error");
                alert('error');
            }
        });
    });
});
</script>
</code>```

My actual server contains only

```<code>  request({
      url: ,
      method: "GET",
      timeout: 10000,
      followRedirect: true,
      maxRedirects: 10
  },function(error, response, body){
      if(!error && response.statusCode == 200){
          console.log('sucess!');
           console.log(response.body);
      }else{
          console.log('error' + response.body);
      }
</code>```

and listen + some variables on start.

答:
So, the term you're looking for is "reverse proxy".  There are a lot of ways to do it, and a lot of potential gotchas, but if you don't want to make use of an existing module like reverse-proxy, then what you probably want to do is use the request module to pipe the request and response streams.  Something like this:

```<code>app.get('/proxy', (req, res) => {
  request('http://example.com/').pipe(res);
});
</code>```

Body:
I am not so good in node, need your help a little bit.

I want to make my node to be  'translator'. What does it mean?

I found something like this:
How to forward a request to other endpoint in node.js

I want send through ajax request to my node server, then this server should send request to json and received data display in browser.

How can i change it to receive responses and throw it to browser?

var express = require('express');
var fs = require('fs');
var path = require('path');
var http = require('http');
var https = require('https');
var app = express();

var HTTP_PORT = 3000;

// Create an HTTP service
http.createServer(app).listen(HTTP_PORT,function() {
  console.log('Listening HTTP on port ' + HTTP_PORT);
});

//endpoint for tracking
app.get('/track', function(req, res) {

  sendRequestToOtherEndPoint(req);

  processRequest(req);
  res.setHeader('Content-Type', 'application/json');
  res.send('Req OK');
});

function processRequest(req){
    console.log("request processed");
}

function sendRequestToOtherEndPoint(req){
    //magic here :)
}

I spend a lot of time on it and don't have ideas.

My ajax request:

My actual server contains only

  request({
      url: ,
      method: "GET",
      timeout: 10000,
      followRedirect: true,
      maxRedirects: 10
  },function(error, response, body){
      if(!error && response.statusCode == 200){
          console.log('sucess!');
           console.log(response.body);
      }else{
          console.log('error' + response.body);
      }

and listen + some variables on start.

Body:
So, the term you're looking for is "reverse proxy".  There are a lot of ways to do it, and a lot of potential gotchas, but if you don't want to make use of an existing module like reverse-proxy, then what you probably want to do is use the request module to pipe the request and response streams.  Something like this:

app.get('/proxy', (req, res) => {
  request('http://example.com/').pipe(res);
});


问:
Apache POI Enable excel editing
I'm using Apache POI to edit Excels in Java. After editing POI is not able to save file because the Excel is always protected. If you open, it will show the option to enable editing. On copying same file to a new Excel will work fine. But is there any way to enable editing from Java for the Excel? Here is a sample of my code:

```<code>import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Test3 {
    public static void main(String args[]) {
        try {
            FileInputStream file = new FileInputStream(new File(
                    "New Microsoft Excel Worksheet.xlsx"));
            // Document document = Jsoup.connect("http://www.google.com").get();
            // Get the workbook instance for XLS file
            XSSFWorkbook workbook = new XSSFWorkbook(file);
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                // Get first sheet from the workbook
                XSSFSheet sheet = workbook.getSheetAt(i);

                // Iterate through each rows from first sheet
                Iterator<Row> rowIterator = sheet.iterator();
                while (rowIterator.hasNext()) {
                    XSSFRow row = (XSSFRow) rowIterator.next();

                    // For each row, iterate through each columns
                    Iterator<Cell> cellIterator = row.cellIterator();

                    while (cellIterator.hasNext()) {
                        // Do something
                    }

                }
            }
            file.close();
            FileOutputStream out = new FileOutputStream(
                    "New Microsoft Excel Worksheet.xlsx");
            workbook.write(out);
            out.close();
            System.out.println("Done!!!!!!!!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

I'm using excel 2007.

答:
So this turns out to be a Office Trust Center setting. When there is potentially unsafe content in the file being opened it will open in protected view, no matter what POI settings are in place.

I was able to work around it by setting my browser to save the file to a folder rather than opening it directly (which actually saves it to a temp folder). Then I added that folder to the Trusted Locations in the Trust Center for Office. This tells office that it's ok to open this file for editing because I trust the location from which it is being opened.

Office support link describing this setting.

For Excel 2013 - Click File tab, then select Options, Trust Center, Trust Center Settings.

Options">

Add your location where the downloads will be stored.

Ensure your directory is added.

While I agree this is not a POI solution, it IS a solution. Yes you will probably have to help your end user to set this up.

Perhaps soon, Apache POI team will add a POI solution into a future release to do this programmatically.

Title: Apache POI Enable excel editing

Body:
I'm using Apache POI to edit Excels in Java. After editing POI is not able to save file because the Excel is always protected. If you open, it will show the option to enable editing. On copying same file to a new Excel will work fine. But is there any way to enable editing from Java for the Excel? Here is a sample of my code:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Test3 {
    public static void main(String args[]) {
        try {
            FileInputStream file = new FileInputStream(new File(
                    "New Microsoft Excel Worksheet.xlsx"));
            // Document document = Jsoup.connect("http://www.google.com").get();
            // Get the workbook instance for XLS file
            XSSFWorkbook workbook = new XSSFWorkbook(file);
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                // Get first sheet from the workbook
                XSSFSheet sheet = workbook.getSheetAt(i);

                // Iterate through each rows from first sheet
                Iterator<Row> rowIterator = sheet.iterator();
                while (rowIterator.hasNext()) {
                    XSSFRow row = (XSSFRow) rowIterator.next();

                    // For each row, iterate through each columns
                    Iterator<Cell> cellIterator = row.cellIterator();

                    while (cellIterator.hasNext()) {
                        // Do something
                    }

                }
            }
            file.close();
            FileOutputStream out = new FileOutputStream(
                    "New Microsoft Excel Worksheet.xlsx");
            workbook.write(out);
            out.close();
            System.out.println("Done!!!!!!!!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

I'm using excel 2007.

Body:
So this turns out to be a Office Trust Center setting. When there is potentially unsafe content in the file being opened it will open in protected view, no matter what POI settings are in place.

I was able to work around it by setting my browser to save the file to a folder rather than opening it directly (which actually saves it to a temp folder). Then I added that folder to the Trusted Locations in the Trust Center for Office. This tells office that it's ok to open this file for editing because I trust the location from which it is being opened.

Office support link describing this setting.

For Excel 2013 - Click File tab, then select Options, Trust Center, Trust Center Settings.

Add your location where the downloads will be stored.

Ensure your directory is added.

While I agree this is not a POI solution, it IS a solution. Yes you will probably have to help your end user to set this up.

Perhaps soon, Apache POI team will add a POI solution into a future release to do this programmatically.


问:
Use values from HTML input
```<code><label for="fullname" name="identity">Name, Surname</label><br/>
<input type="text" name="info" value="" />
</code>```

Once user types inside it something, I want save that into variable. Later be able to use that elsewhere.

```<code><input type="submit" value="send" onclick="myFunction()"/>
</code>```

What function to create and what to do to to use this value?

答:
If you want to keep the data on the same page, then you will be able to use vanilla JavaScript by declaring a variable at the document level scope. Here is a quick example of that:

window.onload = function() {
  document.getElementById("my_form").onsubmit = my_form_submit;
}

var fullname;
function my_form_submit(e) {
  // Stop the form from submitting
  e.preventDefault();

  // Store the value
  fullname = document.getElementById("fullname").value;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="my_form">
  <label for="fullname" name="identity">Name, Surname</label><br/>
  <input type="text" name="info" value="" id="fullname" />
  <input type="submit" value="send" />
</form></code>```

If you want the data to persist across pages, then you'll need to use a server-side language to create cookies. In PHP you'd establish a session and then set the session variable. Here is a quick example of that:

```<code><?php
// Set session variables
session_start();

// Assign the session variable from the form's post
$_SESSION["fullname"] = "info";
?>
</code>```

Title: Use values from HTML input

Body:
Name, Surname

<input type="text" name="info" value="" />

Once user types inside it something, I want save that into variable. Later be able to use that elsewhere.

<input type="submit" value="send" onclick="myFunction()"/>

What function to create and what to do to to use this value?

Body:
If you want to keep the data on the same page, then you will be able to use vanilla JavaScript by declaring a variable at the document level scope. Here is a quick example of that:

window.onload = function() {
  document.getElementById("my_form").onsubmit = my_form_submit;
}

var fullname;
function my_form_submit(e) {
  // Stop the form from submitting
  e.preventDefault();

  // Store the value
  fullname = document.getElementById("fullname").value;
}

<form id="my_form">
  <label for="fullname" name="identity">Name, Surname</label><br/>
  <input type="text" name="info" value="" id="fullname" />
  <input type="submit" value="send" />
</form>

If you want the data to persist across pages, then you'll need to use a server-side language to create cookies. In PHP you'd establish a session and then set the session variable. Here is a quick example of that:

<?php
// Set session variables
session_start();

// Assign the session variable from the form's post
$_SESSION["fullname"] = "info";
?>


答:
You want a map rather than a vector:

```<code>#include <iostream>
#include <map>

struct Item {
    std::string name;
    Item(std::string name) : name(name){}
    bool operator<(const Item& other) const { return name < other.name;}
};

struct Inventory {
    std::map<Item,size_t> data;
    void addItem(const Item& item){ data[item]++; }
    void print(){
        for (auto e : data){
            std::cout << e.first.name << " (" << e.second << ")\n";
        }
    }

};

int main(){
    Item hammer("hammer");
    Item knife("knife");
    Inventory inventory;
    inventory.addItem(hammer);
    inventory.addItem(hammer);
    inventory.addItem(knife);
    inventory.print();
}
</code>```

Live Demo

Item needs a operator<, so you can put it in the map. And data[item]++; adds the key to the map if it does not exist already (default initializes the count if it didnt exist) and increments the count. Finally printing the inventory can be done with a simple loop.

PS: alternatively you could use a std::unordered_map or maybe some other associative container.

Title: C}++ How to display a vector of objects for the user in a certain format

Body:
You want a map rather than a vector:

#include <iostream>
#include <map>

struct Item {
    std::string name;
    Item(std::string name) : name(name){}
    bool operator<(const Item& other) const { return name < other.name;}
};

struct Inventory {
    std::map<Item,size_t> data;
    void addItem(const Item& item){ data[item]++; }
    void print(){
        for (auto e : data){
            std::cout << e.first.name << " (" << e.second << ")\n";
        }
    }

};

int main(){
    Item hammer("hammer");
    Item knife("knife");
    Inventory inventory;
    inventory.addItem(hammer);
    inventory.addItem(hammer);
    inventory.addItem(knife);
    inventory.print();
}

Live Demo

Item needs a operator<, so you can put it in the map. And data[item]++; adds the key to the map if it does not exist already (default initializes the count if it didnt exist) and increments the count. Finally printing the inventory can be done with a simple loop.

PS: alternatively you could use a std::unordered_map or maybe some other associative container.


问:
Box-shadow's 3rd value dramatically decreases page rendering
Using the box-shadow property in Chrome or Firefox, if the 3rd input is a large number, it nearly freezes the browser in Chrome and it slows down Firefox. Is this a bug?

-moz-box-shadow: 0 0 400px #446b6b;
-webkit-box-shadow: 0px 0px 400px #446b6b;

答:
Yeah it is: https://bugs.webkit.org/show_bug.cgi?id=22102

I believe it's been patched and should be available soon :-)

Workarounds include: less shadow or use a png for the shadow..

The problem is they're not caching the shadow so it's getting redrawn whenever you scroll..

ContentLicense: CC BY-SA 2.5


问:
how to print stdclass object name to data
i used ezsql mysqli and my mysql scheme:

```<code>    id---settingname------settingcode
---------------------------------
0    doctype          <!DOCTYPE html>
1    html_lang        en
2    charset          utf8
</code>```

and my php code

```<code><?php echo $doctype; ?>
<html lang="<?php echo $html_lang; ?>">
<meta charset="<?php echo $charset; ?>">
</code>```

how can i fetch stdclass object like this with ezsql mysqli;

```<code>echo $settings['doctype'];
</code>```

答:
Ok, i found the answer, you can change index with array_column() like this;

```<code>$settings = array_column($dbresult,'settingcode','settinguniquename');
</code>```

and you can print this variable like this;

```<code>echo $settings['doctype']; echo $settings['charset']; echo $settings['anysettingname'];
</code>```

Body:
i used ezsql mysqli and my mysql scheme:

    id---settingname------settingcode
---------------------------------
0    doctype          <!DOCTYPE html>
1    html_lang        en
2    charset          utf8

and my php code

<?php echo $doctype; ?>
<html lang="<?php echo $html_lang; ?>">
<meta charset="<?php echo $charset; ?>">

how can i fetch stdclass object like this with ezsql mysqli;

echo $settings['doctype'];

Body:
Ok, i found the answer, you can change index with array_column() like this;

$settings = array_column($dbresult,'settingcode','settinguniquename');

and you can print this variable like this;

echo $settings['doctype']; echo $settings['charset']; echo $settings['anysettingname'];


问:
I want to use this simple sliding panel. jquery panel
Instead of the panel coming down I want it to go from left to right thanks       </p>

```<code><title>Simple Slide Panel</title>

    <script type="text/javascript" src="jquery.js"></script>

    <script type="text/javascript">
    $(document).ready(function(){

        $(".btn-slide").click(function(){
            $("#panel").slideToggle("slow");
            $(this).toggleClass("active"); return false;
        });

    });
    </script>

    <style type="text/css">
    body {
        margin: 0 auto;
        padding: 0;
        width: 570px;
        font: 75%/120% Arial, Helvetica, sans-serif;
    }
    a:focus {
        outline: none;
    }
    #panel {
        background: #754c24;
        height: 200px;
        display: none;
    }
    .slide {
        margin: 0;
        padding: 0;
        border-top: solid 4px #422410;
        background: url(images/btn-slide.gif) no-repeat center top;
    }
    .btn-slide {
        background: url(images/white-arrow.gif) no-repeat right -50px;
        text-align: center;
        width: 144px;
        height: 31px;
        padding: 10px 10px 0 0;
        margin: 0 auto;
        display: block;
        font: bold 120%/100% Arial, Helvetica, sans-serif;
        color: #fff;
        text-decoration: none;
    }
    .active {
        background-position: right 12px;
    }
    </style>
    </head>

    <body>

    <div id="panel">
        <!-- you can put content here -->
    </div>

    <p class="slide"><a href="#" class="btn-slide">Slide Panel</a></p>

    </body>
    </html>
</code>```

答:
Try this

EDIT:

David commented with a good suggestion. The beauty of jQuery is its ability to animate properties of elements. slideup/down/toggle animate the height of elements. Width is another property that can be animated and would give you the horizontal-slide effect you're after. The link I posted is to an article with examples.

Body:
Instead of the panel coming down I want it to go from left to right thanks

<title>Simple Slide Panel</title>

Slide Panel


问:
Sending JSON data from angularjs to nodejs
I having a problem in sending json data from front end angularjs to express nodejs. Here is what i have tried.

frontend.html page

```<code><form ng-submit="func()">
    <textarea name="inputtext" type="text" ng-model="sentence"></textarea>
</form>
</code>```

backend.js page

```<code>$scope.func = function(){

 $scope.jsondata = {"status":"OK","language":"english","sentences":[{"sentence":"That's a nice restaurant."},{"sentence":"Also I went to another bad restaurant."},{"sentence":"I didn't like that movie."}]}

 $http.post('/sample',$scope.jsondata).success(function(data,status){
        console.log("Success");
     })
}
</code>```

server.js

```<code>var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser');
var path = require('path');
var fs = require('fs');

app.set('views', __dirname + '/views');
app.set('view engine' , 'ejs');

app.use(bodyParser.json());
var urlencodedParser = bodyParser.urlencoded({ extended: true });

app.use(express.static('public'));

app.get('/',function(req,res){
    res.render('index',{ title: 'Sentence' });
});
app.post('/sample',urlencodedParser,function(req,res){
    console.log(req.body);
});
http.listen(8888, function(){
   console.log("Server listening on 8888");
});
</code>```

I am not getting exact JSON in the node server part. This is what i am getting.

output

```<code>{ '{"status":"OK","language":"english","sentences":': { '{"sentence":"That\'s a nice restaurant."},{"sentence":"Also I went to another bad restaurant."},{"sentence":"I didn\'t like that movie."},{"sentence":"Thats a very bad movie."}': '' } }
</code>```

Can any one help, how can i get exact json in the node server part. So that i can parse and write only sentence field into a file.

答:
Use application/json in header while POST method

```<code> $http({
    method:'POST',
    dataType: "json",
    url: 'http://localhost:8000/saveform',
    data : $scope.user,
    headers: {
      'Content-Type': 'application/json'
    }
  }).success(function(data){

  });
</code>```

Body:
I having a problem in sending json data from front end angularjs to express nodejs. Here is what i have tried.

frontend.html page

<form ng-submit="func()">
    <textarea name="inputtext" type="text" ng-model="sentence"></textarea>
</form>

backend.js page

$scope.func = function(){

 $scope.jsondata = {"status":"OK","language":"english","sentences":[{"sentence":"That's a nice restaurant."},{"sentence":"Also I went to another bad restaurant."},{"sentence":"I didn't like that movie."}]}

 $http.post('/sample',$scope.jsondata).success(function(data,status){
        console.log("Success");
     })
}

server.js

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser');
var path = require('path');
var fs = require('fs');

app.set('views', __dirname + '/views');
app.set('view engine' , 'ejs');

app.use(bodyParser.json());
var urlencodedParser = bodyParser.urlencoded({ extended: true });

app.use(express.static('public'));

app.get('/',function(req,res){
    res.render('index',{ title: 'Sentence' });
});
app.post('/sample',urlencodedParser,function(req,res){
    console.log(req.body);
});
http.listen(8888, function(){
   console.log("Server listening on 8888");
});

I am not getting exact JSON in the node server part. This is what i am getting.

output

{ '{"status":"OK","language":"english","sentences":': { '{"sentence":"That\'s a nice restaurant."},{"sentence":"Also I went to another bad restaurant."},{"sentence":"I didn\'t like that movie."},{"sentence":"Thats a very bad movie."}': '' } }

Can any one help, how can i get exact json in the node server part. So that i can parse and write only sentence field into a file.

Body:
Use application/json in header while POST method

 $http({
    method:'POST',
    dataType: "json",
    url: 'http://localhost:8000/saveform',
    data : $scope.user,
    headers: {
      'Content-Type': 'application/json'
    }
  }).success(function(data){

  });


问:
ORA-12541 TNS :no listener on 1 specific remote database, but not on others
Some context:  I'm setting up an environment to run some Ruby code our Lead wrote to connect to some remote Databases. I'm using Win10 and have WSL installed.  I have installed SQL*Plus, docker, and Ruby, and am sure I have installed all the dependent gems (actually at this point I know for a fact its not a ruby problem).  I'm using Docker to use a pre-built image of an Oracle Database, and I have populated it with data.

Obfuscated company DB information:

'Broken' DB (TNS no listener)

Username: W-WORK-DEV

Password: password

Host: host1

Port: 999

SID: W-WORK-DB.tech.company

'Working' DB (can connect just fine)

Username: C-OLD-DEV

Password: password

Host: host2

Port: 999

SID: C-OLD-DB.tech.company

Please note the names I have provided here are purely for obfuscation, they do not represent anything about age or even config.  They are essentially the same, just different databases on different hosts.  Also note this is a corporate company and would have a lot of base infrastructure for their internal network.

The issue I am having is that with the specific database I am working on, I cannot connect to it.  I connect to the company intranet via a VPN (I work offsite) and have issues connecting to WORK-DB.tech.company, though I can connect to C-OLD-DB.tech.company.  Methods I have tried to connect with:

Oracle SQL Developer

I have inputted all the correct jdbc strings and username / password.  Have even asked other people to attempt to connect (at least 3 others).  They can all access C-OLD-DB as well as W-WORK-DB.  When using this method, I get The network adapter could not establish the connection.

Side note:  I'm fairly sure I have connected to the DB just fine in the past, though I can't be certain because I'm fairly new to this team and have only accessed it once, if that.

SQL*Plus via WSL

I installed SQL*Plus because I think Ruby was accessing it in some capacity when running the script.  I got to the point where the script was able to connect to my local docker Database, but when it tried to connect to the remote database, it would return TNS: no listener.   I attempted this using sqlplus as well and got the same error.

Example:

sqlplus C-OLD-DEV/password@host2:999/C-OLD-DB.tech.company

This command works and connected to the DB jsut fine.

sqlplus W-WORK-DEV/password@host1:999/W-WORK-DB.tech.company

This command gave me TNS: no listener.

During my research I had found mentions about tnsnames.ora, sqlnet.ora, and listener.ora.  I have found relevant files around the company intranet and attempted to use them in my own personal environment to no avail (one of the sqlnet.ora files actually stopped me from being able to connect to any)  I found mention about a config/database.yml file related to ruby, but our code already has the database information set up and I seem to be getting to the same solution as the script when trying to manually connect via sqlplus.

Here are some relevant environment variables I have set up when doing these installs.  I'm thinking that at some point when trying to set up my environment, I messed up some config that changed the way sqldeveloper or sql plus would connect to that database.

$ echo $ORACLE_HOME: /usr/lib/oracle/12.2/client64/

$ echo $TNS_ADMIN: /usr/lib/oracle/12.2/client64/network/admin

$ echo $LD_LIBRARY_PATH: /usr/lib/oracle/12.2/client64/lib

I hope I have provided all the information I have come across and have explained clearly what my issue is, if you have any questions feel free to comment about it so I can clear it up.  Thank you for any and all your help.

答: So my problem ended up being a 'firewall/port' issue.  In the end i found out that specific port I was connecting to was blocked, but I thought it was only on my system.  Turns out the VPN I'm using was the issue blocking that port.  Company has a Primary Data Center and a Secondary one, and apparently the SDC VPN was blocking that port from me.  I switched to using the PDC VPN and it worked.</p>


问:
Haskell Yesod problems
someone could help me?! I'm working in a Haskell Yesod site for college on a C9 workspace, I've already installed by command Yesod and update cabal,  but when I try "stack build" command, this miserable error message appears:

```<code> $ stack build

aulahaskell-0.0.0: build (lib + exe)
Preprocessing library aulahaskell-0.0.0...
[ 7 of 13] Compiling Handler.Cliente  ( src/Handler/Cliente.hs, .stack-work/dist/x86_64-linux/Cabal-1.24.2.0/build/Handler/Cliente.o )

/home/ubuntu/workspace/web2017/src/Handler/Cliente.hs:10:1: error:
    Failed to load interface for ‘Network.HTTP.Types.Status’
    It is a member of the hidden package ‘http-types-0.9.1’.
    Perhaps you need to add ‘http-types’ to the build-depends in your .cabal file.
    Use -v to see a list of the files searched for.

--  While building package aulahaskell-0.0.0 using:
      /home/ubuntu/.stack/setup-exe-cache/x86_64-linux/Cabal-simple_mPHDZzAJ_1.24.2.0_ghc-8.0.2 --builddir=.stack-work/dist/x86_64-linux/Cabal-1.24.2.0 build lib:aulahaskell exe:aulahaskell --ghc-options " -ddump-hi -ddump-to-file"
    Process exited with code: ExitFailure 1
</code>```

Seriously, I tried a bunch of things to fix it, but nothing is working =S

答:
Just read the error message carefully:

```<code>Failed to load interface for ‘Network.HTTP.Types.Status’
It is a member of the hidden package ‘http-types-0.9.1’.
Perhaps you need to add ‘http-types’ to the build-depends in your .cabal file.
Use -v to see a list of the files searched for.
</code>```

The line Perhaps you need to add ‘http-types’ to the build-depends in your .cabal file tells you what to do: You must add http-types to the build-depends: section of the library aulahaskell in your cabal file.

If this does not help, please post your cabal file.

Title: Haskell Yesod problems

Body:
someone could help me?! I'm working in a Haskell Yesod site for college on a C9 workspace, I've already installed by command Yesod and update cabal,  but when I try "stack build" command, this miserable error message appears:

 $ stack build

aulahaskell-0.0.0: build (lib + exe)
Preprocessing library aulahaskell-0.0.0...
[ 7 of 13] Compiling Handler.Cliente  ( src/Handler/Cliente.hs, .stack-work/dist/x86_64-linux/Cabal-1.24.2.0/build/Handler/Cliente.o )

/home/ubuntu/workspace/web2017/src/Handler/Cliente.hs:10:1: error:
    Failed to load interface for ‘Network.HTTP.Types.Status’
    It is a member of the hidden package ‘http-types-0.9.1’.
    Perhaps you need to add ‘http-types’ to the build-depends in your .cabal file.
    Use -v to see a list of the files searched for.

--  While building package aulahaskell-0.0.0 using:
      /home/ubuntu/.stack/setup-exe-cache/x86_64-linux/Cabal-simple_mPHDZzAJ_1.24.2.0_ghc-8.0.2 --builddir=.stack-work/dist/x86_64-linux/Cabal-1.24.2.0 build lib:aulahaskell exe:aulahaskell --ghc-options " -ddump-hi -ddump-to-file"
    Process exited with code: ExitFailure 1

Seriously, I tried a bunch of things to fix it, but nothing is working =S

Body:
Just read the error message carefully:

Failed to load interface for ‘Network.HTTP.Types.Status’
It is a member of the hidden package ‘http-types-0.9.1’.
Perhaps you need to add ‘http-types’ to the build-depends in your .cabal file.
Use -v to see a list of the files searched for.

The line Perhaps you need to add ‘http-types’ to the build-depends in your .cabal file tells you what to do: You must add http-types to the build-depends: section of the library aulahaskell in your cabal file.

If this does not help, please post your cabal file.


问:
Access Docker socket within container
I am attempting to create a container that can access the host docker remote API via the docker socket file (host machine - /var/run/docker.sock).

The answer here suggests proxying requests to the socket.  How would I go about doing this?

答:
I stumbled across this page while trying to make docker socket calls work from a container that is running as the nobody user.

In my case I was getting access denied errors when my-service would try to make calls to the docker socket to list available containers.

I ended up using docker-socket-proxy to proxy the docker socket to my-service. This is a different approach to accessing the docker socket within a container so I though I would share it.

I made my-service able to receive the docker host it should talk to, docker-socker-proxy in this case, via the DOCKER_HOST environment variable.

Note that docker-socket-proxy will need to run as the root user to be able to proxy the docker socket to my-service.

Example docker-compose.yml:

```<code>version: "3.1"

services:
  my-service:
    image: my-service
    environment:
      - DOCKER_HOST=tcp://docker-socket-proxy:2375
    networks:
      - my-service_my-network
  docker-socket-proxy:
    image: tecnativa/docker-socket-proxy
    environment:
      - SERVICES=1
      - TASKS=1
      - NETWORKS=1
      - NODES=1
    volumes:
     - /var/run/docker.sock:/var/run/docker.sock
    networks:
      - my-service_my-network
    deploy:
      placement:
        constraints: [node.role == manager]

networks:
  my-network:
    driver: overlay
</code>```

Note that the above compose file is swarm ready (docker stack deploy my-service) but it should work in compose mode as well (docker-compose up -d). The nice thing about this approach is that my-service does not need to run on a swarm manager anymore.

Title: Access Docker socket within container

Body:
I stumbled across this page while trying to make docker socket calls work from a container that is running as the nobody user.

In my case I was getting access denied errors when my-service would try to make calls to the docker socket to list available containers.

I ended up using docker-socket-proxy to proxy the docker socket to my-service. This is a different approach to accessing the docker socket within a container so I though I would share it.

I made my-service able to receive the docker host it should talk to, docker-socker-proxy in this case, via the DOCKER_HOST environment variable.

Note that docker-socket-proxy will need to run as the root user to be able to proxy the docker socket to my-service.

Example docker-compose.yml:

version: "3.1"

services:
  my-service:
    image: my-service
    environment:
      - DOCKER_HOST=tcp://docker-socket-proxy:2375
    networks:
      - my-service_my-network
  docker-socket-proxy:
    image: tecnativa/docker-socket-proxy
    environment:
      - SERVICES=1
      - TASKS=1
      - NETWORKS=1
      - NODES=1
    volumes:
     - /var/run/docker.sock:/var/run/docker.sock
    networks:
      - my-service_my-network
    deploy:
      placement:
        constraints: [node.role == manager]

networks:
  my-network:
    driver: overlay

Note that the above compose file is swarm ready (docker stack deploy my-service) but it should work in compose mode as well (docker-compose up -d). The nice thing about this approach is that my-service does not need to run on a swarm manager anymore.


问:
How to make HTTP DELETE method using urllib2?
Does urllib2 support DELETE or PUT method? If yes provide with any example please. I need to use piston API.

答:
You can subclass the urllib2.Request object and override the method when you instantiate the class.

```<code>import urllib2

class RequestWithMethod(urllib2.Request):
  def __init__(self, method, *args, **kwargs):
    self._method = method
    urllib2.Request.__init__(*args, **kwargs)

  def get_method(self):
    return self._method
</code>```

Courtesy of Benjamin Smedberg

Body:
You can subclass the urllib2.Request object and override the method when you instantiate the class.

import urllib2

class RequestWithMethod(urllib2.Request):
  def __init__(self, method, *args, **kwargs):
    self._method = method
    urllib2.Request.__init__(*args, **kwargs)

  def get_method(self):
    return self._method

Courtesy of Benjamin Smedberg


问:
How to update Registry Values as "System" user?
I have a Windows Forms application needs to update registry values. When I debug the application the values are being saved properly. But when I launch the application after the completion of installer (Visual Studio Setup Project - .vdproj), the application launches properly but it is not saving the registry values properly.

I am not getting any errors but can't seem to find the entries at location.

The values are being saved correctly if I double-click the .exe.

Is it because the installer launches the application as "System" user?

How do I solve this?

答:
You should say which registry entries your code is trying to update, but if they are HKCU entries, for example, you are going to see differences running with the system account. </p>

<p>It is also unclear why you need a program to create registry entries when the setup will do this for you and it will just work. In Visual Studio setup projects that's in the Registry view. Many of the values you may want to store in the registry might be available as standard Windows Installer properties, and store them using the square bracket syntax, such as [TARGETDIR]. </p>

Body:
You should say which registry entries your code is trying to update, but if they are HKCU entries, for example, you are going to see differences running with the system account.

It is also unclear why you need a program to create registry entries when the setup will do this for you and it will just work. In Visual Studio setup projects that's in the Registry view. Many of the values you may want to store in the registry might be available as standard Windows Installer properties, and store them using the square bracket syntax, such as [TARGETDIR].


问:
Angular 4 - Propagate Selection Up in PrimeNG Tree not working
The propagateSelectionUp setting is not selecting the above node / parent when data is populated from a json file. There is a property "parent" of typ TreeNode, but i'm not sure how to add that in the json file.

I have printed the node object to the console to be able to discover methods and properties, and saw that the "node.parent" is undefined... is there a method for setting the parent?

```<code><p-tree [value]="filesTree11" layout="horizontal" selectionMode="checkbox" [(selection)]="selectedFile3" [propagateSelectionUp]="true" [propagateSelectionDown]="false" (click)="test()"></p-tree>
</code>```

答:
I also ran into the node.parent == null issue with layout="horizontal" today. I don't think it's intended to be that way.

Probably you've got your own way around it by now. If not (or whoever might need it later): Here are two ways of setting the parent-node:

Quick-n-dirty: You could insert another tree-component into your .html file which acesses the same nodes as your horizontal tree. Then hide it using style:

 [value]="filesTree11" [style]="{'display': 'none'}"
.

This said, it's an ugly and certainly not permanent solution. But for proof-of-concept or testing I don't see why not...

The thorough approach: Iterate and set the parent property recursively through the nodes just after assigning the json data to filesTree11 by calling this.processTreeNodes(filesTree11, null):

```<code>private processTreeNodes(treeNode: TreeNode[], parent: TreeNode) {
    for (const node of treeNode) {
        if (parent != null) {
            node.parent = parent;
        }
        if (node.children.length > 0) {
            this.processTreeNodes(node.children, node);
     }
}
</code>```

To verify if node.parent has been set, you could call this function after the one above:

```<code>private checkTreeNodes(treeNode: TreeNode[]) {
  for (const node of treeNode) {
    node.parent != null ?
        console.log('>> ' + node.parent.label + ' > ' + node.label) :
        console.log('>> ' + 'null');
    if (node.children.length > 0) {
      this.checkTreeNodes(node.children);
    }
  }
}
</code>```

The "manual" approach has the advantage of letting you set a couple of additional properties, like expanded, data, type, ...

Body:
I also ran into the node.parent == null issue with layout="horizontal" today. I don't think it's intended to be that way.

Probably you've got your own way around it by now. If not (or whoever might need it later): Here are two ways of setting the parent-node:

Quick-n-dirty: You could insert another tree-component into your .html file which acesses the same nodes as your horizontal tree. Then hide it using style:

<p-tree> [value]="filesTree11" [style]="{'display': 'none'}"</p-tree>.

This said, it's an ugly and certainly not permanent solution. But for proof-of-concept or testing I don't see why not...

The thorough approach: Iterate and set the parent property recursively through the nodes just after assigning the json data to filesTree11 by calling this.processTreeNodes(filesTree11, null):

private processTreeNodes(treeNode: TreeNode[], parent: TreeNode) {
    for (const node of treeNode) {
        if (parent != null) {
            node.parent = parent;
        }
        if (node.children.length > 0) {
            this.processTreeNodes(node.children, node);
     }
}

To verify if node.parent has been set, you could call this function after the one above:

private checkTreeNodes(treeNode: TreeNode[]) {
  for (const node of treeNode) {
    node.parent != null ?
        console.log('>> ' + node.parent.label + ' > ' + node.label) :
        console.log('>> ' + 'null');
    if (node.children.length > 0) {
      this.checkTreeNodes(node.children);
    }
  }
}

The "manual" approach has the advantage of letting you set a couple of additional properties, like expanded, data, type, ...


问:
change default color for RTE text in craftercms
How can we change the default color of RTE text color option "A".
Please consider attached screen shot for more details.

Screen Shot

答:
Ideally, you want authors to use the style sheet to set the color of items rather than using markup in the RTE (like the forecolor plugin)

To import your stylesheet into the RTE follow this guide:
http://docs.craftercms.org/en/3.0/site-administrators/studio/rte-setup.html

in the setup your RTE is using (general by default)

```<code><rteStylesheets> <!-- This informs the RTE to use the CSS files -->
  <link>
    <loadFromPreview>true</loadFromPreview>
    <url>/static-assets/css/main.css</url>
  </link>
</rteStylesheets>
</code>```

Once you point the config to the style sheet in static assets you H1s etc should be styled appropriately.  Note sometimes style sheets are overly specific and you need to take additional steps.

So for example the style sheet has:

```<code>body {
  color:red;
}
</code>```

The RTE's text will be red.  If someone updates the CSS, the RTE will update too.

Body:
Ideally, you want authors to use the style sheet to set the color of items rather than using markup in the RTE (like the forecolor plugin)

To import your stylesheet into the RTE follow this guide:
http://docs.craftercms.org/en/3.0/site-administrators/studio/rte-setup.html

in the setup your RTE is using (general by default)

<rteStylesheets> <!-- This informs the RTE to use the CSS files -->
  <link>
    <loadFromPreview>true</loadFromPreview>
    <url>/static-assets/css/main.css</url>
  </link>
</rteStylesheets>

Once you point the config to the style sheet in static assets you H1s etc should be styled appropriately.  Note sometimes style sheets are overly specific and you need to take additional steps.

So for example the style sheet has:

body {
  color:red;
}

The RTE's text will be red.  If someone updates the CSS, the RTE will update too.


问:
Uber: how to obtain user's favorite locations to place in deeplinking URI
I'm currently making an app that includes a feature for the user to be able to take an Uber home with the click of a button. I learned that deeplinking does the trick. However, I'm not quite sure how I can obtain the latitude and longitude of the user's home. I would greatly appreciate your help with regards to this matter. Have a nice day.
Shown is the method to get the uri for deeplinking.

```<code> private String getUberUri() {
    StringBuilder uberUri = new StringBuilder("uber://?action=setPickup&client_id=LNC3kco5fh8RGBhJF9hJtqRKPSPCxMt-");
    uberUri.append("&pickup=my_location");
    uberUri.append("&dropoff[nickname]=").append(placeBundle.getString("NAME", "Dropoff"));
    uberUri.append("&dropoff[latitude]=").append(placeBundle.getDouble("PLACE_LAT"));
    uberUri.append("&dropoff[longitude]=").append(placeBundle.getDouble("PLACE_LNG"));

    return uberUri.toString();
}
</code>```

This is the Button's onClickListener:

```<code>Button uberButton = (Button) findViewById(R.id.uberButton);
    uberButton.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (isPackageInstalled("com.ubercab")) {
                        Intent uberIntent = new Intent();
                        uberIntent.setData(Uri.parse(getUberUri()));
                        mActivity.startActivity(uberIntent);
                    } else {
                        Toast.makeText(mActivity, "Please install Uber", Toast.LENGTH_SHORT).show();
                        Uri uberPlayStoreUri = Uri.parse(
                                "https://play.google.com/store/apps/details?id=com.ubercab");
                        Intent uberIntent = new Intent(Intent.ACTION_VIEW, uberPlayStoreUri);
                        uberIntent.setPackage("com.android.vending");
                        mActivity.startActivity(uberIntent);
                    }
                }
            }
    );
</code>```

答:
There are two Uber API endpoints available to set work and home location and to get them.

If you want to set your home or work address you need to use: "PUT /v1.2/places/{place_id}" endpoint. Where "place_id" can be home and work.

To get your your predefined locations you need to use: "GET /v1.2/places/{place_id}"

Example request :

curl -H 'Authorization: Bearer ' \
     -H 'Accept-Language: en_US' \
     -H 'Content-Type: application/json' \
     'https://api.uber.com/v1.2/places/work'

Response:

{
   "address": "685 Market St, San Francisco, CA 94103, USA"
}

The only limitation is you will need to parse address to obtain "end_latitude" and  "end_longitude".

There is also option when you do your ride request to use following parameters:

"start_place_id": "home",
"end_place_id": "work"

Body:
I'm currently making an app that includes a feature for the user to be able to take an Uber home with the click of a button. I learned that deeplinking does the trick. However, I'm not quite sure how I can obtain the latitude and longitude of the user's home. I would greatly appreciate your help with regards to this matter. Have a nice day.
Shown is the method to get the uri for deeplinking.

 private String getUberUri() {
    StringBuilder uberUri = new StringBuilder("uber://?action=setPickup&client_id=LNC3kco5fh8RGBhJF9hJtqRKPSPCxMt-");
    uberUri.append("&pickup=my_location");
    uberUri.append("&dropoff[nickname]=").append(placeBundle.getString("NAME", "Dropoff"));
    uberUri.append("&dropoff[latitude]=").append(placeBundle.getDouble("PLACE_LAT"));
    uberUri.append("&dropoff[longitude]=").append(placeBundle.getDouble("PLACE_LNG"));

    return uberUri.toString();
}

This is the Button's onClickListener:

Button uberButton = (Button) findViewById(R.id.uberButton);
    uberButton.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (isPackageInstalled("com.ubercab")) {
                        Intent uberIntent = new Intent();
                        uberIntent.setData(Uri.parse(getUberUri()));
                        mActivity.startActivity(uberIntent);
                    } else {
                        Toast.makeText(mActivity, "Please install Uber", Toast.LENGTH_SHORT).show();
                        Uri uberPlayStoreUri = Uri.parse(
                                "https://play.google.com/store/apps/details?id=com.ubercab");
                        Intent uberIntent = new Intent(Intent.ACTION_VIEW, uberPlayStoreUri);
                        uberIntent.setPackage("com.android.vending");
                        mActivity.startActivity(uberIntent);
                    }
                }
            }
    );


问:
How to detect a cracked iPhone App and a jailbroken device (different methods)
I'm building a blacklisting service for cracked iPhone apps and I am curious if I missed a method for detecting cracked apps.

In the moment following app crack detection methods are available for the service:

checking plist size

checking signer identity

checking if binary is crypted (not sure if this is working correctly since no cracked app got detected this way)

checking modified date of info.plist against modified date of package (not sure if this is working - used code like: http://snippie.net/snip/f7530ff2 to do that)

I also wonder if it is possible to check if the device is jailbroken?
This would help, too, because the service will work much like a spam blacklist and jailbreak could be used to increase the score.

I have also included a honeypot, which shows me that the tools used by the crackers eliminate some of the checks I do.  For instance the plist check for size or signer identity.

My question is now:

Are there more "good" checks I should use?

and

Is there a way to detect Jailbreak?

答:
NEVER try and block jailbroken devices from using your app, just cracked ones. If you block jailbroken devices they'll be forced to use a patched version with all the checks removed.

Also ALL my devices are jailbroken so if a developer blocks jailbroken devices I would have to ignore their apps.
Over 10% of all iDevices are jailbroken so this is a very bad idea.

EDIT: As I'm getting lots of down votes for this I'll post some methods to detect a jailbreak.

```<code>- (BOOL)fileExistsAtPath:(NSString *)path{
    NSLog(@"Check if file '%@' exists", path);

    struct stat buffer;
    return stat([path UTF8String], &buffer) == 0;
}

- (BOOL)jailbroken{
    return ([self fileExistsAtPath:@"/Applications/Cydia.app"]);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
NEVER try and block jailbroken devices from using your app, just cracked ones. If you block jailbroken devices they'll be forced to use a patched version with all the checks removed.

Also ALL my devices are jailbroken so if a developer blocks jailbroken devices I would have to ignore their apps.
Over 10% of all iDevices are jailbroken so this is a very bad idea.

EDIT: As I'm getting lots of down votes for this I'll post some methods to detect a jailbreak.

- (BOOL)fileExistsAtPath:(NSString *)path{
    NSLog(@"Check if file '%@' exists", path);

    struct stat buffer;
    return stat([path UTF8String], &buffer) == 0;
}

- (BOOL)jailbroken{
    return ([self fileExistsAtPath:@"/Applications/Cydia.app"]);
}