问:
Django Pagination works for first page, does not second page
I have a search view that allows user's to search for their notecards, and then displays results paginated 6 at a time.

I use pagination in all my other views and it works correctly. However, when using it with the query it displays the first 6 results, displays "Page 1 of 2" and the next button, but when you click Next you get no results found.

I've setup the '*' query as a search-all, and when I search for that query the first request call is:

http://127.0.0.1:8000/search/?q=*

When I click next, the call is:

http://127.0.0.1:8000/search/?page=2

The search url is:

url(r'^search/', 'notecard.search.views.search', name="search"),

The search view is:

```<code>@login_required(login_url='/auth/login/')
def search(request):
    query = request.GET.get('q', '')
    results = []
    notecard_list = []
    if query:
        if query == "*":
            results = Notecard.objects.filter(section__semester__user=request.user)
        else:
            results = Notecard.objects.filter(Q(section__semester__user=request.user), Q(notecard_body__icontains=query)|Q(notecard_name__icontains=query))
        paginator = Paginator(results, 6)

        try:
            page = int(request.GET.get('page', '1'))
        except ValueError:
            page = 1

        try:
            notecard_list = paginator.page(page)
        except (EmptyPage, InvalidPage):
            notecard_list = paginator.page(paginator.num_pages)
    return list_detail.object_list(
        request,
        queryset = Notecard.objects.filter(section__semester__user=request.user),
        template_name = "notecards/search.html",
        template_object_name = "results",
        extra_context = {"results": results, "notecard_list": notecard_list,},
    )
</code>```

and the search template is:

```<code>{% extends "base.html" %}
{% block title %} Notecard List | {% endblock %}

{% block content %}
<div id='main'>
<table id='notecards'>
  <tr>
        <th class="name">Search Results</th>
  </tr>
</table>

<table id='known_split'>
        <p>Search results:<a class="edit" href="{% url semester_list %}">Back to Semesters</a></p>
            {% for result in notecard_list.object_list %}
                    <tr>
                        <td class="image">{% if result.known %}<img src="{{ STATIC_URL }}/images/known.png" width="41" height="40" />{% else %}<img src="{{ STATIC_URL }}/images/unknown.png" width="41" height="40" />{% endif %}</td>
                    <td class="text"><a href="{% url notecards.views.notecard_detail result.id %}">{{ result.notecard_name|truncatewords:9 }}</a></td>
                    </tr>
                {% endfor %}
</table>

<div class="pagination">
  <span class="step-links">
{% if notecard_list.has_previous %}
<a class="navlink" href="?page={{ notecard_list.previous_page_number }}">previous</a>
{% endif %}

<span class="current">
Page {{ notecard_list.number }} of {{ notecard_list.paginator.num_pages }}
</span>

{% if notecard_list.has_next %}
<a class="navlink" href="?page={{ notecard_list.next_page_number }}">next</a>
{% endif %}
  </span>
</div>

{% endblock %}
</code>```

As I said, I use basically the same pagination in every other view successfully, so I have to believe this is due to the query somehow.

答:
Need to include q argument in has_previous & has_next URL's,

```<code><a class="navlink" href="?page={{ notecard_list.previous_page_number }}&q1={{ request.GET.q1 }}">previous</a>
</code>```

and,

```<code><a class="navlink" href="?page={{ notecard_list.next_page_number }}&q1={{ request.GET.q1 }}">next</a>
</code>```

Body:
I have a search view that allows user's to search for their notecards, and then displays results paginated 6 at a time.

I use pagination in all my other views and it works correctly. However, when using it with the query it displays the first 6 results, displays "Page 1 of 2" and the next button, but when you click Next you get no results found.

I've setup the '*' query as a search-all, and when I search for that query the first request call is:

http://127.0.0.1:8000/search/?q=*

When I click next, the call is:

http://127.0.0.1:8000/search/?page=2

The search url is:

url(r'^search/', 'notecard.search.views.search', name="search"),

The search view is:

@login_required(login_url='/auth/login/')
def search(request):
    query = request.GET.get('q', '')
    results = []
    notecard_list = []
    if query:
        if query == "*":
            results = Notecard.objects.filter(section__semester__user=request.user)
        else:
            results = Notecard.objects.filter(Q(section__semester__user=request.user), Q(notecard_body__icontains=query)|Q(notecard_name__icontains=query))
        paginator = Paginator(results, 6)

        try:
            page = int(request.GET.get('page', '1'))
        except ValueError:
            page = 1

        try:
            notecard_list = paginator.page(page)
        except (EmptyPage, InvalidPage):
            notecard_list = paginator.page(paginator.num_pages)
    return list_detail.object_list(
        request,
        queryset = Notecard.objects.filter(section__semester__user=request.user),
        template_name = "notecards/search.html",
        template_object_name = "results",
        extra_context = {"results": results, "notecard_list": notecard_list,},
    )

and the search template is:

{% extends "base.html" %}
{% block title %} Notecard List | {% endblock %}

{% block content %}

        Search Results

Search results:Back to Semesters

            {% for result in notecard_list.object_list %}

                        {% if result.known %}{% else %}{% endif %}
                    {{ result.notecard_name|truncatewords:9 }}

                {% endfor %}

{% if notecard_list.has_previous %}
previous
{% endif %}

Page {{ notecard_list.number }} of {{ notecard_list.paginator.num_pages }}

{% if notecard_list.has_next %}
next
{% endif %}

{% endblock %}

As I said, I use basically the same pagination in every other view successfully, so I have to believe this is due to the query somehow.

Body:
Need to include q argument in has_previous & has_next URL's,

<a class="navlink" href="?page={{ notecard_list.previous_page_number }}&q1={{ request.GET.q1 }}">previous</a>

and,

<a class="navlink" href="?page={{ notecard_list.next_page_number }}&q1={{ request.GET.q1 }}">next</a>


来源: stackexchange

问:
How to apply CSS changes in every posts (every posts ID)
I want to hide the side bar and stretch the content box to full width to all posts from my WP blog. To individual posts that's what I'm doing, and it's working fine:

```<code>.postid-72 #main-sidebar {
display: none;
}
.postid-72 #main-content {
width: 100%;
}
</code>```

But I'm looking for some way to apply this changes to all my blog posts, something hypothetical like this:

```<code>.postid-**every id posts** #main-sidebar {
display: none;
}
.postid-**every id posts** #main-content {
width: 100%;
}
</code>```

I know that is possible to do something like this, which isn't usefull for me:

```<code>.postid-72, .postid-53, .postid-115 #main-sidebar {
display: none;
}
</code>```

答:
Every "single post" has a body class of single-post. So you could just do:

```<code>.single-post #main-sidebar {
  display:none;
}
.single-post #main-content {
  width:100%;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to hide the side bar and stretch the content box to full width to all posts from my WP blog. To individual posts that's what I'm doing, and it's working fine:

.postid-72 #main-sidebar {
display: none;
}
.postid-72 #main-content {
width: 100%;
}

But I'm looking for some way to apply this changes to all my blog posts, something hypothetical like this:

.postid-**every id posts** #main-sidebar {
display: none;
}
.postid-**every id posts** #main-content {
width: 100%;
}

I know that is possible to do something like this, which isn't usefull for me:

.postid-72, .postid-53, .postid-115 #main-sidebar {
display: none;
}

Body:
Every "single post" has a body class of single-post. So you could just do:

.single-post #main-sidebar {
  display:none;
}
.single-post #main-content {
  width:100%;
}


问:
Sorting MySQL results in PHP...?
I have a page on my site that lists a bunch of products, each with a user rating. I use one query to pull some data points for each product ("details query"), and a second query that returns the average user rating for each product ("ratings query").

I want to append the user rating for each product onto the "details query" result set, then sort by rating in descending order. I've read a bunch of entries on Stack Overflow, php.net etc. and I think I need to use usort() with a custom function, but every time I pass my MySQL result to usort() I get a php error saying the object I'm passing to usort() isn't an array. For example, I've tried:

```<code>$data = mysql_fetch_array($details_query);
usort($data,"compare");
</code>```

Doing the above will throw an error saying $data isn't an array. What am I doing wrong?

Also, if anyone has any other suggestions on how to get this done I'd really appreciate. I'm having a really tough time with this for some reason...

Thanks!

答: Have you tried outputting the $data array so you can see it with print_r()?  Sounds like $data may be empty, hence not an array.  If that's the case, either the result set is empty, or there's a problem with your query.</p>

ContentLicense: CC BY-SA 2.5

Title: Sorting MySQL results in PHP...?

Body:
I have a page on my site that lists a bunch of products, each with a user rating. I use one query to pull some data points for each product ("details query"), and a second query that returns the average user rating for each product ("ratings query").

I want to append the user rating for each product onto the "details query" result set, then sort by rating in descending order. I've read a bunch of entries on Stack Overflow, php.net etc. and I think I need to use usort() with a custom function, but every time I pass my MySQL result to usort() I get a php error saying the object I'm passing to usort() isn't an array. For example, I've tried:

$data = mysql_fetch_array($details_query);
usort($data,"compare");

Doing the above will throw an error saying $data isn't an array. What am I doing wrong?

Also, if anyone has any other suggestions on how to get this done I'd really appreciate. I'm having a really tough time with this for some reason...

Thanks!


问:
Is there a way to see if MySQL database has been accessed through SQL Injection attack?
I recently discovered that my website had a page with a SQL Injection vulnerability. Upon testing, it was easily exploitable with a pentesting tool like sqlmap. How do I figure out if the site database has been accessed with a SQL Injection attack, possibly exploiting this loophole? The server is running Apache/2.4.18 and MySQL Ver 14.14 Distrib 5.7.16.

答:
No, there's not really a sure way to detect an SQL injection attack.

Some methods that approximate detection rely on keeping a "whitelist" of known legitimate SQL queries that your applications run. Then if the query logs contain any that are not known, that's potentially an clue that they came from an illicit source. Or else they could have been run by the DBA in a query tool.

It also requires that you log every SQL query, and that you had prepared the whitelist of known good queries.

As @alexn commented above, you could review your Apache logs (if you suppose the SQL injection came directly from an http request, which not all SQL injection vulnerabilities do). To do this, you would search for all the http requests in the logs that could have exploited the vulnerability you say you found in your code, and then with that search result, filter out all those that look like they had legitimate requests (e.g. ?id=123 is good, but ?id=123 OR 1=1 is suspicious).

There are other products monitor query traffic and try to guess whether an SQL query is legitimate or a suspicious query while they're happening, but these are prone to false positives and false negatives.


问:
Is it possible to retrieve the user token in an app, after migrating an app from swift to react native?
We have an existing app written in Swift where the logged in user has their oAuth token stored in the app.

The app is now being redeveloped in React Native. If we release the app as a new version of the app in the App Store, when a user upgrades and installs the new version, can we get hold of the user token even though the app is completely differently architected?

答:
You could write a Native Module that reads the value from the native application and passes it to React Native.

More information about Native Modules for iOS here: http://facebook.github.io/react-native/docs/native-modules-ios.html


问:
Why OpenCV return strange value for pixel intensity?
I've c++ and OpenCV 3.1 and i separated the RGB three channels with these code :

```<code>Mat src = imread("original_image.jpg",CV_LOAD_IMAGE_COLOR);
Mat bgr[3] , bluemat ;
split(src,bgr);
bluemat = bgr[0];
std::cout << "bluemat.at<int>(0,1); : " << bluemat.at<int>(0,1) << '\n';
</code>```

The strange thing is it print out a big number : 1415208581 , why is that ?

Isn't it suppose to be in 0-255 range ? why it is not ?

答:
The main difference here is casting the memory byte to uchar vs int. What form the data you have depends on how you read it in. CV_LOAD_IMAGE_COLOR read the image as 16-bit/32-bit values. I cannot compile the code you gave me becuase of the memory issues that are created by converting that data to an int.

Now, if you use uchar, that will be solved. The problem however with the cout printing a character, has to do with the overload functions of <<

```<code>Mat src = imread("1.jpg", CV_LOAD_IMAGE_COLOR);

