问:
Adding resources with jwt_required?
I've created an API using flask, where the authentication is all working fine using flask_jwt_extended.

However if I add a resource that has a jwt_required decorator I get this error.

```<code>  File "/Library/Python/2.7/site-packages/flask_jwt/__init__.py", line 176, in decorator
    _jwt_required(realm or current_app.config['JWT_DEFAULT_REALM'])
KeyError: 'JWT_DEFAULT_REALM'
</code>```

Example resource:

```<code>class Endpoint(Resource):

    @jwt_required()
    def get(self):
        return {"State": "Success"}
</code>```

Initialising the app:

```<code>app = Flask(__name__)
api = Api(app)
</code>```

Adding the resource:

```<code>api.add_resource(resource_class, "/myEndpoint")
</code>```

The only way I can get it to work is to define the Endpoint class in the same file as the API.

I think I need someway to pass the Realm into the endpoint class and have use the optional parameter on jwt_required to set the Realm.

答:
I think you forgot to initialize JWT instance. You can do it in 2 ways. First:

```<code>from flask import Flask
from flask_jwt import jwt_required, JWT
from flask_restful import Resource, Api

class Endpoint(Resource):

    @jwt_required()
    def get(self):
        return {"State": "Success"}

app = Flask(__name__)
app.config['SECRET_KEY'] = 'super-secret'

def authenticate(username, password):
    # you should find user in db here
    # you can see example in docs
    user = None
    if user:
        # do something
        return user

def identity(payload):
    # custom processing. the same as authenticate. see example in docs
    user_id = payload['identity']
    return None
# here what you need
jwt = JWT(app, authenticate, identity)
api = Api(app)

api.add_resource(Endpoint, '/myEndpoint')

if __name__ == '__main__':
  app.run(debug=True)
  app.run(host='0.0.0.0')
</code>```

The second way is update our configuration of application. Just change:

```<code>jwt = JWT(app, authenticate, identity)
</code>```

To:

```<code>app.config.update(
     JWT=JWT(app, authenticate, identity)
)
</code>```

Let's open our route. You will see:

```<code>{
  "description": "Request does not contain an access token",
  "error": "Authorization Required",
  "status_code": 401
}
</code>```

Hope it helps.

Title: Adding resources with jwt_required?

Body:
I've created an API using flask, where the authentication is all working fine using flask_jwt_extended.

However if I add a resource that has a jwt_required decorator I get this error.

  File "/Library/Python/2.7/site-packages/flask_jwt/__init__.py", line 176, in decorator
    _jwt_required(realm or current_app.config['JWT_DEFAULT_REALM'])
KeyError: 'JWT_DEFAULT_REALM'

Example resource:

class Endpoint(Resource):

    @jwt_required()
    def get(self):
        return {"State": "Success"}

Initialising the app:

app = Flask(__name__)
api = Api(app)

Adding the resource:

api.add_resource(resource_class, "/myEndpoint")

The only way I can get it to work is to define the Endpoint class in the same file as the API.

I think I need someway to pass the Realm into the endpoint class and have use the optional parameter on jwt_required to set the Realm.

Body:
I think you forgot to initialize JWT instance. You can do it in 2 ways. First:

from flask import Flask
from flask_jwt import jwt_required, JWT
from flask_restful import Resource, Api

class Endpoint(Resource):

    @jwt_required()
    def get(self):
        return {"State": "Success"}

app = Flask(__name__)
app.config['SECRET_KEY'] = 'super-secret'

def authenticate(username, password):
    # you should find user in db here
    # you can see example in docs
    user = None
    if user:
        # do something
        return user

def identity(payload):
    # custom processing. the same as authenticate. see example in docs
    user_id = payload['identity']
    return None
# here what you need
jwt = JWT(app, authenticate, identity)
api = Api(app)

api.add_resource(Endpoint, '/myEndpoint')

if __name__ == '__main__':
  app.run(debug=True)
  app.run(host='0.0.0.0')

The second way is update our configuration of application. Just change:

jwt = JWT(app, authenticate, identity)

To:

app.config.update(
     JWT=JWT(app, authenticate, identity)
)

Let's open our route. You will see:

{
  "description": "Request does not contain an access token",
  "error": "Authorization Required",
  "status_code": 401
}

Hope it helps.


来源: stackexchange

问:
Compiled PHP 7 missing mysql extension in WordPress
I have built PHP 7 with a configuration that worked for a previous version of PHP.
Now my WordPress websites get the message:

Your PHP installation appears to be missing the MySQL extension which is required by WordPress.

Other websites using mysqli do work. What am I missing?

I've also included all .so files with mysql in the name:

```<code>extension=dba.so
extension=mysql.so
extension=mysqli.so
extension=mysqlnd_mysql.so
extension=mysqlnd_mysqli.so
extension=mysqlnd.so
extension=pdo.so
extension=pdo_mysql.so
extension=pdo_odbc.so
extension=odbc.so
</code>```

答:
On Ubuntu, I fixed this error by running

```<code>sudo apt-get install php-mysql
</code>```

And then restarting my server (caddy, but you might be using apache or nginx).

source

ContentLicense: CC BY-SA 3.0

Body:
I have built PHP 7 with a configuration that worked for a previous version of PHP.
Now my WordPress websites get the message:

Your PHP installation appears to be missing the MySQL extension which is required by WordPress.

Other websites using mysqli do work. What am I missing?

I've also included all .so files with mysql in the name:

extension=dba.so
extension=mysql.so
extension=mysqli.so
extension=mysqlnd_mysql.so
extension=mysqlnd_mysqli.so
extension=mysqlnd.so
extension=pdo.so
extension=pdo_mysql.so
extension=pdo_odbc.so
extension=odbc.so

Body:
On Ubuntu, I fixed this error by running

sudo apt-get install php-mysql

And then restarting my server (caddy, but you might be using apache or nginx).

source


问:
python function returns nonetype, but i can convert it to string and its not null
So basically a class has been imported and and a function called from it. The called function is supposed to return a float, but when I perform addition on it it says cannot add type float and NoneType.

Yet I can convert the returned value to string and print it so it cant be null. I though NoneType was null or no value returned.

Calling function

```<code>    def showPositions(self):
         runningprofit = float(0)
         for trade in self.trades:
         #self.output.log("what does this show?" + str(trade.showTrade()))
         runningprofit += trade.showTrade()
</code>```

Called function

```<code>def showTrade(self):
    tradeStatus = "Entry Price: "+str(self.entryPrice)+"\tStatus: "+str(self.status)+"\tExit Price: "+str(self.exitPrice)

    if (self.status == "CLOSED"):
        tradeStatus = tradeStatus + "\tProfit: "
        if (self.exitPrice > self.entryPrice):
            tradeStatus = tradeStatus + "\033[92m"
        else:
            tradeStatus = tradeStatus + "\033[91m"

        tradeStatus = tradeStatus+str(self.exitPrice - self.entryPrice)+"\033[0m"
        self.output.log(tradeStatus)
        return(float(self.exitPrice - self.entryPrice))
</code>```

And the returned error is:

```<code>runningprofit += trade.showTrade()

TypeError: unsupported operand type(s) for +=: 'float' and 'NoneType'
</code>```

答:
this happens because the following condition is False:

```<code>if (self.status == "CLOSED"):
</code>```

then, there is no branch which returns proper value and hence None is returned.

None can not be added to a Float therefore you are getting the error.

Your options are either to handle all the non-CLOSED statuses within showTrade() or handle None in showPositions().

Body:
So basically a class has been imported and and a function called from it. The called function is supposed to return a float, but when I perform addition on it it says cannot add type float and NoneType.

Yet I can convert the returned value to string and print it so it cant be null. I though NoneType was null or no value returned.

Calling function

    def showPositions(self):
         runningprofit = float(0)
         for trade in self.trades:
         #self.output.log("what does this show?" + str(trade.showTrade()))
         runningprofit += trade.showTrade()

Called function

def showTrade(self):
    tradeStatus = "Entry Price: "+str(self.entryPrice)+"\tStatus: "+str(self.status)+"\tExit Price: "+str(self.exitPrice)

    if (self.status == "CLOSED"):
        tradeStatus = tradeStatus + "\tProfit: "
        if (self.exitPrice > self.entryPrice):
            tradeStatus = tradeStatus + "\033[92m"
        else:
            tradeStatus = tradeStatus + "\033[91m"

        tradeStatus = tradeStatus+str(self.exitPrice - self.entryPrice)+"\033[0m"
        self.output.log(tradeStatus)
        return(float(self.exitPrice - self.entryPrice))

And the returned error is:

runningprofit += trade.showTrade()

TypeError: unsupported operand type(s) for +=: 'float' and 'NoneType'

Body:
this happens because the following condition is False:

if (self.status == "CLOSED"):

then, there is no branch which returns proper value and hence None is returned.

None can not be added to a Float therefore you are getting the error.

Your options are either to handle all the non-CLOSED statuses within showTrade() or handle None in showPositions().


问:
What api to call to create token for wailon user
I am trying to create a token for login using this api:
Login API Using Token

But i am not able to understand the token cration api for the above.

I see there is a token creation api: Api for token cration but i am not able to create the token.

Let me know the api call format for Login token creation.

答:
I found answer to this:
You can create the token manually that lasts for 100 days.

using : http://hosting.wialon.com/login.html


问:
sending console JS commands to an Electron app
I'm looking to automate an existing Electron app. It gives access to the Developer Tools, so I could just paste Javascript code into the console, but there must be a way to do this remotely, ideally using Node or from the Terminal?

I've seen this option for running Chrome : --remote-debugging-port=9222 ... that hints at a solution but I can't seem to get closer.

答:
If you launch your Electron app with --remote-debugging-port=9222 then you will enable remote debugging via Chrome DevTools protocol. You can use a Chrome developer tools instance as a client, or use one of the clients here: https://github.com/ChromeDevTools/awesome-chrome-devtools#chrome-devtools-protocol

The debuggable Chrome instance will be running on localhost:9222. Which means as long as you are trying to debug from the same machine you are fine. However if you want to debug from a remote machine you need some additional setup.

Setup an SSH tunnel on the source machine:

ssh -L 0.0.0.0:9223:localhost:9222 localhost -N

This will accept incoming traffic on the 9223 port and route it to Chrome remote debugging.

Then on your client machine use the address: source-machine-ip:9223 to access the remote debugging.

Note: This may not work on Windows without additional SSH setup as SSH is not prepackaged with Windows.


问:
How to add gulp task to angular cli build
I'm switching my deployment tool for an Angular 4 project to angular/cli. The command ng build will put the resulting bundles in a dist folder by default.

I need to figure out how to add my custom task to this process. Specifically, I have a lot of .svg files that I need to bundle and minify into a sprite.defs.svg file, and place the result in dist/assets/svg/.  With my previous deployment toolchain, I used gulp with the gulp-svg-sprite plugin.  Here was my bundling step:

```<code>const svgSprite = require('gulp-svg-sprite');

gulp.src('**/*.svg')
  .pipe(svgSprite({
    mode: {
      defs: {
        dest:'.',
        sprite:"sprite.defs.svg"
      }
    }
  }))
  .pipe(gulp.dest('dist/assets/svg'));
</code>```

Is there a simple way to integrate something like this into angular/cli's ng build?

答:
Say, you manually run this gulp task as

