问:
Flask doesn't print to console
I'm new to flask, and I'm trying to add print info to debug server side code.
When launch my flask app with debug=True, i can't get any info print to console

I tried to use logging instead, but no success.
So how to debug flask program with console.

```<code>@app.route('/getJSONResult', methods=['GET', 'POST'])
def getJSONResult():

    if request.method == 'POST':
        uut = request.form['uut']
        notes = request.form['notes']
        temperature = request.form['temperature']

        logging.info("enter getJSONReuslt")
        print('enter getJSONReuslt')
        filter_by_query = {k: v for k, v in {
            'uut': uut, 'notes': notes, 'temperature': temperature}.items() if v != ""}
        s = session.query(UUT_TEST_INFO).filter_by(**filter_by_query).first()
        return jsonify(s.serialize)

if __name__ == '__main__':
    app.secret_key = ''.join(random.choice(
        string.ascii_uppercase + string.digits) for x in range(32))
    app.debug = True
    app.run(host='127.0.0.1', port=5000)

> 127.0.0.1 - - [07/Jun/2017 15:20:48] "GET /qyer HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:20:48] "GET /static/css/bootstrap.min.css HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:20:48] "GET /static/js/bootstrap.min.js HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:20:51] "GET /static/css/bootstrap.min.css.map HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:21:58] "POST /getJSONResult HTTP/1.1" 500 -
</code>```

I fixed server side 500 error issue, now request get 200 code, and console displays following info

```<code>$ python project.py
INFO:werkzeug: * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
INFO:werkzeug: * Restarting with stat
WARNING:werkzeug: * Debugger is active!
INFO:werkzeug: * Debugger pin code: 158-624-607
INFO:werkzeug:127.0.0.1 - - [08/Jun/2017 11:33:33] "GET /qyer HTTP/1.1" 200 -
INFO:root:Enter getJSONResult
INFO:werkzeug:127.0.0.1 - - [08/Jun/2017 11:33:43] "POST /getJSONResult HTTP/1.1" 200 -
</code>```

Still no info from print command

答:
Try this and see if it helps:

For python2:

```<code>from __future__ import print_function
import sys

print('This is error output', file=sys.stderr)
print('This is standard output', file=sys.stdout)
</code>```

For python3 you don't need to import from future print_function:

```<code>import sys

print('This is error output', file=sys.stderr)
print('This is standard output', file=sys.stdout)
</code>```

See if it helps to print to console.

Title: Flask doesn't print to console

Body:
I'm new to flask, and I'm trying to add print info to debug server side code.
When launch my flask app with debug=True, i can't get any info print to console

I tried to use logging instead, but no success.
So how to debug flask program with console.

@app.route('/getJSONResult', methods=['GET', 'POST'])
def getJSONResult():

    if request.method == 'POST':
        uut = request.form['uut']
        notes = request.form['notes']
        temperature = request.form['temperature']

        logging.info("enter getJSONReuslt")
        print('enter getJSONReuslt')
        filter_by_query = {k: v for k, v in {
            'uut': uut, 'notes': notes, 'temperature': temperature}.items() if v != ""}
        s = session.query(UUT_TEST_INFO).filter_by(**filter_by_query).first()
        return jsonify(s.serialize)

if __name__ == '__main__':
    app.secret_key = ''.join(random.choice(
        string.ascii_uppercase + string.digits) for x in range(32))
    app.debug = True
    app.run(host='127.0.0.1', port=5000)

> 127.0.0.1 - - [07/Jun/2017 15:20:48] "GET /qyer HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:20:48] "GET /static/css/bootstrap.min.css HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:20:48] "GET /static/js/bootstrap.min.js HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:20:51] "GET /static/css/bootstrap.min.css.map HTTP/1.1" 200 -
> 127.0.0.1 - - [07/Jun/2017 15:21:58] "POST /getJSONResult HTTP/1.1" 500 -

I fixed server side 500 error issue, now request get 200 code, and console displays following info

$ python project.py
INFO:werkzeug: * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
INFO:werkzeug: * Restarting with stat
WARNING:werkzeug: * Debugger is active!
INFO:werkzeug: * Debugger pin code: 158-624-607
INFO:werkzeug:127.0.0.1 - - [08/Jun/2017 11:33:33] "GET /qyer HTTP/1.1" 200 -
INFO:root:Enter getJSONResult
INFO:werkzeug:127.0.0.1 - - [08/Jun/2017 11:33:43] "POST /getJSONResult HTTP/1.1" 200 -

Still no info from print command

Body:
Try this and see if it helps:

For python2:

from __future__ import print_function
import sys

print('This is error output', file=sys.stderr)
print('This is standard output', file=sys.stdout)

For python3 you don't need to import from future print_function:

import sys

print('This is error output', file=sys.stderr)
print('This is standard output', file=sys.stdout)

See if it helps to print to console.


来源: stackexchange

问:
"this" pointer in C (not C++)
I'm trying to create a stack in C for fun, and came up with the idea of using struct to represent the stack. Then I add function pointers to the struct for push() and pop() operations.

So far all is good it seems, but, for the implementation of the push() and pop() functions I need to refer to *this somehow. How can that (can it?) be done?

This is my struct

```<code>struct Stack {
    int *data;
    int current_size;
    int max_size;
    int (*push)(int);
    int (*pop)();
};
</code>```

And as an example here's push

```<code>int push(int val) {
    if(current_size == max_size -1)
            return 0;

    data[current_size] = val;
    current_size++;

    return 1;
}
</code>```

As you can imagine, the compiler has no idea what current_size is, as it would expect something like stack->current_size.

Is this possible to overcome somehow?

答: Obviously you can have a Stack * member in the struct and then just initialize it with the address of the struct before you use the function pointers. Then make the Stack * a parameter on the function pointers.</p>

ContentLicense: CC BY-SA 2.5

Title: "this" pointer in C (not C++)

Body:
I'm trying to create a stack in C for fun, and came up with the idea of using struct to represent the stack. Then I add function pointers to the struct for push() and pop() operations.

So far all is good it seems, but, for the implementation of the push() and pop() functions I need to refer to *this somehow. How can that (can it?) be done?

This is my struct

struct Stack {
    int *data;
    int current_size;
    int max_size;
    int (*push)(int);
    int (*pop)();
};

And as an example here's push

int push(int val) {
    if(current_size == max_size -1)
            return 0;

    data[current_size] = val;
    current_size++;

    return 1;
}

As you can imagine, the compiler has no idea what current_size is, as it would expect something like stack->current_size.

Is this possible to overcome somehow?


问:
How can I properly use HTML5 url with AngularJS?
I'm pretty new with AngularJS and server config stuff, and this is a problem I haven't found a satisfactory solution so far.