Mat bgr[3], bluemat;
split(src, bgr);
bluemat = bgr[0];
std::cout << "bluemat.at<uchar>(0,1); : " << (int)bluemat.at<uchar>(0, 1) << '\n';
</code>```

What I changed was just to insert the typecast int. This issue is expanded here, but tells the output stream that this is a number, not a character.

Body:
I've c++ and OpenCV 3.1 and i separated the RGB three channels with these code :

Mat src = imread("original_image.jpg",CV_LOAD_IMAGE_COLOR);
Mat bgr[3] , bluemat ;
split(src,bgr);
bluemat = bgr[0];
std::cout << "bluemat.at<int>(0,1); : " << bluemat.at<int>(0,1) << '\n';

The strange thing is it print out a big number : 1415208581 , why is that ?

Isn't it suppose to be in 0-255 range ? why it is not ?

Body:
The main difference here is casting the memory byte to uchar vs int. What form the data you have depends on how you read it in. CV_LOAD_IMAGE_COLOR read the image as 16-bit/32-bit values. I cannot compile the code you gave me becuase of the memory issues that are created by converting that data to an int.

Now, if you use uchar, that will be solved. The problem however with the cout printing a character, has to do with the overload functions of <<

Mat src = imread("1.jpg", CV_LOAD_IMAGE_COLOR);

Mat bgr[3], bluemat;
split(src, bgr);
bluemat = bgr[0];
std::cout << "bluemat.at<uchar>(0,1); : " << (int)bluemat.at<uchar>(0, 1) << '\n';

What I changed was just to insert the typecast int. This issue is expanded here, but tells the output stream that this is a number, not a character.


问:
electron browser javascript error
I am very new to node, javascript, and electron. I am just trying to write a simple app that opens a local HTML file in a browser window. The local file has some complex embedded javascript (tiddlywiki). Here is some sample code (I did not use local file in this one, but the result is the same):

```<code>const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')

let win