```<code>gulp processSVG
</code>```

In the scripts section of package.json, define a command like this:

```<code>"prebuild": "gulp processSVG"
</code>```

npm script is smart enough to run the command with the "pre" prefix before the command with the same name, but without this prefix. Now, run the following command:

```<code>npm run build
</code>```

This command will run the prebuild command first and then the build command.

Body:
I'm switching my deployment tool for an Angular 4 project to angular/cli. The command ng build will put the resulting bundles in a dist folder by default.

I need to figure out how to add my custom task to this process. Specifically, I have a lot of .svg files that I need to bundle and minify into a sprite.defs.svg file, and place the result in dist/assets/svg/.  With my previous deployment toolchain, I used gulp with the gulp-svg-sprite plugin.  Here was my bundling step:

const svgSprite = require('gulp-svg-sprite');

gulp.src('**/*.svg')
  .pipe(svgSprite({
    mode: {
      defs: {
        dest:'.',
        sprite:"sprite.defs.svg"
      }
    }
  }))
  .pipe(gulp.dest('dist/assets/svg'));

Is there a simple way to integrate something like this into angular/cli's ng build?

Body:
Say, you manually run this gulp task as

gulp processSVG

In the scripts section of package.json, define a command like this:

"prebuild": "gulp processSVG"

npm script is smart enough to run the command with the "pre" prefix before the command with the same name, but without this prefix. Now, run the following command:

npm run build

This command will run the prebuild command first and then the build command.


问:
How do I extract the text from the html tag and how do I filter the text that it contains?
So What I am trying to do is grab the text from the particular tag within the link and what I want to do is return the html only if the text contains certain words for example: if text contains "chemical" then return that link if not pass

here is my code:

```<code>import requests
from bs4 import BeautifulSoup
import webbrowser

jobsearch = input("What type of job?: ")
location = input("What is your location: ")
url = ("https://ca.indeed.com/jobs?q=" + jobsearch + "&l=" + location)
base_url = 'https://ca.indeed.com/'

r = requests.get(url)
rcontent = r.content
prettify = BeautifulSoup(rcontent, "html.parser")

all_job_url = []

def get_all_joblinks():
    for tag in prettify.find_all('a', {'data-tn-element':"jobTitle"}):
        link = tag['href']
        all_job_url.append(link)

def filter_links():

    for eachurl in all_job_url:
        rurl = requests.get(base_url + eachurl)
        content = rurl.content
        soup = BeautifulSoup(content, "html.parser")
        summary = soup.find('td', {'class':'snip'}).get_text()
        print(summary)

def search_job():

    while True:

        if prettify.select('div.no_results'):
            print("no job matches found")
            break
        else:
            # opens the web page of job search if entries are found
            website = webbrowser.open_new(url);
            break

get_all_joblinks()
filter_links()
</code>```

答:
You seem to be getting all the links from a single indeed.ca page in your get_all_joblinks function. Here's how you could check whether a typical link mentions 'chemical' somewhere in the text in its body element.

```<code>>>> import requests
>>> import bs4
>>> page = requests.get('https://jobs.sanofi.us/job/-/-/507/4895612?utm_source=indeed.com&utm_campaign=sanofi%20sem%20campaign&utm_medium=job_aggregator&utm_content=paid_search&ss=paid').content
>>> soup = bs4.BeautifulSoup(page, 'lxml')
>>> body = soup.find('body').text
>>> chemical_present = body.lower().find('chemical')>-1
>>> chemical_present
True
</code>```

I hope this is what you were looking for.

Edit, in response to comment.

```<code>>>> import webbrowser
>>> job_type = 'engineer'
>>> location = 'Toronto'
>>> url = "https://ca.indeed.com/jobs?q=" + job_type + "&l=" + location
>>> base_url = '%s://%s' % parse.urlparse(url)[0:2]
>>> page = requests.get(url).content
>>> soup = bs4.BeautifulSoup(page, 'lxml')
>>> for link in soup.find_all('a', {'data-tn-element':"jobTitle"}):
...     job_page = requests.get(base_url+link['href']).content
...     job_soup = bs4.BeautifulSoup(job_page, 'lxml')
...     body = job_soup.find('body').text
...     if body.lower().find('chemical')>-1:
...         webbrowser.open(base_url+link['href'])
</code>```

Body:
So What I am trying to do is grab the text from the particular tag within the link and what I want to do is return the html only if the text contains certain words for example: if text contains "chemical" then return that link if not pass

here is my code:

import requests
from bs4 import BeautifulSoup
import webbrowser

jobsearch = input("What type of job?: ")
location = input("What is your location: ")
url = ("https://ca.indeed.com/jobs?q=" + jobsearch + "&l=" + location)
base_url = 'https://ca.indeed.com/'

r = requests.get(url)
rcontent = r.content
prettify = BeautifulSoup(rcontent, "html.parser")

all_job_url = []

def get_all_joblinks():
    for tag in prettify.find_all('a', {'data-tn-element':"jobTitle"}):
        link = tag['href']
        all_job_url.append(link)

def filter_links():

    for eachurl in all_job_url:
        rurl = requests.get(base_url + eachurl)
        content = rurl.content
        soup = BeautifulSoup(content, "html.parser")
        summary = soup.find('td', {'class':'snip'}).get_text()
        print(summary)

def search_job():

    while True:

        if prettify.select('div.no_results'):
            print("no job matches found")
            break
        else:
            # opens the web page of job search if entries are found
            website = webbrowser.open_new(url);
            break

get_all_joblinks()
filter_links()

Body:
You seem to be getting all the links from a single indeed.ca page in your get_all_joblinks function. Here's how you could check whether a typical link mentions 'chemical' somewhere in the text in its body element.

>>> import requests
>>> import bs4
>>> page = requests.get('https://jobs.sanofi.us/job/-/-/507/4895612?utm_source=indeed.com&utm_campaign=sanofi%20sem%20campaign&utm_medium=job_aggregator&utm_content=paid_search&ss=paid').content
>>> soup = bs4.BeautifulSoup(page, 'lxml')
>>> body = soup.find('body').text
>>> chemical_present = body.lower().find('chemical')>-1
>>> chemical_present
True

I hope this is what you were looking for.

Edit, in response to comment.

>>> import webbrowser
>>> job_type = 'engineer'
>>> location = 'Toronto'
>>> url = "https://ca.indeed.com/jobs?q=" + job_type + "&l=" + location
>>> base_url = '%s://%s' % parse.urlparse(url)[0:2]
>>> page = requests.get(url).content
>>> soup = bs4.BeautifulSoup(page, 'lxml')
>>> for link in soup.find_all('a', {'data-tn-element':"jobTitle"}):
...     job_page = requests.get(base_url+link['href']).content
...     job_soup = bs4.BeautifulSoup(job_page, 'lxml')
...     body = job_soup.find('body').text
...     if body.lower().find('chemical')>-1:
...         webbrowser.open(base_url+link['href'])


问:
How can I specify where I want my UI elements to go on orientation change in Interface Builder?
Ok so I know this is a bit of a newbie question, but being that I am a newbie its ok! I have a view that I am trying to make orientation friendly in IB, and I am having some difficulties.

I have everything looking nice in portrait of course, but then when I go to landscape mode (by hitting that arrow in the top-right corner) everything gets all messed up.

Now, because of the way the view is laid out, I need to align 3 buttons along the bottom of an image view in portrait, and then in landscape, those three buttons need to be symmetrically aligned along the right side.

No combination of fiddling with those red arrows in the size inspector are rewarding me the results I am seeking. Is it possible to set up the buttons one way in one orientation in IB, and then on change, set them completely different?

I have looked all around for a useful IB tutorial, but haven't been able to find anything.

答: Using IB's autosizing features can only do so much. PengOne does a good job of describing them in his second paragraph. If they are not enough, you have to move the elements programmatically. See Responding to Orientation Changes. Otherwise, you can just use a completely different view, again as mentioned by PengOne.</p>

ContentLicense: CC BY-SA 2.5


问:
Color cycling for multiple matplotlib pyplot contour plots
It is possible to cycle line colors with basic plots in matplotlib.pyplot:

```<code>import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_prop_cycle(plt.cycler('color', ['c', 'm', 'y', 'k']))

x = np.linspace(-1.0, 1.0, 50)
for f in [1.0, 2.0, 3.0, 4.0]:
    ax.plot(x, np.sin(x * f))
plt.show()
</code>```

This results in each partial sinewave plot having the next color from the cycler list, and it will wrap as necessary:

I am using the contour plot to draw a single contour. For each case I want to draw a single contour but I want the color shown to automatically cycle through a specified palette (so I can show a readable color-coded legend). However ax.set_prop_cycle doesn't seem to have the same effect here:

```<code>fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_prop_cycle(plt.cycler('color', ['c', 'm', 'y', 'k']))

x = np.linspace(-1.0, 1.0, 50)
y = np.linspace(-1.0, 1.0, 50)
z = np.zeros((len(x), len(y)))

# simple function to create useful contours:
def get_z(x, y, f):
    for i, u in enumerate(x):
        for j, v in enumerate(y):
            z[i, j] = (f * u) ** 2 + (f * v) ** 2
    return z

# plot for multiple values of `f`
for f in [1.0, 2.0, 3.0, 4.0]:
    ax.contour(x, y, get_z(x, y, f), levels=[1], linewidth=2)
plt.show()
</code>```

Each plot (ring) has the same color - it hasn't automatically cycled. I would like to have each plot a different color. I know that each "full" contour plot does cycle through colors for each contour drawn as part of a single plot, but in my case I'm just drawing a single contour at a fixed "level".

Is there a reasonably straightforward way to do this without explicitly specifying a color for each plot? I eventually plan to plot a dynamic number of plots, so it is not really practical to specify them all, and I need it to wrap around when required.

Perhaps there is a way to set or rotate the starting offset of a contour plot's color map?

答:
Since you anyway loop over your parameters, you may simply loop over the colors at the same time.

```<code># plot for multiple values of `f`
for f, c in zip([1.0, 2.0, 3.0, 4.0], ['c', 'm', 'y', 'k']):
    ax.contour(x, y, get_z(x, y, f), levels=[1], linewidth=2, colors=c)
</code>```

Or, if the number of plots is unknown,

```<code>colors = ['c', 'm', 'y', 'k']
for i,f in enumerate([1.0, 2.0, 3.0, 4.0]):
    ax.contour(x, y, get_z(x, y, f), levels=[1], linewidth=2, colors=colors[i%len(colors)])
plt.show()
</code>```

The argument not to be wanting to "explicitly specify a color for each plot" therefore would only make sense if no loop is used.

So to obtain the same result without a loop, you can specify several levels to the same contour plot and use a colormap.

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

fig = plt.figure()
ax = fig.add_subplot(111)

x = np.linspace(-1.0, 1.0, 50)
y = np.linspace(-1.0, 1.0, 50)
z = np.zeros((len(x), len(y)))

# simple function to create useful contours:
def get_z(x, y, f):
    for i, u in enumerate(x):
        for j, v in enumerate(y):
            z[i, j] = (f * u) ** 2 + (f * v) ** 2
    return z

colors = ['c', 'm', 'y', 'k']
levels = 1./np.array([1.0, 2.0, 3.0, 4.0][::-1])**2
cmcol =  zip(plt.Normalize(levels.min(), levels.max())(levels),colors[::-1])