I would like to be able to use the HTML5 url on a website (without hashbangs), so that I could use addresses like "mydomain/contact" to navigate (I'll stick with the "contact" example for simplicity).

To do that, as I've found so far, one should do two things:

Enable HTML5 on the client side

Enable the HTML5 format on the app/app.js file (also adding the dependency)

```<code>$locationProvider.html5Mode(true);
</code>```

It makes possible to click on links and get the proper url. Still, it doesn't allow someone to access directly the HTML5 url. To get to the "contact" page, I still can't directly access "mydomain/contact" (we get a 404) and I know it makes sense. To solve this, it is still necessary to implement something server-side.

Server-side config

Configure the server to respond with the right file, i.e., I should configure the server to make it respond the same way when I request "mydomain/#/contact" and "mydomain/contact".

The last item is where I'm stuck. I've found many answers like this: "you should configure your server" (they assume the reader already knows how to do this. I don't), but I can't find a complete example on how to do that or where to put any needed files.

I'm using AngularJS 1.6.x and npm 3.10.9 (npm start). My question is: is there any complete example on how to fully use HTML5 urls with AngularJS?

答:
The only problem that exists is that angular can't handle requests it doesn't receive. You need some catch-all so that all routes (/contact etc) are passed to your main index-file.

When you say .htaccess I assume apache. Even so I'd still put nginx in front of apache since it's lightweight and easy to configure (at least compared to the apache behemoth). Sorry, I know that is a very opinionated answer. Anyway with nginx the entire config could look like this:

```<code># usually this file goes in /etc/nginx/conf.d/anyfilename.conf
# but it might vary with os/distro.
server {
  listen 80
  root /var/www/myapp;

  location / {
    try_files $uri $uri/ index.html;
  }

  # And if you want to pass some route to apache:
  location /apache {
    proxy_pass http://127.0.0.1:81; # Apache listening on port 81.
  }
}
</code>```

I'm sure the same can be achieved with apache alone, but I couldn't tell you how. But perhaps this can be of help: htaccess redirect for Angular routes

There are so many silly toolpacks and utilities I've wasted time learning in my life, but nginx is the one tool I'll never regret I picked up.

ContentLicense: CC BY-SA 3.0

Body:
I'm pretty new with AngularJS and server config stuff, and this is a problem I haven't found a satisfactory solution so far.

I would like to be able to use the HTML5 url on a website (without hashbangs), so that I could use addresses like "mydomain/contact" to navigate (I'll stick with the "contact" example for simplicity).

To do that, as I've found so far, one should do two things:

Enable HTML5 on the client side

Enable the HTML5 format on the app/app.js file (also adding the dependency)

$locationProvider.html5Mode(true);

It makes possible to click on links and get the proper url. Still, it doesn't allow someone to access directly the HTML5 url. To get to the "contact" page, I still can't directly access "mydomain/contact" (we get a 404) and I know it makes sense. To solve this, it is still necessary to implement something server-side.

Server-side config

Configure the server to respond with the right file, i.e., I should configure the server to make it respond the same way when I request "mydomain/#/contact" and "mydomain/contact".

The last item is where I'm stuck. I've found many answers like this: "you should configure your server" (they assume the reader already knows how to do this. I don't), but I can't find a complete example on how to do that or where to put any needed files.

I'm using AngularJS 1.6.x and npm 3.10.9 (npm start). My question is: is there any complete example on how to fully use HTML5 urls with AngularJS?

Body:
The only problem that exists is that angular can't handle requests it doesn't receive. You need some catch-all so that all routes (/contact etc) are passed to your main index-file.

When you say .htaccess I assume apache. Even so I'd still put nginx in front of apache since it's lightweight and easy to configure (at least compared to the apache behemoth). Sorry, I know that is a very opinionated answer. Anyway with nginx the entire config could look like this:

# usually this file goes in /etc/nginx/conf.d/anyfilename.conf
# but it might vary with os/distro.
server {
  listen 80
  root /var/www/myapp;

  location / {
    try_files $uri $uri/ index.html;
  }

  # And if you want to pass some route to apache:
  location /apache {
    proxy_pass http://127.0.0.1:81; # Apache listening on port 81.
  }
}

I'm sure the same can be achieved with apache alone, but I couldn't tell you how. But perhaps this can be of help: htaccess redirect for Angular routes

There are so many silly toolpacks and utilities I've wasted time learning in my life, but nginx is the one tool I'll never regret I picked up.


问:
Warning: date(): and Cannot modify header information on a contact form
i had a little contact form from the net and trying to insdtall it but i am getting these 2 errors and i must admit, i am not very good with php esp server side.
the errors are:

Error 1: *Warning: date(): It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function.* contactform/include/class.phpmailer.php on line 1612 and the same warning for line 1616 of the same file class.phpmailer.php

line 1612 to line 1616 of class.phpmailer.php is

```<code>1612- $tz = date('Z');
1613- $tzs = ($tz < 0) ? '-' : '+';
1614- $tz = abs($tz);
1315- $tz = (int)($tz/3600)*100 + ($tz%3600)/60;
1316- $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);
</code>```

Error 2: Warning: Cannot modify header information - headers already sent by (output started at /home/massa/public_html/mydomain.com/folder/contactform/include/class.phpmailer.php:1612) in /home/massa/public_html/mydomain.com/folder/contactform/include/fgcontactform.php on line 143

line 143 of fgcontactform.php is .

```<code>143-  header("Location: $url");
144-  exit;
</code>```

I must specity this are not my codes, its just a free basic contact form i had on internet and try to implement it on my site..
Any help will be appreciated.
Just how to insert the right time zone on line 1612 and what to insert in line 143 of the other file..
Thanks in advance.
Michelle

答:
The problem is in your php.ini settings. Follow the warning's suggestion and either edit the file and add this:

```<code>date.timezone="Australia/Sydney"
</code>```

Or alternatively, add the call to date_default_timezone_set("Australia/Sydney") somewhere in the beginning of your code.

Once the error is resolved, your other problem will be gone as well. PHP echoes all errors it encounters and unless your output is buffered, it will send the HTTP response headers along with the first thing it outputs. After that it will be too late to use header('Location: ...') because the headers are already sent to the client.

Body:
i had a little contact form from the net and trying to insdtall it but i am getting these 2 errors and i must admit, i am not very good with php esp server side.
the errors are:

Error 1: *Warning: date(): It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function.* contactform/include/class.phpmailer.php on line 1612 and the same warning for line 1616 of the same file class.phpmailer.php

line 1612 to line 1616 of class.phpmailer.php is

1612- $tz = date('Z');
1613- $tzs = ($tz < 0) ? '-' : '+';
1614- $tz = abs($tz);
1315- $tz = (int)($tz/3600)*100 + ($tz%3600)/60;
1316- $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);

Error 2: Warning: Cannot modify header information - headers already sent by (output started at /home/massa/public_html/mydomain.com/folder/contactform/include/class.phpmailer.php:1612) in /home/massa/public_html/mydomain.com/folder/contactform/include/fgcontactform.php on line 143

line 143 of fgcontactform.php is .

143-  header("Location: $url");
144-  exit;

I must specity this are not my codes, its just a free basic contact form i had on internet and try to implement it on my site..
Any help will be appreciated.
Just how to insert the right time zone on line 1612 and what to insert in line 143 of the other file..
Thanks in advance.
Michelle

Body:
The problem is in your php.ini settings. Follow the warning's suggestion and either edit the file and add this:

date.timezone="Australia/Sydney"

Or alternatively, add the call to date_default_timezone_set("Australia/Sydney") somewhere in the beginning of your code.

Once the error is resolved, your other problem will be gone as well. PHP echoes all errors it encounters and unless your output is buffered, it will send the HTTP response headers along with the first thing it outputs. After that it will be too late to use header('Location: ...') because the headers are already sent to the client.


问:
System Verilog : Concatenate 0's n times when n is unknown at compile time

I am trying to concatenate 0 "n" times but "n 'is unknown to me at compile time.

"n" is calculated using some calculation which depends on random input(temp_i).

```<code>    string s=temp_i;
      int n,d_zero;
   int i=0;
    int l=s.len()*8;//l=24
     int k=447-l;
     int T=0;
     if(k<0)
       k=512+k;

     do
     begin
      d[i]=l%2;
      i++;
     end while(l>0);

     T=l+1+k+d.size();
     n=T/512;
</code>```

This "n" numbers of zero has to be concatenated with the input. Something like:

```<code>    temp_out={temp_i,n'{1'b0}}
</code>```

But I am getting a syntax error concatenating like this.

Can someone please help me out with this? Is there any other way I can get this done ?

答:
Got it working by just declaring "n"  as localparam.

```<code>    localparam n;
</code>```

and temp_out as

```<code>  temp_out={temp_i,{n{1'b0}}};
</code>```

Body:
I am trying to concatenate 0 "n" times but "n 'is unknown to me at compile time.

"n" is calculated using some calculation which depends on random input(temp_i).

    string s=temp_i;
      int n,d_zero;
   int i=0;
    int l=s.len()*8;//l=24
     int k=447-l;
     int T=0;
     if(k<0)
       k=512+k;

     do
     begin
      d[i]=l%2;
      i++;
     end while(l>0);

     T=l+1+k+d.size();
     n=T/512;

This "n" numbers of zero has to be concatenated with the input. Something like:

    temp_out={temp_i,n'{1'b0}}

But I am getting a syntax error concatenating like this.

Can someone please help me out with this? Is there any other way I can get this done ?

Body:
Got it working by just declaring "n"  as localparam.

    localparam n;

and temp_out as

  temp_out={temp_i,{n{1'b0}}};


问:
Displaying Evernote Notes in Angular 2 - Sanitizing HTML stripped some content
Currently I have it set up so my Notes in evernote can be displayed on a website for content, but they don't show the way they should. I can't figure out how to get it to just display the way I try. Pictures don't show, links, videos, it all gets stripped out and says

```<code>WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).
</code>```

I understand to prevent xss attacks they've done this to me, but how to I stop it??

Currently I'm using this in the HTML template

```<code><div [innerHTML]="note"></div>
</code>```

where note is the string containing my ENML.

I'm just not sure where to start. I am hoping there's a quick easy way to just make it display the way it displays in Evernote itself.

答: Found the solution! I just did a pipe to mark the content as safe, like this guy did here:D</p>

Body:
Currently I have it set up so my Notes in evernote can be displayed on a website for content, but they don't show the way they should. I can't figure out how to get it to just display the way I try. Pictures don't show, links, videos, it all gets stripped out and says

WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).

I understand to prevent xss attacks they've done this to me, but how to I stop it??

Currently I'm using this in the HTML template

where note is the string containing my ENML.

I'm just not sure where to start. I am hoping there's a quick easy way to just make it display the way it displays in Evernote itself.


问:
C#.NET Getting User Name of machine using Windows Service
I am having difficulty getting the User Name of a person logged into a machine using a windows service.

When using both System.Environment.UserName or WindowsIdentity.GetCurrent().UserName I get NTAUTHORITY\SYSTEM but when this application gets pushed I need to be able to map to the UserID of the person logged in to the system.  The operating system this will be used on will be Windows XP.

Any help would be very appreciated.

答:
Windows service always runs under the credential supplied in the service Properties / Log On tab. This has nothing to do with the credentials of the person / people that are currently logged into Windows in their own sessions.

The value of NTAUTHORITY\SYSTEM is correct because your service is running under 'Local System account' credentials.

You cannot run windows service under the account of 'currently logged on' user - that's not what windows service is for.


问:
bash: npm: command not found
When I check the version of Node, it says

```<code>v8.0.0
</code>```

but when I check the version of NPM, it says

```<code>bash: npm: command not found
</code>```

Previously, my action was

npm install -g "@angular/cli"

That's when it consistently shows the npm: command not found message.

I tried searching for possible solutions but none worked like the brew and others.

答: The npm file should be in /usr/local/bin/npm. If it's not there, install node.js again with the package on their website. This worked in my case.</p>

Title: bash: npm: command not found

Body:
When I check the version of Node, it says

v8.0.0

but when I check the version of NPM, it says

bash: npm: command not found

Previously, my action was

npm install -g "@angular/cli"

That's when it consistently shows the npm: command not found message.

I tried searching for possible solutions but none worked like the brew and others.


问:
how to save json data nsuserdefault and use it next view controller Swift 3.0?
```<code>if let con  = country [ "country_id"] as? Int{
        print("++++++ \(con ) ++++")

        self.countryidID.append(con)
        UserDefaults.standard.set(self.countryidID, forKey: "Key")
                print(self.countryidID)
</code>```

I create two type of dropdown (country, city) when I click "country" button then passed "city-ID" and show dropdown list selected country cities.

My problem is that I'm not saving my city id data and can't retrieve it. I'm not able to correctly save the data object to userDefaults and retrieve.

答:
Save a string with UserDefaults.standard.set("random_strong", forKey: "object_string")

Save with UserDefaults.standard.synchronize() to save immediatly

Retrieve with var variable = UserDefaults.standard.object(forKey: "object")

Body:
if let con  = country [ "country_id"] as? Int{
        print("++++++ \(con ) ++++")

        self.countryidID.append(con)
        UserDefaults.standard.set(self.countryidID, forKey: "Key")
                print(self.countryidID)

I create two type of dropdown (country, city) when I click "country" button then passed "city-ID" and show dropdown list selected country cities.

My problem is that I'm not saving my city id data and can't retrieve it. I'm not able to correctly save the data object to userDefaults and retrieve.


问:
Webscraping results to data frame
Im in the process of trying to figure out how to take my scraped data and convert it to a dataframe using pandas,

I scraped data off a grocery website as an experiment. Using Beautiful soup, once I import the URL and use beautiful soup  I then created a loop to pull anything within a certain class with div tags. Then i used the code below to pull the data below:

```<code>import urllib2
import requests
import pandas as pd
from bs4 import BeautifulSoup
import pickle

link=requests.get("https://www.iga.net/en/online_grocery/frozen_grocery")
soup = BeautifulSoup(link.content, 'html.parser')
##print soup.prettify()
bowl=soup.find_all('div',class_='js-product js-equalized js-addtolist-container js-ga')

for bowls in bowl:
    list=bowls.get('data-product')
    print list
</code>```

list printed:

```<code>{'ProductId':'00000_000000005500059917','BrandName':'Nestle','FullDisplayName':'10 Pack Mini Rolo Bars','IsAgeRequired':false,'SizeLabel':'','Size':'10 x 45 ml','ProductUrl':'/en/product/mini-rolo-bars10-pack/00000_000000005500059917','ProductImageUrl':'https://az836796.vo.msecnd.net/media/image/product/en/medium/0005500059917.jpg','HasNewPrice':false,'PromotionName':null,'RegularPrice':6.49000,'SalesPrice':null}
{'ProductId':'00000_000000005574253356','BrandName':'Compliments','FullDisplayName':'100% Pure Frozen Concentrate Pulp Free Juice','IsAgeRequired':false,'SizeLabel':'','Size':'283 ml','ProductUrl':'/en/product/juice100--pure-frozen-concentrate-pulp-free/00000_000000005574253356','ProductImageUrl':'https://az836796.vo.msecnd.net/media/image/product/en/medium/0005574253356.jpg','HasNewPrice':false,'PromotionName':null,'RegularPrice':1.79000,'SalesPrice':null}
</code>```

I'm trying to take the productID, size and regular price for example and dump that into a table. I'd even be ok to take the entire keys and values and dump them into a data frame so i can play around with it in excel.

I've tried to do the following but i get an error (added in the data frame in the last block:

```<code>import urllib2
import requests
import pandas as pd
from bs4 import BeautifulSoup
import pickle

link=requests.get("https://www.iga.net/en/online_grocery/frozen_grocery")
soup = BeautifulSoup(link.content, 'html.parser')
##print soup.prettify()
bowl=soup.find_all('div',class_='js-product js-equalized js-addtolist-container js-ga')

for bowls in bowl:
    list=bowls.get('data-product')
    df = pd.DataFrame(list)
    print df
</code>```

This results in an error. Any help is appreciated. I'm a rookie to this.

答:
You need convert each data-product to be a valid python dictionary, then merge all of them to one dictionary, after that, you can convert to dataframe like this:

```<code>import urllib2
import requests
import pandas as pd
from bs4 import BeautifulSoup
import pickle
import json
import collections

link=requests.get("https://www.iga.net/en/online_grocery/frozen_grocery")
soup = BeautifulSoup(link.content, 'html.parser')
##print soup.prettify()
bowl=soup.find_all('div',class_='js-product js-equalized js-addtolist-container js-ga')

super_dict = collections.defaultdict(list)

for bowls in bowl:
    data=bowls.get('data-product')
    data = data.replace("\'","\"") #json.loads accepts only double quotes for json properties, so replace ' with "
    dict_data = json.loads(data) #convert to valid python dictionary
    for k, v in dict_data.iteritems():  # d.items() in Python 3+
        super_dict[k].append(v) #merge all dictionary
df = pd.DataFrame(dict(super_dict))
df
</code>```

Output will be the dataframe you want:

Update:

if you want to view the dataframe in excel file, you can write to excel file with below code:

```<code>writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Close the Pandas Excel writer and output the Excel file.
writer.save()
</code>```

Then you can open file pandas_simple.xlsx to check the data in excel format.

Title: Webscraping results to data frame

Body:
Im in the process of trying to figure out how to take my scraped data and convert it to a dataframe using pandas,

I scraped data off a grocery website as an experiment. Using Beautiful soup, once I import the URL and use beautiful soup  I then created a loop to pull anything within a certain class with div tags. Then i used the code below to pull the data below:

import urllib2
import requests
import pandas as pd
from bs4 import BeautifulSoup
import pickle

link=requests.get("https://www.iga.net/en/online_grocery/frozen_grocery")
soup = BeautifulSoup(link.content, 'html.parser')
##print soup.prettify()
bowl=soup.find_all('div',class_='js-product js-equalized js-addtolist-container js-ga')

for bowls in bowl:
    list=bowls.get('data-product')
    print list

list printed:

{'ProductId':'00000_000000005500059917','BrandName':'Nestle','FullDisplayName':'10 Pack Mini Rolo Bars','IsAgeRequired':false,'SizeLabel':'','Size':'10 x 45 ml','ProductUrl':'/en/product/mini-rolo-bars10-pack/00000_000000005500059917','ProductImageUrl':'https://az836796.vo.msecnd.net/media/image/product/en/medium/0005500059917.jpg','HasNewPrice':false,'PromotionName':null,'RegularPrice':6.49000,'SalesPrice':null}
{'ProductId':'00000_000000005574253356','BrandName':'Compliments','FullDisplayName':'100% Pure Frozen Concentrate Pulp Free Juice','IsAgeRequired':false,'SizeLabel':'','Size':'283 ml','ProductUrl':'/en/product/juice100--pure-frozen-concentrate-pulp-free/00000_000000005574253356','ProductImageUrl':'https://az836796.vo.msecnd.net/media/image/product/en/medium/0005574253356.jpg','HasNewPrice':false,'PromotionName':null,'RegularPrice':1.79000,'SalesPrice':null}

I'm trying to take the productID, size and regular price for example and dump that into a table. I'd even be ok to take the entire keys and values and dump them into a data frame so i can play around with it in excel.

I've tried to do the following but i get an error (added in the data frame in the last block:

import urllib2
import requests
import pandas as pd
from bs4 import BeautifulSoup
import pickle

link=requests.get("https://www.iga.net/en/online_grocery/frozen_grocery")
soup = BeautifulSoup(link.content, 'html.parser')
##print soup.prettify()
bowl=soup.find_all('div',class_='js-product js-equalized js-addtolist-container js-ga')

for bowls in bowl:
    list=bowls.get('data-product')
    df = pd.DataFrame(list)
    print df

This results in an error. Any help is appreciated. I'm a rookie to this.

Body:
You need convert each data-product to be a valid python dictionary, then merge all of them to one dictionary, after that, you can convert to dataframe like this:

import urllib2
import requests
import pandas as pd
from bs4 import BeautifulSoup
import pickle
import json
import collections

link=requests.get("https://www.iga.net/en/online_grocery/frozen_grocery")
soup = BeautifulSoup(link.content, 'html.parser')
##print soup.prettify()
bowl=soup.find_all('div',class_='js-product js-equalized js-addtolist-container js-ga')

super_dict = collections.defaultdict(list)

for bowls in bowl:
    data=bowls.get('data-product')
    data = data.replace("\'","\"") #json.loads accepts only double quotes for json properties, so replace ' with "
    dict_data = json.loads(data) #convert to valid python dictionary
    for k, v in dict_data.iteritems():  # d.items() in Python 3+
        super_dict[k].append(v) #merge all dictionary
df = pd.DataFrame(dict(super_dict))
df

Output will be the dataframe you want:

Update:

if you want to view the dataframe in excel file, you can write to excel file with below code:

writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')

# Close the Pandas Excel writer and output the Excel file.
writer.save()

Then you can open file pandas_simple.xlsx to check the data in excel format.


问:
PostgreSQL: List databases user has privilege to connect
How do I list only the databases the user has CONNECT privilege on PostgreSQL?

For instance, user1 has access to database db1 and user2 has access to db2.

When each of these users login/connect to their databases and they need to retrieve the databases list they can connect with.

Here is what i've done so far:

Created two databases db1 and db2 on my new prostgreSQL server.

```<code>CREATE DATABASE db1
    WITH
    OWNER = admin
    ENCODING = 'WIN1252'
    CONNECTION LIMIT = -1;

CREATE DATABASE db2
    WITH
    OWNER = admin
    ENCODING = 'WIN1252'
    CONNECTION LIMIT = -1;
</code>```

I've also created two new users (other than admin) user1 and user2

```<code>CREATE USER user1 WITH LOGIN ENCRYPTED PASSWORD 'user1';
CREATE USER user2 WITH LOGIN ENCRYPTED PASSWORD 'user2';
</code>```

Then I ran the following queries to make user1 as owner of db1 and user2 as the onwer of db2

```<code>BEGIN;
ALTER DATABASE db1 owner to user1;
REVOKE CONNECT ON DATABASE db1 FROM public;
GRANT CONNECT ON DATABASE db1 TO user1;
COMMIT

BEGIN;
ALTER DATABASE db2 owner to user2;
REVOKE CONNECT ON DATABASE db2 FROM public;
GRANT CONNECT ON DATABASE db2 TO user2;
COMMIT
</code>```

This way user1 cannot connect to db2 and user2 cannot connect to db1.

Running this query

```<code>SELECT datname , (aclexplode(datacl)).grantor,
       (aclexplode(datacl)).grantee,
       (aclexplode(datacl)).privilege_type,
       (aclexplode(datacl)).is_grantable FROM pg_database
</code>```

gives this:

```<code> datname | grantor | grantee | privilege_type | is_grantable
---------+---------+---------+----------------+--------------
 db1     |   16386 |       0 | TEMPORARY      | f
 db1     |   16386 |   16386 | CREATE         | f
 db1     |   16386 |   16386 | TEMPORARY      | f
 db1     |   16386 |   16386 | CONNECT        | f
 db2     |   16387 |       0 | TEMPORARY      | f
 db2     |   16387 |   16387 | CREATE         | f
 db2     |   16387 |   16387 | TEMPORARY      | f
 db2     |   16387 |   16387 | CONNECT        | f
(8 rows)
</code>```

omitted template1 and template0 from results

How do I interpret if user1 has access to CONNECT db2 or not?

Is there any other way to achieve this?

答:
aclexplode().grantee can be joined to pg_user.usesysid to get the name of the user.

However, the simpler solution is to use the access privilege inquiry functions.

To check if user1 can connect to db2:

```<code>SELECT has_database_privilege('user1', 'db2', 'CONNECT')
</code>```

To list all databases which are accessible to user1:

```<code>SELECT datname
FROM pg_database
WHERE has_database_privilege('user1', datname, 'CONNECT')
</code>```

Body:
How do I list only the databases the user has CONNECT privilege on PostgreSQL?

For instance, user1 has access to database db1 and user2 has access to db2.

When each of these users login/connect to their databases and they need to retrieve the databases list they can connect with.

Here is what i've done so far:

Created two databases db1 and db2 on my new prostgreSQL server.

CREATE DATABASE db1
    WITH
    OWNER = admin
    ENCODING = 'WIN1252'
    CONNECTION LIMIT = -1;

CREATE DATABASE db2
    WITH
    OWNER = admin
    ENCODING = 'WIN1252'
    CONNECTION LIMIT = -1;

I've also created two new users (other than admin) user1 and user2

CREATE USER user1 WITH LOGIN ENCRYPTED PASSWORD 'user1';
CREATE USER user2 WITH LOGIN ENCRYPTED PASSWORD 'user2';

Then I ran the following queries to make user1 as owner of db1 and user2 as the onwer of db2

BEGIN;
ALTER DATABASE db1 owner to user1;
REVOKE CONNECT ON DATABASE db1 FROM public;
GRANT CONNECT ON DATABASE db1 TO user1;
COMMIT

BEGIN;
ALTER DATABASE db2 owner to user2;
REVOKE CONNECT ON DATABASE db2 FROM public;
GRANT CONNECT ON DATABASE db2 TO user2;
COMMIT

This way user1 cannot connect to db2 and user2 cannot connect to db1.

Running this query

SELECT datname , (aclexplode(datacl)).grantor,
       (aclexplode(datacl)).grantee,
       (aclexplode(datacl)).privilege_type,
       (aclexplode(datacl)).is_grantable FROM pg_database

gives this:

 datname | grantor | grantee | privilege_type | is_grantable
---------+---------+---------+----------------+--------------
 db1     |   16386 |       0 | TEMPORARY      | f
 db1     |   16386 |   16386 | CREATE         | f
 db1     |   16386 |   16386 | TEMPORARY      | f
 db1     |   16386 |   16386 | CONNECT        | f
 db2     |   16387 |       0 | TEMPORARY      | f
 db2     |   16387 |   16387 | CREATE         | f
 db2     |   16387 |   16387 | TEMPORARY      | f
 db2     |   16387 |   16387 | CONNECT        | f
(8 rows)

omitted template1 and template0 from results

How do I interpret if user1 has access to CONNECT db2 or not?

Is there any other way to achieve this?

Body:
aclexplode().grantee can be joined to pg_user.usesysid to get the name of the user.

However, the simpler solution is to use the access privilege inquiry functions.

To check if user1 can connect to db2:

SELECT has_database_privilege('user1', 'db2', 'CONNECT')

To list all databases which are accessible to user1:

SELECT datname
FROM pg_database
WHERE has_database_privilege('user1', datname, 'CONNECT')


问:
Default value for models.GenericIpAddressField
i am trying to add another column in my model:

ip_address = models.GenericIPAddressField()

and when i run makemigrations, i have to set a default value. what should i put? thanks in advance.

models.py

```<code>class Prospect(models.Model):
    full_name = models.CharField(max_length=120)
    email = models.CharField(max_length=80)
    contact_number = models.CharField(max_length=14)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    user = models.ForeignKey(VendicsUser, null=True)
    ip_address = models.GenericIPAddressField()

    def __unicode__(self):
        return self.full_name

    def __str__(self):
        return self.email
</code>```

答:
You can use   </p>

```<code>ip_address = models.GenericIPAddressField(default='192.0.2.30')
</code>```

Body:
i am trying to add another column in my model:

ip_address = models.GenericIPAddressField()

and when i run makemigrations, i have to set a default value. what should i put? thanks in advance.

models.py

class Prospect(models.Model):
    full_name = models.CharField(max_length=120)
    email = models.CharField(max_length=80)
    contact_number = models.CharField(max_length=14)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    user = models.ForeignKey(VendicsUser, null=True)
    ip_address = models.GenericIPAddressField()

    def __unicode__(self):
        return self.full_name

    def __str__(self):
        return self.email

Body:
You can use

ip_address = models.GenericIPAddressField(default='192.0.2.30')


问:
How do I validate header parameters in compojure/swagger?
Is there an idiomatic/best practices way to do the following in compojure-api:

The user calls our api with the following curl calls:

```<code>curl https://some/api/v1/example?a=b -H "u: userid" -H "p: auth-ticket"

curl -X PUT https://some/api/v1/other-example -d '{"c":"d"}' -H "u: userid" -H "p: auth-ticket"
</code>```

I want to be able to send u and p to another (internal) service and validate whether they constitute an authorized/non-expired ticket.

I can check for the values in the middleware (wrapped using wrap-routes), but it latches on BEFORE the swagger/compojure validation that checks for the required presence of u and p.

I can't seem to find a way to sink the custom validation into the swagger/compojure validation.  Is there a good way to do this, or am I stuck validating before?

EDIT: I've done some more searching in the raw swagger, and I've found the idea of "Security Schema Objects" and "Authorizations", but I don't see any examples of how to use them with clojure/compojure.

EDIT: Code example.

```<code>(swag/GET* "/item/:item"
  [item]
  :summary "item"
  :path-params [item :- (swag/describe s/Str "The item.")]
  :description "Get the description of the item."
  :header-params [ticket :- (swag/describe s/Str "security ticket")
                  userid :- (swag/describe s/Str "user ticket")]
  (ok (find-item item))

(swag/GET* "/item/:item/detailed"
  [item]
  :summary "item - detailed"
  :path-params [item :- (swag/describe s/Str "The item.")]
  :description "Get a detailed description of the item."
  :header-params [ticket :- (swag/describe s/Str "security ticket")
                  userid :- (swag/describe s/Str "user ticket")]
  (ok (find-item item :detailed))
</code>```

My problem is how do I avoid writing the :header-params section over and over again on every endpoint and throw an "Access Denied" if there's a missing ticket/userid or if it doesn't validate.

答:
You can accomplish this using a combination of context and :middleware.

```<code>(swag/context "/item/:item" [item]
  :path-params [item :- (swag/describe s/Str "The item.")]
  :header-params [ticket :- (swag/describe s/Str "security ticket")
                  userid :- (swag/describe s/Str "user ticket")]
  :middleware [wrap-check-headers]

  (swag/GET "/" req
    :summary "item"
    :description "Get the description of the item."
    (ok (find-item item)))

  (swag/GET "/detailed" req
    :summary "item - detailed"
    :description "Get a detailed description of the item."
    (ok (find-item item :detailed))))
</code>```

And you can define wrap-check-headers something like:

```<code>(defn wrap-check-headers [handler]
  (fn [{{:strs [ticket userid]} :headers :as request}]
    (if (and (= ticket "123") (= userid "456"))
      (handler request)
      (forbidden "authorization header mismatch"))))
</code>```

This will produce a Swagger API that looks like:

And an API that behaves as desired:

```<code>$ curl -w '\nstatus:%{http_code}\n' -H Ticket:123 http://localhost:3000/item/abc/
{"errors":{"userid":"missing-required-key"}}
status:400

$ curl -w '\nstatus:%{http_code}\n' -H UserID:456 http://localhost:3000/item/abc/
{"errors":{"ticket":"missing-required-key"}}
status:400

$ curl -w '\nstatus:%{http_code}\n' -H Ticket:Wrong -H UserID:456 http://localhost:3000/item/abc/
authorization header mismatch
status:403

$ curl -w '\nstatus:%{http_code}\n' -H Ticket:123 -H UserID:456 http://localhost:3000/item/abc/
found ("abc")
status:200
</code>```

Body:
Is there an idiomatic/best practices way to do the following in compojure-api:

The user calls our api with the following curl calls:

curl https://some/api/v1/example?a=b -H "u: userid" -H "p: auth-ticket"

curl -X PUT https://some/api/v1/other-example -d '{"c":"d"}' -H "u: userid" -H "p: auth-ticket"

I want to be able to send u and p to another (internal) service and validate whether they constitute an authorized/non-expired ticket.

I can check for the values in the middleware (wrapped using wrap-routes), but it latches on BEFORE the swagger/compojure validation that checks for the required presence of u and p.

I can't seem to find a way to sink the custom validation into the swagger/compojure validation.  Is there a good way to do this, or am I stuck validating before?

EDIT: I've done some more searching in the raw swagger, and I've found the idea of "Security Schema Objects" and "Authorizations", but I don't see any examples of how to use them with clojure/compojure.

EDIT: Code example.

(swag/GET* "/item/:item"
  [item]
  :summary "item"
  :path-params [item :- (swag/describe s/Str "The item.")]
  :description "Get the description of the item."
  :header-params [ticket :- (swag/describe s/Str "security ticket")
                  userid :- (swag/describe s/Str "user ticket")]
  (ok (find-item item))

(swag/GET* "/item/:item/detailed"
  [item]
  :summary "item - detailed"
  :path-params [item :- (swag/describe s/Str "The item.")]
  :description "Get a detailed description of the item."
  :header-params [ticket :- (swag/describe s/Str "security ticket")
                  userid :- (swag/describe s/Str "user ticket")]
  (ok (find-item item :detailed))

My problem is how do I avoid writing the :header-params section over and over again on every endpoint and throw an "Access Denied" if there's a missing ticket/userid or if it doesn't validate.

Body:
You can accomplish this using a combination of context and :middleware.

(swag/context "/item/:item" [item]
  :path-params [item :- (swag/describe s/Str "The item.")]
  :header-params [ticket :- (swag/describe s/Str "security ticket")
                  userid :- (swag/describe s/Str "user ticket")]
  :middleware [wrap-check-headers]

  (swag/GET "/" req
    :summary "item"
    :description "Get the description of the item."
    (ok (find-item item)))

  (swag/GET "/detailed" req
    :summary "item - detailed"
    :description "Get a detailed description of the item."
    (ok (find-item item :detailed))))

And you can define wrap-check-headers something like:

(defn wrap-check-headers [handler]
  (fn [{{:strs [ticket userid]} :headers :as request}]
    (if (and (= ticket "123") (= userid "456"))
      (handler request)
      (forbidden "authorization header mismatch"))))

This will produce a Swagger API that looks like:

And an API that behaves as desired:

$ curl -w '\nstatus:%{http_code}\n' -H Ticket:123 http://localhost:3000/item/abc/
{"errors":{"userid":"missing-required-key"}}
status:400

$ curl -w '\nstatus:%{http_code}\n' -H UserID:456 http://localhost:3000/item/abc/
{"errors":{"ticket":"missing-required-key"}}
status:400

$ curl -w '\nstatus:%{http_code}\n' -H Ticket:Wrong -H UserID:456 http://localhost:3000/item/abc/
authorization header mismatch
status:403

$ curl -w '\nstatus:%{http_code}\n' -H Ticket:123 -H UserID:456 http://localhost:3000/item/abc/
found ("abc")
status:200


问:
Detect headphones Android
I program in recent years to Android and I wonder something:

How to detect the presence of headphones?

There is a method: isWiredHeadsetOn() but it doesn't work.

I've tried that but it doesn't work:

```<code>AudioManager am = (AudioManager)getSystemService(AUDIO_SERVICE);
Log.i("am.isWiredHeadsetOn()", am.isWiredHeadsetOn() + "");

if (am.isWiredHeadsetOn()) {
   //code
}
</code>```

Thank you (and sorry if I made spelling mistakes, I am French)

答:
@Phil answer at https://stackoverflow.com/a/19102661/4758255 is a good implementation to detect the headphone.

Here I'm quoting from his answer. Please upvoted his answer not this!

Upvote the answer: https://stackoverflow.com/a/19102661/4758255

I've had an app in the store for three years that monitors both the wired headset and bluetooth state and nobody has ever complained about battery drain. But that is because I am successfully using a single service and broadcast receiver for detecting events from both. Here's the two key classes:

```<code>public class HeadsetStateBroadcastReceiver extends BroadcastReceiver {

    public static final String[] HEADPHONE_ACTIONS = {
        Intent.ACTION_HEADSET_PLUG,
        "android.bluetooth.headset.action.STATE_CHANGED",
        "android.bluetooth.headset.profile.action.CONNECTION_STATE_CHANGED"
    };

    @Override
    public void onReceive(final Context context, final Intent intent) {

        boolean broadcast = false;

        // Wired headset monitoring
        if (intent.getAction().equals(HEADPHONE_ACTIONS[0]) {
            final int state = intent.getIntExtra("state", 0);
            AudioPreferences.setWiredHeadphoneState(context, state > 0);
            broadcast = true;
        }

        // Bluetooth monitoring
        // Works up to and including Honeycomb
        if (intent.getAction().equals(HEADPHONE_ACTIONS[1])) {
            int state = intent.getIntExtra("android.bluetooth.headset.extra.STATE", 0);
            AudioPreferences.setBluetoothHeadsetState(context, state == 2);
            broadcast = true;
        }

        // Works for Ice Cream Sandwich
        if (intent.getAction().equals(HEADPHONE_ACTIONS[2])) {
            int state = intent.getIntExtra("android.bluetooth.profile.extra.STATE", 0);
            AudioPreferences.setBluetoothHeadsetState(context, state == 2);
            broadcast = true;
        }

        // Used to inform interested activities that the headset state has changed
        if (broadcast) {
            LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("headsetStateChange"));
        }

    }

}
</code>```

Here is the service I use to register the broadcast receiver:

```<code>public class HeadsetMonitoringService extends Service {

    HeadsetStateBroadcastReceiver headsetStateReceiver;

    @Override
    public void onCreate() {

        headsetStateReceiver = new HeadsetStateBroadcastReceiver();
        final IntentFilter filter = new IntentFilter();
        for (String action: HeadsetStateBroadcastReceiver.HEADPHONE_ACTIONS) {
            filter.addAction(action);
        }

        registerReceiver(headsetStateReceiver, filter);

    }

    @Override
    public int onStartCommand(final Intent intent, final int flags, final int startId) {
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(headsetStateReceiver);
    }

    @Override
    public IBinder onBind(final Intent intent) {
        return null;
    }

}
</code>```

And here is my manifest entry:

```<code>    <service
        android:name=".services.HeadsetMonitoringService"
        android:enabled="true"
        android:exported="false" >
        <intent-filter>
            <action android:name="initialiseHeadsetService" />
        </intent-filter>
    </service>
</code>```

How it works is as follows:

I use an on boot broadcast receiver to send a start service message to the HeadsetMonitoringService (you don't have to do it this way, you could just do this when your application starts instead). The HeadsetMonitoringService in turn registers an instance of a broadcast listener that listens to all the headset events I am interested in - they are held in the HEADPHONE_ACTIONS array. Because the service is sticky it hangs around - and therefore so does the broadcast listener. But because both the service and the broadcast listener are event driven they do not consume any power until a headset state change occurs. Additionally, because the service is sticky, it will be restarted by the OS if it dies unexpectedly.

Whenever I receive a headset state change event I also fire a local broadcast so that interested activities can check the new state and take action if required.

For completeness, I should point out that I use another class (not shown here), AudioPreferences, to store as preferences both the Bluetooth and wired headset state, which can then be accessed whenever I need to know the headset state.

Your application will need the android.permission.BLUETOOTH permission if you are interested in the state of a Bluetooth headset. If not, just take out the Bluetooth related actions from the HEADPHONE_ACTIONS array and delete the associated if blocks from the onReceive method.

Title: Detect headphones Android

Body:
I program in recent years to Android and I wonder something:

How to detect the presence of headphones?

There is a method: isWiredHeadsetOn() but it doesn't work.

I've tried that but it doesn't work:

AudioManager am = (AudioManager)getSystemService(AUDIO_SERVICE);
Log.i("am.isWiredHeadsetOn()", am.isWiredHeadsetOn() + "");

if (am.isWiredHeadsetOn()) {
   //code
}

Thank you (and sorry if I made spelling mistakes, I am French)

Body:
@Phil answer at https://stackoverflow.com/a/19102661/4758255 is a good implementation to detect the headphone.

Here I'm quoting from his answer. Please upvoted his answer not this!

Upvote the answer: https://stackoverflow.com/a/19102661/4758255

I've had an app in the store for three years that monitors both the wired headset and bluetooth state and nobody has ever complained about battery drain. But that is because I am successfully using a single service and broadcast receiver for detecting events from both. Here's the two key classes:

public class HeadsetStateBroadcastReceiver extends BroadcastReceiver {

    public static final String[] HEADPHONE_ACTIONS = {
        Intent.ACTION_HEADSET_PLUG,
        "android.bluetooth.headset.action.STATE_CHANGED",
        "android.bluetooth.headset.profile.action.CONNECTION_STATE_CHANGED"
    };

    @Override
    public void onReceive(final Context context, final Intent intent) {

        boolean broadcast = false;

        // Wired headset monitoring
        if (intent.getAction().equals(HEADPHONE_ACTIONS[0]) {
            final int state = intent.getIntExtra("state", 0);
            AudioPreferences.setWiredHeadphoneState(context, state > 0);
            broadcast = true;
        }

        // Bluetooth monitoring
        // Works up to and including Honeycomb
        if (intent.getAction().equals(HEADPHONE_ACTIONS[1])) {
            int state = intent.getIntExtra("android.bluetooth.headset.extra.STATE", 0);
            AudioPreferences.setBluetoothHeadsetState(context, state == 2);
            broadcast = true;
        }

        // Works for Ice Cream Sandwich
        if (intent.getAction().equals(HEADPHONE_ACTIONS[2])) {
            int state = intent.getIntExtra("android.bluetooth.profile.extra.STATE", 0);
            AudioPreferences.setBluetoothHeadsetState(context, state == 2);
            broadcast = true;
        }

        // Used to inform interested activities that the headset state has changed
        if (broadcast) {
            LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("headsetStateChange"));
        }

    }

}

Here is the service I use to register the broadcast receiver:

public class HeadsetMonitoringService extends Service {

    HeadsetStateBroadcastReceiver headsetStateReceiver;

    @Override
    public void onCreate() {

        headsetStateReceiver = new HeadsetStateBroadcastReceiver();
        final IntentFilter filter = new IntentFilter();
        for (String action: HeadsetStateBroadcastReceiver.HEADPHONE_ACTIONS) {
            filter.addAction(action);
        }

        registerReceiver(headsetStateReceiver, filter);

    }

    @Override
    public int onStartCommand(final Intent intent, final int flags, final int startId) {
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(headsetStateReceiver);
    }

    @Override
    public IBinder onBind(final Intent intent) {
        return null;
    }

}

And here is my manifest entry:

    <service
        android:name=".services.HeadsetMonitoringService"
        android:enabled="true"
        android:exported="false" >
        <intent-filter>
            <action android:name="initialiseHeadsetService" />
        </intent-filter>
    </service>

How it works is as follows:

I use an on boot broadcast receiver to send a start service message to the HeadsetMonitoringService (you don't have to do it this way, you could just do this when your application starts instead). The HeadsetMonitoringService in turn registers an instance of a broadcast listener that listens to all the headset events I am interested in - they are held in the HEADPHONE_ACTIONS array. Because the service is sticky it hangs around - and therefore so does the broadcast listener. But because both the service and the broadcast listener are event driven they do not consume any power until a headset state change occurs. Additionally, because the service is sticky, it will be restarted by the OS if it dies unexpectedly.

Whenever I receive a headset state change event I also fire a local broadcast so that interested activities can check the new state and take action if required.

For completeness, I should point out that I use another class (not shown here), AudioPreferences, to store as preferences both the Bluetooth and wired headset state, which can then be accessed whenever I need to know the headset state.

Your application will need the android.permission.BLUETOOTH permission if you are interested in the state of a Bluetooth headset. If not, just take out the Bluetooth related actions from the HEADPHONE_ACTIONS array and delete the associated if blocks from the onReceive method.


问:
Switch between Fragments in BottomNavigationView
I'm working with a simple app with Bottom Navigation View. I have 3 fragments (layout and java). I have BottonNavigationView, declared in my MainActivity.java. My bottonnavigation have 3 items, for the 3 fragments. So, in my MainActivity.java, when i select a item, it start one fragment. So, when i select again another item, nothing happens, because in the java fragment i need to declare the BottonNavigationView, but i don't know how to set it to switch the actual fragment with another fragment.
I tried this link, but no success: https://developer.android.com/training/basics/fragments/fragment-ui.html

Sorry my bad english

Here the codes:

Main Activity

```<code> @Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    Fragment selectedFragment = null;
    switch (item.getItemId()) {
        case R.id.navigation_home:
            selectedFragment = HomeFragment.newInstance();
            break;
        case R.id.navigation_dashboard:
            selectedFragment = DashboardFragment.newInstance();
            break;
        case R.id.navigation_notifications:
            selectedFragment = NotificationsFragment.newInstance();
            break;
    }
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.content, selectedFragment);
    transaction.commit();
    return true;
}
</code>```

Fragment Java Example

```<code>public class HomeFragment extends Fragment {
public static HomeFragment newInstance() {
HomeFragment fragment = new HomeFragment();
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.navigation_home, container, false);
return inflater.inflate(R.layout.navigation_home, container, false);
}
</code>```

答:
You can try it:</p>

```<code>@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    Fragment selectedFragment = null;
    switch (item.getItemId()) {
        case R.id.navigation_home:
            selectedFragment = HomeFragment.newInstance();
            break;
        case R.id.navigation_dashboard:
            selectedFragment = DashboardFragment.newInstance();
            break;
        case R.id.navigation_notifications:
            selectedFragment = NotificationsFragment.newInstance();
            break;
    }
    getSupportFragmentManager().beginTransaction().replace(R.id.content, selectedFragment).commit();
    return true;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm working with a simple app with Bottom Navigation View. I have 3 fragments (layout and java). I have BottonNavigationView, declared in my MainActivity.java. My bottonnavigation have 3 items, for the 3 fragments. So, in my MainActivity.java, when i select a item, it start one fragment. So, when i select again another item, nothing happens, because in the java fragment i need to declare the BottonNavigationView, but i don't know how to set it to switch the actual fragment with another fragment.
I tried this link, but no success: https://developer.android.com/training/basics/fragments/fragment-ui.html

Sorry my bad english

Here the codes:

Main Activity

 @Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    Fragment selectedFragment = null;
    switch (item.getItemId()) {
        case R.id.navigation_home:
            selectedFragment = HomeFragment.newInstance();
            break;
        case R.id.navigation_dashboard:
            selectedFragment = DashboardFragment.newInstance();
            break;
        case R.id.navigation_notifications:
            selectedFragment = NotificationsFragment.newInstance();
            break;
    }
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.content, selectedFragment);
    transaction.commit();
    return true;
}

Fragment Java Example

public class HomeFragment extends Fragment {
public static HomeFragment newInstance() {
HomeFragment fragment = new HomeFragment();
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.navigation_home, container, false);
return inflater.inflate(R.layout.navigation_home, container, false);
}

Body:
You can try it:

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    Fragment selectedFragment = null;
    switch (item.getItemId()) {
        case R.id.navigation_home:
            selectedFragment = HomeFragment.newInstance();
            break;
        case R.id.navigation_dashboard:
            selectedFragment = DashboardFragment.newInstance();
            break;
        case R.id.navigation_notifications:
            selectedFragment = NotificationsFragment.newInstance();
            break;
    }
    getSupportFragmentManager().beginTransaction().replace(R.id.content, selectedFragment).commit();
    return true;
}


问:
Set video tag as background image and match the content
Here's my code:

```<code>.video-bg-container {
    position: relative;
    z-index: 9;
}

.video-bg {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    /*z-index: 9;*/
}

.video-bg-boxes {
    position: relative;
    /*position: absolute;*/
    /*top: 0;*/
    /*left: 0;*/
    /*right: 0;*/
    /*bottom: 0;*/
    padding: 70px 10%;
    z-index: 10;
}

.video-bg-boxes .blue-box {
    color: #ffffff;
    background-color: #0091cf!important;
    padding: 30px 30px 80px 30px;
    font-size: 16px;
    cursor: pointer;
    margin-bottom: 30px;
}
</code>```

Read full + demo at: https://jsfiddle.net/lanford/aeqx6ubp/4/

I want the video tag acts like an background image with back ground size cover: the width is always 100% but the height scale with the height of the contents inside and always responsive. Is there anyway to achive it by jquery or CSS?

答:
I think this might do the trick for you. But in this case on large devices the video will displayed properly with full width of the video visible. and the reason behind that is in most cases our video element aspect ratio will be different than our video source aspect ratio. So have used the overflow:hidden.One more thing that needs to be taken care of is to hide the video on mobile devices and just show a background image. This is because most mobile platforms won’t autoplay HTML5 video and will display it with an embedded play button on top of our content. And thats not an expected behaviour.

Remove width from video element. Keep position:absolute;top:0;left:0 and give overflow: hidden; to video-bg class.

.video-module {
  margin-bottom: 50px;
}

.video-bg-container {
  position: relative;
  z-index: 9;
}

.video-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
  /*z-index: 9;*/
}

video {
   position: absolute;
    top: 0;
    left: 0;
    height: 100%;
}

.video-bg-boxes {
  position: relative;
  /*position: absolute;*/
  /*top: 0;*/
  /*left: 0;*/
  /*right: 0;*/
  /*bottom: 0;*/
  padding: 70px 10%;
  z-index: 10;
}

.video-bg-boxes .blue-box {
  color: #ffffff;
  background-color: #0091cf!important;
  padding: 30px 30px 80px 30px;
  font-size: 16px;
  cursor: pointer;
  margin-bottom: 30px;
}

.video-bg-boxes .blue-box strong {
  font-size: 30px;
  color: #ffffff;
  text-transform: uppercase;
}

.video-bg-boxes .blue-box:hover {
  background-color: #E4E1E0!important;
  color: #4C4145!important;
}

.video-bg-boxes .blue-box:hover strong {
  color: #0091CF!important;
}

.video-bg-boxes .blue-box a {
  text-decoration: none;
  color: #ffffff;
}

.video-bg-boxes .blue-box:hover a {
  color: #0091CF;
}

.video-bg-boxes .grey-box {
  border: none!important;
  padding: 30px 30px 80px 30px;
  background: url("https://cdn2.hubspot.net/hubfs/3372283/axon-active/img/p1/blue-arrow-ico.png");
  background-position: center 90%;
  background-repeat: no-repeat;
  font-size: 16px;
  cursor: pointer;
  margin-bottom: 30px;
  background-color: #E4E1E0;
  color: #4C4145!important;
}

.video-bg-boxes .grey-box strong {
  font-size: 30px;
  color: #0091CF;
  text-transform: uppercase;
}

.video-bg-boxes .grey-box:hover {
  background: url("https://cdn2.hubspot.net/hubfs/3372283/axon-active/img/p1/arrow-ico.png")!important;
  background-position: center 90%!important;
  background-repeat: no-repeat!important;
  background-color: #0091cf!important;
  color: #ffffff!important;
}

.video-bg-boxes .grey-box:hover strong {
  color: #ffffff!important;
}

.video-bg-boxes .grey-box a {
  text-decoration: none;
  color: #4C4145;
}

.video-bg-boxes .grey-box:hover a {
  color: #ffffff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="video-module">
  <div class="video-bg-container">
    <div class="video-bg">
      <video autoplay="autoplay" loop="loop" controls="controls">
            <source src="https://cdn2.hubspot.net/hubfs/3372283/axon-active/img/p1/VerseQuence%20-%20Wilt%20(VOEZ%20Official%20Soundtrack)%20-%20YouTube.mp4?t=1496825800724" type="video/mp4">
      </video>
    </div>

    <div class="video-bg-boxes">
      <div class="blue-box">
        <div style="text-align: center;"><strong>Title</strong></div>
        <div style="text-align: center;"> </div>
        <div style="text-align: center;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed condimentum enim eu finibus tincidunt. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent eget neque scelerisque, molestie turpis sed,
          tristique turpis. Proin placerat pretium libero, at pellentesque lorem condimentum eu.</div>
      </div>

      <div class="blue-box">
        <div style="text-align: center;"><strong>Title</strong></div>
        <div style="text-align: center;"> </div>
        <div style="text-align: center;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed condimentum enim eu finibus tincidunt. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent eget neque scelerisque, molestie turpis sed,
          tristique turpis. Proin placerat pretium libero, at pellentesque lorem condimentum eu.</div>
      </div>

      <div class="blue-box">
        <div style="text-align: center;"><strong>Title</strong></div>
        <div style="text-align: center;"> </div>
        <div style="text-align: center;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed condimentum enim eu finibus tincidunt. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent eget neque scelerisque, molestie turpis sed,
          tristique turpis. Proin placerat pretium libero, at pellentesque lorem condimentum eu.</div>
      </div>
    </div>
  </div></code>```

Updated Fiddle

Hope it helps :)

Body:
Here's my code:

.video-bg-container {
    position: relative;
    z-index: 9;
}

.video-bg {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    /*z-index: 9;*/
}

.video-bg-boxes {
    position: relative;
    /*position: absolute;*/
    /*top: 0;*/
    /*left: 0;*/
    /*right: 0;*/
    /*bottom: 0;*/
    padding: 70px 10%;
    z-index: 10;
}

.video-bg-boxes .blue-box {
    color: #ffffff;
    background-color: #0091cf!important;
    padding: 30px 30px 80px 30px;
    font-size: 16px;
    cursor: pointer;
    margin-bottom: 30px;
}

Read full + demo at: https://jsfiddle.net/lanford/aeqx6ubp/4/

I want the video tag acts like an background image with back ground size cover: the width is always 100% but the height scale with the height of the contents inside and always responsive. Is there anyway to achive it by jquery or CSS?

Body:
I think this might do the trick for you. But in this case on large devices the video will displayed properly with full width of the video visible. and the reason behind that is in most cases our video element aspect ratio will be different than our video source aspect ratio. So have used the overflow:hidden.One more thing that needs to be taken care of is to hide the video on mobile devices and just show a background image. This is because most mobile platforms won’t autoplay HTML5 video and will display it with an embedded play button on top of our content. And thats not an expected behaviour.

Remove width from video element. Keep position:absolute;top:0;left:0 and give overflow: hidden; to video-bg class.

.video-module {
  margin-bottom: 50px;
}

.video-bg-container {
  position: relative;
  z-index: 9;
}

.video-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
  /*z-index: 9;*/
}

video {
   position: absolute;
    top: 0;
    left: 0;
    height: 100%;
}

.video-bg-boxes {
  position: relative;
  /*position: absolute;*/
  /*top: 0;*/
  /*left: 0;*/
  /*right: 0;*/
  /*bottom: 0;*/
  padding: 70px 10%;
  z-index: 10;
}

.video-bg-boxes .blue-box {
  color: #ffffff;
  background-color: #0091cf!important;
  padding: 30px 30px 80px 30px;
  font-size: 16px;
  cursor: pointer;
  margin-bottom: 30px;
}

.video-bg-boxes .blue-box strong {
  font-size: 30px;
  color: #ffffff;
  text-transform: uppercase;
}

.video-bg-boxes .blue-box:hover {
  background-color: #E4E1E0!important;
  color: #4C4145!important;
}

.video-bg-boxes .blue-box:hover strong {
  color: #0091CF!important;
}

.video-bg-boxes .blue-box a {
  text-decoration: none;
  color: #ffffff;
}

.video-bg-boxes .blue-box:hover a {
  color: #0091CF;
}

.video-bg-boxes .grey-box {
  border: none!important;
  padding: 30px 30px 80px 30px;
  background: url("https://cdn2.hubspot.net/hubfs/3372283/axon-active/img/p1/blue-arrow-ico.png");
  background-position: center 90%;
  background-repeat: no-repeat;
  font-size: 16px;
  cursor: pointer;
  margin-bottom: 30px;
  background-color: #E4E1E0;
  color: #4C4145!important;
}

.video-bg-boxes .grey-box strong {
  font-size: 30px;
  color: #0091CF;
  text-transform: uppercase;
}

.video-bg-boxes .grey-box:hover {
  background: url("https://cdn2.hubspot.net/hubfs/3372283/axon-active/img/p1/arrow-ico.png")!important;
  background-position: center 90%!important;
  background-repeat: no-repeat!important;
  background-color: #0091cf!important;
  color: #ffffff!important;
}

.video-bg-boxes .grey-box:hover strong {
  color: #ffffff!important;
}

.video-bg-boxes .grey-box a {
  text-decoration: none;
  color: #4C4145;
}

.video-bg-boxes .grey-box:hover a {
  color: #ffffff;
}

<div class="video-module">
  <div class="video-bg-container">
    <div class="video-bg">
      <video autoplay="autoplay" loop="loop" controls="controls">
            <source src="https://cdn2.hubspot.net/hubfs/3372283/axon-active/img/p1/VerseQuence%20-%20Wilt%20(VOEZ%20Official%20Soundtrack)%20-%20YouTube.mp4?t=1496825800724" type="video/mp4">
      </video>
    </div>

    <div class="video-bg-boxes">
      <div class="blue-box">
        <div style="text-align: center;"><strong>Title</strong></div>
        <div style="text-align: center;">&nbsp;</div>
        <div style="text-align: center;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed condimentum enim eu finibus tincidunt. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent eget neque scelerisque, molestie turpis sed,
          tristique turpis. Proin placerat pretium libero, at pellentesque lorem condimentum eu.</div>
      </div>

      <div class="blue-box">
        <div style="text-align: center;"><strong>Title</strong></div>
        <div style="text-align: center;">&nbsp;</div>
        <div style="text-align: center;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed condimentum enim eu finibus tincidunt. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent eget neque scelerisque, molestie turpis sed,
          tristique turpis. Proin placerat pretium libero, at pellentesque lorem condimentum eu.</div>
      </div>

      <div class="blue-box">
        <div style="text-align: center;"><strong>Title</strong></div>
        <div style="text-align: center;">&nbsp;</div>
        <div style="text-align: center;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed condimentum enim eu finibus tincidunt. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent eget neque scelerisque, molestie turpis sed,
          tristique turpis. Proin placerat pretium libero, at pellentesque lorem condimentum eu.</div>
      </div>
    </div>
  </div>

Updated Fiddle

Hope it helps :)


答:
The typical approach in C is to have functions expect this as the first parameter.

```<code>int push(Stack *self, int val)
{
  if (self->current_size == self->max_size -1) return 0;
  self->data[self->current_size++] = val;
  return 1;
}
</code>```

This has the added benefit that, unless you need polymorphism, you don't need to put the functions in the stack, because you could just call push(stack, 10) instead of stack->push(stack,10).

Title: "this" pointer in C (not C++)

Body:
I'm trying to create a stack in C for fun, and came up with the idea of using struct to represent the stack. Then I add function pointers to the struct for push() and pop() operations.

So far all is good it seems, but, for the implementation of the push() and pop() functions I need to refer to *this somehow. How can that (can it?) be done?

This is my struct

struct Stack {
    int *data;
    int current_size;
    int max_size;
    int (*push)(int);
    int (*pop)();
};

And as an example here's push

int push(int val) {
    if(current_size == max_size -1)
            return 0;

    data[current_size] = val;
    current_size++;

    return 1;
}

As you can imagine, the compiler has no idea what current_size is, as it would expect something like stack->current_size.

Is this possible to overcome somehow?

Body:
The typical approach in C is to have functions expect this as the first parameter.

int push(Stack *self, int val)
{
  if (self->current_size == self->max_size -1) return 0;
  self->data[self->current_size++] = val;
  return 1;
}

This has the added benefit that, unless you need polymorphism, you don't need to put the functions in the stack, because you could just call push(stack, 10) instead of stack->push(stack,10).


问:
Carousel String Offset in a button
I am trying to create a carousel with button "Read More" in every slide, it should be redirect to an image however it is not fetching the data instead it shows an error when im trying to put the button Illegal string offset (image2) -"image2 is the row in my sql table"

This is the carousel script.

```<code>                                    <?php
                                    include "db.php";
                                    $query      = "select * from carousel1 order by id desc limit 10";
                                    $res        = mysqli_query($con,$query);
                                    $count      =   mysqli_num_rows($res);
                                    while($c=mysqli_fetch_array($res)){

                                        $titlee  = $c['titlee'];
                                        $konten = $c['konten'];
                                        $gbr    = $c['image'];
                                        $gbr2    = $c['image2'];

                                        if($counter==0)
                                        {

                                            echo"<div class='item active'>";
                                            echo    "<a href=''>";
                                            echo        "<img src='images/$gbr'>";

                                            echo    "</a>";
                                            echo    "<div class='container'>";
                                            echo    "<div class='carousel-caption left-caption style='background-color:#EE0930'>";
                                            echo        "<a href=''> <font color=#ffffffff style='font-family: Verdana,Arial,Helvetica,Georgia; font-size: 13px;'>";
                                            echo            "<h5 class='text-left'>".$titlee."</h5></font>";
                                            echo       "</a>";

                                            echo "<a class=\"btn btn-primary btn-sm\" href=\"{$gbr2["image2"]}\">Read More</a>";
                                            echo   "</div>";
                                            echo    "</div>";
                                            echo    "</div>";

                                        }
                                        else
                                        {
                                            echo    "<div class='item'>";
                                            echo        "<a href=''>";
                                            echo            "<img src='images/$gbr'>";
                                            echo        "</a>";
                                            echo        "<div class='container'>";

                                            echo        "<div class='carousel-caption left-caption style='background-color:#EE0930'>";
                                            echo            "<a href=''> <font color=#ffffffff style='font-family: Verdana,Arial,Helvetica,Georgia; font-size: 13px;'><h5 class='text-left'>".$titlee."</h5></font>
                                            </a>";
                                            echo "<a class=\"btn btn-primary btn-sm\" href=\"{$gbr2["image2"]}\">Read More</a>";
                                            echo    "</div>";
                                            echo    "</div>";
                                            echo    "</div>";
                                                    }
                                                    $counter++;
                                                    }

                                            echo"</div>";
                                            echo    "<a class='left carousel-control' href='#myCarousel' data-slide='prev'>‹</a>";
                                            echo    "<a class='right carousel-control' href='#myCarousel' data-slide='next'>›</a>";

                                            echo"</div>";

                                            echo"<!-- End Slider Caraousel-->";
                                            ?>
</code>```

答:
The value of image2 is already being stored in $gbr2 ($gbr2    = $c['image2'];) . And then you're trying to use $gbr2["image2"] to get the value

Replace $gbr2["image2"] with  $gbr2

Title: Carousel String Offset in a button

Body:
I am trying to create a carousel with button "Read More" in every slide, it should be redirect to an image however it is not fetching the data instead it shows an error when im trying to put the button Illegal string offset (image2) -"image2 is the row in my sql table"

This is the carousel script.

                                    <?php
                                    include "db.php";
                                    $query      = "select * from carousel1 order by id desc limit 10";
                                    $res        = mysqli_query($con,$query);
                                    $count      =   mysqli_num_rows($res);
                                    while($c=mysqli_fetch_array($res)){

                                        $titlee  = $c['titlee'];
                                        $konten = $c['konten'];
                                        $gbr    = $c['image'];
                                        $gbr2    = $c['image2'];

                                        if($counter==0)
                                        {

                                            echo"
";
                                            echo    "";
                                            echo        "";

                                            echo    "";
                                            echo    "
";
                                            echo    "
";
                                            echo        " ";
                                            echo            "
".$titlee."
";
                                            echo       "";

                                            echo "Read More";
                                            echo   "
";
                                            echo    "
";
                                            echo    "
";

                                        }
                                        else
                                        {
                                            echo    "
";
                                            echo        "";
                                            echo            "";
                                            echo        "";
                                            echo        "
";

                                            echo        "
";
                                            echo            "
".$titlee."

                                            ";
                                            echo "Read More";
                                            echo    "
";
                                            echo    "
";
                                            echo    "
";
                                                    }
                                                    $counter++;
                                                    }

                                            echo"
";
                                            echo    "‹";
                                            echo    "›";

                                            echo"
";

                                            echo"";
                                            ?>


问:
expandable iOS tableViewCell
I have a custom tableViewControlelr that has rounded card view cells. The tableViewCells also have the ability to be clicked and when clicked, it expands.

```<code> func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.selectedIndex = indexPath
        self.didExpandCell()

    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if isExpanded && self.selectedIndex == indexPath{
            return 300
        }
        return 126
</code>```

within my tableviewcell, I have a custom view that is white, this is what allows for the card view appearance and it is also rounded. When the cell is not clicked, the cell is the standard height and looks like this:

And when the cell is clicked, it expands and looks like this:

As you can see when the cell is not clicked, the bottom part is straight and not rounded, I attempted to use this code to make it rounded but it did not work.

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cells", for: indexPath) as! ProfileTableViewCell

if TableView.rowHeight == 126 {

            cell.CustomView = UIView(frame: CGRect(x: 7, y: 8, width: 359, height: 20))

            return cell
        }
        else{

        }
}
</code>```

答:
I solved the problem doing this:</p>

```<code> func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cells", for: indexPath) as! ProfileTableViewCell
if isExpanded && self.selectedIndex == indexPath {
            cell.CustomView.frame = CGRect(x: 7, y: 8, width: 359, height: 283)
        }
       else {
       cell.CustomView.frame = CGRect(x: 7, y: 8, width: 359, height: 116)
        }
}
</code>```

Title: expandable iOS tableViewCell

Body:
I have a custom tableViewControlelr that has rounded card view cells. The tableViewCells also have the ability to be clicked and when clicked, it expands.

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.selectedIndex = indexPath
        self.didExpandCell()

    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if isExpanded && self.selectedIndex == indexPath{
            return 300
        }
        return 126

within my tableviewcell, I have a custom view that is white, this is what allows for the card view appearance and it is also rounded. When the cell is not clicked, the cell is the standard height and looks like this:

And when the cell is clicked, it expands and looks like this:

As you can see when the cell is not clicked, the bottom part is straight and not rounded, I attempted to use this code to make it rounded but it did not work.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cells", for: indexPath) as! ProfileTableViewCell

if TableView.rowHeight == 126 {

            cell.CustomView = UIView(frame: CGRect(x: 7, y: 8, width: 359, height: 20))

            return cell
        }
        else{

        }
}

Body:
I solved the problem doing this:

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cells", for: indexPath) as! ProfileTableViewCell
if isExpanded && self.selectedIndex == indexPath {
            cell.CustomView.frame = CGRect(x: 7, y: 8, width: 359, height: 283)
        }
       else {
       cell.CustomView.frame = CGRect(x: 7, y: 8, width: 359, height: 116)
        }
}


问:
Python opencv cv2.KMEANS_RANDOM_CENTERS
Based on the cv2.kmeans function, I have written a function "F(Image)" with "label" as output.

```<code>ret,label,center=cv2.kmeans(Image,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
</code>```

The output of F(Image), "label", is later used for other image processing.

However, I need to run F(Image) for numerous images. I noticed that the labels are different if I ran, say, F(Image1) and F(Image2) consecutively versus F(Image1) and F(Image2) separately.

My suspicion is that every time cv2.KMEANS_RANDOM_CENTERS is ran, it starts at a different random number.

Without going into the source code of cv2.KMEANS_RANDOM_CENTERS, is there any way to ensure that the labels are the same every time I run the code? Or run F(Image1) and F(Image2) as in they are ran separately.

答:
cv2.kmeans() takes 2 type of flags: cv2.KMEANS_PP_CENTERS and cv2.KMEANS_RANDOM_CENTERS.

cv2.KMEANS_RANDOM_CENTERS:

With this flag enabled, the method always starts with a random set of initial samples, and tries to converge from there depending upon your TermCirteria.

Pros:

Saves computation Time.

Cons:

Doesn't guarantee same labels for the exact same image.

cv2.KMEANS_PP_CENTERS:

With this flag enabled, the method first iterates the whole image to determine the probable centers and then starts to converge.

Pros:

Would yield optimum and consistent results for same input image

Cons:

Takes extra computation time for iterating all the pixels and determining probable samples.

Note: I have also read about another flag cv::KMEANS_USE_INITIAL_LABELS, using which you can pass custom samples, which are used by the method to converge, But in the documentation linked, that flag is not mentioned, Not Sure if it has been deprecated or the documentation is not updated.

Title: Python opencv cv2.KMEANS_RANDOM_CENTERS

Body:
Based on the cv2.kmeans function, I have written a function "F(Image)" with "label" as output.

ret,label,center=cv2.kmeans(Image,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)

The output of F(Image), "label", is later used for other image processing.

However, I need to run F(Image) for numerous images. I noticed that the labels are different if I ran, say, F(Image1) and F(Image2) consecutively versus F(Image1) and F(Image2) separately.

My suspicion is that every time cv2.KMEANS_RANDOM_CENTERS is ran, it starts at a different random number.

Without going into the source code of cv2.KMEANS_RANDOM_CENTERS, is there any way to ensure that the labels are the same every time I run the code? Or run F(Image1) and F(Image2) as in they are ran separately.


问:
Iteratively Subset DataFrame based on Unique Times
Given the following example DataFrame:

```<code>>>> df
                 Times  Values
0  05/10/2017 01:01:03       1
1  05/10/2017 01:05:00       2
2  05/10/2017 01:06:10       3
3  05/11/2017 08:25:20       4
4  05/11/2017 08:30:14       5
5  05/11/2017 08:30:35       6
</code>```

I want to subset this DataFrame by the 'Time' column, by matching a partial string up to the hour.  For example, I want to subset using partial strings which contain "05/10/2017 01:" and "05/11/2017 08:" which breaks up the subsets into two new data frames:

```<code>>>> df1
                 Times  Values
0  05/10/2017 01:01:03       1
1  05/10/2017 01:05:00       2
2  05/10/2017 01:06:10       3
</code>```

and

```<code>>>> df2
0  05/11/2017 08:25:20       4
1  05/11/2017 08:30:14       5
2  05/11/2017 08:30:35       6
</code>```

Is it possible to make this subset iterative in Pandas, for multiple dates/times that similarly have the date/hour as the common identifier?

答:
If you use the datetime type you can extract things like hours and days.</p>

```<code>times = pd.to_datetime(df['Times'])
hours = times.apply(lambda x: x.hour)
df1 = df[hours == 1]
</code>```

Body:
Given the following example DataFrame:

>>> df
                 Times  Values
0  05/10/2017 01:01:03       1
1  05/10/2017 01:05:00       2
2  05/10/2017 01:06:10       3
3  05/11/2017 08:25:20       4
4  05/11/2017 08:30:14       5
5  05/11/2017 08:30:35       6

I want to subset this DataFrame by the 'Time' column, by matching a partial string up to the hour.  For example, I want to subset using partial strings which contain "05/10/2017 01:" and "05/11/2017 08:" which breaks up the subsets into two new data frames:

>>> df1
                 Times  Values
0  05/10/2017 01:01:03       1
1  05/10/2017 01:05:00       2
2  05/10/2017 01:06:10       3

and

>>> df2
0  05/11/2017 08:25:20       4
1  05/11/2017 08:30:14       5
2  05/11/2017 08:30:35       6

Is it possible to make this subset iterative in Pandas, for multiple dates/times that similarly have the date/hour as the common identifier?

Body:
If you use the datetime type you can extract things like hours and days.

times = pd.to_datetime(df['Times'])
hours = times.apply(lambda x: x.hour)
df1 = df[hours == 1]


问:
How do I add a border to a Collection View in Swift?
Not a collection view cell, I figured that out by applying specific border functions such as borderColor and cornerRadius methods in my ViewController. I'm talking about encapsulating the whole view of cells with one border, kind of like this:

Much appreciated.

答:
You can do that using UICollectionViewDelegateFlowLayout and here's how.

```<code>// your margin for top, botom, right, left
let inBetweenMargin: CGFloat = 30

let collectionViewSize: CGSize = {

    // define the max width of your collection view
    let screen = UIScreen.main.bounds.size.width

    // your margin for top, botom, right, left
    let inBetweenMargin: CGFloat = 30

    // left, mind, right 'inBetweenMargin * 3'
    let cellSquareSize = screen - (inBetweenMargin * 3);

    return CGSize(width: cellSquareSize, height: cellSquareSize)
}()

// MARK: - UICollectionViewDelegateFlowLayout

// computed cell size
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    return collectionViewSize
}

// for spacing in between cells
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {

    return inBetweenMargin
}

// for spacing in between cells
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {

    return inBetweenMargin
}

// we define inset for us to achieved an equal margin for top, botom, right, left
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

    return UIEdgeInsets(top: inBetweenMargin, left: inBetweenMargin, bottom: inBetweenMargin, right: inBetweenMargin)
}
</code>```

Body:
You can do that using UICollectionViewDelegateFlowLayout and here's how.

// your margin for top, botom, right, left
let inBetweenMargin: CGFloat = 30

let collectionViewSize: CGSize = {

    // define the max width of your collection view
    let screen = UIScreen.main.bounds.size.width

    // your margin for top, botom, right, left
    let inBetweenMargin: CGFloat = 30

    // left, mind, right 'inBetweenMargin * 3'
    let cellSquareSize = screen - (inBetweenMargin * 3);

    return CGSize(width: cellSquareSize, height: cellSquareSize)
}()

// MARK: - UICollectionViewDelegateFlowLayout

// computed cell size
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    return collectionViewSize
}

// for spacing in between cells
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {

    return inBetweenMargin
}

// for spacing in between cells
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {

    return inBetweenMargin
}

// we define inset for us to achieved an equal margin for top, botom, right, left
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

    return UIEdgeInsets(top: inBetweenMargin, left: inBetweenMargin, bottom: inBetweenMargin, right: inBetweenMargin)
}


问:
What is the maximum number of table names under a single schema in a DB2 subsystem?
What is the maximum number of results possible from the following SQL query for DB2 on z/OS?

```<code>SELECT NAME FROM SYSIBM.SYSTABLES WHERE TYPE='T' AND CREATOR=? ORDER BY NAME ASC
</code>```

This query is intended to fetch a list of all table names under a specific schema/creator in a DB2 subsystem.

I am having trouble finding a definitive answer. According to IBM's "Limits in DB2 for z/OS" article, the maximum number of internal objects for a DB2 database is 32767. Objects include views, indexes, etc.

I would prefer a more specific answer for maximum number of table names under one schema. For instance, here is an excerpt from an IDUG thread for a related question:

Based on the limit of 32767 objects in one database, where each tablespace takes two entries, and tables and indexes take one entry each, then the theoretical max would seem to be, with one tablespace per database,
  32767 - 2 (for the single tablespace) = 32765 / 2 = 16382 tables, assuming you need at least one index per table.

Are these assumptions valid (each tablespace takes two entries, at least one index per table)?

答:
I'm not sure your assumptions are appropriate because there are just too many possibilities to consider and in the grand scheme of things probably doesn't make much difference to the answer from your point of view

I'll rephrase your question to make sure I understand you correctly, you are after the maximum number of rows i.e. worst case scenario, that could possibly be returned by your SQL query?

DB2 System Limits

Maximum databases

Limited by system storage and EDM pool size

Maximum number of databases

65217

Maximum number of internal objects for each database

32767

The number of internal object descriptors (OBDs) for external objects are as follows

Table space: 2 (minimum required)

Table: 1

Therefore the maximum number of rows from your SQL query:

65217 * (32767 - 2) = 2,136,835,005

N.B. DB2 for z/OS does not have a 1:1 ratio between schemas and databases

N.N.B. This figure assumes 32,765 tables/tablespace/database i.e. 32765:1:1

I'm sure ±2 billion rows is NOT a "reasonable" expectation for max number of table names that might show up under a schema but it is possible

Body:
What is the maximum number of results possible from the following SQL query for DB2 on z/OS?

SELECT NAME FROM SYSIBM.SYSTABLES WHERE TYPE='T' AND CREATOR=? ORDER BY NAME ASC

This query is intended to fetch a list of all table names under a specific schema/creator in a DB2 subsystem.

I am having trouble finding a definitive answer. According to IBM's "Limits in DB2 for z/OS" article, the maximum number of internal objects for a DB2 database is 32767. Objects include views, indexes, etc.

I would prefer a more specific answer for maximum number of table names under one schema. For instance, here is an excerpt from an IDUG thread for a related question:

Based on the limit of 32767 objects in one database, where each tablespace takes two entries, and tables and indexes take one entry each, then the theoretical max would seem to be, with one tablespace per database,
  32767 - 2 (for the single tablespace) = 32765 / 2 = 16382 tables, assuming you need at least one index per table.

Are these assumptions valid (each tablespace takes two entries, at least one index per table)?


问:
MOSS/SharePoint 2007 Subsite navigation tool tip shows the word 'Subsite' - users not too happy about it
Not fully SharePoint xpert...yet quite functional. So, I understand 'SharePointish'...
Here is the problem...the subsite navigations- MOSS2007* (the look has been customise) show the tool tip with the word 'subsite'. which it is but Customer not too happy with that. To be fair....when you hover over a menu link 'About US' - the tool tip should be a tip attached the an example with the toooltip...

Appreciate your response.
~JustE

(Ok-Stackoverflow - didn't like me because I have been just reading and not answering your Questions :))
I couldnt'post the image)

But if you hover 'ABOUT US' - the tool Tip shows 'About Us subsite'

答:
Can you check what was entered as the description while Creating the Site ?
The tooltip is whatever is entered into description.

You can edit the description by going to Site Settings -> Title, description and Icon.


问:
Use query twice mysql_fetch_array
a simple

```<code>$stuff = mysql_query("SELECT * FROM users");

while($s = mysql_fetch_array($stuff)){
# ....
}

while($r = mysql_fetch_array($stuff)){
# ...
}
</code>```

The last while() does not work. I have tried run foreach($stuff as $s) but then i get invalid array error.

How can i use the same query twice?

答:
Here is another simpler solution:

```<code>$slq = "SELECT * FROM users";

$stuff1 = mysql_query($slq);

while($s = mysql_fetch_array($stuff1)){
# ....
}

$stuff2 = mysql_query($slq);

while($r = mysql_fetch_array($stuff2)){
# ...
}
</code>```

Assign the sql to a variable, and call mysql multiple times.

no more mysql. use mysqli or pdo

Title: Use query twice mysql_fetch_array

Body:
a simple

$stuff = mysql_query("SELECT * FROM users");

while($s = mysql_fetch_array($stuff)){
# ....
}

while($r = mysql_fetch_array($stuff)){
# ...
}

The last while() does not work. I have tried run foreach($stuff as $s) but then i get invalid array error.

How can i use the same query twice?

Body:
Here is another simpler solution:

$slq = "SELECT * FROM users";

$stuff1 = mysql_query($slq);

while($s = mysql_fetch_array($stuff1)){
# ....
}

$stuff2 = mysql_query($slq);

while($r = mysql_fetch_array($stuff2)){
# ...
}

Assign the sql to a variable, and call mysql multiple times.

no more mysql. use mysqli or pdo