function createWindow () {
// Create the browser window.
win = new BrowserWindow({width: 800, height: 600})

// and load the index.html of the app.
win.loadURL(url.format({
    pathname: 'tiddlywiki.com',
    protocol: 'http:',
    slashes: true,
    webPreferences: {
      nodeIntegration: false,
 }
 }))
</code>```

When the electron app launches I get the following error in the browser dev tools.

```<code>Uncaught TypeError: Cannot read property 'length' of undefined
    at Object.$tw.boot.startup (tiddlywiki.com/:27506)
    at tiddlywiki.com/:27765
    at Object.$tw.boot.decryptEncryptedTiddlers (tiddlywiki.com/:27053)
    at Object.$tw.boot.boot (tiddlywiki.com/:27763)
    at _boot (tiddlywiki.com/:27772)
    at tiddlywiki.com/:27782
</code>```

I assume this is because of some integration of the node.js object model? Sorry for the lack of understanding. Thanks in advance for the help.

答:
The way I ended up solving this was to use the following code in main.js:

```<code> win.loadURL(url.format({
    pathname: path.join(__dirname, 'index2.html'),
    protocol: 'file:',
    slashes: true
}))
</code>```

then index2 contains the following:

```<code><html>
  <body>
    <webview id="webView" src="http://tiddlywiki.com" style="display:inline-flex; width:100%; height:100%" </webview>
  </body>
</html>
</code>```

Also tested with a local file:empty.html from tiddlywiki.com and that worked OK. I think this gives me the ability to preLoad a .js file to control some of the tiddlywiki events. Will have to learn more to test that out.

Title: electron browser javascript error

Body:
I am very new to node, javascript, and electron. I am just trying to write a simple app that opens a local HTML file in a browser window. The local file has some complex embedded javascript (tiddlywiki). Here is some sample code (I did not use local file in this one, but the result is the same):

const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')

let win

function createWindow () {
// Create the browser window.
win = new BrowserWindow({width: 800, height: 600})

// and load the index.html of the app.
win.loadURL(url.format({
    pathname: 'tiddlywiki.com',
    protocol: 'http:',
    slashes: true,
    webPreferences: {
      nodeIntegration: false,
 }
 }))

When the electron app launches I get the following error in the browser dev tools.

Uncaught TypeError: Cannot read property 'length' of undefined
    at Object.$tw.boot.startup (tiddlywiki.com/:27506)
    at tiddlywiki.com/:27765
    at Object.$tw.boot.decryptEncryptedTiddlers (tiddlywiki.com/:27053)
    at Object.$tw.boot.boot (tiddlywiki.com/:27763)
    at _boot (tiddlywiki.com/:27772)
    at tiddlywiki.com/:27782

I assume this is because of some integration of the node.js object model? Sorry for the lack of understanding. Thanks in advance for the help.

Body:
The way I ended up solving this was to use the following code in main.js:

 win.loadURL(url.format({
    pathname: path.join(__dirname, 'index2.html'),
    protocol: 'file:',
    slashes: true
}))

then index2 contains the following:

<html>
  <body>
    <webview id="webView" src="http://tiddlywiki.com" style="display:inline-flex; width:100%; height:100%" </webview>
  </body>
</html>

Also tested with a local file:empty.html from tiddlywiki.com and that worked OK. I think this gives me the ability to preLoad a .js file to control some of the tiddlywiki events. Will have to learn more to test that out.


问:
How to compare two hash sets in java?
How can I compare two hash sets in java ? My first hash sets looks like below.

```<code>static Set<String> nounPhrases = new HashSet<>();
</code>```

Above hash set contains elements like this.

List of Noun Parse : [java, jsp, book]

2nd hash set

```<code>static Set<String> nounPhrases2 = new HashSet<>();
</code>```

List of Noun Parse : [web, php, java,book]

Note - I need to check if there are equal nouns in both sets. and if they have similar nouns then I need to do another task

答:
If u want to find the common element then use collect(Collectors.toList()) instead of count , If u want simply to find how many set has common element using java 8</p>

```<code>long count = nounPhrases.stream().filter(tempstring -> {
            return nounPhrases2.stream().anyMatch(tempstring2 -> {
                return tempstring.equals(tempstring2);
            });
        }).count();
        if (count > 0)
            System.out.println("has common elements-"+count);
        else
            System.out.println("not common");
</code>```

Title: How to compare two hash sets in java?

Body:
How can I compare two hash sets in java ? My first hash sets looks like below.

static Set<String> nounPhrases = new HashSet<>();

Above hash set contains elements like this.

List of Noun Parse : [java, jsp, book]

2nd hash set

static Set<String> nounPhrases2 = new HashSet<>();

List of Noun Parse : [web, php, java,book]

Note - I need to check if there are equal nouns in both sets. and if they have similar nouns then I need to do another task

Body:
If u want to find the common element then use collect(Collectors.toList()) instead of count , If u want simply to find how many set has common element using java 8

long count = nounPhrases.stream().filter(tempstring -> {
            return nounPhrases2.stream().anyMatch(tempstring2 -> {
                return tempstring.equals(tempstring2);
            });
        }).count();
        if (count > 0)
            System.out.println("has common elements-"+count);
        else
            System.out.println("not common");


问:
PHP add first table column id to another table column id
There are 2 Table in the Database.

tbl_second_category

tbl_third_category

I'm already passing
col_first_category_id
from
table1 tbl_second_category
to
Table2 tbl_third_category col_second_category_id
using select box control
You can see id 13 in both the Tables

when I'm passing above id, at the same time how can I pass col_second_category_id from Table1
tbl_second_category to column col_for_delete_row Table2 tbl_third_category.

Thank you

答:
then use trigger, you may need more then one for update and delete events... for example: </p>

```<code>CREATE TRIGGER trigger_name AFTER INSERT ON tbl_second_category
FOR EACH ROW
UPDATE tbl_third_category
SET col_for_delete_row  = NEW.col_second_category_id
WHERE col_second_category_id = NEW.col_first_category_id;
</code>```

Body:
then use trigger, you may need more then one for update and delete events... for example:

CREATE TRIGGER trigger_name AFTER INSERT ON tbl_second_category
FOR EACH ROW
UPDATE tbl_third_category
SET col_for_delete_row  = NEW.col_second_category_id
WHERE col_second_category_id = NEW.col_first_category_id;


问:
Laravel Queue:work is consuming all my RAM
I am experiencing an issue with Laravel 5.4 and I am hoping that someone can help. I have a laravel 5.4 project where I send emails using queue and execute various commands like below:

```<code>1. Kernel.php

protected function schedule(Schedule $schedule)
{
    // $schedule->command('inspire')
    //          ->hourly();

    $schedule->command('queue:work')->everyMinute();

    // Execute command at midnight daily to reject expired applications
    $schedule->command('application:reject')->daily();
}
</code>```

In /etc/crontab, I have got the following:

* * * * * bob cd /opt/lampp/htdocs/oap/ && /usr/local/bin/php artisan schedule:run >> /dev/null 2>&1
* * * * * bob cd /opt/lampp/htdocs/ims/ && /usr/local/bin/php artisan schedule:run >> /dev/null 2>&1

When I view my linux system monitor, I notice that every minute, a new php process is started and takes 13.8MB of memory. In about an hour I begin to see my free memory very low. The processes are /opt/lampp/bin/php-7.1.4 artisan queue:work and /usr/local/bin/php artisan schedule:run

When the above happens, I would run artisan queue:restart and all the php processes would be killed.

What can be the cause of this?

This is weird to me because I have this same code in Laravel 5.1 and I am not experiencing this. What can I do to solve this?

答:
Your problem is that You're scheduling some command in code.

Some kind of scheduling inside the code that being scheduled every minute. (:

In 5.1 it was working because of there were 2 commands: queue:listen that was living long and queue:work that was working until queue is empty.

Seems like laravel team going to remove queue:listen

So here is solution:

1) Just remove Your code from Kernel.php and schedule it as normal artisan call:

```<code># daily
0 0 * * * bob cd /opt/lampp/htdocs/ims/ && /usr/local/bin/php artisan application:reject >> /dev/null 2>&1
</code>```

2) Run manually or supervise queue:work with supervisor:

```<code>cd /opt/lampp/htdocs/oap/ && nohup php artisan queue:work &
</code>```

Body:
I am experiencing an issue with Laravel 5.4 and I am hoping that someone can help. I have a laravel 5.4 project where I send emails using queue and execute various commands like below:

1. Kernel.php

protected function schedule(Schedule $schedule)
{
    // $schedule->command('inspire')
    //          ->hourly();

    $schedule->command('queue:work')->everyMinute();

    // Execute command at midnight daily to reject expired applications
    $schedule->command('application:reject')->daily();
}

In /etc/crontab, I have got the following:

* * * * * bob cd /opt/lampp/htdocs/oap/ && /usr/local/bin/php artisan schedule:run >> /dev/null 2>&1
* * * * * bob cd /opt/lampp/htdocs/ims/ && /usr/local/bin/php artisan schedule:run >> /dev/null 2>&1

When I view my linux system monitor, I notice that every minute, a new php process is started and takes 13.8MB of memory. In about an hour I begin to see my free memory very low. The processes are /opt/lampp/bin/php-7.1.4 artisan queue:work and /usr/local/bin/php artisan schedule:run

When the above happens, I would run artisan queue:restart and all the php processes would be killed.

What can be the cause of this?

This is weird to me because I have this same code in Laravel 5.1 and I am not experiencing this. What can I do to solve this?

Body:
Your problem is that You're scheduling some command in code.

Some kind of scheduling inside the code that being scheduled every minute. (:

In 5.1 it was working because of there were 2 commands: queue:listen that was living long and queue:work that was working until queue is empty.

Seems like laravel team going to remove queue:listen

So here is solution:

1) Just remove Your code from Kernel.php and schedule it as normal artisan call:

# daily
0 0 * * * bob cd /opt/lampp/htdocs/ims/ && /usr/local/bin/php artisan application:reject >> /dev/null 2>&1

2) Run manually or supervise queue:work with supervisor:

cd /opt/lampp/htdocs/oap/ && nohup php artisan queue:work &


答:
The queue worker is a daemon which will keep polling. Stop running queue workers using cron. They're long-lived processes and you run workers based on your requirements from your server, not spawning a new worker every minute.

https://laravel.com/docs/5.4/queues#running-the-queue-worker

Read the documentation. If you're not too familiar then just install Supervisor and let it handle all the work.

Title: Laravel Queue:work is consuming all my RAM


问:
Slack bot that goes out and reads data from external page then posts?
I have an external website that has some dynamic data on it that refreshes regularly. I'd like to set up a Slack bot reaches out to that site (maybe by a curl or with screen scraping) and return the first line of data into a message in a channel.

I browsed some integrations and I haven't found anything that fits the bill quite yet. I don't have control over the external site to put a send to Slack button on it.

Thanks!

答:
If you are writing your bot in Go, you are more than welcome to use my Slack Bot framework https://github.com/shomali11/slacker

You can easily create a bot that responds to mentions and direct messages then respond back.

For example:

```<code>package main

import (
    "github.com/shomali11/slacker"
    "log"
)

func main() {
    bot := slacker.NewClient("<YOUR SLACK BOT TOKEN>")

    bot.Command("ping", "Ping!", func(request *slacker.Request, response *slacker.Response) {
        response.Reply("pong")
    })

    bot.Command("read <url>", "Read content of a URL", func(request *slacker.Request, response *slacker.Response) {
        urlContent := readData(request.Param("url"))
        response.Reply(urlContent)
    })

    err := bot.Listen()
    if err != nil {
        log.Fatal(err)
    }
}
</code>```

As for the readData method, reading data from external pages should be relatively straightforward in Go. Here is an example using gorequest:

```<code>request := gorequest.New()
response, body, errs := request.Get("http://example.com/").End()
</code>```

Body:
If you are writing your bot in Go, you are more than welcome to use my Slack Bot framework https://github.com/shomali11/slacker

You can easily create a bot that responds to mentions and direct messages then respond back.

For example:

package main

import (
    "github.com/shomali11/slacker"
    "log"
)

func main() {
    bot := slacker.NewClient("<YOUR SLACK BOT TOKEN>")

    bot.Command("ping", "Ping!", func(request *slacker.Request, response *slacker.Response) {
        response.Reply("pong")
    })

    bot.Command("read <url>", "Read content of a URL", func(request *slacker.Request, response *slacker.Response) {
        urlContent := readData(request.Param("url"))
        response.Reply(urlContent)
    })

    err := bot.Listen()
    if err != nil {
        log.Fatal(err)
    }
}

As for the readData method, reading data from external pages should be relatively straightforward in Go. Here is an example using gorequest:

request := gorequest.New()
response, body, errs := request.Get("http://example.com/").End()


问:
Tomcat 8 Unicode filename war file deploy issue
On Linux(openSUSE) machine I'm trying to deploy on Tomcat 8 application(war file) that contains a files with names with Unicode characters.

Inside of the war file the name looks like:

```<code>бжк-природний-1496336830201.xml
</code>```

but after deploy the file looks like:

```<code>???-?????????????-1496336830201.xml
</code>```

How to tell Tomcat to properly deploy the file names ?

UPDATED

This is a sample war file with Unicode file name inside: war file

What is wrong with the file name of the file inside in this war ?

UPDATED

I have installed unzip-rcc as it was suggested here https://superuser.com/questions/1215670/opensuse-unzip-unicode-issue and now unzip(console command) on the WAR file is working fine but Tomcat still deploy the files with the same issue.

答:
Try putting these settings in Tomcat startup script:

```<code>export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8
</code>```

From experience, Java will print up-side-down question mark for characters it does not know how to encode.

Body:
On Linux(openSUSE) machine I'm trying to deploy on Tomcat 8 application(war file) that contains a files with names with Unicode characters.

Inside of the war file the name looks like:

бжк-природний-1496336830201.xml

but after deploy the file looks like:

???-?????????????-1496336830201.xml

How to tell Tomcat to properly deploy the file names ?

UPDATED

This is a sample war file with Unicode file name inside: war file

What is wrong with the file name of the file inside in this war ?

UPDATED

I have installed unzip-rcc as it was suggested here https://superuser.com/questions/1215670/opensuse-unzip-unicode-issue and now unzip(console command) on the WAR file is working fine but Tomcat still deploy the files with the same issue.

Body:
Try putting these settings in Tomcat startup script:

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8

From experience, Java will print up-side-down question mark for characters it does not know how to encode.


问:
How to get actual file path for pdf file in android?
I successfully got the actual address of Video file using this code.

```<code>Uri selectedVideo = data.getData();
String[] filePathColumn = {MediaStore.Video.Media.DATA};
Cursor cursor = getContentResolver().query(selectedVideo, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mediaPath1 = cursor.getString(columnIndex);
</code>```

Since Pdf is not media file i can't use MediaStore.

Using the below mentioned code gave me "content://com.android.providers.media.documents/....." as the path

Actually i am uploading pdf files using retrofit 2 to server.
When i hardcoded the address as shown in file manager to the mediapath1 i was able to upload the file successfully.

I found many solution for getting address from uri but none gave me the correct address.

Thanks in advance.

```<code>Uri uri = data.getData();
File file = new File(uri.toString());
mediaPath1 = file.getAbsolutePath();
uploadPdf();
</code>```

答:
After spending hours i finally got the answer.

http://www.limbaniandroid.com/2014/03/how-to-get-absolute-path-when-select.html

```<code>import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

public class ImageFilePath
{

 /**
  * Method for return file path of Gallery image
  *
  * @param context
  * @param uri
  * @return path of the selected image file from gallery
  */
 public static String getPath(final Context context, final Uri uri)
 {

  //check here to KITKAT or new version
  final boolean isKitKat = Build.VERSION.SDK_INT >=
  Build.VERSION_CODES.KITKAT;

  // DocumentProvider
  if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {

   // ExternalStorageProvider
   if (isExternalStorageDocument(uri)) {
   final String docId = DocumentsContract.getDocumentId(uri);
   final String[] split = docId.split(":");
   final String type = split[0];

   if ("primary".equalsIgnoreCase(type)) {
    return Environment.getExternalStorageDirectory() + "/" + split[1];
   }
  }
  // DownloadsProvider
  else if (isDownloadsDocument(uri)) {

   final String id = DocumentsContract.getDocumentId(uri);
   final Uri contentUri = ContentUris.withAppendedId(
   Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

   return getDataColumn(context, contentUri, null, null);
  }
  // MediaProvider
  else if (isMediaDocument(uri)) {
    final String docId = DocumentsContract.getDocumentId(uri);
    final String[] split = docId.split(":");
    final String type = split[0];

    Uri contentUri = null;
    if ("image".equals(type)) {
       contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    } else if ("video".equals(type)) {
       contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
    } else if ("audio".equals(type)) {
       contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    }

   final String selection = "_id=?";
   final String[] selectionArgs = new String[] {
   split[1]
 };

  return getDataColumn(context, contentUri, selection, selectionArgs);
 }
}
 // MediaStore (and general)
 else if ("content".equalsIgnoreCase(uri.getScheme())) {

     // Return the remote address
     if (isGooglePhotosUri(uri))
     return uri.getLastPathSegment();

    return getDataColumn(context, uri, null, null);
  }
  // File
  else if ("file".equalsIgnoreCase(uri.getScheme())) {
   return uri.getPath();
   }

   return null;
 }

 /**
  * Get the value of the data column for this Uri. This is useful for
  * MediaStore Uris, and other file-based ContentProviders.
  *
  * @param context The context.
  * @param uri The Uri to query.
  * @param selection (Optional) Filter used in the query.
  * @param selectionArgs (Optional) Selection arguments used in the query.
  * @return The value of the _data column, which is typically a file path.
  */
 public static String getDataColumn(Context context, Uri uri, String selection,
   String[] selectionArgs) {

  Cursor cursor = null;
  final String column = "_data";
  final String[] projection = {
   column
  };

  try {
   cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
 null);
   if (cursor != null && cursor.moveToFirst()) {
    final int index = cursor.getColumnIndexOrThrow(column);
   return cursor.getString(index);
   }
  } finally {
   if (cursor != null)
    cursor.close();
  }
  return null;
 }

 /**
  * @param uri The Uri to check.
  * @return Whether the Uri authority is ExternalStorageProvider.
  */
 public static boolean isExternalStorageDocument(Uri uri) {
  return "com.android.externalstorage.documents".equals(uri.getAuthority());
 }

 /**
  * @param uri The Uri to check.
  * @return Whether the Uri authority is DownloadsProvider.
  */
 public static boolean isDownloadsDocument(Uri uri) {
  return
"com.android.providers.downloads.documents".equals(uri.getAuthority());
 }

 /**
  * @param uri The Uri to check.
  * @return Whether the Uri authority is MediaProvider.
  */
 public static boolean isMediaDocument(Uri uri) {
  return "com.android.providers.media.documents".equals(uri.getAuthority());
 }

 /**
  * @param uri The Uri to check.
  * @return Whether the Uri authority is Google Photos.
  */
 public static boolean isGooglePhotosUri(Uri uri) {
  return
"com.google.android.apps.photos.content".equals(uri.getAuthority());
 }
}
</code>```

Body:
I successfully got the actual address of Video file using this code.

Uri selectedVideo = data.getData();
String[] filePathColumn = {MediaStore.Video.Media.DATA};
Cursor cursor = getContentResolver().query(selectedVideo, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mediaPath1 = cursor.getString(columnIndex);

Since Pdf is not media file i can't use MediaStore.

Using the below mentioned code gave me "content://com.android.providers.media.documents/....." as the path

Actually i am uploading pdf files using retrofit 2 to server.
When i hardcoded the address as shown in file manager to the mediapath1 i was able to upload the file successfully.

I found many solution for getting address from uri but none gave me the correct address.

Thanks in advance.

Uri uri = data.getData();
File file = new File(uri.toString());
mediaPath1 = file.getAbsolutePath();
uploadPdf();

Body:
After spending hours i finally got the answer.

http://www.limbaniandroid.com/2014/03/how-to-get-absolute-path-when-select.html

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

public class ImageFilePath
{

 /**
  * Method for return file path of Gallery image
  *
  * @param context
  * @param uri
  * @return path of the selected image file from gallery
  */
 public static String getPath(final Context context, final Uri uri)
 {

  //check here to KITKAT or new version
  final boolean isKitKat = Build.VERSION.SDK_INT >=
  Build.VERSION_CODES.KITKAT;

  // DocumentProvider
  if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {

   // ExternalStorageProvider
   if (isExternalStorageDocument(uri)) {
   final String docId = DocumentsContract.getDocumentId(uri);
   final String[] split = docId.split(":");
   final String type = split[0];

   if ("primary".equalsIgnoreCase(type)) {
    return Environment.getExternalStorageDirectory() + "/" + split[1];
   }
  }
  // DownloadsProvider
  else if (isDownloadsDocument(uri)) {

   final String id = DocumentsContract.getDocumentId(uri);
   final Uri contentUri = ContentUris.withAppendedId(
   Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

   return getDataColumn(context, contentUri, null, null);
  }
  // MediaProvider
  else if (isMediaDocument(uri)) {
    final String docId = DocumentsContract.getDocumentId(uri);
    final String[] split = docId.split(":");
    final String type = split[0];

    Uri contentUri = null;
    if ("image".equals(type)) {
       contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    } else if ("video".equals(type)) {
       contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
    } else if ("audio".equals(type)) {
       contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    }

   final String selection = "_id=?";
   final String[] selectionArgs = new String[] {
   split[1]
 };

  return getDataColumn(context, contentUri, selection, selectionArgs);
 }
}
 // MediaStore (and general)
 else if ("content".equalsIgnoreCase(uri.getScheme())) {

     // Return the remote address
     if (isGooglePhotosUri(uri))
     return uri.getLastPathSegment();

    return getDataColumn(context, uri, null, null);
  }
  // File
  else if ("file".equalsIgnoreCase(uri.getScheme())) {
   return uri.getPath();
   }

   return null;
 }

 /**
  * Get the value of the data column for this Uri. This is useful for
  * MediaStore Uris, and other file-based ContentProviders.
  *
  * @param context The context.
  * @param uri The Uri to query.
  * @param selection (Optional) Filter used in the query.
  * @param selectionArgs (Optional) Selection arguments used in the query.
  * @return The value of the _data column, which is typically a file path.
  */
 public static String getDataColumn(Context context, Uri uri, String selection,
   String[] selectionArgs) {

  Cursor cursor = null;
  final String column = "_data";
  final String[] projection = {
   column
  };

  try {
   cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
 null);
   if (cursor != null && cursor.moveToFirst()) {
    final int index = cursor.getColumnIndexOrThrow(column);
   return cursor.getString(index);
   }
  } finally {
   if (cursor != null)
    cursor.close();
  }
  return null;
 }

 /**
  * @param uri The Uri to check.
  * @return Whether the Uri authority is ExternalStorageProvider.
  */
 public static boolean isExternalStorageDocument(Uri uri) {
  return "com.android.externalstorage.documents".equals(uri.getAuthority());
 }

 /**
  * @param uri The Uri to check.
  * @return Whether the Uri authority is DownloadsProvider.
  */
 public static boolean isDownloadsDocument(Uri uri) {
  return
"com.android.providers.downloads.documents".equals(uri.getAuthority());
 }

 /**
  * @param uri The Uri to check.
  * @return Whether the Uri authority is MediaProvider.
  */
 public static boolean isMediaDocument(Uri uri) {
  return "com.android.providers.media.documents".equals(uri.getAuthority());
 }

 /**
  * @param uri The Uri to check.
  * @return Whether the Uri authority is Google Photos.
  */
 public static boolean isGooglePhotosUri(Uri uri) {
  return
"com.google.android.apps.photos.content".equals(uri.getAuthority());
 }
}

ContentLicense: CC BY-SA 4.0


问:
Flash app not updating well on server
I'm trying to learn as3 in flash development but I'm having a hard time following because of the refresh that's not working well in flash.

I have external as3 classes but when I edit something like content_txt.text = 'something else' it doesn't even change on the flash app on the server.

Even when I change the background color of my flash app, republish it and put in on the server to replace the old one. Still the old one is displayed.

How can I get around this? cause it's very frustrating to learn and develop stuff that won't cooperate. I'm trying to have facebook integration if anyone's asking.

答:
You could also check the answer to this question:

Fixing Flash's aggressive caching

Practically you can force Flash Player to reload the movie by appending parameters to the swf url. Several methods are offered in the answers , pick the one that suits you best!

Title: Flash app not updating well on server


问:
Open the VC by pressing a button from the XIB
Help me please.
There is a map with markers, clicking on them brings up a XIB = UIVIew, there is a button in it, you need to click the button to open the viewController</p>

答:
```<code>let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "MarkerVC")
self.navigationController?.pushViewController(vc, animated: true)
</code>```


问:
Flowtype nominal typing for primitive
I'm looking for the best solution to separate the usage of strings as identifiers for translated messages and literal text values.

So i might have an object field called title, which in this case refers to the title of a form and it will have the value SIGNUP_FORM_TITLE or MAIL_FORM_TITLE so it will refer to a localized string and will be passed to a function like format(id) which returns the actual localized text for the current locale.

But then i might also have an object field name which refers to a person's name and is not localized, so it might have the value John Doe.

How can i make sure i get a type error when i pass name to format(id), and vice versa when i pass title to an API that expects a plain (text) string.

I can't (of course) just say type LocalizationIdentifierType = string as this is just an alias.

Maybe i could make a subclass of string class LocalizationIdentifier extends String but this would still allow LocalizationIdentifier to be passed to a string based API (or at least i think thats the case).

Has anyone a better idea to sort of nominally type a string?
Or maybe i'm completely on the wrong track? ("Auf dem Holzweg" as we say in Germany)

There is a related question and a proposal to add similar functionality to typescript.
Choosing typescript over flowtype is, of course, not an option.

答:
Literal types almost work. You can specify the signature of format as

```<code>function format(id: "SIGNUP_FORM_TITLE" | "MAIL_FORM_TITLE" | ...): string {
   ...
}
</code>```

Unfortunately, this falls apart for your other case (localized text wrongly passed to the plain text API). An object literal type seem like the JavaScript path of least resistance:

```<code>type LocalizedString = {
  +field: "SIGNUP_FORM_TITLE" | "MAIL_FORM_TITLE"
};
type PlainText = string;

const signupFormTitle: LocalizedString = { field: "SIGNUP_FORM_TITLE" };
const mailFormTitle: LocalizedString = { field: "MAIL_FORM_TITLE" };
</code>```

If you need to introduce variations on LocalizedString, an additional tag field in the objects works nicely, e.g.:

```<code>type LocalizedString = {
  +variant: "variant1",
  +field: "SIGNUP_FORM_TITLE" | "MAIL_FORM_TITLE"
};
</code>```

Title: Flowtype nominal typing for primitive

Body:
Literal types almost work. You can specify the signature of format as

function format(id: "SIGNUP_FORM_TITLE" | "MAIL_FORM_TITLE" | ...): string {
   ...
}

Unfortunately, this falls apart for your other case (localized text wrongly passed to the plain text API). An object literal type seem like the JavaScript path of least resistance:

type LocalizedString = {
  +field: "SIGNUP_FORM_TITLE" | "MAIL_FORM_TITLE"
};
type PlainText = string;

const signupFormTitle: LocalizedString = { field: "SIGNUP_FORM_TITLE" };
const mailFormTitle: LocalizedString = { field: "MAIL_FORM_TITLE" };

If you need to introduce variations on LocalizedString, an additional tag field in the objects works nicely, e.g.:

type LocalizedString = {
  +variant: "variant1",
  +field: "SIGNUP_FORM_TITLE" | "MAIL_FORM_TITLE"
};


问:
Executing JavaScript on C# with CefSharp WPF causes Error
Whenever I try to execute JavaScript through C# using CefSharp (Stable 57.0), I get an error. I am simply trying to execute the alert function, so I can make sure that works and later test it out with my own function. However, I seem to be getting errors trying to do so.

```<code>public partial class WebBrowserWindow : Window
{
    public WebBrowserWindow()
    {
        InitializeComponent();
        webBrowser.MenuHandler = new ContextMenuHandler();
        webBrowser.RequestHandler = new RequestHandler();
    }

    //Trying to execute this with either method gives me an error.
    public void ExecuteJavaScript()
    {
        //webBrowser.GetMainFrame().ExecuteJavaScriptAsync("alert('test')");

        //webBrowser.ExecuteScriptAsync("alert('test');");
    }
}
</code>```

I have tried both ways of executing the script.

The first one:

```<code>webBrowser.GetMainFrame().ExecuteJavaScriptAsync("alert('test')");
</code>```

Gives me this error:

The second:

```<code>webBrowser.ExecuteScriptAsync("alert('test');");
</code>```

Gives me this error:

My objective is to create a C# function that can execute a JavaScript function in my CefSharp Browser.

I tried many links/references and there weren't that many on stack overflow. I also read The FAQ for CefSharp and couldn't find any simple examples that allow me to execute JavaScript at will through C#.

In addition, I've verified the events where the Frame is loaded (it finishes loading), and unloaded (it does not unload), and if the webbrowser is null (which it's not), and the message from the:

```<code>webBrowser.GetMainFrame().ExecuteJavaScriptAsync("alert('test')");
</code>```

still causes the first error to occur.

I tested for GetMainFrame(). It always returns null. ALWAYS. Doesn't matter how long I wait, or what conditions I check for.

IMPORTANT

I forgot to add one crucial piece of information, I have 2 assemblies in my project. Both of them compile into separate executables:

Helper.exe
Main.exe

main.exe has a window "CallUI" that, when a button gets clicked, it executes the method I created "ExecuteJavaScript()", which is inside of my window "BrowserWindow". The CallUI window is declared and initialized in Helper.exe.

So basically I am trying to use a separate program to open a window, click a button that calls the method and execute javascript. So I think because they are different processes, it tells me the browser is null. However, when I do it all in Main.exe it works fine. Is there a workaround that allows me to use the separate process to create the window from Helper.exe and execute the Javascript from Main.exe?

答:
Have you tried this link? Contains a snippet that checks if the browser is initialised first.

cefsharp execute javascript

```<code>private void OnIsBrowserInitializedChanged(object sender, IsBrowserInitializedChangedEventArgs args)
{
    if(args.IsBrowserInitialized)
    {
        browser.ExecuteScriptAsync("alert('test');");
    }
}
</code>```

Body:
Whenever I try to execute JavaScript through C# using CefSharp (Stable 57.0), I get an error. I am simply trying to execute the alert function, so I can make sure that works and later test it out with my own function. However, I seem to be getting errors trying to do so.

public partial class WebBrowserWindow : Window
{
    public WebBrowserWindow()
    {
        InitializeComponent();
        webBrowser.MenuHandler = new ContextMenuHandler();
        webBrowser.RequestHandler = new RequestHandler();
    }

    //Trying to execute this with either method gives me an error.
    public void ExecuteJavaScript()
    {
        //webBrowser.GetMainFrame().ExecuteJavaScriptAsync("alert('test')");

        //webBrowser.ExecuteScriptAsync("alert('test');");
    }
}

I have tried both ways of executing the script.

The first one:

webBrowser.GetMainFrame().ExecuteJavaScriptAsync("alert('test')");

Gives me this error:

The second:

webBrowser.ExecuteScriptAsync("alert('test');");

Gives me this error:

My objective is to create a C# function that can execute a JavaScript function in my CefSharp Browser.

I tried many links/references and there weren't that many on stack overflow. I also read The FAQ for CefSharp and couldn't find any simple examples that allow me to execute JavaScript at will through C#.

In addition, I've verified the events where the Frame is loaded (it finishes loading), and unloaded (it does not unload), and if the webbrowser is null (which it's not), and the message from the:

webBrowser.GetMainFrame().ExecuteJavaScriptAsync("alert('test')");

still causes the first error to occur.

I tested for GetMainFrame(). It always returns null. ALWAYS. Doesn't matter how long I wait, or what conditions I check for.

IMPORTANT

I forgot to add one crucial piece of information, I have 2 assemblies in my project. Both of them compile into separate executables:

Helper.exe
Main.exe

main.exe has a window "CallUI" that, when a button gets clicked, it executes the method I created "ExecuteJavaScript()", which is inside of my window "BrowserWindow". The CallUI window is declared and initialized in Helper.exe.

So basically I am trying to use a separate program to open a window, click a button that calls the method and execute javascript. So I think because they are different processes, it tells me the browser is null. However, when I do it all in Main.exe it works fine. Is there a workaround that allows me to use the separate process to create the window from Helper.exe and execute the Javascript from Main.exe?

Body:
Have you tried this link? Contains a snippet that checks if the browser is initialised first.

cefsharp execute javascript

private void OnIsBrowserInitializedChanged(object sender, IsBrowserInitializedChangedEventArgs args)
{
    if(args.IsBrowserInitialized)
    {
        browser.ExecuteScriptAsync("alert('test');");
    }
}


问:
UI Testing with Xcode: How to find a button that has no title?
I have some buttons in my user interface that only display an image and no title. How can I access them during a UI Test?  window.buttons["delete"].click() doesn't find the button due to lack of title. And I cannot set the title because the image has some transparency.

答:
You can find buttons through the accessibilityLabel. So, first set the label:

```<code>deleteButton.setAccessibilityLabel("delete")
</code>```

And then you can access it as normal with:

```<code> untitledWindow.buttons["delete"].click()
</code>```

Body:
You can find buttons through the accessibilityLabel. So, first set the label:

deleteButton.setAccessibilityLabel("delete")

And then you can access it as normal with:

 untitledWindow.buttons["delete"].click()


问:
Android Studio: Creating new Activity: "package not recognized"
Package On the Left Dropdown Menu

Any idea why this is happening?

答:
You shuold change "layout" with the name of you package.

You can read the name of your package in the first line code in your MainActivity.java


问:
Create timeline chart based on annual data
How does one automatically create a continuous chart over time based on data that is only available as each year?

For example, most data comes in the form of the following:

```
         j | f | m | a | m | j | j | a | s | o | n | d |
year 1   x   y
year 2           z
year 3
```

However, in order to create a chart than spans multiple years, I need the data transposed and combined  as below:

```
year 1 | j  x
       | f  y
       | m
       | a
       | m
       | j
       | j
       | a
       | s
       | o
       | n
       | d
year 2 | j
       | f
       | m  z
       | a
       | m
       | j
       | j
       | a
       | s
       | o
       | n
       | d
year 3 | j
       | f
       | m
       | a
       | m
       | j
       | j
       | a
       | s
       | o
       | n
       | d
```

Is there a simple way to do this with pivot tables or something else?

答:
Assuming your data is in Sheet1. In Sheet2 A2 put this:

```<code>=TRANSPOSE(SPLIT(ArrayFormula(JOIN(" , , , , , , , , , , , ,",FILTER(Sheet1!A2:A,Sheet1!A2:A <> ""))),","))
</code>```

In Sheet2 B2 put:

=ArrayFormula(transpose(split(rept(join(",",transpose(Sheet1!B1:N1)),countA(Sheet1!A2:A)),",")))

These will expand if years are added.
To get the data, this will work, however, a query will need to be added for each additional year:

```<code>=transpose({query(Sheet1!B2:M2,"select *"),query(Sheet1!B3:M3,"select *"),query(Sheet1!B4:M4,"select *")})
</code>```

Body:
How does one automatically create a continuous chart over time based on data that is only available as each year?

For example, most data comes in the form of the following:

         j | f | m | a | m | j | j | a | s | o | n | d |
year 1   x   y
year 2           z
year 3

However, in order to create a chart than spans multiple years, I need the data transposed and combined  as below:

year 1 | j  x
       | f  y
       | m
       | a
       | m
       | j
       | j
       | a
       | s
       | o
       | n
       | d
year 2 | j
       | f
       | m  z
       | a
       | m
       | j
       | j
       | a
       | s
       | o
       | n
       | d
year 3 | j
       | f
       | m
       | a
       | m
       | j
       | j
       | a
       | s
       | o
       | n
       | d

Is there a simple way to do this with pivot tables or something else?

Body:
Assuming your data is in Sheet1. In Sheet2 A2 put this:

=TRANSPOSE(SPLIT(ArrayFormula(JOIN(" , , , , , , , , , , , ,",FILTER(Sheet1!A2:A,Sheet1!A2:A <> ""))),","))

In Sheet2 B2 put:

=ArrayFormula(transpose(split(rept(join(",",transpose(Sheet1!B1:N1)),countA(Sheet1!A2:A)),",")))

These will expand if years are added.
To get the data, this will work, however, a query will need to be added for each additional year:

=transpose({query(Sheet1!B2:M2,"select *"),query(Sheet1!B3:M3,"select *"),query(Sheet1!B4:M4,"select *")})


问:
cannot cast to java.lang.Comparable
Although this question has already been asked but I have an implementation specific doubt.

I am trying to print the top view of the binary tree and following is the complete code for it:

```<code>import java.util.*;

class Node{
    int data;
    Node right;
    Node left;
    Node(int data){
        this.data = data;
    }
}

class Pair<F,S>{
    private F first;
    private S second;
    public Pair(F first, S second){
        this.first = first;
        this.second = second;
    }

    public F getFirst(){return first;}
    public S getSecond(){return second;}
}

class BinaryTreeTopView{

    public static void printTopView(Node root){

        if(root == null)
            return;

    Queue <Pair<Node,Integer>> q = new Queue<>();
    Map <Integer,Node> map = new HashMap<>();
    Pair<Node,Integer> p = new Pair<>(root, 0);
    q.add(p);

    /*
    I am storing nodes and the corresponding horizontal distances
    in the form of a pair which then are being stored in the queue
    to ensure level order traversal
    */

    while(!q.isEmpty()){
        Pair<Node,Integer> temp = q.peek();
        q.remove();

        if(map.containsKey(temp.getSecond())==true){
            map.put(temp.getSecond(),temp.getFirst());
        } else {
            System.out.println(temp.getFirst().data);
            map.put(temp.getSecond(),temp.getFirst());
        }

        if(temp.getFirst().left!=null){
            Pair<Node,Integer> left = new Pair<>(temp.getFirst().left, temp.getSecond()-1);
            q.add(left);
        }

        if(temp.getFirst().right!=null){
            Pair<Node,Integer> right = new Pair<> (temp.getFirst().right, temp.getSecond()+1);
            q.add(right);
        }

    }
}
public static void main(String[] args) {
    Node root = new Node(1);
    root.left = new Node(2);
    root.right = new Node(3);
    root.left.right = new Node(5);
    root.left.left = new Node(4);
    root.right.left = new Node(6);
    root.right.right = new Node(7);
    root.right.left.right = new Node(8);
    root.right.right.left = new Node(10);
    root.right.right.right = new Node(9);
    root.right.right.left.right = new Node(11);
    root.right.right.left.right.right = new Node(12);

    printTopView(root);
}
}
</code>```

It compiles fine but an exception is being raised at the runtime.
Now I have been getting the following exception and I am unable to figure out what the problem is:

```<code>Exception in thread "main" java.lang.ClassCastException:
Pair cannot be cast to java.lang.Comparable at  java.util.PriorityQueue.siftUpComparable(PriorityQueue.java:652)
at java.util.PriorityQueue.siftUp(PriorityQueue.java:647)
at java.util.PriorityQueue.offer(PriorityQueue.java:344)
at java.util.PriorityQueue.add(PriorityQueue.java:321)
</code>```

答:
You're trying to add Pair instances to a PriorityQueue, so your Pair class must be Comparable. A reasonable implementation could be to force F and S to be Comparable on their own right, and then compare by the first element, and then the second one:

```<code>class Pair<F extends Comparable<F>, S extends Comparable<S>>
    implements Comparable<Pair<F, S>> {

    // All the code you already have is fine

    @Override
    public int compareTo(Pair<F, S> o) {
        int retVal = getFirst().compareTo(o.getFirst());
        if (retVal != 0) {
            return retVal;
        }
        return getSecond().compareTo(o.getSecond());
    }
}
</code>```

Title: cannot cast to java.lang.Comparable

Body:
Although this question has already been asked but I have an implementation specific doubt.

I am trying to print the top view of the binary tree and following is the complete code for it:

import java.util.*;

class Node{
    int data;
    Node right;
    Node left;
    Node(int data){
        this.data = data;
    }
}

class Pair<F,S>{
    private F first;
    private S second;
    public Pair(F first, S second){
        this.first = first;
        this.second = second;
    }

    public F getFirst(){return first;}
    public S getSecond(){return second;}
}

class BinaryTreeTopView{

    public static void printTopView(Node root){

        if(root == null)
            return;

    Queue <Pair<Node,Integer>> q = new Queue<>();
    Map <Integer,Node> map = new HashMap<>();
    Pair<Node,Integer> p = new Pair<>(root, 0);
    q.add(p);

    /*
    I am storing nodes and the corresponding horizontal distances
    in the form of a pair which then are being stored in the queue
    to ensure level order traversal
    */

    while(!q.isEmpty()){
        Pair<Node,Integer> temp = q.peek();
        q.remove();

        if(map.containsKey(temp.getSecond())==true){
            map.put(temp.getSecond(),temp.getFirst());
        } else {
            System.out.println(temp.getFirst().data);
            map.put(temp.getSecond(),temp.getFirst());
        }

        if(temp.getFirst().left!=null){
            Pair<Node,Integer> left = new Pair<>(temp.getFirst().left, temp.getSecond()-1);
            q.add(left);
        }

        if(temp.getFirst().right!=null){
            Pair<Node,Integer> right = new Pair<> (temp.getFirst().right, temp.getSecond()+1);
            q.add(right);
        }

    }
}
public static void main(String[] args) {
    Node root = new Node(1);
    root.left = new Node(2);
    root.right = new Node(3);
    root.left.right = new Node(5);
    root.left.left = new Node(4);
    root.right.left = new Node(6);
    root.right.right = new Node(7);
    root.right.left.right = new Node(8);
    root.right.right.left = new Node(10);
    root.right.right.right = new Node(9);
    root.right.right.left.right = new Node(11);
    root.right.right.left.right.right = new Node(12);

    printTopView(root);
}
}

It compiles fine but an exception is being raised at the runtime.
Now I have been getting the following exception and I am unable to figure out what the problem is:

Exception in thread "main" java.lang.ClassCastException:
Pair cannot be cast to java.lang.Comparable at  java.util.PriorityQueue.siftUpComparable(PriorityQueue.java:652)
at java.util.PriorityQueue.siftUp(PriorityQueue.java:647)
at java.util.PriorityQueue.offer(PriorityQueue.java:344)
at java.util.PriorityQueue.add(PriorityQueue.java:321)

Body:
You're trying to add Pair instances to a PriorityQueue, so your Pair class must be Comparable. A reasonable implementation could be to force F and S to be Comparable on their own right, and then compare by the first element, and then the second one:

class Pair<F extends Comparable<F>, S extends Comparable<S>>
    implements Comparable<Pair<F, S>> {

    // All the code you already have is fine

    @Override
    public int compareTo(Pair<F, S> o) {
        int retVal = getFirst().compareTo(o.getFirst());
        if (retVal != 0) {
            return retVal;
        }
        return getSecond().compareTo(o.getSecond());
    }
}


问:
how to root and use google play service
i am using project tango development kit( Tablet model NX-74751) and the lenovo phab2 pro(smartphone model Lenovo PB2-690N) to develop project tango.

problem 1:
how to root the tablet of project tango development kit( Tablet model NX-74751)

problem 2:
how to use google play service on lenovo phab2 pro(smartphone model Lenovo PB2-690N). Because I am inside China GreatFireWall, the rom in my phab2pro does not include Google Play Service.
so, i need the international rom for phab2pro and the instructure how to flash the new rom,
Or, any patch to install GoogleService on the Chinese edition of  the phab2pro, thanks

problem3:
how to root the lenovo phab2 pro(smartphone model Lenovo PB2-690N) .

答: best way to root the tablet is via the root package for yellowstone by chainfire. google "cf-auto-root for yellowstone tablet"    i have nothing to suggest for your other 2 questions. </p>

Title: how to root and use google play service


问:
How to update each and every keys of redux state by iteration with immutable principle
I have a redux state as follows:-

```<code>data = {"facebook":true,"twitter":false,"google":false,"instagram":false,"watsapp":false}
</code>```

I will be passing the key values in action ex:-("facebook","twitter")

lets say i passed "facebook".
Then I want the state to be updated to

```<code>{"facebook":true,"twitter":false,"google":false,"instagram":false,"watsapp":false}
</code>```

here is my reducer function

```<code>function data = (state=initialstate,action) => {
   return {...state, [action.account]=true}
}
</code>```

For first time, it will give desired result.

```<code>{"facebook":true,"twitter":false,"google":false,"instagram":false,"watsapp":false}
</code>```

Now lets say, I am passing the key "twitter"

What I want:

```<code>{"facebook":false,"twitter":true,"google":false,"instagram":false,"watsapp":false}
</code>```

What I was getting with above reducer function (as expected)

```<code>{"facebook":true,"twitter":true,"google":false,"instagram":false,"watsapp":false}
</code>```

So I updated my reducer function to as following:-

```<code>function data = (state, action) => {
  Object.keys(state).forEach(function(key) {
    if(key!=action.account){
      state[key]=false;
    } else {
      state[key]=true;
    }
   });
  return state
}
</code>```

But this is against redux principle of immutable data.
As I am using selector as well, it is showing some unexpected behaviour.

How to update my reducer function which will set all the previously set values to false and will only set the current key to true keeping in mind immutable data principle of redux

答:
Simply, use a new empty object instead of modifying the original state object.</p>

```<code>function data = (state, action) => {
  const newState = {};
  Object.keys(state).forEach(function(key) {
    if(key!=action.account){
      newState[key]=false;
    } else {
      newState[key]=true;
    }
   });
  return newState
}
</code>```

Body:
I have a redux state as follows:-

data = {"facebook":true,"twitter":false,"google":false,"instagram":false,"watsapp":false}

I will be passing the key values in action ex:-("facebook","twitter")

lets say i passed "facebook".
Then I want the state to be updated to

{"facebook":true,"twitter":false,"google":false,"instagram":false,"watsapp":false}

here is my reducer function

function data = (state=initialstate,action) => {
   return {...state, [action.account]=true}
}

For first time, it will give desired result.

{"facebook":true,"twitter":false,"google":false,"instagram":false,"watsapp":false}

Now lets say, I am passing the key "twitter"

What I want:

{"facebook":false,"twitter":true,"google":false,"instagram":false,"watsapp":false}

What I was getting with above reducer function (as expected)

{"facebook":true,"twitter":true,"google":false,"instagram":false,"watsapp":false}

So I updated my reducer function to as following:-

function data = (state, action) => {
  Object.keys(state).forEach(function(key) {
    if(key!=action.account){
      state[key]=false;
    } else {
      state[key]=true;
    }
   });
  return state
}

But this is against redux principle of immutable data.
As I am using selector as well, it is showing some unexpected behaviour.

How to update my reducer function which will set all the previously set values to false and will only set the current key to true keeping in mind immutable data principle of redux

Body:
Simply, use a new empty object instead of modifying the original state object.

function data = (state, action) => {
  const newState = {};
  Object.keys(state).forEach(function(key) {
    if(key!=action.account){
      newState[key]=false;
    } else {
      newState[key]=true;
    }
   });
  return newState
}


问:
Casting Const to non Const in c
I'm working on a school project in which I need to reproduce many of the C library functions. I'm just struggling with one specific aspect of it.

If you look at the man page for memchr you will see that it takes a const void * as input and returns a plain void *. I would assume that somewhere in the function they are casting from const to non const for the return variable.

However, when I do this (clang -Weverything +Werror) it won't compile. It works without the -Weverything tag but I would prefer to use it if possible anyway.

Is there any "correct" way to do this?

答:
As you correctly noted, some C library functions must cast their const pointer argument to remove the const qualifier for the return value: memchr, strchr, strstr etc. Other standard functions store a pointer to the end of the parsed string into a char **, although it points into the array to which they were passed a const char *: strtol, strod...

If your compiler is anal about this and produces warnings, try casting to uintptr_t before casting to unsigned char *. You can also use a union with both pointer types.

The C Standard specifies memcpy this way:

7.24.5.1 The memchr function

Synopsis

```<code>#include <string.h>

void *memchr(const void *s, int c, size_t n);
</code>```

Description

The memchr function locates the first occurrence of c (converted to an unsigned char) in the initial n characters (each interpreted as unsigned char) of the object pointed to by s. The implementation shall behave as if it reads the characters sequentially and stops as soon as a matching character is found.

Returns

The memchr function returns a pointer to the located character, or a null pointer if the character does not occur in the object.

If you cannot use other types, you may get away with a cast as size_t to suppress the compiler warning, here is a possible implementation:

```<code>void *my_memchr(const void *ptr, int c, size_t num) {
    const unsigned char *cptr = ptr;

    while (num-- > 0) {
        if (*cptr++ == (unsigned char)c) {
            /* const pointer is cast first as size_t to avoid a compiler warning.
             * a more appropriate type for this intermediary cast would be uintptr_t,
             * but this type is not allowed here.
             */
            return (void *)(size_t)(cptr - 1);
        }
    }
    return NULL;
}
</code>```

UPDATE:

Using return cptr - 1; will issue a warning because the const qualifier is removed by the implicit conversion to void *.

Casting the return value explicitly as return (void *)(cptr - 1); should suffice but some compilers still issue a warning to try and help programmers avoid mistakes. Using an extra intermediary cast as return (void *)(uintptr_t)(cptr - 1); or return (void *)(size_t)(cptr - 1); does not change the semantics of the conversion because uintptr_t and size_t should be large enough to accommodate a roundtrip conversion between pointer and integer types, and it usually stops the compiler warning.

Title: Casting Const to non Const in c

Body:
As you correctly noted, some C library functions must cast their const pointer argument to remove the const qualifier for the return value: memchr, strchr, strstr etc. Other standard functions store a pointer to the end of the parsed string into a char **, although it points into the array to which they were passed a const char *: strtol, strod...

If your compiler is anal about this and produces warnings, try casting to uintptr_t before casting to unsigned char *. You can also use a union with both pointer types.

The C Standard specifies memcpy this way:

7.24.5.1 The memchr function

Synopsis

#include <string.h>

void *memchr(const void *s, int c, size_t n);

Description

The memchr function locates the first occurrence of c (converted to an unsigned char) in the initial n characters (each interpreted as unsigned char) of the object pointed to by s. The implementation shall behave as if it reads the characters sequentially and stops as soon as a matching character is found.

Returns

The memchr function returns a pointer to the located character, or a null pointer if the character does not occur in the object.

If you cannot use other types, you may get away with a cast as size_t to suppress the compiler warning, here is a possible implementation:

void *my_memchr(const void *ptr, int c, size_t num) {
    const unsigned char *cptr = ptr;

    while (num-- > 0) {
        if (*cptr++ == (unsigned char)c) {
            /* const pointer is cast first as size_t to avoid a compiler warning.
             * a more appropriate type for this intermediary cast would be uintptr_t,
             * but this type is not allowed here.
             */
            return (void *)(size_t)(cptr - 1);
        }
    }
    return NULL;
}

UPDATE:

Using return cptr - 1; will issue a warning because the const qualifier is removed by the implicit conversion to void *.

Casting the return value explicitly as return (void *)(cptr - 1); should suffice but some compilers still issue a warning to try and help programmers avoid mistakes. Using an extra intermediary cast as return (void *)(uintptr_t)(cptr - 1); or return (void *)(size_t)(cptr - 1); does not change the semantics of the conversion because uintptr_t and size_t should be large enough to accommodate a roundtrip conversion between pointer and integer types, and it usually stops the compiler warning.


问:
What does "Error starting process" could mean in my case?
I was learning C++ coding on Eclipse and I made a little Cash Register program and help you calculate how much change you should give in dollars and quarters and dimes and pennies.

When I tried to run it, it always gives me this error message:

'Launching XXX.exe' has encountered a problem. Error Starting process.

Here is my code:

```<code>#include <iostream>
using namespace std;

double askprice(double&);

int main()
{
// Todo place code here
    double price;
    double total=0;
    char answer='y';
    double cashin;
    double change;
    int dollar;
    int qt;
    int dm;
    int ct;

    cout<<"Do you have more items? y/n"<<endl;
    cin>>answer;
    while (answer == 'y')
    {
        askprice(price);
        total=total+price;

    }
    cout<<"How much do you pay?"<<endl;
    cin>>cashin;
    change=cashin-total;
    dollar = change;
    int intchange = change*100;
    qt = intchange%100/25;
    dm = intchange*100%25/10;
    ct = intchange*100%10;

    cout<<"Your change is "<<dollar<<" dollars "<<qt<<" quarters "<<dm<<" dimes and "<<ct<<" cents."<<endl;

return (0);
}

double askprice(double price)
{
    cout<<"Enter the price of your item"<<endl;
    cin>>price;
    return price;
}
</code>```

(here as image if you prefer)

Does anyone can give me an incentive about what could I do wrong here?

答:
try

```<code>double askprice(double price);
</code>```

for

```<code>double askprice(double&);
</code>```

Body:
I was learning C++ coding on Eclipse and I made a little Cash Register program and help you calculate how much change you should give in dollars and quarters and dimes and pennies.

When I tried to run it, it always gives me this error message:

'Launching XXX.exe' has encountered a problem. Error Starting process.

Here is my code:

#include <iostream>
using namespace std;

double askprice(double&);

int main()
{
// Todo place code here
    double price;
    double total=0;
    char answer='y';
    double cashin;
    double change;
    int dollar;
    int qt;
    int dm;
    int ct;

    cout<<"Do you have more items? y/n"<<endl;
    cin>>answer;
    while (answer == 'y')
    {
        askprice(price);
        total=total+price;

    }
    cout<<"How much do you pay?"<<endl;
    cin>>cashin;
    change=cashin-total;
    dollar = change;
    int intchange = change*100;
    qt = intchange%100/25;
    dm = intchange*100%25/10;
    ct = intchange*100%10;

    cout<<"Your change is "<<dollar<<" dollars "<<qt<<" quarters "<<dm<<" dimes and "<<ct<<" cents."<<endl;

return (0);
}

double askprice(double price)
{
    cout<<"Enter the price of your item"<<endl;
    cin>>price;
    return price;
}

(here as image if you prefer)

Does anyone can give me an incentive about what could I do wrong here?

Body:
try

double askprice(double price);

for

double askprice(double&);


问:
How to use `def` to define a function?
I'm new to Python so I don't know a lot of things. But right now, I need to know about the define function.
I was trying to repeat my program (script) and I learned that I can use the 'def' statement. So I put 'def start():' where I needed to repeat the program (script), but then, whatever was after it didn't work at all

This is the program I'm working on.

```<code>def start():
word=random.choice(words)
length=len(word)
if word=='hello':
    print('This is a word that you say when you greet someone')
elif word=='car':
    print('This is a machine that you ride to go to a place to another')
elif word=='run':
    print('This is to go faster than walking')
elif word=='apple':
    print('This is a round and red fruit that grows on the tree')
elif word=='day':
    print('This is the time of light between one night until the next night')
elif word=='month':
    print('This is a measure of time. Each 28~31 days is one of this')
elif word=='cat':
    print('This is an carnivore animal that is also treated as a pet from home')
elif word=='dog':
    print('This is an animal that is related to wolves, foxes, and gray wolves')
elif word=='water':
    print('This is a liquid that people needs to drink to survive')
elif word=='candy':
    print('This is a crystallized form of sugar')
elif word=='snack':
    print('This is a light meal that you eat between regular meals')
elif word=='food':
    print('This is a obect that people needs to eat to survive')
elif word=='smell':
    print('This is a sense that you feel by your nose')
elif word=='fast':
    print('This is to do something quickly than usual')
elif word=='hard':
    print('This is something to not be easily broken')
elif word=='cool':
    print('This is something you feel when you little cold')
elif word=='safe':
    print('This is to be away from harm')
elif word=='hurt':
    print('This is to have pain')
elif word=='time':
    print('This is a period when an event happens')
elif word=='glass':
    print("This is an object that doesn't absorb a lot of light so you can see through it")
else:
    print('This is a animal that can fly above the sky')
while life > 0:
    print('The length of the word is {0} letters'.format(length))
    fl=input('Guess the first letter of the word! :')
    if fl==word[0]:
        print('Whoah! Nice guess {0}'.format(pn))
        sl=input('Now guess the second letter of the word! :')
        score+=1
        if sl==word[1]:
            print('Great job! You got it {0}'.format(pn))
            if len(word)==3:
                tl=input('Now you need to guess the last letter! :')
                if tl==word[2]:
                    print('You got some skills on guessing {0}!'.format(pn))
                    finalWordThird=input('Now write the word that you guessed! :')
                    score+=1
                    if finalWordThird==word:
                        print('You got the word! Congratulations!')
                        score+=5
                        start()
                    else:
                        life-=1
                        print('I guess you typed the word wrong! You have {0} lives left!'.format(life))
                else:
                    life-=1
                    print('Nice guess but wrong. Try again! You have {0} lives left!'.format(life))
            else:
                ttl=input('Now guess the third letter! :')
                if ttl==word[2]:
                    print('You got some skills on guessing {0}!'.format(pn))
                    score+=1
                    if len(word)==4:
                        ql=input('Now you need to guess the last letter! : ')
                        if ql==word[3]:
                            print('You guessed the last letter right {0}!'.format(pn))
                            finalWordFourth=input('Now write the word you guessed! : ')
                            score+=1
                            if finalWordFourth==word:
                                print('You guessed the word right! Congratulations!')
                                score+=6
                                start()
                            else:
                                 life-=1
                                 print('I guess you typed the word wrong! You have {0} lives left!'.format(life))
                        else:
                            life-=1
                            print('Nice guess but wrong. Try again! You have {0} lives left!'.format(life))
                    else:
                        qql=input('Now guess the fourth letter! : ')
                        if qql==word[3]:
                            print('You are an incredible guesser {0}!'.format(pn))
                            score+=1
                            if len(word)==5:
                                cl=input('Now guess the last fifth letter! : ')
                                if cl==word[4]:
                                    print('You guessed your final letter right {0}!'.format(pn))
                                    finalWordFifth=input('Now write the word that you guessed! : ')
                                    score+=1
                                    if finalWordFifth==word:
                                        print('You got the word! Congratulations!')
                                        score+=7
                                        start()
                                    else:
                                        life-=1
                                        print('I guess you typed the word wrong! You have {0} lives left!'.format(life))
                                else:
                                    life-=1
                                    print('Nice guess but wrong. Try again! You have {0} lives left!'.format(life))
                        else:
                            life-=1
                            print('Nice guess but wrong. Try again! You have {0} lives left!'.format(life))
                else:
                    life-=1
                    print('I guess you typed the word wrong! You have {0} lives left!'.format(life))
        else:
            life-=1
            print('Nice guess but wrong. Try again! You have {0} lives left!'.format(life))
    else:
        life-=1
        print('Nice guess but wrong. Try again! You have {0} lives left!'.format(life))

print('Your score is {0}! Great job {1}!'.format(score,pn))
restart=input('Will you play again? (Y/N): ')
if restart == "Y" or "y":
    start()
else:
    quit()
</code>```

Sorry about the long program.

答:
It looks like you forgot about the indentation.</p>

```<code>def start():
    word=random.choice(words)
    length=len(word)
    if word=='hello':
        # etc.
</code>```

Title: How to use `def` to define a function?

Body:
I'm new to Python so I don't know a lot of things. But right now, I need to know about the define function.
I was trying to repeat my program (script) and I learned that I can use the 'def' statement. So I put 'def start():' where I needed to repeat the program (script), but then, whatever was after it didn't work at all

This is the program I'm working on.

def start():
word=random.choice(words)
length=len(word)
if word=='hello':
    print('This is a word that you say when you greet someone')
elif word=='car':
    print('This is a machine that you ride to go to a place to another')
elif word=='run':
    print('This is to go faster than walking')
elif word=='apple':
    print('This is a round and red fruit that grows on the tree')
elif word=='day':
    print('This is the time of light between one night until the next night')
elif word=='month':
    print('This is a measure of time. Each 28~31 days is one of this')
elif word=='cat':
    print('This is an carnivore animal that is also treated as a pet from home')
elif word=='dog':
    print('This is an animal that is related to wolves, foxes, and gray wolves')
elif word=='water':
    print('This is a liquid that people needs to drink to survive')
elif word=='candy':
    print('This is a crystallized form of sugar')
elif word=='snack':
    print('This is a light meal that you eat between regular meals')
elif word=='food':
    print('This is a obect that people needs to eat to survive')
elif word=='smell':
    print('This is a sense that you feel by your nose')
elif word=='fast':
    print('This is to do something quickly than usual')
elif word=='hard':
    print('This is something to not be easily broken')
elif word=='cool':
    print('This is something you feel when you little cold')
elif word=='safe':
    print('This is to be away from harm')
elif word=='hurt':
    print('This is to have pain')
elif word=='time':
    print('This is a period when an event happens')
elif word=='glass':
    print("This is an object that doesn't absorb a lot of light so you can see through it")
else:
    print('This is a animal that can fly above the sky')
while life > 0:
    print('The length of the word is {0} letters'.format(length))
    fl=input('Guess the first letter of the word! :')
    if fl==word[0]:
        print('Whoah! Nice guess {0}'.format(pn))
        sl=input('Now guess the second letter of the word! :')
        score+=1
        if sl==word[1]:
            print('Great job! You got it {0}'.format(pn))
            if len(word)==3:
                tl=input('Now you need to guess the last letter! :')
                if tl==word[2]:
                    print('You got some skills on guessing {0}!'.format(pn))
                    finalWordThird=input('Now write the word that you guessed! :')
                    score+=1
                    if finalWordThird==word:
                        print('You got the word! Congratulations!')
                        score+=5
                        start()
                    else:
                        life-=1
                        print('I guess you typed the word wrong! You have {0} lives left!'.format(life))
                else:
                    life-=1
                    print('Nice guess but wrong. Try again! You have {0} lives left!'.format(life))
            else:
                ttl=input('Now guess the third letter! :')
                if ttl==word[2]:
                    print('You got some skills on guessing {0}!'.format(pn))
                    score+=1
                    if len(word)==4:
                        ql=input('Now you need to guess the last letter! : ')
                        if ql==word[3]:
                            print('You guessed the last letter right {0}!'.format(pn))
                            finalWordFourth=input('Now write the word you guessed! : ')
                            score+=1
                            if finalWordFourth==word:
                                print('You guessed the word right! Congratulations!')
                                score+=6
                                start()
                            else:
                                 life-=1
                                 print('I guess you typed the word wrong! You have {0} lives left!'.format(life))
                        else:
                            life-=1
                            print('Nice guess but wrong. Try again! You have {0} lives left!'.format(life))
                    else:
                        qql=input('Now guess the fourth letter! : ')
                        if qql==word[3]:
                            print('You are an incredible guesser {0}!'.format(pn))
                            score+=1
                            if len(word)==5:
                                cl=input('Now guess the last fifth letter! : ')
                                if cl==word[4]:
                                    print('You guessed your final letter right {0}!'.format(pn))
                                    finalWordFifth=input('Now write the word that you guessed! : ')
                                    score+=1
                                    if finalWordFifth==word:
                                        print('You got the word! Congratulations!')
                                        score+=7
                                        start()
                                    else:
                                        life-=1
                                        print('I guess you typed the word wrong! You have {0} lives left!'.format(life))
                                else:
                                    life-=1
                                    print('Nice guess but wrong. Try again! You have {0} lives left!'.format(life))
                        else:
                            life-=1
                            print('Nice guess but wrong. Try again! You have {0} lives left!'.format(life))
                else:
                    life-=1
                    print('I guess you typed the word wrong! You have {0} lives left!'.format(life))
        else:
            life-=1
            print('Nice guess but wrong. Try again! You have {0} lives left!'.format(life))
    else:
        life-=1
        print('Nice guess but wrong. Try again! You have {0} lives left!'.format(life))

print('Your score is {0}! Great job {1}!'.format(score,pn))
restart=input('Will you play again? (Y/N): ')
if restart == "Y" or "y":
    start()
else:
    quit()

Sorry about the long program.

Body:
It looks like you forgot about the indentation.

def start():
    word=random.choice(words)
    length=len(word)
    if word=='hello':
        # etc.


问:
Using falcor to retrieve the value of a "node" rather than a "leaf"
For example, with the following code, I can retrieve a value for "leaf" c from a Falcor model

```<code>var model = new falcor.Model({ cache: { a: { b: { c: 'hi!'}}} })
model.getValue('a.b.c').then(val => console.log(val));
</code>```

However, I'm interested in how to retrieve "node" b, i.e. so that the resulting json is { c: 'hi!' }.

Any help appreciated.

答: you can do this is by storing "c"as a jsongraph atom into b.</p>

Body:
For example, with the following code, I can retrieve a value for "leaf" c from a Falcor model

var model = new falcor.Model({ cache: { a: { b: { c: 'hi!'}}} })
model.getValue('a.b.c').then(val => console.log(val));

However, I'm interested in how to retrieve "node" b, i.e. so that the resulting json is { c: 'hi!' }.

Any help appreciated.


问:
Holding event is not fired on touch screen device
I'm trying to create a simple uwp app where I require to display a context menu, if user right clicks on non-touch device and if user holds on touch screen device.
I'm using righttapped event which works perfectly on my desktop. The other side, I use holding event which should be triggered when screen is long pressed but it doesn't work(on touch screen mobile).

```<code>private void Webview_Holding(object sender, HoldingRoutedEventArgs e)
    {
        Webview.ContextFlyout.ShowAt(sender as FrameworkElement);
    }
</code>```

Do I need to use some other event for showing context menu, if yes then which one?

答:
You should use RightTapped event for both touch and non-touch devices as I answered here. However, WebView does not support all of the touch or keyboard events.

Remarks section of MSDN for WebView control:

As indicated in the Events table, WebView doesn’t support most of the
  user input events inherited from UIElement, such as KeyDown, KeyUp,
  and PointerPressed. A common workaround is to use InvokeScriptAsync
  with the JavaScript eval function to use the HTML event handlers, and
  to use window.external.notify from the HTML event handler to notify
  the application using WebView.ScriptNotify.

Body:
I'm trying to create a simple uwp app where I require to display a context menu, if user right clicks on non-touch device and if user holds on touch screen device.
I'm using righttapped event which works perfectly on my desktop. The other side, I use holding event which should be triggered when screen is long pressed but it doesn't work(on touch screen mobile).

private void Webview_Holding(object sender, HoldingRoutedEventArgs e)
    {
        Webview.ContextFlyout.ShowAt(sender as FrameworkElement);
    }

Do I need to use some other event for showing context menu, if yes then which one?


问:
Do HTML5 elements mean anything to search engines?
Let me just say first that I'm not looking to start a flame war :-)

I'm aware of the semantic meaning that tags such as
 give a document, but what benefits does one get from using them?

Do search engines look at them differently? If not, what other benefits are there?

答:
There are the obvious benefits that one day search engines might use them or microdata to associate more meaning to your site.  I'm not totaly sure if that is the case yet, but some of the other answers so far provide some good links to answer that question.

Another benefit is cleaner markup.  It helps to clean up the div soup that solved so many of our organization issues with HTML 4.01. Take this example:

```<code><div class="post">
<h1>Example Blog Post</h1>
   <div class="entry">
      <p>Blog text goes here...</p>
   </div>
   <div class="entryFooter">
      <p> Posted in example category.</p>
   </div>
</div>
</code>```

is not as readable or as clean as:

```<code><article>
   <header>
      <h1>Example Blog Post</h1>
   </header>
   <p>Blog text goes here...</p>
   <footer>
      <p>Posted in example category.</p>
   </footer>
</article>
</code>```

Cleaner markup will make maintaining the markup a lot easier and that is always a benefit in my opinion.

Body:
There are the obvious benefits that one day search engines might use them or microdata to associate more meaning to your site.  I'm not totaly sure if that is the case yet, but some of the other answers so far provide some good links to answer that question.

Another benefit is cleaner markup.  It helps to clean up the div soup that solved so many of our organization issues with HTML 4.01. Take this example:

<div class="post">
<h1>Example Blog Post</h1>
   <div class="entry">
      <p>Blog text goes here...</p>
   </div>
   <div class="entryFooter">
      <p> Posted in example category.</p>
   </div>
</div>

is not as readable or as clean as:

<article>
   <header>
      <h1>Example Blog Post</h1>
   </header>
   <p>Blog text goes here...</p>
   <footer>
      <p>Posted in example category.</p>
   </footer>
</article>

Cleaner markup will make maintaining the markup a lot easier and that is always a benefit in my opinion.


问:
Android status bar hide/change color in splash screen
I implemented a layout-less splash screen in my app following this tutorial: https://www.bignerdranch.com/blog/splash-screens-the-right-way/

I managed to change the color of the status bar for my MainActivity and even to make it fullscreen using a theme. However none of the methods I've tried are working with the splash screen. Maybe it's because it doesn't use a layout but directly a drawable as background:

```<code><style
    name="AppTheme"
    parent="@android:style/Theme.Material.Light.NoActionBar">

    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:textColor">@color/textColor</item>
    <item name="iconColor">@color/iconColor</item>
    <item name="android:statusBarColor">@color/colorPrimaryDark</item>
    <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>

<style
    name="SplashTheme"
    parent="AppTheme">

    <item name="android:windowBackground">@drawable/splash_screen</item>
</style>
</code>```

I tried using a Fullscreen theme, setting android:statusBarColor in the theme used by the activity, I also tried the two following bits of code:

```<code>View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);

Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));
</code>```

These 4 methods are working for my normal activity but not for the splash screen. Is there anything I can do?

EDIT: I'm targetting minSdkVersion 23

答:
Use <item name="android:windowFullscreen">true</item>

```<code><style
    name="SplashTheme"
    parent="AppTheme">
    <item name="android:windowFullscreen">true</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="android:windowBackground">@drawable/splash_screen</item>
</style>
</code>```

Body:
I implemented a layout-less splash screen in my app following this tutorial: https://www.bignerdranch.com/blog/splash-screens-the-right-way/

I managed to change the color of the status bar for my MainActivity and even to make it fullscreen using a theme. However none of the methods I've tried are working with the splash screen. Maybe it's because it doesn't use a layout but directly a drawable as background:

I tried using a Fullscreen theme, setting android:statusBarColor in the theme used by the activity, I also tried the two following bits of code:

View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);

Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));

These 4 methods are working for my normal activity but not for the splash screen. Is there anything I can do?

EDIT: I'm targetting minSdkVersion 23

Body:
Use <item name="android:windowFullscreen">true</item>

<style
    name="SplashTheme"
    parent="AppTheme">
    <item name="android:windowFullscreen">true</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="android:windowBackground">@drawable/splash_screen</item>
</style>