cmap=matplotlib.colors.LinearSegmentedColormap.from_list("m", cmcol)
cont = ax.contour(x, y, get_z(x, y, 1), levels=levels, linewidth=2, cmap=cmap)

plt.show()
</code>```

Body:
It is possible to cycle line colors with basic plots in matplotlib.pyplot:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_prop_cycle(plt.cycler('color', ['c', 'm', 'y', 'k']))

x = np.linspace(-1.0, 1.0, 50)
for f in [1.0, 2.0, 3.0, 4.0]:
    ax.plot(x, np.sin(x * f))
plt.show()

This results in each partial sinewave plot having the next color from the cycler list, and it will wrap as necessary:

I am using the contour plot to draw a single contour. For each case I want to draw a single contour but I want the color shown to automatically cycle through a specified palette (so I can show a readable color-coded legend). However ax.set_prop_cycle doesn't seem to have the same effect here:

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_prop_cycle(plt.cycler('color', ['c', 'm', 'y', 'k']))

x = np.linspace(-1.0, 1.0, 50)
y = np.linspace(-1.0, 1.0, 50)
z = np.zeros((len(x), len(y)))

# simple function to create useful contours:
def get_z(x, y, f):
    for i, u in enumerate(x):
        for j, v in enumerate(y):
            z[i, j] = (f * u) ** 2 + (f * v) ** 2
    return z

# plot for multiple values of `f`
for f in [1.0, 2.0, 3.0, 4.0]:
    ax.contour(x, y, get_z(x, y, f), levels=[1], linewidth=2)
plt.show()

Each plot (ring) has the same color - it hasn't automatically cycled. I would like to have each plot a different color. I know that each "full" contour plot does cycle through colors for each contour drawn as part of a single plot, but in my case I'm just drawing a single contour at a fixed "level".

Is there a reasonably straightforward way to do this without explicitly specifying a color for each plot? I eventually plan to plot a dynamic number of plots, so it is not really practical to specify them all, and I need it to wrap around when required.

Perhaps there is a way to set or rotate the starting offset of a contour plot's color map?

Body:
Since you anyway loop over your parameters, you may simply loop over the colors at the same time.

# plot for multiple values of `f`
for f, c in zip([1.0, 2.0, 3.0, 4.0], ['c', 'm', 'y', 'k']):
    ax.contour(x, y, get_z(x, y, f), levels=[1], linewidth=2, colors=c)

Or, if the number of plots is unknown,

colors = ['c', 'm', 'y', 'k']
for i,f in enumerate([1.0, 2.0, 3.0, 4.0]):
    ax.contour(x, y, get_z(x, y, f), levels=[1], linewidth=2, colors=colors[i%len(colors)])
plt.show()

The argument not to be wanting to "explicitly specify a color for each plot" therefore would only make sense if no loop is used.

So to obtain the same result without a loop, you can specify several levels to the same contour plot and use a colormap.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

fig = plt.figure()
ax = fig.add_subplot(111)

x = np.linspace(-1.0, 1.0, 50)
y = np.linspace(-1.0, 1.0, 50)
z = np.zeros((len(x), len(y)))

# simple function to create useful contours:
def get_z(x, y, f):
    for i, u in enumerate(x):
        for j, v in enumerate(y):
            z[i, j] = (f * u) ** 2 + (f * v) ** 2
    return z

colors = ['c', 'm', 'y', 'k']
levels = 1./np.array([1.0, 2.0, 3.0, 4.0][::-1])**2
cmcol =  zip(plt.Normalize(levels.min(), levels.max())(levels),colors[::-1])

cmap=matplotlib.colors.LinearSegmentedColormap.from_list("m", cmcol)
cont = ax.contour(x, y, get_z(x, y, 1), levels=levels, linewidth=2, cmap=cmap)

plt.show()


问:
Faster alternative to push_back(size is known)
I have a float vector. As I process certain data, I push it back.I always know what the size will be while declaring the vector.

For the largest case, it is 172,490,752 floats. This takes about eleven seconds just to push_back everything.

Is there a faster alternative, like a different data structure or something?

答:
The usual way of speeding up a vector when you know the size beforehand is to call reserve on it before using push_back. This eliminates the overhead of reallocating memory and copying the data every time the previous capacity is filled.

Sometimes for very demanding applications this won't be enough. Even though push_back won't reallocate, it still needs to check the capacity every time. There's no way to know how bad this is without benchmarking, since modern processors are amazingly efficient when a branch is always/never taken.

You could try resize instead of reserve and use array indexing, but the resize forces a default initialization of every element; this is a waste if you know you're going to set a new value into every element anyway.

An alternative would be to use std::unique_ptr<float[]> and allocate the storage yourself.


问:
Azure Media Analytics vs Cognitive Services Video API
Azure is coming is with new Video Analytics API under the Azure Media Analytics(AMA) bracket, and looks promising. In the meantime, Azure Cognitive Services has also come up with Video API which can do some of the analytics jobs which already exist in AMA.
                                                      Why is Microsoft following these two different tracks to come up with analytics solution, rather than having one team look at it completely ?</p>

答:
Cognitive Services was designed to be a lightweight series of API's enabling cognitive capabilities for application developers.  This suite comprised different forms of AI such as speech and image analysis, in addition to Video.  </p>

<p>In the case of the Video APIs, these are actually hosted as Media Processors on the Azure Media Services (AMS) platform at the core.  </p>

Body:
Cognitive Services was designed to be a lightweight series of API's enabling cognitive capabilities for application developers.  This suite comprised different forms of AI such as speech and image analysis, in addition to Video.

In the case of the Video APIs, these are actually hosted as Media Processors on the Azure Media Services (AMS) platform at the core.


问:
4 Wide Columns in HTML/CSS
I apologize for the dumb question, but really don't want to send this to my devs. I am trying to add a fourth column to this area for another automotive brand. I tried duplicating one of the lists -- and it placed it on a separate line. Looking to go four wide.

Here is what is looks like live with three-wide.

Most popular selections:

Volkswagen

MK7 GTI 2.0T

MK7 Golf R 2.0T

MK6 GTI 2.0T

MK6 Golf R 2.0T

CC 2.0 TSI

MK5 R32 3.2L

Audi

S3 2.0T

A4 2.0 FSI Quattro

S4 2.7T

A4 1.8T Quattro

A3 2.0T FSI

S5 4.2L

Porsche

911 Turbo 997.2 3.8TT

911 Turbo 997.1 3.6TT

911 Turbo 996 3.6TT

```

答:
 .col-outer { display:inline-block; vertical-align:top;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <ul class="col-wrapper">
        <li class="col-outer">
            <ul class="col-inner-wrapper">
                <li class="col-inner col-title"><h3>Volkswagen</h3></li>
                <li class="col-inner">MK7 GTI 2.0T</li>
                <li class="col-inner">MK7 Golf R 2.0T</li>
                <li class="col-inner">MK6 GTI 2.0T</li>
                <li class="col-inner">MK6 Golf R 2.0T</li>
                <li class="col-inner">CC 2.0 TSI</li>
                <li class="col-inner">MK5 R32 3.2L</li>
            </ul>
        </li>
        <li class="col-outer">
            <ul class="col-inner-wrapper">
                <li class="col-inner col-title"><h3>Audi</h3></li>
                <li class="col-inner">S3 2.0T</li>
                <li class="col-inner">A4 2.0 FSI Quattro</li>
                <li class="col-inner">S4 2.7T</li>
                <li class="col-inner">A4 1.8T Quattro</li>
                <li class="col-inner">A3 2.0T FSI</li>
                <li class="col-inner">S5 4.2L</li>
            </ul>
        </li>
        <li class="col-outer">
            <ul class="col-inner-wrapper">
                <li class="col-inner col-title"><h3>Porsche</h3></li>
                <li class="col-inner">911 Turbo 997.2 3.8TT</li>
                <li class="col-inner">911 Turbo 997.1 3.6TT</li>
                <li class="col-inner">911 Turbo 996 3.6TT </li>
            </ul>
        </li>

    </ul></code>```

Title: 4 Wide Columns in HTML/CSS

Body:
 .col-outer { display:inline-block; vertical-align:top;}

 <ul class="col-wrapper">
        <li class="col-outer">
            <ul class="col-inner-wrapper">
                <li class="col-inner col-title"><h3>Volkswagen</h3></li>
                <li class="col-inner"><a href="{$current_location}/Volkswagen--Golf-GTI-Rabbit--MK7--2015--2.0T">MK7 GTI 2.0T</a></li>
                <li class="col-inner"><a href="{$current_location}/Volkswagen--.-R-Models--MK7-R--2015--2.0T">MK7 Golf R 2.0T</a></li>
                <li class="col-inner"><a href="{$current_location}/Volkswagen--Golf-GTI-Rabbit--MK6--10-2014--2.0T">MK6 GTI 2.0T</a></li>
                <li class="col-inner"><a href="{$current_location}/Volkswagen--.-R-Models--MK6-R--2012-2013--2.0T-FSI">MK6 Golf R 2.0T</a></li>
                <li class="col-inner"><a href="{$current_location}/Volkswagen--CC--2009--2.0-TSI">CC 2.0 TSI</a></li>
                <li class="col-inner"><a href="{$current_location}/Volkswagen--.-R-Models--MK5-R32--2008--VR6-3.2L">MK5 R32 3.2L</a></li>
            </ul>
        </li>
        <li class="col-outer">
            <ul class="col-inner-wrapper">
                <li class="col-inner col-title"><h3>Audi</h3></li>
                <li class="col-inner"><a href="{$current_location}/Audi--S3--2015--2.0T">S3 2.0T</a></li>
                <li class="col-inner"><a href="{$current_location}/Audi--A4--B7--05.5-2008--2.0T-FSI--Quattro">A4 2.0 FSI Quattro</a></li>
                <li class="col-inner"><a href="{$current_location}/Audi--S4--B5--00-2002--2.7T">S4 2.7T</a></li>
                <li class="col-inner"><a href="{$current_location}/Audi--A4--B6--02-2005--1.8T--Quattro">A4 1.8T Quattro</a></li>
                <li class="col-inner"><a href="{$current_location}/Audi--A3--8P--05-2013--2.0T-FSI">A3 2.0T FSI</a></li>
                <li class="col-inner"><a href="{$current_location}/Audi--S5--B8--2008-2012--V8-4.2L">S5 4.2L</a></li>
            </ul>
        </li>
        <li class="col-outer">
            <ul class="col-inner-wrapper">
                <li class="col-inner col-title"><h3>Porsche</h3></li>
                <li class="col-inner"><a href="{$current_location}/Porsche--911-Turbo--997.2--10-2012--3.8TT">911 Turbo 997.2 3.8TT</a></li>
                <li class="col-inner"><a href="{$current_location}/Porsche--911-Turbo--997.1--07-2009--3.6TT">911 Turbo 997.1 3.6TT</a></li>
                <li class="col-inner"><a href="{$current_location}/Porsche--911-Turbo--996--01-2005--3.6TT">911 Turbo 996 3.6TT </a></li>
            </ul>
        </li>

    </ul>


问:
How do I add an internal style sheet (not inline) at run time in Angular?
In my Angular 4 app, I have a page whose content is stored into a JSON (partly CSS definitions and partly HTML markup) at a certain URL on my server. So I've made a shell component to host the content in Angular.

For HTML, I had to use

 in the template and this.my_html = this.sanitizer.bypassSecurityTrustHtml(my_html); in the script.

For CSS, I tried

with different combinations of sanitization but Angular
always compromise the . In other words, the element is useless.

答: In the end, I had to use jQuery $('

Body: In the end, I had to use jQuery $('<style>').text(my_css).appendTo('head'); in the ngOnInit() handler, which works nicely, but doesn't feel... Angular.


问:
What is Oracle error ORA-01536?
I got the following error on Oracle: ORA-01536

What is the problem?

答:
ORA-01536: space quota exceeded for tablespace 'string'

Cause:  The space quota for the segment owner in the tablespace has been exhausted and the operation attempted the creation of a new segment extent in the tablespace.

Action:  Either drop unnecessary objects in the tablespace to reclaim space or have a privileged user increase the quota on this tablespace for the segment owner.

Title: What is Oracle error ORA-01536?


问:
Properly format BigQuery response
Querying data from a BigQuery project:

```<code>def post(self):
        lat = self.request.get("lat")
        lng = self.request.get("lng")
        query = '''query'''
        query_data = {
            'query': (query)
        }
        logging.info(query)
        query_request = service.jobs()
        query_response = query_request.query(projectId=PROJECTID, body=query_data).execute()
</code>```

The rows return something similar to this:

```<code>"rows": [{"f": [{"v": "area name."}, {"v": "example"}, {"v": " 100233"}, {"v": "0.0000"}, {"v": "0.0000"}, {"v": "761"}, {"v": "street name"}, {"v": "50"}, {"v": "City"}, {"v": "25"}, {"v": "Town"}, {"v": "distance value"}]
</code>```

Is there a way I could possible format it to something of this nature?

```<code>  [{
    "streetName": "street name",
    "streetId": "16833",
    "data": "example",
    "latitude": "0.0000",
    "longitude": "0.0000",
    "areaId": "847",
    "areaName": "area name",
    "townId": "50",
    "townName": "town",
    "stateId": "25",
    "stateName": "City",
    "distance": "distance value"
  }]
</code>```

答:
Are you using the generic API client instead of the Cloud-specific client? (By the latter, I mean the one installed by running pip install google-cloud). The latter provides a QueryResults class that has the rows pre-parsed for you.

```<code>query = client.run_sync_query(SQL_CODE)
query.run()
# insert some job.reload/job.state busy waiting
print(query.rows)
</code>```

Anyway, I believe the Cloud Python client is recommended. That said, since the original question seems to refer to the generic API client, you'll want to use the schema field on your query object in addition to the rows.

The schema will serve as a map that you compare against as you traverse the rows object.

I have used the below on a schema that has deeply nested/repeated fields; I don't have any samples, however, for what happens on a REPEATED field that is not a RECORD (e.g. REPEATED STRING or some such). Treat such behavior as undefined.

def merge_schema_to_rows(rows, schema):
  acc = {}
  if isinstance(rows, list):
    return list(map(lambda x: merge_schema_to_rows(x, schema), rows))

  if rows is None:
    return None
  # If a field is a REPEATED RECORD, each entry in that field's f list will only
  # have a v.
  if 'f' not in rows:
    rows = rows['v']

  for i, field in enumerate(rows['f']):
    if schema['fields'][i]['type'] == 'RECORD':
      acc[schema['fields'][i]['name']] = merge_schema_to_rows(field['v'], schema['fields'][i])
    else:
      acc[schema['fields'][i]['name']] = field['v']

  return acc
```

EDIT: Poking around GitHub, I was able to find a more canonical solution (i.e., what the Google Cloud client does, which is a more robust, but much lengthier version, of the solution I provided above.)

Title: Properly format BigQuery response

Body:
Querying data from a BigQuery project:

def post(self):
        lat = self.request.get("lat")
        lng = self.request.get("lng")
        query = '''query'''
        query_data = {
            'query': (query)
        }
        logging.info(query)
        query_request = service.jobs()
        query_response = query_request.query(projectId=PROJECTID, body=query_data).execute()

The rows return something similar to this:

"rows": [{"f": [{"v": "area name."}, {"v": "example"}, {"v": " 100233"}, {"v": "0.0000"}, {"v": "0.0000"}, {"v": "761"}, {"v": "street name"}, {"v": "50"}, {"v": "City"}, {"v": "25"}, {"v": "Town"}, {"v": "distance value"}]

Is there a way I could possible format it to something of this nature?

  [{
    "streetName": "street name",
    "streetId": "16833",
    "data": "example",
    "latitude": "0.0000",
    "longitude": "0.0000",
    "areaId": "847",
    "areaName": "area name",
    "townId": "50",
    "townName": "town",
    "stateId": "25",
    "stateName": "City",
    "distance": "distance value"
  }]

Body:
Are you using the generic API client instead of the Cloud-specific client? (By the latter, I mean the one installed by running pip install google-cloud). The latter provides a QueryResults class that has the rows pre-parsed for you.

query = client.run_sync_query(SQL_CODE)
query.run()
# insert some job.reload/job.state busy waiting
print(query.rows)

Anyway, I believe the Cloud Python client is recommended. That said, since the original question seems to refer to the generic API client, you'll want to use the schema field on your query object in addition to the rows.

The schema will serve as a map that you compare against as you traverse the rows object.

I have used the below on a schema that has deeply nested/repeated fields; I don't have any samples, however, for what happens on a REPEATED field that is not a RECORD (e.g. REPEATED STRING or some such). Treat such behavior as undefined.

def merge_schema_to_rows(rows, schema):
  acc = {}
  if isinstance(rows, list):
    return list(map(lambda x: merge_schema_to_rows(x, schema), rows))

  if rows is None:
    return None
  # If a field is a REPEATED RECORD, each entry in that field's f list will only
  # have a v.
  if 'f' not in rows:
    rows = rows['v']

  for i, field in enumerate(rows['f']):
    if schema['fields'][i]['type'] == 'RECORD':
      acc[schema['fields'][i]['name']] = merge_schema_to_rows(field['v'], schema['fields'][i])
    else:
      acc[schema['fields'][i]['name']] = field['v']

  return acc

EDIT: Poking around GitHub, I was able to find a more canonical solution (i.e., what the Google Cloud client does, which is a more robust, but much lengthier version, of the solution I provided above.)


问:
Writing content into txt file python
Here I am writing some content to text file in python,when I try running this without writing a function, it runs well and I get the desired result but when I try applying a def function(): the same doesn't happen.Any help would be useful to learn.</p>

```<code>def fu(self):
    self.xmldoc = minidom.parse('C:\\Users\\xyz\\Doc\\abc.xml')
    self.tree = ET.parse('C:\\Users\\xyz\\Doc\\abc.xml')
    self.root = self.tree.getroot()
    self.validate_model = self.xmldoc.getElementsByTagName('MODEL')
    self.extract_model = self.validate_model[0].firstChild.nodeValue
    # print("hi "+extract_model[len(extract_model)-1:])
    self.headerlist = self.xmldoc.getElementsByTagName('HW_VERSION')
    self.validate_header = self.headerlist[0].firstChild.nodeValue
    # print("HW_VERSION: " + validate_header)
    # print("Length of HW_VERSION: " + str(len(validate_header)))
    if re.match('^[A-Za-z][A-Za-z0-9.]*$', self.validate_header):
        print("The HW_VERSION is valid")
    else:
        print("Sorry")
        self.save_path = "C:\\Users\\c\\Downloads\\errors"
        self.name_of_file = "Error_log1"
        self.completeName = os.path.join(self.save_path,
        self.name_of_file + ".txt")
        file1 = open(self.completeName, 'rw')
        file1.write("Error Log file created at " + "\n")
        file1.write(str(datetime.datetime.now()) + "\n")
        file1.write("-------------------------------------" + "\n")
    file1.close()
</code>```

答:
Here's a couple things to check:

Your indentation. Your else statement (and all code below) isn't indented properly with respect to everything else.

How you called different variables, etc, from packages. Since you didn't post all  of your code, I don't know for sure, but you might need to do from xml import etree (among other things) and then do etree.ElementTree instead of ET.

Did you actually call the function with the appropriate argument? After adding in all the necessary import statements and fixing the indentation, I got no errors. For reference, here's the code I ended up using:

```<code>import os
import re
import datetime
from xml import dom
from xml import etree

def fu(self):
    self.xmldoc = dom.minidom.parse('C:\\Users\\xyz\\Doc\\abc.xml')
    self.tree = etree.ElementTree.parse('C:\\Users\\xyz\\Doc\\abc.xml')
    self.root = self.tree.getroot()
    self.validate_model = self.xmldoc.getElementsByTagName('MODEL')
    self.extract_model = self.validate_model[0].firstChild.nodeValue
    # print("hi "+extract_model[len(extract_model)-1:])
    self.headerlist = self.xmldoc.getElementsByTagName('HW_VERSION')
    self.validate_header = self.headerlist[0].firstChild.nodeValue
    # print("HW_VERSION: " + validate_header)
    # print("Length of HW_VERSION: " + str(len(validate_header)))
    if re.match('^[A-Za-z][A-Za-z0-9.]*$', self.validate_header):
        print("The HW_VERSION is valid")
    else:
        print("Sorry")
    self.save_path = "C:\\Users\\c\\Downloads\\errors"
    self.name_of_file = "Error_log1"
    self.completeName = os.path.join(self.save_path, self.name_of_file + ".txt")
    file1 = open(self.completeName, 'w')
    file1.write("Error Log file created at " + "\n")
    file1.write(str(datetime.datetime.now()) + "\n")
    file1.write("-------------------------------------" + "\n")
    file1.close()
</code>```

If as you say in your comment you ran this as print(fu()) then there's another problem. Your function needs an argument! If your function fu() was in an object, then that would have worked; instead, you need to provide an argument, probably (as @CaryShindell's answer says) your file name/path.

Title: Writing content into txt file python

Body:
Here I am writing some content to text file in python,when I try running this without writing a function, it runs well and I get the desired result but when I try applying a def function(): the same doesn't happen.Any help would be useful to learn.

def fu(self):
    self.xmldoc = minidom.parse('C:\\Users\\xyz\\Doc\\abc.xml')
    self.tree = ET.parse('C:\\Users\\xyz\\Doc\\abc.xml')
    self.root = self.tree.getroot()
    self.validate_model = self.xmldoc.getElementsByTagName('MODEL')
    self.extract_model = self.validate_model[0].firstChild.nodeValue
    # print("hi "+extract_model[len(extract_model)-1:])
    self.headerlist = self.xmldoc.getElementsByTagName('HW_VERSION')
    self.validate_header = self.headerlist[0].firstChild.nodeValue
    # print("HW_VERSION: " + validate_header)
    # print("Length of HW_VERSION: " + str(len(validate_header)))
    if re.match('^[A-Za-z][A-Za-z0-9.]*$', self.validate_header):
        print("The HW_VERSION is valid")
    else:
        print("Sorry")
        self.save_path = "C:\\Users\\c\\Downloads\\errors"
        self.name_of_file = "Error_log1"
        self.completeName = os.path.join(self.save_path,
        self.name_of_file + ".txt")
        file1 = open(self.completeName, 'rw')
        file1.write("Error Log file created at " + "\n")
        file1.write(str(datetime.datetime.now()) + "\n")
        file1.write("-------------------------------------" + "\n")
    file1.close()

Body:
Here's a couple things to check:

Your indentation. Your else statement (and all code below) isn't indented properly with respect to everything else.

How you called different variables, etc, from packages. Since you didn't post all  of your code, I don't know for sure, but you might need to do from xml import etree (among other things) and then do etree.ElementTree instead of ET.

Did you actually call the function with the appropriate argument? After adding in all the necessary import statements and fixing the indentation, I got no errors. For reference, here's the code I ended up using:

import os
import re
import datetime
from xml import dom
from xml import etree

def fu(self):
    self.xmldoc = dom.minidom.parse('C:\\Users\\xyz\\Doc\\abc.xml')
    self.tree = etree.ElementTree.parse('C:\\Users\\xyz\\Doc\\abc.xml')
    self.root = self.tree.getroot()
    self.validate_model = self.xmldoc.getElementsByTagName('MODEL')
    self.extract_model = self.validate_model[0].firstChild.nodeValue
    # print("hi "+extract_model[len(extract_model)-1:])
    self.headerlist = self.xmldoc.getElementsByTagName('HW_VERSION')
    self.validate_header = self.headerlist[0].firstChild.nodeValue
    # print("HW_VERSION: " + validate_header)
    # print("Length of HW_VERSION: " + str(len(validate_header)))
    if re.match('^[A-Za-z][A-Za-z0-9.]*$', self.validate_header):
        print("The HW_VERSION is valid")
    else:
        print("Sorry")
    self.save_path = "C:\\Users\\c\\Downloads\\errors"
    self.name_of_file = "Error_log1"
    self.completeName = os.path.join(self.save_path, self.name_of_file + ".txt")
    file1 = open(self.completeName, 'w')
    file1.write("Error Log file created at " + "\n")
    file1.write(str(datetime.datetime.now()) + "\n")
    file1.write("-------------------------------------" + "\n")
    file1.close()

If as you say in your comment you ran this as print(fu()) then there's another problem. Your function needs an argument! If your function fu() was in an object, then that would have worked; instead, you need to provide an argument, probably (as @CaryShindell's answer says) your file name/path.


问:
Using pointers and structs
Hello i'm not sure if I'm understand the following piece of code. I would glad if someone could read my explanations and correct me if I'm wrong.

 So first of all I'm declaring a struct with three arrays of char and an integer.

```<code>struct Employee
{
    char last[16];
    char first[11];
    char title[16];
    int salary;
};
</code>```

 After that I declare a function which takes three pointers to char and an integer value. This function uses malloc() and sizeof() to create a struct on the heap. Now this creations of the object on the heap is not really clear to me. When I use struct Employee* p = malloc(sizeof(struct Employee)), what happens there exactly?
 What happens when I use the function struct Employee* createEmployee (char* last, char* first, char* title, int salary) several times with different input. I know that I will get back a pointer p but isn't that the same pointer to the same struct on the heap. So do I rewrite the information on the heap, when I use the function several times? Or does it always create a new object in a different memory space?

```<code>struct Employee* createEmployee(char*, char*, char*, int);

struct Employee* createEmployee(char* last, char* first, char* title, int salary)
{
    struct Employee* p = malloc(sizeof(struct Employee));
    if (p != NULL)
    {
        strcpy(p->last, last);
        strcpy(p->first, first);
        strcpy(p->title, title);
        p->salary = salary;
    }
    return p;
}
</code>```

I would be glad if someone could explain it to me. Thank you very much.

答:
malloc assigns you a block of memory equal to its first argument, in this case the size of the Employee.

Every time you call createEmployee, you call malloc a separate time, and every time you call malloc, it gives you a fresh piece of memory.

This is what allows you to have different employees: if they all used the same memory, you would only be able to create one.

This is why calling free, and freeing that memory is important: the operating system has no other way of knowing whether you're using the memory or not.

If you want to edit an existing employee, maintain a pointer reference to it, and add a strcpy(p->title, newTitle); to change its title to newTitle.

Also, something that has been mentioned, strcpy is dangerous, as it will continue to write its strings regardless of whether it has exceeded the 11 characters allotted for it.

Title: Using pointers and structs

Body:
Hello i'm not sure if I'm understand the following piece of code. I would glad if someone could read my explanations and correct me if I'm wrong.

 So first of all I'm declaring a struct with three arrays of char and an integer.

struct Employee
{
    char last[16];
    char first[11];
    char title[16];
    int salary;
};

 After that I declare a function which takes three pointers to char and an integer value. This function uses malloc() and sizeof() to create a struct on the heap. Now this creations of the object on the heap is not really clear to me. When I use struct Employee* p = malloc(sizeof(struct Employee)), what happens there exactly?
 What happens when I use the function struct Employee* createEmployee (char* last, char* first, char* title, int salary) several times with different input. I know that I will get back a pointer p but isn't that the same pointer to the same struct on the heap. So do I rewrite the information on the heap, when I use the function several times? Or does it always create a new object in a different memory space?

struct Employee* createEmployee(char*, char*, char*, int);

struct Employee* createEmployee(char* last, char* first, char* title, int salary)
{
    struct Employee* p = malloc(sizeof(struct Employee));
    if (p != NULL)
    {
        strcpy(p->last, last);
        strcpy(p->first, first);
        strcpy(p->title, title);
        p->salary = salary;
    }
    return p;
}

I would be glad if someone could explain it to me. Thank you very much.


问:
BOOST::ASIO. Making sure io_service.run() is invoked only after async_receive(...) is called?
I have a problem where two threads are called like this, one after another.

new boost::thread( &SERVER::start_receive, this);

new boost::thread( &SERVER::run_io_service, this);

Where the first thread calls this function.

```<code>void start_receive()
{
    udp_socket.async_receive(....);
}
</code>```

and the second thread calls,

```<code>void run_io_service()
{
    io_service.run();
}
</code>```

and sometimes the io_service thread ends up finishing before the start_receive() thread and then the server cannot receive packets.

I thought about putting a sleep function between the two threads to wait a while for the start_receive() to complete and that works but I wondered if there was another sure fire way to make this happen?

答:
If you want to keep the io_service running, create a work object:

```<code>boost::asio::io_service svc;
auto work = std::make_shared<boost::asio::io_service::work>(svc);
svc.run(); // this will block as long as the work object is valid.
</code>```

The nice thing about this approach is that the work object above will keep the svc object "running", but not block any other operations on it.

Body:
I have a problem where two threads are called like this, one after another.

new boost::thread( &SERVER::start_receive, this);

new boost::thread( &SERVER::run_io_service, this);

Where the first thread calls this function.

void start_receive()
{
    udp_socket.async_receive(....);
}

and the second thread calls,

void run_io_service()
{
    io_service.run();
}

and sometimes the io_service thread ends up finishing before the start_receive() thread and then the server cannot receive packets.

I thought about putting a sleep function between the two threads to wait a while for the start_receive() to complete and that works but I wondered if there was another sure fire way to make this happen?

Body:
If you want to keep the io_service running, create a work object:

boost::asio::io_service svc;
auto work = std::make_shared<boost::asio::io_service::work>(svc);
svc.run(); // this will block as long as the work object is valid.

The nice thing about this approach is that the work object above will keep the svc object "running", but not block any other operations on it.


问:
Jquery validate plugin validation with thymeleaf not working
Validation not working when I click submit button because of th:field, but if do not use it (th:field) validation working fine. So please help me out.

Html code

```<code><input class="input-text full-width" type="text" th:name="houseNo" th:field="*{billingInfo.houseNo}" th:id="houseNo" placeholder="House No" />
</code>```

jQuery code

```<code>$("#review").validate({

        rules: {
            houseNo: "required"
        },
        messages: {
            houseNo: $("#houseN").text()
        },
        submitHandler: function(form) {
            alert("submit here");
            form.submit();
        }
    });
</code>```

答:
th:field overwrites the name and value properties of the <input /> it is attached to.  (And additionally, it's will generate the id if it has not already been chosen.

w/th:field

Therefore, you need to change your javascript to match what th:field is doing.

```<code><input class="input-text full-width" type="text" name="billingInfo.houseNo" id="houseNo" placeholder="House No" />
</code>```

goes with

```<code>$("#review").validate({
    rules: {
        "billingInfo.houseNo": "required"
    },
    messages: {
        "billingInfo.houseNo": $("#houseN").text()
    },
    submitHandler: function(form) {
        alert("submit here");
        form.submit();
    }
});
</code>```

Body:
Validation not working when I click submit button because of th:field, but if do not use it (th:field) validation working fine. So please help me out.

Html code

<input class="input-text full-width" type="text" th:name="houseNo" th:field="*{billingInfo.houseNo}" th:id="houseNo" placeholder="House No" />

jQuery code

$("#review").validate({

        rules: {
            houseNo: "required"
        },
        messages: {
            houseNo: $("#houseN").text()
        },
        submitHandler: function(form) {
            alert("submit here");
            form.submit();
        }
    });

Body:
th:field overwrites the name and value properties of the <input /> it is attached to.  (And additionally, it's will generate the id if it has not already been chosen.

w/th:field

Therefore, you need to change your javascript to match what th:field is doing.

<input class="input-text full-width" type="text" name="billingInfo.houseNo" id="houseNo" placeholder="House No" />

goes with

$("#review").validate({
    rules: {
        "billingInfo.houseNo": "required"
    },
    messages: {
        "billingInfo.houseNo": $("#houseN").text()
    },
    submitHandler: function(form) {
        alert("submit here");
        form.submit();
    }
});


问:
How to create a sliding window in R to divide data into test and train samples to test accuracy of forecasts?
We are using the forecast package in R to read 3 weeks worth of hourly data (3*7*24 data points) and make predictions for the next 24 hours. It's a time-series with multiple seasonality.

We have the forecast model running just fine and it seems to be doing well. Now, we wish to quantify the accuracy of our approach / forecasting algorithm for our data. We wish to use the accuracy function in forecast package for this purpose. We understand that the accuracy function works so that it f is the forecast and x is the actual observation vector then accuracy(f,x) would give us the several accuracy measurements for this forecast.

We have data from the past several months and we wish to write a sliding window algorithm that picks (3*7*24) hour values and then predicts the next 24 hours. Then, compares these values against actual data for the next day / 24 hours, displays the accuracy, then slides the window by (24 points / hours) / next day and repeats.

The sample data is generated as follows:

```<code>library("forecast")

time <- 1:(12*168)
set.seed(1)
ds <- msts(sin(2*pi*time/24)+c(1,1,1.2,0.8,1,0,0)[((time-1)%/%24)%%7+1]+ time/400+rnorm(length(time),0,0.2),seasonal.periods=c(24,168))
plot(ds)
head(ds)
tail(ds)
length(ds)
length(time)
</code>```

Forecasting procedure is as follows:

```<code>model <- tbats(ds[1:504])
fcst <- forecast(model,h=24,level=90)
accuracy(fcst,ds[505:528])     ##Test accuracy of forecast against next/actual 24 values
</code>```

Now, we wish to slide the "window" by 24 and repeat the same procedure, that is, the next set of values used to build the model will be ds[25:528] and their accuracy will be tested against ds[529:552] ... and so on. How can we implement this?

Also, is there a better way to test overall accuracy of this forecasting algorithm for our scenario?

答:
I would do this by creating a vector of times representing the front edge of the sliding windows, then using lapply to iterate the forecasting and scoring process over the windows those edges imply. Like...

```<code># set a couple of parameters we'll use to slice the series into chunks:
# window width (w) and the time step at which you want to end the first
# training set
w = 24 ; start = 504

# now use those parameters to make a vector of the time steps at which each
# window will end
steps <- seq(start + w, length(ds), by = w)

# using lapply, iterate the forecasting-and-scoring process over the
# windows that created
cv_list <- lapply(steps, function(x) {

    train <- ds[1:(x - w)]
    test <- ds[(x - w + 1):x]

    model <- tbats(train)
    fcst <- forecast(model, h = w, level = 90)
    accuracy(fcst, test)

})
</code>```

Example output for the first window:

```<code>> cv_list[[1]]
                       ME      RMSE       MAE        MPE     MAPE      MASE
Training set 0.0001587681 0.3442898 0.2689754 34.3957362 84.30841 0.9560206
Test set     0.2619029897 0.8961109 0.7868256 -0.6832273 36.64301 2.7966186
                   ACF1
Training set 0.02588145
Test set             NA
</code>```

If you want summaries of the scores for the whole list, you can do something like...

```<code>rmse <- mean(unlist(lapply(cv_list, '[[', "Test set","RMSE")))
</code>```

...which produces this:

```<code>[1] 1.011177
</code>```

Body:
We are using the forecast package in R to read 3 weeks worth of hourly data (3*7*24 data points) and make predictions for the next 24 hours. It's a time-series with multiple seasonality.

We have the forecast model running just fine and it seems to be doing well. Now, we wish to quantify the accuracy of our approach / forecasting algorithm for our data. We wish to use the accuracy function in forecast package for this purpose. We understand that the accuracy function works so that it f is the forecast and x is the actual observation vector then accuracy(f,x) would give us the several accuracy measurements for this forecast.

We have data from the past several months and we wish to write a sliding window algorithm that picks (3*7*24) hour values and then predicts the next 24 hours. Then, compares these values against actual data for the next day / 24 hours, displays the accuracy, then slides the window by (24 points / hours) / next day and repeats.

The sample data is generated as follows:

library("forecast")

time <- 1:(12*168)
set.seed(1)
ds <- msts(sin(2*pi*time/24)+c(1,1,1.2,0.8,1,0,0)[((time-1)%/%24)%%7+1]+ time/400+rnorm(length(time),0,0.2),seasonal.periods=c(24,168))
plot(ds)
head(ds)
tail(ds)
length(ds)
length(time)

Forecasting procedure is as follows:

model <- tbats(ds[1:504])
fcst <- forecast(model,h=24,level=90)
accuracy(fcst,ds[505:528])     ##Test accuracy of forecast against next/actual 24 values

Now, we wish to slide the "window" by 24 and repeat the same procedure, that is, the next set of values used to build the model will be ds[25:528] and their accuracy will be tested against ds[529:552] ... and so on. How can we implement this?

Also, is there a better way to test overall accuracy of this forecasting algorithm for our scenario?

Body:
I would do this by creating a vector of times representing the front edge of the sliding windows, then using lapply to iterate the forecasting and scoring process over the windows those edges imply. Like...

# set a couple of parameters we'll use to slice the series into chunks:
# window width (w) and the time step at which you want to end the first
# training set
w = 24 ; start = 504

# now use those parameters to make a vector of the time steps at which each
# window will end
steps <- seq(start + w, length(ds), by = w)

# using lapply, iterate the forecasting-and-scoring process over the
# windows that created
cv_list <- lapply(steps, function(x) {

    train <- ds[1:(x - w)]
    test <- ds[(x - w + 1):x]

    model <- tbats(train)
    fcst <- forecast(model, h = w, level = 90)
    accuracy(fcst, test)

})

Example output for the first window:

> cv_list[[1]]
                       ME      RMSE       MAE        MPE     MAPE      MASE
Training set 0.0001587681 0.3442898 0.2689754 34.3957362 84.30841 0.9560206
Test set     0.2619029897 0.8961109 0.7868256 -0.6832273 36.64301 2.7966186
                   ACF1
Training set 0.02588145
Test set             NA

If you want summaries of the scores for the whole list, you can do something like...

rmse <- mean(unlist(lapply(cv_list, '[[', "Test set","RMSE")))

...which produces this:

[1] 1.011177


问:
Python encoding problems: zip csv buffers (Django)
In a Django view, I want to create some csv files in memory, and zip them to download.

I'm using Django 1.11 / Python 2.7. My code:

```<code>import csv
import zipfile
import StringIO

files = []

csv_buffer = StringIO.StringIO()
writer = csv.writer(csv_buffer)
writer.writerow(["val1", "str1"])

csv_buffer.seek(0)

files.append(csv_buffer)

zipped_file = StringIO.StringIO()

with zipfile.ZipFile(zipped_file, 'w') as zipper:
    for i, file in enumerate(files):
        file.seek(0)
        zipper.writestr("{}.csv".format(i), file.read())

zipped_file.seek(0)

# response = HttpResponse(csv_buffer, content_type='text/csv')
# response['Content-Disposition'] = 'attachment; filename=results.csv'
response = HttpResponse(zipped_file, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=results.zip'
return response
</code>```

With this code, the csv is encoded utf-8 but my editor complains about 'invalid characters'.

If I just return the csv file, I get an empty csv. No idea why..

I think the StringIO buffer has a wrong encoding, but I don't know how to make this work. If I do:

```<code>csv_buffer = StringIO.StringIO("")
</code>```

I can create a readable CSV file, but then the zip part of the code fails:

```<code>    'ascii' codec can't decode byte 0xd4 in position 10: ordinal not in range(128)
</code>```

Any explanation what's going wrong here would be appreciated!

Edit: Typo
Edit 2 : Added zip error message

答:
I solved it by explicitly defining the filename of the csv in the zip using the ZipInfo method like so:

```<code>zipinfo = zipfile.ZipInfo("{}.csv".format(i))
zipper.writestr(zipinfo, myfile.read())
</code>```

And miraculously it worked! Might have to do with zipfile not supporting UTF filenames. But instead of throwing an error, it messes up the zipped file itself.

Body:
In a Django view, I want to create some csv files in memory, and zip them to download.

I'm using Django 1.11 / Python 2.7. My code:

import csv
import zipfile
import StringIO

files = []

csv_buffer = StringIO.StringIO()
writer = csv.writer(csv_buffer)
writer.writerow(["val1", "str1"])

csv_buffer.seek(0)

files.append(csv_buffer)

zipped_file = StringIO.StringIO()

with zipfile.ZipFile(zipped_file, 'w') as zipper:
    for i, file in enumerate(files):
        file.seek(0)
        zipper.writestr("{}.csv".format(i), file.read())

zipped_file.seek(0)

# response = HttpResponse(csv_buffer, content_type='text/csv')
# response['Content-Disposition'] = 'attachment; filename=results.csv'
response = HttpResponse(zipped_file, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=results.zip'
return response

With this code, the csv is encoded utf-8 but my editor complains about 'invalid characters'.

If I just return the csv file, I get an empty csv. No idea why..

I think the StringIO buffer has a wrong encoding, but I don't know how to make this work. If I do:

csv_buffer = StringIO.StringIO("")

I can create a readable CSV file, but then the zip part of the code fails:

    'ascii' codec can't decode byte 0xd4 in position 10: ordinal not in range(128)

Any explanation what's going wrong here would be appreciated!

Edit: Typo
Edit 2 : Added zip error message

Body:
I solved it by explicitly defining the filename of the csv in the zip using the ZipInfo method like so:

zipinfo = zipfile.ZipInfo("{}.csv".format(i))
zipper.writestr(zipinfo, myfile.read())

And miraculously it worked! Might have to do with zipfile not supporting UTF filenames. But instead of throwing an error, it messes up the zipped file itself.


问:
Scrollview in two Linearlayouts?
I have 4 TextViews in my Activity and i am using LinearLayout with vertical orientation. Top one TextView is kind of header (no need to scroll) next one is some kind of description which i want to make scrollable. 3rd one is again a heading (no scroll needed) and 4th is description (need to scroll).
I tried but only top TextView (header) and 2nd TextView (description) is being showed on the screen. Description is scrollable but the problem is, other two TextView are hidden.
Its kind of silly question to ask but i am kind of stuck here because i am new to android. Here is my xml.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="?android:attr/actionBarSize"
android:orientation="vertical"
android:padding="15dp"

>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#d0f7c9"
    android:orientation="vertical"
    android:padding="10dp"

    >

    <TextView
        android:id="@+id/tvTitle"
        style="?android:attr/listSeparatorTextViewStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="#ffffff"
        android:textSize="20dp" />

</LinearLayout>

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#b3cff4"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tvShow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/black"
            android:textSize="20dp" />
    </LinearLayout>
</ScrollView>

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Program Output"
    android:textColor="@color/black"
    android:textSize="25dp" />

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#d2b3f4">

        <TextView
            android:id="@+id/tvOutput"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#ffffff"
            android:textSize="20dp" />

    </LinearLayout>

</ScrollView>
</code>```

答:
The way I would probably do this is create two layouts. One being number 1 and 2 text view. The other layout being 3 and 4. and then in the first layout, include the second.

```<code><include layout="@layout/layout2"/>
</code>```

Something like this.
LAYOUT ONE

```<code><linearlayout>
<text view>
<linearlayout>
<scrollview>
<textview>
</scrollview>
</linearlayout>

<include layout="@layout/layout2"/>

</linearlayout>
</code>```

LAYOUT TWO

```<code>   <linearlayout>
    <text view>
    <linearlayout>
    <scrollview>
    <textview>
    </scrollview>
    </linearlayout>
    </linear layout>
</code>```

Title: Scrollview in two Linearlayouts?

Body:
I have 4 TextViews in my Activity and i am using LinearLayout with vertical orientation. Top one TextView is kind of header (no need to scroll) next one is some kind of description which i want to make scrollable. 3rd one is again a heading (no scroll needed) and 4th is description (need to scroll).
I tried but only top TextView (header) and 2nd TextView (description) is being showed on the screen. Description is scrollable but the problem is, other two TextView are hidden.
Its kind of silly question to ask but i am kind of stuck here because i am new to android. Here is my xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="?android:attr/actionBarSize"
android:orientation="vertical"
android:padding="15dp"

>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#d0f7c9"
    android:orientation="vertical"
    android:padding="10dp"

    >

    <TextView
        android:id="@+id/tvTitle"
        style="?android:attr/listSeparatorTextViewStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="#ffffff"
        android:textSize="20dp" />

</LinearLayout>

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#b3cff4"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tvShow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/black"
            android:textSize="20dp" />
    </LinearLayout>
</ScrollView>

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Program Output"
    android:textColor="@color/black"
    android:textSize="25dp" />

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#d2b3f4">

        <TextView
            android:id="@+id/tvOutput"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#ffffff"
            android:textSize="20dp" />

    </LinearLayout>

</ScrollView>

Body:
The way I would probably do this is create two layouts. One being number 1 and 2 text view. The other layout being 3 and 4. and then in the first layout, include the second.

<include layout="@layout/layout2"/>

Something like this.
LAYOUT ONE

<linearlayout>
<text view>
<linearlayout>
<scrollview>
<textview>
</scrollview>
</linearlayout>

<include layout="@layout/layout2"/>

</linearlayout>

LAYOUT TWO

   <linearlayout>
    <text view>
    <linearlayout>
    <scrollview>
    <textview>
    </scrollview>
    </linearlayout>
    </linear layout>


问:
Old-School Windows 2000 Printing, or When is a Port Name a Computer?
A few years back, another clever programmer set up a VB.NET service to print to one of the server's installed printers.  The job queried a database table to see if it had any print requests, which specify the file to print and the name of the printer to send it to.  The job constructs a 3-part command line incantation and executes it; it goes a little something like this:

```<code>net use LPT2: IP_1.2.3.4 /user:domain\userid password >> netuse1.out
copy someExistingFile.pdf LPT2 >> copy.out
net use LPT2: /delete >> netuse2.out
</code>```

We've been asked to make other unrelated changes to this job, and happily complied.  Only any version of the job we deploy and run simply will not print.  The first statement fails with "System error 67 has occurred.  The network name cannot be found."

The job has queried the registry to find the port name for the printer specified by the user.  The port it tries is indeed the port "name" we see when looking at the printer's properties.  So that's, uh, correct.

Except...wait a minute, what in the heck is a "port name"?  It's not a valid IP address (though it IS the IP address of the printer itself, prefixed with "IP_".  Nothing I can find on NET USE ever says anything about a printer port, only a computer/share [and optional volume].

Can anyone shed any light as to whether this could have EVER worked?

[Of course, no one can provide us with the source for the version of the service that actually still works.  We've not touched this portion of the service, only what precedes this printing.  And the client swears they haven't either.  Grrr...]

We are looking at a more modern way of printing, though the fact that it needs to run as a service complicates things.

答:
The "IP_1.2.3.4" parameter is the printer share name, not a port name.  You must have shared one of the existing installed printers giving it the name "IP_1.2.3.4" at some point in the past, and this share name is missing.

If you just need a passthrough printer, you can install the "Generic/Text Only" printer, assign it to the desired port, and share it using the name in your "net use" command.

Body:
A few years back, another clever programmer set up a VB.NET service to print to one of the server's installed printers.  The job queried a database table to see if it had any print requests, which specify the file to print and the name of the printer to send it to.  The job constructs a 3-part command line incantation and executes it; it goes a little something like this:

net use LPT2: IP_1.2.3.4 /user:domain\userid password >> netuse1.out
copy someExistingFile.pdf LPT2 >> copy.out
net use LPT2: /delete >> netuse2.out

We've been asked to make other unrelated changes to this job, and happily complied.  Only any version of the job we deploy and run simply will not print.  The first statement fails with "System error 67 has occurred.  The network name cannot be found."

The job has queried the registry to find the port name for the printer specified by the user.  The port it tries is indeed the port "name" we see when looking at the printer's properties.  So that's, uh, correct.

Except...wait a minute, what in the heck is a "port name"?  It's not a valid IP address (though it IS the IP address of the printer itself, prefixed with "IP_".  Nothing I can find on NET USE ever says anything about a printer port, only a computer/share [and optional volume].

Can anyone shed any light as to whether this could have EVER worked?

[Of course, no one can provide us with the source for the version of the service that actually still works.  We've not touched this portion of the service, only what precedes this printing.  And the client swears they haven't either.  Grrr...]

We are looking at a more modern way of printing, though the fact that it needs to run as a service complicates things.


问:
How can i get avg,sum of sub attribute?
I have problem with writing average query!

In my Rethink db, i have some documents in one table like this:

document1:

```<code>{
    a:{
        last:3
    },
    b:{
        last:4
    },
    c:{
        last:6
    },
}
</code>```

document2:

```<code>{
    a:{
        last:7
    },
    b:{
        last:9
    },
    c:{
        last:2
    },
}
</code>```

document3:

```<code>{
    a:{
        last:5
    },
    b:{
        last:8
    },
    c:{
        last:4
    },
}
</code>```

I want to get average of last attribute in every object like this:

```<code>{
    sum_a_last:15,
    sum_b_last:21,
    sum_c_last:12,
    avg_a_last:5,
    avg_b_last:7,
    avg_c_last:4
}
</code>```

What is the query to return this result?

答:
I believe what you're looking for is

```<code>r.db('dbName').table('tableName').avg((doc) => doc('a')('last'));
</code>```

If you're trying to dynamically look for the last member for all objects in a doc there will obviously be more work.

https://rethinkdb.com/api/javascript/avg/

Title: How can i get avg,sum of sub attribute?

Body:
I have problem with writing average query!

In my Rethink db, i have some documents in one table like this:

document1:

{
    a:{
        last:3
    },
    b:{
        last:4
    },
    c:{
        last:6
    },
}

document2:

{
    a:{
        last:7
    },
    b:{
        last:9
    },
    c:{
        last:2
    },
}

document3:

{
    a:{
        last:5
    },
    b:{
        last:8
    },
    c:{
        last:4
    },
}

I want to get average of last attribute in every object like this:

{
    sum_a_last:15,
    sum_b_last:21,
    sum_c_last:12,
    avg_a_last:5,
    avg_b_last:7,
    avg_c_last:4
}

What is the query to return this result?

Body:
I believe what you're looking for is

r.db('dbName').table('tableName').avg((doc) => doc('a')('last'));

If you're trying to dynamically look for the last member for all objects in a doc there will obviously be more work.

https://rethinkdb.com/api/javascript/avg/


问:
Please provide me the logic to print the result using PRINTF
need an programming logic to print an 4 decimal points

```<code>  EX: scalar should be 0 to -5
  value = 10006 , scalar = -3 then print result = 10.0060 (4 decimals)
  value = 123   ,scalar = -5  then print result = 0.0012 (4 decimals)**
  required value/divisor = 10 , value%divisor = 0060 (required logic after decimals )
</code>```

I tried like this:

```<code> divisor =  std::pow(10,std::abs(scalar));

 **Result = snprintf(X,Y,"%d.%0*d",value/scalar,4,value%scalar);**
</code>```

I'm not allowed to use  float , setprecision() .

It does not necessarily represent the actual value , but we can format that value to print with logic like the original one (by using the logic , add ...subtract...pow etc)

std::int32_t divisor = static_cast(std::pow( 10.0F,  std::abs( Scalar)) );

but int the above result modulus scalar value with 0 are not considering.
      **Please provide me the logic to print the above result with scalar condition

答:
In order to print decimals (easily), you need floating point:

```<code>printf("%10.6f", static_cast<double>(1) / 3);
</code>```

If one of the arguments to division is floating point, the compiler will promote the expression to floating point.

Integral or scalar division will lose decimals.

You are always welcome to write your own division function.

Edit 1: Shifting

You don't need to use the pow function (especially since it's floating point).

Use a loop, in the loop multiply your divisor by 10 each time.

```<code>double result = (double) scalar / value;
int divisor = 10;
int i;
for (i = 0; i < NUMBER_OF_DECIMALS; ++)
{
  // Isolate a digit using math.
  // print the digit
  divisor += 10;
}
</code>```

The math part is left as an exercise for the OP.

Body:
need an programming logic to print an 4 decimal points

  EX: scalar should be 0 to -5
  value = 10006 , scalar = -3 then print result = 10.0060 (4 decimals)
  value = 123   ,scalar = -5  then print result = 0.0012 (4 decimals)**
  required value/divisor = 10 , value%divisor = 0060 (required logic after decimals )

I tried like this:

 divisor =  std::pow(10,std::abs(scalar));

 **Result = snprintf(X,Y,"%d.%0*d",value/scalar,4,value%scalar);**

I'm not allowed to use  float , setprecision() .

It does not necessarily represent the actual value , but we can format that value to print with logic like the original one (by using the logic , add ...subtract...pow etc)

std::int32_t divisor = static_cast(std::pow( 10.0F,  std::abs( Scalar)) );

but int the above result modulus scalar value with 0 are not considering.
      **Please provide me the logic to print the above result with scalar condition

Body:
In order to print decimals (easily), you need floating point:

printf("%10.6f", static_cast<double>(1) / 3);

If one of the arguments to division is floating point, the compiler will promote the expression to floating point.

Integral or scalar division will lose decimals.

You are always welcome to write your own division function.

Edit 1: Shifting

You don't need to use the pow function (especially since it's floating point).

Use a loop, in the loop multiply your divisor by 10 each time.

double result = (double) scalar / value;
int divisor = 10;
int i;
for (i = 0; i < NUMBER_OF_DECIMALS; ++)
{
  // Isolate a digit using math.
  // print the digit
  divisor += 10;
}

The math part is left as an exercise for the OP.


问:
Notepad++ Regex for append in begin of line Expression Part of Line
NotePad++ Regexp: I Would Want on a Line to Look for and to Isolate a Word and both Previous two words. The Word and to add them at the beginning of the Line

RegEx For Select In Line:

```<code>([a-zA-Z.,'*]+[ ])([a-zA-Z.,'*]+[ ])(Vs )([a-zA-Z.,'*]+[ ])([a-zA-Z.,'*]+[ ])
</code>```

Would appreciate help on achieving this! Think

Exemple Lines Before:

```<code>- The Candidate o'Brien Vs O'Bama Presidential Test.
- traveling by plane Vs By TGV train.
- live stream info Chile vs Portugal How to watch Confederations Cup.
- band Cock Robin - Peter kingsbery Vs only the very best.
</code>```

Lines After:

```<code>- Candidate o'Brien Vs O'Bama Presidential - Candidate o'Brien Vs O'Bama Presidential
- by plane Vs Train TGV - traveling by plane Vs Train TGV French.
- info Chile vs Portugal How - live stream info Chile vs Portugal How to watch Confederations Cup.
- Peter kingsbery Vs only the - band Cock Robin - Peter kingsbery Vs only the very best.
</code>```

Nota :

When Append Firt Name Composite Ex: Jean-Claude The Line is Ignored.

martial arts action Chuck Norris Vs Jean-Claude Van Damme and abbreviated as JCVD.

答:
I think you confused the output for the first and second lines, and the main problem is that you want to be able to match the whole string and capture the pattern you have provided to later be able to use the backreferences to both the whole line and Capturing group 1.

I suggest using

```<code>.*?((?:[a-zA-Z.,'*]+\h+){2}Vs(?:\h+[a-zA-Z.,'*]+){2}).*
</code>```

and replace with - $1 $0.

The pattern is actually yours, I added .*? at the start and .* at the end (to match the whole line) and your pattern (with small enhancements) is put inside a capturing group (...) to be able to reference it later with $1. The $0  is the backreference to the whole match (here, the whole line).

Pattern details:

.*? - any 0+ chars other than line break chars, as few as possible (lazy match)

((?:[a-zA-Z.,'*]+\h+){2}Vs(?:\h+[a-zA-Z.,'*]+){2}) - Group 1 capturing:

(?:[a-zA-Z.,'*]+\h+){2} - exactly 2 occurrences of

[a-zA-Z.,'*]+ - one or more ASCII letters, dots, ,, ', or *

\h+ - 1 or more horizontal whitespaces

Vs  - a Vs  substring

(?:\h+[a-zA-Z.,'*]+){2} - see above

.*  -  any 0+ chars other than line break chars, as many as possible (greedy match)

Body:
NotePad++ Regexp: I Would Want on a Line to Look for and to Isolate a Word and both Previous two words. The Word and to add them at the beginning of the Line

RegEx For Select In Line:

([a-zA-Z.,'*]+[ ])([a-zA-Z.,'*]+[ ])(Vs )([a-zA-Z.,'*]+[ ])([a-zA-Z.,'*]+[ ])

Would appreciate help on achieving this! Think

Exemple Lines Before:

- The Candidate o'Brien Vs O'Bama Presidential Test.
- traveling by plane Vs By TGV train.
- live stream info Chile vs Portugal How to watch Confederations Cup.
- band Cock Robin - Peter kingsbery Vs only the very best.

Lines After:

- Candidate o'Brien Vs O'Bama Presidential - Candidate o'Brien Vs O'Bama Presidential
- by plane Vs Train TGV - traveling by plane Vs Train TGV French.
- info Chile vs Portugal How - live stream info Chile vs Portugal How to watch Confederations Cup.
- Peter kingsbery Vs only the - band Cock Robin - Peter kingsbery Vs only the very best.

Nota :

When Append Firt Name Composite Ex: Jean-Claude The Line is Ignored.

martial arts action Chuck Norris Vs Jean-Claude Van Damme and abbreviated as JCVD.

Body:
I think you confused the output for the first and second lines, and the main problem is that you want to be able to match the whole string and capture the pattern you have provided to later be able to use the backreferences to both the whole line and Capturing group 1.

I suggest using

.*?((?:[a-zA-Z.,'*]+\h+){2}Vs(?:\h+[a-zA-Z.,'*]+){2}).*

and replace with - $1 $0.

The pattern is actually yours, I added .*? at the start and .* at the end (to match the whole line) and your pattern (with small enhancements) is put inside a capturing group (...) to be able to reference it later with $1. The $0  is the backreference to the whole match (here, the whole line).

Pattern details:

.*? - any 0+ chars other than line break chars, as few as possible (lazy match)

((?:[a-zA-Z.,'*]+\h+){2}Vs(?:\h+[a-zA-Z.,'*]+){2}) - Group 1 capturing:

(?:[a-zA-Z.,'*]+\h+){2} - exactly 2 occurrences of

[a-zA-Z.,'*]+ - one or more ASCII letters, dots, ,, ', or *

\h+ - 1 or more horizontal whitespaces

Vs  - a Vs  substring

(?:\h+[a-zA-Z.,'*]+){2} - see above

.*  -  any 0+ chars other than line break chars, as many as possible (greedy match)


问:
Remove "V" letter in column names when a matrix without column names is converted to data.frame
When a matrix is converted to a date frame, the original column names are removed while V1, V2, ... are added as the new column names.

Is there any options to disable that? I expect the same column names as that in the matrix, e.g. 1, 2.

```<code>m <- cbind(1:2, 2:3); m

      [,1] [,2]
[1,]    1    2
[2,]    2    3

as.data.frame(m)

   V1 V2
1  1  2
2  2  3
</code>```

答:
You said "When a matrix is converted to a date frame, the original column names are removed while V1, V2, ... are added as the new column names."

That's not the case. A matrix by default has no column names:

```<code>> m = matrix(1:4, ncol=2)
> colnames(m)
NULL
</code>```

A data frame, however, has to have column names. If they aren't specified, it creates them in various ways. For example, if not specified in data.frame, they are named from the expression, with an X prefix:

```<code>> d = data.frame(1:2,3:4)
> colnames(d)
[1] "X1.2" "X3.4"
</code>```

Or when converted from a matrix with no column names, it gets column numbers prefixed with a V, as you see:

```<code>> colnames(as.data.frame(m))
[1] "V1" "V2"
</code>```

If the matrix has column names, then they are preserved by as.data.frame:

```<code>> colnames(m)=c("First","Second")
> as.data.frame(m)
  First Second
1     1      3
2     2      4
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When a matrix is converted to a date frame, the original column names are removed while V1, V2, ... are added as the new column names.

Is there any options to disable that? I expect the same column names as that in the matrix, e.g. 1, 2.

m <- cbind(1:2, 2:3); m

      [,1] [,2]
[1,]    1    2
[2,]    2    3

as.data.frame(m)

   V1 V2
1  1  2
2  2  3

Body:
You said "When a matrix is converted to a date frame, the original column names are removed while V1, V2, ... are added as the new column names."

That's not the case. A matrix by default has no column names:

> m = matrix(1:4, ncol=2)
> colnames(m)
NULL

A data frame, however, has to have column names. If they aren't specified, it creates them in various ways. For example, if not specified in data.frame, they are named from the expression, with an X prefix:

> d = data.frame(1:2,3:4)
> colnames(d)
[1] "X1.2" "X3.4"

Or when converted from a matrix with no column names, it gets column numbers prefixed with a V, as you see:

> colnames(as.data.frame(m))
[1] "V1" "V2"

If the matrix has column names, then they are preserved by as.data.frame:

> colnames(m)=c("First","Second")
> as.data.frame(m)
  First Second
1     1      3
2     2      4


问:
Codechef KCHAR wrong answer
Recently I was solving the following problem on codechef:

Alice has quarreled with Chef recently. So Chef gives a problem to Alice.
  Initially you are given an empty string and are allowed following two operations.

Operation-1: Every 'a' becomes 'c' and every 'c' becomes 'a'. For example, "acc" becomes "caa".

  Operation-2: String is reversed. For Example, "acc" becomes "cca".

Chef gives following generating equation SN = SN-1 + "a" + Operation-1(Operation-2(SN-1))

where S0 = "" (empty string).

Alice easily finds out next few sequences as:

S1 = "a"

  S2 = "aac"

  S3 = "aacaacc"

Now Chef asks to find Kth character of SLOC, where LOC = 102017. You need to help Alice find the answer.

1 ≤ T ≤ 100

  1 ≤ K ≤ 1018

I have tried to solve the problem using following code:

```<code>scanf("%lld",&t);
while(t--)
{
    scanf("%lld",&k);
    count=0;
    while(1)
    {
        lg=(double)log(k)/log(2);
        av=pow(2,lg);
        if(av!=k)
        {
            diff=k-av;
            k=av-diff;
            count++;
        }
        else
        {
            if(count%2==0)
            {
                printf("a\n");
            }
            else
            {
                printf("c\n");
            }
            break;
        }
    }

}
</code>```

What is wrong in the solution?

I have tried out various inputs and I get correct answer but the I am getting WA when I submit. Can anyone provide some test cases where the solution is failing.

答:
Your code doesn't work for k=576460752303423478. It doesn't terminate. I haven't debugged it fully, but the root cause is numerical inaccuracy: av should be the largest power of 2 less than or equal to k, but it ends up larger than k. I expect there's other cases that terminate but produce the wrong result.

To find the failing case, I wrote my own version of the code and tried testing it for many values of k. That didn't turn up anything, so then tried near-powers-of-2. That found the example above.

Here's the code that finds the problem case (here x() is your code, and y() is my code). I added asserts to your code which demonstrate the problem, but you can remove them and see that the code doesn't terminate.

```<code>#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

char x(long long int k) {
    long long int count=0;
    while(1) {
        long long int lg=(double)log(k)/log(2);
        long long int av=pow(2,lg);
        assert((av & (av-1)) == 0); // av is a power of 2
        assert(av <= k);  // ... that's at most k
        if(av!=k) {
            long long int diff=k-av;
            k=av-diff;
            count++;
        } else {
            if(count%2==0) return 'a';
            return 'c';
        }
    }
}

char y(long long int k) {
    int count = 0;
    long long int j = 1;
    while(j < k) j *= 2;
    while (1) {
        if (j == k) {
            return count % 2 ? 'c' : 'a';
        } else if (k > j) {
            k = 2*j-k;
            count += 1;
        }
        j >>= 1;
    }
}

int main(int argc, char **argv) {
    int t = 60;
    while(t--) {
        for (int k = -10; k < 10; k++) {
            long long int r = (1LL<<t) + k;
            if (r <= 0) continue;
            printf("%lld\n", r);
            printf("y: %c\n", y(r));
            printf("x: %c\n", x(r));
            if (x(r) != y(r)) exit(1);
        }
    }
    return 0;
}
</code>```

Title: Codechef KCHAR wrong answer

Body:
Recently I was solving the following problem on codechef:

Alice has quarreled with Chef recently. So Chef gives a problem to Alice.
  Initially you are given an empty string and are allowed following two operations.

Operation-1: Every 'a' becomes 'c' and every 'c' becomes 'a'. For example, "acc" becomes "caa".

  Operation-2: String is reversed. For Example, "acc" becomes "cca".

Chef gives following generating equation SN = SN-1 + "a" + Operation-1(Operation-2(SN-1))

where S0 = "" (empty string).

Alice easily finds out next few sequences as:

S1 = "a"

  S2 = "aac"

  S3 = "aacaacc"

Now Chef asks to find Kth character of SLOC, where LOC = 102017. You need to help Alice find the answer.

1 ≤ T ≤ 100

  1 ≤ K ≤ 1018

I have tried to solve the problem using following code:

scanf("%lld",&t);
while(t--)
{
    scanf("%lld",&k);
    count=0;
    while(1)
    {
        lg=(double)log(k)/log(2);
        av=pow(2,lg);
        if(av!=k)
        {
            diff=k-av;
            k=av-diff;
            count++;
        }
        else
        {
            if(count%2==0)
            {
                printf("a\n");
            }
            else
            {
                printf("c\n");
            }
            break;
        }
    }

}

What is wrong in the solution?

I have tried out various inputs and I get correct answer but the I am getting WA when I submit. Can anyone provide some test cases where the solution is failing.

Body:
Your code doesn't work for k=576460752303423478. It doesn't terminate. I haven't debugged it fully, but the root cause is numerical inaccuracy: av should be the largest power of 2 less than or equal to k, but it ends up larger than k. I expect there's other cases that terminate but produce the wrong result.

To find the failing case, I wrote my own version of the code and tried testing it for many values of k. That didn't turn up anything, so then tried near-powers-of-2. That found the example above.

Here's the code that finds the problem case (here x() is your code, and y() is my code). I added asserts to your code which demonstrate the problem, but you can remove them and see that the code doesn't terminate.

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

char x(long long int k) {
    long long int count=0;
    while(1) {
        long long int lg=(double)log(k)/log(2);
        long long int av=pow(2,lg);
        assert((av & (av-1)) == 0); // av is a power of 2
        assert(av <= k);  // ... that's at most k
        if(av!=k) {
            long long int diff=k-av;
            k=av-diff;
            count++;
        } else {
            if(count%2==0) return 'a';
            return 'c';
        }
    }
}

char y(long long int k) {
    int count = 0;
    long long int j = 1;
    while(j < k) j *= 2;
    while (1) {
        if (j == k) {
            return count % 2 ? 'c' : 'a';
        } else if (k > j) {
            k = 2*j-k;
            count += 1;
        }
        j >>= 1;
    }
}

int main(int argc, char **argv) {
    int t = 60;
    while(t--) {
        for (int k = -10; k < 10; k++) {
            long long int r = (1LL<<t) + k;
            if (r <= 0) continue;
            printf("%lld\n", r);
            printf("y: %c\n", y(r));
            printf("x: %c\n", x(r));
            if (x(r) != y(r)) exit(1);
        }
    }
    return 0;
}