问:
How to generate unique persistent url which redirects to random user defined array of urls
I was trying to find an online tool to generate a new link which randomly redirects to user defined array of links.

Please check out http://mathstatic.co.nz/auto to see what I am trying to do.  Problem with that site is that it is wordpress and you can only enter 2 links.  I want to do something similar but with user defined number of links.

Please take a look at the code I have for what I put together today: http://rpantaev.com/RedirectLinkTool/

After researching, it seems that I need to use PHP and perhaps a database like mysql to store users' data, but I am not familiar with PHP so any pointers will be greatly appreciated.

So far php is installed on my server and I added .htaccess so html can read php.  I put together a webpage with html/css/js that takes in user defined number of links, checks for http://, stores in array and redirects to randomly chosen url (array is not persistent and no new url is generated).

How can I recreate what the first link does and incorporate that into my website?

Thank you!

答:
So the language you use will depend on what languages your server supports or whether you can install your own. If your looking to run a server on your computer to just test this out, you just need to install the language you want to use then find a way to run as server on your computer.

You can use any database (postgres, mongodb), to store your urls. If it's ok to use memory for this project then you can use a dictionary to store the random urls.

Here's a way to do this using Node.js. In this solution, I create a server on port 9898 and create an in memory database using a dictionary. When there are entries, the database will look like this:

```<code>{
   "uuid1": { id: "uuid1", urls: ["https://www.google.com", "https://youtube.com"] },
   "uuid2": { id: "uuid2", urls: ["https://www.google.com", "https://youtube.com"] }
}
</code>```

uuid1 and uuid2 would be replaced with actual unique IDs.

In this solution, I'm expecting that the client will send a json object.

The solution depends on expressjs and body-parser packages. Here's actual code that I test on my computer.

```<code>const express = require('express')
const bodyParser = require('body-parser');
const app = express()

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

const port = 9898
const host = `http://localhost:${port}`

// you would replace this with an actual database
const db = {}

// to generate a uuid
// from: https://stackoverflow.com/a/2117523
function uuidv4() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

function success(message) {
    return JSON.stringify({
        success: message
    })
}

function error(message) {
    return JSON.stringify({
        error: message
    })
}

// assuming body looks like this { urls: ['www.google.com', 'www.gmail.com'] }
app.post('/gen', (req, res) => {
    const gen = req.body
    // check if the json in the request has the list of urls
    if(!(gen && gen.urls && gen.urls.length > 0)) {
        // if not then log the body and return a json object with the error object
        console.log('body', req.body)
        return res.send(error('I cannot find the list of urls in json body.'))
    }
    // generate a uuid
    const id = uuidv4()
    // save the urls with the new id
    db[id] = {
        id: id,
        urls: gen.urls
    }
    // respond with the url that the user should use
    res.send(success(host + '/' + id))
})

app.get('/:id', (req, res) => {
    // get the id paramater from the request
    const id = req.params.id
    // check if that id was saved, if not send an error message
    if(!db[id])
        return res.send(error('that url does not exist'))
    // grab a random element from the list of urls
    const urls = db[id].urls
    const url = urls[Math.floor(Math.random() * urls.length)]
    // redirect the user to the random url
    res.redirect(url)
})

// start the server
app.listen(port, () => {
    console.log('listening on port: '+port);
})

/*

example request:
curl -X POST -H "Content-Type: application/json" -d '{"urls": ["https://www.google.com", "https://www.yahoo.com", "https://www.youtube.com"]}' localhost:9898/gen

after doing this you grab the url generated and paste into your browser.
for example when I ran this it generated: http://localhost:9898/aa582177-4ab5-4ede-99c5-a06b43976c12

*/
</code>```

If you've never setup a nodejs project before this page can get you up to speed: https://docs.npmjs.com/getting-started/installing-node
After install nodejs and npm. create a folder for the project. In your command line, go to this directory. To setup the project and install the two packages, write:

```<code>npm init -y
npm install express body-parser
</code>```

After doing that create a file named index.js in that folder. Then paste the code in. Then to run the server use this command:

```<code>node index.js
</code>```

If your on MacOS or Linux, or have a way to use curl on Windows you can use this example request:

```<code>curl -X POST -H "Content-Type: application/json" -d '{"urls": ["https://www.google.com", "https://www.yahoo.com", "https://www.youtube.com"]}' localhost:9898/gen
</code>```

Then that should return a url for you to use. For example for me it generated this:

```<code>http://localhost:9898/aa582177-4ab5-4ede-99c5-a06b43976c12
</code>```

You would paste the url generated into your browser and it should reroute you to one of the urls in the list.

Body:
So the language you use will depend on what languages your server supports or whether you can install your own. If your looking to run a server on your computer to just test this out, you just need to install the language you want to use then find a way to run as server on your computer.

You can use any database (postgres, mongodb), to store your urls. If it's ok to use memory for this project then you can use a dictionary to store the random urls.

Here's a way to do this using Node.js. In this solution, I create a server on port 9898 and create an in memory database using a dictionary. When there are entries, the database will look like this:

{
   "uuid1": { id: "uuid1", urls: ["https://www.google.com", "https://youtube.com"] },
   "uuid2": { id: "uuid2", urls: ["https://www.google.com", "https://youtube.com"] }
}

uuid1 and uuid2 would be replaced with actual unique IDs.

In this solution, I'm expecting that the client will send a json object.

The solution depends on expressjs and body-parser packages. Here's actual code that I test on my computer.

const express = require('express')
const bodyParser = require('body-parser');
const app = express()

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

const port = 9898
const host = `http://localhost:${port}`

// you would replace this with an actual database
const db = {}

// to generate a uuid
// from: https://stackoverflow.com/a/2117523
function uuidv4() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

function success(message) {
    return JSON.stringify({
        success: message
    })
}

function error(message) {
    return JSON.stringify({
        error: message
    })
}

// assuming body looks like this { urls: ['www.google.com', 'www.gmail.com'] }
app.post('/gen', (req, res) => {
    const gen = req.body
    // check if the json in the request has the list of urls
    if(!(gen && gen.urls && gen.urls.length > 0)) {
        // if not then log the body and return a json object with the error object
        console.log('body', req.body)
        return res.send(error('I cannot find the list of urls in json body.'))
    }
    // generate a uuid
    const id = uuidv4()
    // save the urls with the new id
    db[id] = {
        id: id,
        urls: gen.urls
    }
    // respond with the url that the user should use
    res.send(success(host + '/' + id))
})

app.get('/:id', (req, res) => {
    // get the id paramater from the request
    const id = req.params.id
    // check if that id was saved, if not send an error message
    if(!db[id])
        return res.send(error('that url does not exist'))
    // grab a random element from the list of urls
    const urls = db[id].urls
    const url = urls[Math.floor(Math.random() * urls.length)]
    // redirect the user to the random url
    res.redirect(url)
})

// start the server
app.listen(port, () => {
    console.log('listening on port: '+port);
})

/*

example request:
curl -X POST -H "Content-Type: application/json" -d '{"urls": ["https://www.google.com", "https://www.yahoo.com", "https://www.youtube.com"]}' localhost:9898/gen

after doing this you grab the url generated and paste into your browser.
for example when I ran this it generated: http://localhost:9898/aa582177-4ab5-4ede-99c5-a06b43976c12

*/

If you've never setup a nodejs project before this page can get you up to speed: https://docs.npmjs.com/getting-started/installing-node
After install nodejs and npm. create a folder for the project. In your command line, go to this directory. To setup the project and install the two packages, write:

npm init -y
npm install express body-parser

After doing that create a file named index.js in that folder. Then paste the code in. Then to run the server use this command:

node index.js

If your on MacOS or Linux, or have a way to use curl on Windows you can use this example request:

curl -X POST -H "Content-Type: application/json" -d '{"urls": ["https://www.google.com", "https://www.yahoo.com", "https://www.youtube.com"]}' localhost:9898/gen

Then that should return a url for you to use. For example for me it generated this:

http://localhost:9898/aa582177-4ab5-4ede-99c5-a06b43976c12

You would paste the url generated into your browser and it should reroute you to one of the urls in the list.


来源: stackexchange

问:
Use Git in SSH to pull specific directories
Total newbie question but what is the best practice when it comes to using SSH with Git? I'm working on a WordPress project. In the root I have gulp and other dev files/folders like SASS and Scripts that I don't need on the server and in the same project I have my WordPress folder that contains a theme and a few custom plugins. As you can imagine when the theme or any of the plugins are ready to be deployed I don't want to pull everything in my repository on the server. So far as a newbie I've always just pull and pushed the entire repository and used FTP to upload what I need to the server, so how is this done with SSH and Git and is there a better way to have my setup?

EDIT: To make my question a little bit more clear let me give you an example of what I think my issue is. In my main project folder, I have a SASS folder next to my WordPress folder. All I really need to deploy to the server is the WordPress folder. My build process that happens on my dev machine combines all of the SASS files into a single CSS that is then placed into the WordPress folder. I need the SASS folder to be tracked by Git so that any other developer can pull them and continue developing so I can't have git ignore it. However none of those SASS files need to be on the server for WordPress to work either. I just simply need to deploy the WordPress folder and everything that's in it.

I understand the idea of creating a bare repository on the server and using post-receive hook to point the git folder sitting outside your web root to point to where the web root is. But that's basically how GIT and SSH work and that's not answering my concern.

答:
So, based on your question and comment, there are three computers involved. There is a web server (when you say "server", I take it as a Web server in this scenario, or the server computer that runs a Web server program). There is another server where your git repo is hosted. And, there is your dev workstation. Is this correct?

It seems like, you have a cloned git repo on your Web server. Your current practice/workflow appears to be (1) (based on your expression "SSH'ed into my server") you log into the web server via SSH (just like Telnet) from your workstation (SSH is just a protocol, which can be used for different purposes). (2) you pull from your repo on hosted service (e.g., github), and (3) deploy it to your "www" directory on the same server. Is this correct?

(I can think of an alternative scenario based on your use of the word "FTP", etc., but let's focus on the above scenario, for now.)

Now, your question is, whenever you "pull" (on your Web server), you feel like you are pulling everything from your repo on your hosted service. And, is there a better way? Am I understanding your question correctly?

If so, as another commenter suggested, git (and, any version control system, in general) is very good at fetching "deltas" only. If you are worried about "fetching everything" every time you pull (the step (2) above), then your worry is unfounded.

Now, the question is, why do you have a git repo on your Web server, if that is indeed the case? This is a pretty legit setup and I've done this before (e.g., on EC2). But, as a best practice, people generally don't do that on "production" servers. It's because you have to "build" your web app, and you really don't want to do that on production servers.

The next question is, what do you exactly do in Step (3)? The build process (whatever process you use) typically generates an "output" which can be directly deployed to the web server. (The convention is the output is generally a single folder, "public", "www", "dist", or whatever, or a single file (e.g., tar.gz, zip, jar, war), etc.) Regardless of whether you build the deployable output on your dev workstation (or, a build machine) or on your Web server, you don't generally do "deltas" in this context. Even if you've only changed a single file (say, a CSS file), you generally build the whole output again (instead of, say, just replacing the changed CSS file only). When you use FTP to upload files, etc., you can selectively upload certain files and/or directories, etc., but as a general practice, we don't do that. We always build the complete output from scratch and deploy it to the Web server. (This is mainly to reduce the potential deployment errors and increase the reliability.)

So, to answer your question, (A) If you are pulling git repo on your Web server, you should really change that practice, and move the build process to your dev computer or a dedicated build machine. (BTW, services like github, gitlab, TFS, ... provide the build service for you.) (B) If you are currently selectively FTP'ing your web app files to your Web server, then you should really consider adopting some kind of formal build, and deployment, process moving forward.

ContentLicense: CC BY-SA 3.0


问:
where goes the ret instruction of the main
I learned how assembly (x86) globally works in the book : "Programming from ground up".
In this book, every program ends with an interruption call to exit.

However, in C compiled programs, I found out that programs end with a ret. This supposes that there is an address to be popped and that would lead to the end of the program.

So my question is :
What is this address? (And what is the code there?)

答:
You start your program by asking the OS to pass control to the start or _start function of your program by jumping to that label in your code. In a C program the start function comes from the C library and (as others already said before) does some platform specific environment initialization. Then the start function calls your main and the control is yours. After you return from the main, it passes control back to the C library that terminates the program properly and does the platform specific system call to return control back to the OS.

So the address main pops is a label coming from the C library. If you want to check it, it should be in stdlib.h (cstdlib) and you will see it calling exit that does the cleanup.

Its function is to destroy the static objects (C++ of course) at program termination or thread termination (C++11). In the C case it just closes the streams, flushes their buffers, calls atexit functions and does the system call.

I hope this is the answer you seek.


问:
Variable in string that's evaluated upon usage
I'm setting up a Powershell script to provide some user notifications. The notification is legal in nature and may be updated/changed from time to time so it must be fairly easy to locate. It also has a few 'fill in the blank' variables that depend on the person receiving the notification.

I wanted to have a secondary Powershell file that contained the copy (text) to be used, so something like...

```<code>$body = "By accessing this system, you agree that your name ($currentUserName) and IP address ($currentUserIPAddr) will be recorded and stored for up to ($currentUserRetentionPeriod)."
</code>```

The file could be updated as needed without actually opening the script, finding the line to edit, and potentially messing up other items/just being difficult. However, I'm looping through several thousand users in a single execution, so all the $currentUser... variables will be re-used frequently. This poses a problem because $body tries to get the variables immediately and acts as a static string instead of evaluating the variable contents each time it's invoked.

Is there a clever way for me to define $body a single time (i.e. not inside a loop) but still allow for redefinition of internal variables? I'd also rather not split the string up into multiple parts so it became $part1 + $var1 + part2 + var2....n+1 times.

答:
A simple approach would be to just dot-source the script containing the copy whenever you need the variable "re-compiled":

BodyDef.ps1:

```<code>$body = "By accessing this system, you agree that your name ($currentUserName) and IP address ($currentUserIPAddr) will be recorded and stored for up to ($currentUserRetentionPeriod)."
</code>```

Send-Notification.ps1

```<code>$bodyDefPath = (Join-Path $PSScriptRoot BodyDef.ps1)
foreach($user in Get-Users){
    $currentUserName = $user.UserName
    $currentUserIPAddr = $user.IPAddress
    $currentUserRetentionPeriod = $user.RententionPeriod
    . $bodyDefPath
    Send-MailMessage -Body $body
}
</code>```

The above would work just fine, but it's not very powershell-idiomatic, and kind of silly, reading the file over and over again.

As suggested in the comments, you should define a second function (or just a scriptblock) if you want to reuse the same template with different values:

Send-Notification.ps1

```<code># You could as well define this as a function, doesn't make much difference
$NotificationSender = {
    param($User)

    $body = "By accessing this system, you agree that your name ($($user.UserName)) and IP address ($($user.IPAddress)) will be recorded and stored for up to $($user.RetentionPeriod)."
    Send-MailMessage -Body $body
}

foreach($user in Get-Users){
    & $NotificationSender -user $user
}
</code>```

Body:
I'm setting up a Powershell script to provide some user notifications. The notification is legal in nature and may be updated/changed from time to time so it must be fairly easy to locate. It also has a few 'fill in the blank' variables that depend on the person receiving the notification.

I wanted to have a secondary Powershell file that contained the copy (text) to be used, so something like...

$body = "By accessing this system, you agree that your name ($currentUserName) and IP address ($currentUserIPAddr) will be recorded and stored for up to ($currentUserRetentionPeriod)."

The file could be updated as needed without actually opening the script, finding the line to edit, and potentially messing up other items/just being difficult. However, I'm looping through several thousand users in a single execution, so all the $currentUser... variables will be re-used frequently. This poses a problem because $body tries to get the variables immediately and acts as a static string instead of evaluating the variable contents each time it's invoked.

Is there a clever way for me to define $body a single time (i.e. not inside a loop) but still allow for redefinition of internal variables? I'd also rather not split the string up into multiple parts so it became $part1 + $var1 + part2 + var2....n+1 times.

Body:
A simple approach would be to just dot-source the script containing the copy whenever you need the variable "re-compiled":

BodyDef.ps1:

$body = "By accessing this system, you agree that your name ($currentUserName) and IP address ($currentUserIPAddr) will be recorded and stored for up to ($currentUserRetentionPeriod)."

Send-Notification.ps1

$bodyDefPath = (Join-Path $PSScriptRoot BodyDef.ps1)
foreach($user in Get-Users){
    $currentUserName = $user.UserName
    $currentUserIPAddr = $user.IPAddress
    $currentUserRetentionPeriod = $user.RententionPeriod
    . $bodyDefPath
    Send-MailMessage -Body $body
}

The above would work just fine, but it's not very powershell-idiomatic, and kind of silly, reading the file over and over again.

As suggested in the comments, you should define a second function (or just a scriptblock) if you want to reuse the same template with different values:

Send-Notification.ps1

# You could as well define this as a function, doesn't make much difference
$NotificationSender = {
    param($User)

    $body = "By accessing this system, you agree that your name ($($user.UserName)) and IP address ($($user.IPAddress)) will be recorded and stored for up to $($user.RetentionPeriod)."
    Send-MailMessage -Body $body
}

foreach($user in Get-Users){
    & $NotificationSender -user $user
}


问:
(iphone) how to set 'atomic' @property for a variable?
I want to use an integer variable from multiple threads.

Hence I want to make getter/setter atomic operation.

at header file

```<code>@property (retain) NSNumber* myNumber;
</code>```

at implementation file

```<code>@synthesize myNumber;
</code>```

won't compile, what am i missing?

(type of property ‘myNumber’ does not match type of ivar ‘myNumber’)

- edit, I declared it as int myNumber; compilation problem solved

Also, can I use plain int for this? (not NSNumber* )

答:
Check your instance variable type.

Something like this in your header file:

```<code>@interface Foo : NSObject {
    NSNumber *myNumber;
}
@property (retain) NSNumber *myNumber;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I want to use an integer variable from multiple threads.

Hence I want to make getter/setter atomic operation.

at header file

@property (retain) NSNumber* myNumber;

at implementation file

@synthesize myNumber;

won't compile, what am i missing?

(type of property ‘myNumber’ does not match type of ivar ‘myNumber’)

- edit, I declared it as int myNumber; compilation problem solved

Also, can I use plain int for this? (not NSNumber* )

Body:
Check your instance variable type.

Something like this in your header file:

@interface Foo : NSObject {
    NSNumber *myNumber;
}
@property (retain) NSNumber *myNumber;


问:
How can I vectorize logical operator on multiple columns of a pandas dataframe?
I am trying to apply the logical or operator on multiple boolean columns of a dataframe, but I do not know in advance these columns. I resorted to use apply (see example below), but I would like to vectorize this operation.

example:

```<code>df =
    A       B      C
0   True    False  False
1   False   False  True
2   False   False  False

list_columns = df.columns
</code>```

Using apply :

```<code>df[list_columns].apply(lambda row: any(row), axis=1)
</code>```

Any ideas how to vectorize this?

答:
Is that what you want?</p>

```<code>In [369]: df[list_columns].any(axis=1)
Out[369]:
0     True
1     True
2    False
dtype: bool
</code>```

Body:
I am trying to apply the logical or operator on multiple boolean columns of a dataframe, but I do not know in advance these columns. I resorted to use apply (see example below), but I would like to vectorize this operation.

example:

df =
    A       B      C
0   True    False  False
1   False   False  True
2   False   False  False

list_columns = df.columns

Using apply :

df[list_columns].apply(lambda row: any(row), axis=1)

Any ideas how to vectorize this?

Body:
Is that what you want?

In [369]: df[list_columns].any(axis=1)
Out[369]:
0     True
1     True
2    False
dtype: bool


问:
How to seperate declaration and implementation of a templated class with a default template parameter?
I like to separate the declaration and implementation of my classes. I know that the implementation of class templates and function also has to go into the header file, that's not the problem.

I'm having trouble implementing this class:

```<code>template <size_t S, std::enable_if_t<(S > 0), int> = 0>
class Foo {
public:
    Foo();
}
</code>```

So far I have tried:

```<code>template<size_t S>
Foo<S>::Foo() {}
</code>```

which failed with

error C3860: template argument list following class template name must list parameters in the order used in template parameter list

error C2976: 'Foo<S,<__formal>>' : too few template arguments

and

```<code>template<size_t S, int i>
Foo<S, i>::Foo() {}
</code>```

which failed with

error C3860: template argument list following class template name must list parameters in the order used in template parameter list

error C3855: 'Foo<S,<unnamed-symbol>>' : template parameter '__formal' is incompatible with the declaration

I have also tried changing the template declaration to

template <size_t S, typename = std::enable_if_t<(S > 0)>>

which also failed with the first error message.

What is the correct way of doing this?

答:
Keep it simple:

```<code>template <size_t S>
class Foo {
public:
    Foo();
};

template <size_t S>
Foo<S>::Foo() { }

template <>
class Foo<0>;
</code>```

In this particular case, I'm not sure adding SFINAE gives you any extra benefits. It's possible that even the explicit specialization is unnecessary, and just a simple static_assert(S > 0, "!") would suffice.

Body:
I like to separate the declaration and implementation of my classes. I know that the implementation of class templates and function also has to go into the header file, that's not the problem.

I'm having trouble implementing this class:

template <size_t S, std::enable_if_t<(S > 0), int> = 0>
class Foo {
public:
    Foo();
}

So far I have tried:

template<size_t S>
Foo<S>::Foo() {}

which failed with

error C3860: template argument list following class template name must list parameters in the order used in template parameter list

error C2976: 'Foo<S,<__formal>>' : too few template arguments

and

template<size_t S, int i>
Foo<S, i>::Foo() {}

which failed with

error C3860: template argument list following class template name must list parameters in the order used in template parameter list

error C3855: 'Foo<S,<unnamed-symbol>>' : template parameter '__formal' is incompatible with the declaration

I have also tried changing the template declaration to

template <size_t S, typename = std::enable_if_t<(S > 0)>>

which also failed with the first error message.

What is the correct way of doing this?

Body:
Keep it simple:

template <size_t S>
class Foo {
public:
    Foo();
};

template <size_t S>
Foo<S>::Foo() { }

template <>
class Foo<0>;

In this particular case, I'm not sure adding SFINAE gives you any extra benefits. It's possible that even the explicit specialization is unnecessary, and just a simple static_assert(S > 0, "!") would suffice.


问:
Positional Audio in SceneKit / ARKit with AudioKit
I have been exploring positional audio in Scene Kit / ARKit and would like to see if it’s possible to use AudioKit in this context to benefit from its higher level tools for analysis, sound generation, effects, etc.

For some background, a SCNView comes with an AVAudioEnvironmentNode, an AVAudioEngine, and an audioListener (SCNNode). These properties come initialized, with the environment node already configured to the engine. A positional audio source is added to the scene via a SCNAudioPlayer, which can be initialized with an AVAudioNode - the AVAudioNode must be connected to the environment node and have a mono output.

The SCNAudioPlayer is then added to a SCNNode in the scene and automatically takes care of modifying the output of the AVAudioNode according to its position in the scene as well as the position and orientation of the audioListener node.

My hope is that it will be possible to initialize AudioKit with the AVAudioEngine property of a SCNView, configure the SCNView’s environment node within the engine’s node graph, use the AVAudioNode property of AKNodes to initialize SCNAudioPlayers, and ensure all sources properly connect to the environment node. I’ve already began modifying AudioKit source code, but having trouble figuring out what classes I will need to adapt and how to integrate the environment node into the AudioKit pipeline. In particular I’m having trouble understanding connectionPoints and the outputNode property.

Does anyone believe this might be not possible given how AudioKit is structured or have any pointers about approach?

I will of course be happy to share any of my findings.

答:
AudioKit creates its own instance of AVAudioEngine at line 38 of AudioKit.swift:

https://github.com/AudioKit/AudioKit/blob/master/AudioKit/Common/Internals/AudioKit.swift#L38

but it is open, so it should be possible to overwrite it with SceneView's audio engine. I don't see anything that would prevent it.


问:
How to Create a CircularProgress in Xamarin Android
I code in Xamarin.Android and now I need a Circular ProgressBar to show the actual progress. I am not talking about the ProgressBar spinners, they only indicate that a process is running, but not the actual progress.

I have found some libraries, but those are exclusively for Java Android. For Xamarin I only found the RadialProgress library but it is not as customizable as I need.

Thanks.

I want something like that:

答:
You can pack Java Android library you found into a Xamarin Binding and then just reference it in your Xamarin.Android project as a regular Xamarin.Android library and start using the component you like.

You can read more about Xamarin Bindings here


问:
Button with an icon CSS
I created a simple login (via Gmail) button with green color.
Look at this, please

```<code> <!DOCTYPE html>
<html>
<head>
<style>
.button {
    background-color: #4CAF50;
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
}
.button:icon {
    background: url(gmail-icon.png) no-repeat;
    float: left;
    width: 10px;
    height: 40px;
}
</style>
</head>
<body>

<button class="button"><span class="icon"></span>Button</button>

</body>
</code>```

But I can't see my icon on the button.
Please tell me why?

答:
Try declaring the icon as a class ".icon" and nesting it inside the button.  Style as needed from there. </p>

```<code>.button .icon {
background: url(gmail-icon.png) no-repeat;
float: left;
width: 10px;
height: 40px;
}
</code>```

Title: Button with an icon CSS

Body:
I created a simple login (via Gmail) button with green color.
Look at this, please

 <!DOCTYPE html>

<button class="button">Button</button>

But I can't see my icon on the button.
Please tell me why?

Body:
Try declaring the icon as a class ".icon" and nesting it inside the button.  Style as needed from there.

.button .icon {
background: url(gmail-icon.png) no-repeat;
float: left;
width: 10px;
height: 40px;
}


问:
How to get data from form and make and array
I am just making a railway reservation project to my college therefor I have to get passenger details and make a 2d array and send it to another page to show the summary but I just don't know how to do that.

my code is

```<code><?php
    include('connection.php');
    session_start();
    $train_number = $_GET['train_number'];
    $train_name = $_GET['train_name'];
    $coachid = $_GET['coachid'];
    $date = $_SESSION['date'];
    $day = $_SESSION['day'];
    $coachtype = $_SESSION['coachtype'];
    $useremail = $_SESSION['useremail'];
    if($_SERVER['REQUEST_METHOD']='POST')
    {
        if(!empty($_POST['proceed']))
        {
            $i = 1;
            while($i<7)
            {
                "What to write here";
            }
        }
    }
?>
<!DOCTYPE html>
<html>
<head>
    <title>Buy Tickets </title>
    <link rel="stylesheet" href="css.css">
</head>
<body>
<div class="wrapper">
    <div class="header">
        <img src="banner.jpg" height="100%" width="100%"/>
    </div>
    <div class="navbar">
        <ul>
            <li><a href="dashboard.php">Dashboard </a></li>
            <li><a href="buytickets.php">Buy Ticket </a></li>
            <li><a href="calcelticket.php">Cancel ticket</a></li>
            <li><a href="edit_profile_user.php">Edit Profile</a></li>
            <li id="last"><a href="logout.php">Logout</a></li>
        </ul>
    </div>

    <div>
        <?php
            echo "<h4 align='center'><u>Booking for </u></h4>";
            echo "<table align='center'>
              <thead>
              <tr style='border: 1px solid #dddddd;text-align: left; padding: 8px;'>
                <th style='border: 1px solid #dddddd;text-align: left; padding: 8px;'> Train Number </th>
                <th style='border: 1px solid #dddddd;text-align: left; padding: 8px;'> Train name </th>
                <th style='border: 1px solid #dddddd;text-align: left; padding: 8px;'> Date </th>
                <th style='border: 1px solid #dddddd;text-align: left; padding: 8px;'> Coach type </th>
              </tr>
              </thead>";
            echo "<tr>";
            echo "<td style='border: 1px solid #dddddd;text-align: left; padding: 8px;'>".$train_number."</td>";
            echo "<td style='border: 1px solid #dddddd;text-align: left; padding: 8px;'>".$train_name."</td>";
            echo "<td style='border: 1px solid #dddddd;text-align: left; padding: 8px;'>".$date."</td>";
            echo "<td style='border: 1px solid #dddddd;text-align: left; padding: 8px;'>".$coachtype."</td>";
            echo "</tr>";
            echo "</table>";
            echo "<h4 align='center'><u>Passenger details </u></h4>";
            echo "<table align='center'>
              <thead>
              <tr style='border: 1px solid #dddddd;text-align: left; padding: 8px;'>
                <th style='border: 1px solid #dddddd;text-align: left; padding: 8px;'> No </th>
                <th style='border: 1px solid #dddddd;text-align: left; padding: 8px;'> Passenger Name </th>
                <th style='border: 1px solid #dddddd;text-align: left; padding: 8px;'> Age </th>
                <th style='border: 1px solid #dddddd;text-align: left; padding: 8px;'> Gender type </th>
              </tr>
              </thead>";
            $iforlist = 1;
            while($iforlist<7)
            {
                echo "<form method='post'>";
                echo "<tr>";
                echo "<td style='border: 1px solid #dddddd;text-align: left; padding: 8px;'>".$iforlist."</td>";
                echo "<td style='border: 1px solid #dddddd;text-align: left; padding: 8px;'><input type='text' name='passenger_name.".$iforlist."' value='' placeholder='Enter name '></td>";
                echo "<td style='border: 1px solid #dddddd;text-align: left; padding: 8px;'><input type='number' name='passenger_age.".$iforlist."' value='' max='100' min='1' placeholder='Enter passenger age '></td>";
                echo "<td style='border: 1px solid #dddddd;text-align: left; padding: 8px;'><select name='passenger_gender.".$iforlist."'>
                    <option value='Male'>Male</option>
                    <option value='Female'>Female</option>
                    </select></td></td>";
                echo "</tr>";
                $iforlist++;
            }
            echo "</table>";
            echo "<div align='center' style='margin-top:10px;'><input type='submit' align='center' name='proceed' value='Proceed' style='width:100px;height:40px;' placeholder='Enter name '></div>";
            echo "</form>";
        ?>
    </div>

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

So, tell me how can i make fetch data if only 2 or 3 field are filled and make a 2d array of it.
if you want any other information i'll give you..

答:
Here is an example of how to use 2D Arrays in PHP

```<code>$cars = array
  (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
  );
</code>```

Now to access the data, you must specify the row and column:

```<code><?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
</code>```

In this case:

```<code>array("Volvo",22,18)
</code>```

That is a single row (0) and it has three columns (Volvo at row=0 column=0, 22 at row=0 colum=1, etc)

I took the example from here: https://www.w3schools.com/php/php_arrays_multi.asp

Let me know if this helps.

Body:
I am just making a railway reservation project to my college therefor I have to get passenger details and make a 2d array and send it to another page to show the summary but I just don't know how to do that.

my code is

<?php
    include('connection.php');
    session_start();
    $train_number = $_GET['train_number'];
    $train_name = $_GET['train_name'];
    $coachid = $_GET['coachid'];
    $date = $_SESSION['date'];
    $day = $_SESSION['day'];
    $coachtype = $_SESSION['coachtype'];
    $useremail = $_SESSION['useremail'];
    if($_SERVER['REQUEST_METHOD']='POST')
    {
        if(!empty($_POST['proceed']))
        {
            $i = 1;
            while($i<7)
            {
                "What to write here";
            }
        }
    }
?>
<!DOCTYPE html>

    <title>Buy Tickets </title>
    <link rel="stylesheet" href="css.css">

Dashboard

Buy Ticket

Cancel ticket

Edit Profile

Logout

        <?php
            echo "
Booking for
";
            echo "

                 Train Number
                 Train name
                 Date
                 Coach type

";
            echo "
";
            echo "".$train_number."	";
            echo "".$train_name."	";
            echo "".$date."	";
            echo "".$coachtype."	";
            echo "
";
            echo "
";
            echo "
Passenger details
";
            echo "

                 No
                 Passenger Name
                 Age
                 Gender type

";
            $iforlist = 1;
            while($iforlist<7)
            {
                echo "<form method='post'>";
                echo "
";
                echo "".$iforlist."	";
                echo "<input type='text' name='passenger_name.".$iforlist."' value='' placeholder='Enter name '>	";
                echo "<input type='number' name='passenger_age.".$iforlist."' value='' max='100' min='1' placeholder='Enter passenger age '>	";
                echo "<select name='passenger_gender.".$iforlist."'>
                    <option value='Male'>Male</option>
                    <option value='Female'>Female</option>
                    </select>		";
                echo "
";
                $iforlist++;
            }
            echo "
";
            echo "
<input type='submit' align='center' name='proceed' value='Proceed' style='width:100px;height:40px;' placeholder='Enter name '>
";
            echo "</form>";
        ?>

So, tell me how can i make fetch data if only 2 or 3 field are filled and make a 2d array of it.
if you want any other information i'll give you..

Body:
Here is an example of how to use 2D Arrays in PHP

$cars = array
  (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
  );

Now to access the data, you must specify the row and column:

<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>

In this case:

array("Volvo",22,18)

That is a single row (0) and it has three columns (Volvo at row=0 column=0, 22 at row=0 colum=1, etc)

I took the example from here: https://www.w3schools.com/php/php_arrays_multi.asp

Let me know if this helps.


问:
Asynchronous action methods with synchronous API calls
I have an action method that inserts some data into the database. I'm trying to make it asynchronous. The code looks like this:

```<code>public async Task<ActionResult> Create([DataSourceRequest] DataSourceRequest request, MyClass model)
{
    return await Task.Run(() =>
    {
        if (model != null && ModelState.IsValid)
        {
            try
            {
                repository.Insert(model);

                anotherSyncCall(model);
            }
            catch { ModelState.AddModelError("", "Error"); }
        }

        return Json(new[] { model }.ToDataSourceResult(request, ModelState));
    });
}
</code>```

Repository's insert method is synchronous, do I have to make it asynchronous to make this action method asynchronous?

Repository Insert code:

```<code>private EFDbContext context;
public Repository()
{
    context = new EFDbContext(Authentication.GetConnectionClaim);
}
//......
public void Insert(T entity)
{
    context.Set<T>().Add(entity);
    context.SaveChanges();
}
</code>```

This a picture of  timings, under repetitive requests.

As you can see they're working synchronously. I'm sure that my client side Ajax calls are async, because all of the requests are made at once and they receive their responses over time.

UPDATE

This is the code that I'm testing my app with:

```<code>for (var i = 0; i < 100; i++) {
        $.ajax({
            method: 'post',
            url: 'http://192.168.1.8/xx/xx/Read',
            data: 'sort=&page=1&pageSize=10&group=&filter='
        });
    }
</code>```

And I've tried setting SessionState to Readonly as @Dan suggested but id didn't change the timings.

On the second thought, maybe it's ToDataSourceResult extension method of Kendo UI that is causing this issue? But I'm making a different Task for this action method anyway.

答: Using Task.Run in a synchronous method by nature, does not mean your code will perform faster. You will rather ended up blocking your server responsiveness (as shown in your pictures). Server cannot process all these requests at the same time, that is why you get above behavior.  If your intention is a non-blocking behavior in the client side. You should call this synchronous method using ajax from the client side so user would not freeze. If you want to dive into async/await in the server side mostly is used for apps that have a limited amount of users, I recommend you this slides Stephen Cleary Conference as well as reading his blog.</p>

Body:
I have an action method that inserts some data into the database. I'm trying to make it asynchronous. The code looks like this:

public async Task<ActionResult> Create([DataSourceRequest] DataSourceRequest request, MyClass model)
{
    return await Task.Run(() =>
    {
        if (model != null && ModelState.IsValid)
        {
            try
            {
                repository.Insert(model);

                anotherSyncCall(model);
            }
            catch { ModelState.AddModelError("", "Error"); }
        }

        return Json(new[] { model }.ToDataSourceResult(request, ModelState));
    });
}

Repository's insert method is synchronous, do I have to make it asynchronous to make this action method asynchronous?

Repository Insert code:

private EFDbContext context;
public Repository()
{
    context = new EFDbContext(Authentication.GetConnectionClaim);
}
//......
public void Insert(T entity)
{
    context.Set<T>().Add(entity);
    context.SaveChanges();
}

This a picture of  timings, under repetitive requests.

As you can see they're working synchronously. I'm sure that my client side Ajax calls are async, because all of the requests are made at once and they receive their responses over time.

UPDATE

This is the code that I'm testing my app with:

for (var i = 0; i < 100; i++) {
        $.ajax({
            method: 'post',
            url: 'http://192.168.1.8/xx/xx/Read',
            data: 'sort=&page=1&pageSize=10&group=&filter='
        });
    }

And I've tried setting SessionState to Readonly as @Dan suggested but id didn't change the timings.

On the second thought, maybe it's ToDataSourceResult extension method of Kendo UI that is causing this issue? But I'm making a different Task for this action method anyway.


问:
Display the customer city in new order email notification
When a new order is created, woocommerce will send an email to admin, and I want it to send customer's city location inside the email as well.

Adding this code in function.php file will only show the IP requiring additional step to open browser and search for IP location to find the city:

```<code>add_action('woocommerce_email_customer_details',    'send_customer_ip_adress', 10, 4);
function send_customer_ip_adress($order, $sent_to_admin, $plain_text, $email){

// Just for admin new order notification
if( 'new_order' == $email->id )
    echo '<br><p><strong>Customer IP address:</strong> '. get_post_meta( $order->id, '_customer_ip_address', true ).'</p>';
}
</code>```

There are clients placing fake orders using false address while this will show me the real city location.

So how can I display the customer City?

Code comes from: Display the customer IP Address in new order email notification

答:
You can add to the customer IP address, his billing city too, this way:

```<code>add_action( 'woocommerce_email_customer_details', 'send_customer_city', 10, 4 );
function send_customer_city( $order, $sent_to_admin, $plain_text, $email ){

    // Just for admin new order notification
    if( 'new_order' == $email->id ){
        echo '<br>
        <p><strong>'.__('Customer IP address').':</strong> '. get_post_meta( $order->id, '_customer_ip_address', true ).'</p>
        <p><strong>'.__('Customer city').':</strong> '. get_post_meta( $order->get_id(), '_billing_city', true ).'</p>';
    }
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works

Body:
When a new order is created, woocommerce will send an email to admin, and I want it to send customer's city location inside the email as well.

Adding this code in function.php file will only show the IP requiring additional step to open browser and search for IP location to find the city:

add_action('woocommerce_email_customer_details',    'send_customer_ip_adress', 10, 4);
function send_customer_ip_adress($order, $sent_to_admin, $plain_text, $email){

// Just for admin new order notification
if( 'new_order' == $email->id )
    echo '

Customer IP address: '. get_post_meta( $order->id, '_customer_ip_address', true ).'
';
}

There are clients placing fake orders using false address while this will show me the real city location.

So how can I display the customer City?

Code comes from: Display the customer IP Address in new order email notification

Body:
You can add to the customer IP address, his billing city too, this way:

add_action( 'woocommerce_email_customer_details', 'send_customer_city', 10, 4 );
function send_customer_city( $order, $sent_to_admin, $plain_text, $email ){

    // Just for admin new order notification
    if( 'new_order' == $email->id ){
        echo '<br>
        <p><strong>'.__('Customer IP address').':</strong> '. get_post_meta( $order->id, '_customer_ip_address', true ).'</p>
        <p><strong>'.__('Customer city').':</strong> '. get_post_meta( $order->get_id(), '_billing_city', true ).'</p>';
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works


问:
why cant I define a global function in a header file?
I have this function I am trying to define in  my header in which i also have defined a class, but for some reason it this not possible, as I don't see why it is causing so many problems.

database.h

```<code>//#pragma once

#ifndef DATABASE_H
#define DATABASE_H

#include "record.h"
#include "spectogram.h"
#include <iostream>
#include <experimental/filesystem>

#define string_dir_to_test_files "/home/noob/soundcloud/src/include/database/test_files/"

class database {
public:
    vector<AudioFile<SAMPLE>> list_of_files;
    database();

};

int number_of_files(std::experimental::filesystem::path path);

#endif DATABASE_H
</code>```

database.cpp

```<code>#include "database.h"

int number_of_files(std::experimental::filesystem::path path)
{
    using std::experimental::filesystem::directory_iterator;
    return std::distance(directory_iterator(path),directory_iterator(path));
}

database::database()
{
    std::experimental::filesystem::path _path(string_dir_to_test_files);
    if (std::experimental::filesystem::exists(_path))
    {
        std::cout << "exists() = " << std::experimental::filesystem::exists(_path) << "\n"
             << "root_name() = " << _path.root_name() << "\n"
             << "root_path() = " << _path.root_path() << "\n"
             << "relative_path() = " << _path.relative_path() << "\n"
             << "parent_path() = " << _path.parent_path() << "\n"
             << "filename() = " << _path.filename() << "\n"
             << "stem() = " << _path.stem() << "\n"
             << "extension() = " << _path.extension() << "\n";

        std::cout << "Number of files in directory: " << number_of_files(_path) << std::endl;
    }

}
</code>```

spectogram.h

```<code>#pragma once

#include <sigpack.h>
#include "AudioFile.h"
#include <iostream>

typedef float SAMPLE;

class spectogram {
public:
    spectogram();
    arma::mat generate_spectogram(const AudioFile<SAMPLE> *file)
    {
        arma::mat output;
        if(file->getNumChannels() == 2)
        {
            std::cout << "I am here" << std::endl;
            arma::Col<SAMPLE> ch1 = file->samples[0];
            arma::Col<SAMPLE> ch2 = file->samples[1];
            arma::mat output = sp::specgram(ch1);
            return output;
        }
        else
        {
            std::cout << "I am am here" << std::endl;
            arma::Col<SAMPLE> ch1 = file->samples[0];
            arma::mat output = sp::specgram(ch1);
            std::cout << output << std::endl;
            return output;
        }

    }
};
</code>```

record.h the audiofile include is this one

```<code>#pragma once
#include <iostream> // Functionality: COUT
#include "portaudio.h"
#include <stdio.h>
#include <stdlib.h>
#include <chrono>  //Functionality: Sleep
#include <thread>   //Functionality: Sleep
#include <algorithm> //Functionality: fill_n
#include "AudioFile.h"
#define SAMPLE_RATE (44100)

typedef float SAMPLE;

#define NUM_SECONDS 10
#define NUM_CHANNELS  1
#define SAMPLE_SILENCE 0.0f
#define PA_SAMPLE_TYPE  paFloat32
#define FRAMES_PER_BUFFER (512)
#define TRUE (1==1)
#define FALSE (!TRUE)
#define WRITE_TO_FILE   TRUE

typedef struct
{
    int     frameIndex;
    int     maxFrameindex;
    SAMPLE  *recordedSamples;
}
paTestData;

class record {
public:
    record();
    void start_record();
    AudioFile<SAMPLE>           file;

private:
    PaStreamParameters  inputParameters,
                        outputParameters;
    PaStream*           stream;
    PaError             err = paNoError;
    paTestData          data;
    int                 totalFrames;
    int                 numSamples;
    int                 numBytes;
    SAMPLE              max, val;
    double              average;
    int recordCallback(const void *inputBuffer, void *outputBuffer,
                       unsigned long framesPerBuffer,
                       const PaStreamCallbackTimeInfo* timeInfo,
                       PaStreamCallbackFlags statusFlags, void *userData);

    static int recordCallbackSub(const void *inputBuffer, void *outputBuffer,
                       unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo,
                       PaStreamCallbackFlags statusFlags, void *userData)
    {
        auto pThis = reinterpret_cast<record*>(userData);  // get back the this pointer.
        return pThis->recordCallback( inputBuffer, outputBuffer,framesPerBuffer, timeInfo,statusFlags, nullptr);

    }
};
</code>```

match.h

```<code>#pragma once
#include <iostream>

class match {
public:

};
</code>```

main.cpp

```<code>#include <record.h>
#include <database.h>
#include <match.h>
#include <spectogram.h>
#include <iostream>

int main()
{
    database start;
    //record  somethis;
    //somethis.start_record();
    //spectogram specto;
    //specto.generate_spectogram(&somethis.file);
    return 0;
}
</code>```

gives me these warnings:

```<code>make
[ 42%] Built target project_portaudio
[ 57%] Built target record
[ 68%] Built target spectogram
[ 78%] Built target database
Scanning dependencies of target match
[ 84%] Building CXX object src/include/match/CMakeFiles/match.dir/match.cpp.o
[ 89%] Linking CXX static library libmatch.a
[ 89%] Built target match
Scanning dependencies of target cmakeDemo
[ 94%] Building CXX object src/CMakeFiles/cmakeDemo.dir/main.cpp.o
In file included from /home/noob/soundcloud/src/main.cpp:2:0:
/home/noob/soundcloud/src/include/database/database.h:25:8: warning: extra tokens at end of #endif directive [-Wendif-labels]
 #endif DATABASE_H
        ^~~~~~~~~~
[100%] Linking CXX executable ../cmakeDemo
[100%] Built target cmakeDemo
</code>```

but the warnings remove if #include<match.h> is commented?

```<code>make
[ 42%] Built target project_portaudio
[ 57%] Built target record
[ 68%] Built target spectogram
[ 78%] Built target database
[ 89%] Built target match
[100%] Built target cmakeDemo
</code>```

Something is very weird?

答:
The problem is you are lacking header guards. Each time you include the header it is considered as a redefinition of the function.
You should add #pragma once at the start of your header to solve this problem

Body:
I have this function I am trying to define in  my header in which i also have defined a class, but for some reason it this not possible, as I don't see why it is causing so many problems.

database.h

//#pragma once

#ifndef DATABASE_H
#define DATABASE_H

#include "record.h"
#include "spectogram.h"
#include <iostream>
#include <experimental/filesystem>

#define string_dir_to_test_files "/home/noob/soundcloud/src/include/database/test_files/"

class database {
public:
    vector<AudioFile<SAMPLE>> list_of_files;
    database();

};

int number_of_files(std::experimental::filesystem::path path);

#endif DATABASE_H

database.cpp

#include "database.h"

int number_of_files(std::experimental::filesystem::path path)
{
    using std::experimental::filesystem::directory_iterator;
    return std::distance(directory_iterator(path),directory_iterator(path));
}

database::database()
{
    std::experimental::filesystem::path _path(string_dir_to_test_files);
    if (std::experimental::filesystem::exists(_path))
    {
        std::cout << "exists() = " << std::experimental::filesystem::exists(_path) << "\n"
             << "root_name() = " << _path.root_name() << "\n"
             << "root_path() = " << _path.root_path() << "\n"
             << "relative_path() = " << _path.relative_path() << "\n"
             << "parent_path() = " << _path.parent_path() << "\n"
             << "filename() = " << _path.filename() << "\n"
             << "stem() = " << _path.stem() << "\n"
             << "extension() = " << _path.extension() << "\n";

        std::cout << "Number of files in directory: " << number_of_files(_path) << std::endl;
    }

}

spectogram.h

#pragma once

#include <sigpack.h>
#include "AudioFile.h"
#include <iostream>

typedef float SAMPLE;

class spectogram {
public:
    spectogram();
    arma::mat generate_spectogram(const AudioFile<SAMPLE> *file)
    {
        arma::mat output;
        if(file->getNumChannels() == 2)
        {
            std::cout << "I am here" << std::endl;
            arma::Col<SAMPLE> ch1 = file->samples[0];
            arma::Col<SAMPLE> ch2 = file->samples[1];
            arma::mat output = sp::specgram(ch1);
            return output;
        }
        else
        {
            std::cout << "I am am here" << std::endl;
            arma::Col<SAMPLE> ch1 = file->samples[0];
            arma::mat output = sp::specgram(ch1);
            std::cout << output << std::endl;
            return output;
        }

    }
};

record.h the audiofile include is this one

#pragma once
#include <iostream> // Functionality: COUT
#include "portaudio.h"
#include <stdio.h>
#include <stdlib.h>
#include <chrono>  //Functionality: Sleep
#include <thread>   //Functionality: Sleep
#include <algorithm> //Functionality: fill_n
#include "AudioFile.h"
#define SAMPLE_RATE (44100)

typedef float SAMPLE;

#define NUM_SECONDS 10
#define NUM_CHANNELS  1
#define SAMPLE_SILENCE 0.0f
#define PA_SAMPLE_TYPE  paFloat32
#define FRAMES_PER_BUFFER (512)
#define TRUE (1==1)
#define FALSE (!TRUE)
#define WRITE_TO_FILE   TRUE

typedef struct
{
    int     frameIndex;
    int     maxFrameindex;
    SAMPLE  *recordedSamples;
}
paTestData;

class record {
public:
    record();
    void start_record();
    AudioFile<SAMPLE>           file;

private:
    PaStreamParameters  inputParameters,
                        outputParameters;
    PaStream*           stream;
    PaError             err = paNoError;
    paTestData          data;
    int                 totalFrames;
    int                 numSamples;
    int                 numBytes;
    SAMPLE              max, val;
    double              average;
    int recordCallback(const void *inputBuffer, void *outputBuffer,
                       unsigned long framesPerBuffer,
                       const PaStreamCallbackTimeInfo* timeInfo,
                       PaStreamCallbackFlags statusFlags, void *userData);

    static int recordCallbackSub(const void *inputBuffer, void *outputBuffer,
                       unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo,
                       PaStreamCallbackFlags statusFlags, void *userData)
    {
        auto pThis = reinterpret_cast<record*>(userData);  // get back the this pointer.
        return pThis->recordCallback( inputBuffer, outputBuffer,framesPerBuffer, timeInfo,statusFlags, nullptr);

    }
};

match.h

#pragma once
#include <iostream>

class match {
public:

};

main.cpp

#include <record.h>
#include <database.h>
#include <match.h>
#include <spectogram.h>
#include <iostream>

int main()
{
    database start;
    //record  somethis;
    //somethis.start_record();
    //spectogram specto;
    //specto.generate_spectogram(&somethis.file);
    return 0;
}

gives me these warnings:

make
[ 42%] Built target project_portaudio
[ 57%] Built target record
[ 68%] Built target spectogram
[ 78%] Built target database
Scanning dependencies of target match
[ 84%] Building CXX object src/include/match/CMakeFiles/match.dir/match.cpp.o
[ 89%] Linking CXX static library libmatch.a
[ 89%] Built target match
Scanning dependencies of target cmakeDemo
[ 94%] Building CXX object src/CMakeFiles/cmakeDemo.dir/main.cpp.o
In file included from /home/noob/soundcloud/src/main.cpp:2:0:
/home/noob/soundcloud/src/include/database/database.h:25:8: warning: extra tokens at end of #endif directive [-Wendif-labels]
 #endif DATABASE_H
        ^~~~~~~~~~
[100%] Linking CXX executable ../cmakeDemo
[100%] Built target cmakeDemo

but the warnings remove if #include<match.h> is commented?

make
[ 42%] Built target project_portaudio
[ 57%] Built target record
[ 68%] Built target spectogram
[ 78%] Built target database
[ 89%] Built target match
[100%] Built target cmakeDemo

Something is very weird?


问:
Converting struct with embedded interface into JSON
I have a struct that I want to marshal to JSON. It has a defined field called Foo (exported as foo) and a data interface field to which I want to pass a dynamic struct with additional JSON fields.

However when the data field is an interface instead of the specific struct it never gets exported as JSON. How can I make this work?

```<code>package main

import (
    "encoding/json"
    "fmt"
)

type data interface{}

type foo struct {
    Foo string `json:"foo,omitempty"`
    data
}

type bar struct {
    Bar string `json:"bar,omitempty"`
}

func main() {
    b := bar{"bar"}
    f := foo{"foo", b}

    byt, err := json.Marshal(f)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(byt))
}
</code>```

I need to output to look like this (it needs to be flat, not nested):

```<code>{"foo": "foo", "bar": "bar"}
</code>```

答:
2 options:

Set to it type json.RawMessage so it won’t be decoded automatically and left as an interface.  https://golang.org/pkg/encoding/json/#RawMessage

Write custom unmarshaler on the structure.

Body:
I have a struct that I want to marshal to JSON. It has a defined field called Foo (exported as foo) and a data interface field to which I want to pass a dynamic struct with additional JSON fields.

However when the data field is an interface instead of the specific struct it never gets exported as JSON. How can I make this work?

package main

import (
    "encoding/json"
    "fmt"
)

type data interface{}

type foo struct {
    Foo string `json:"foo,omitempty"`
    data
}

type bar struct {
    Bar string `json:"bar,omitempty"`
}

func main() {
    b := bar{"bar"}
    f := foo{"foo", b}

    byt, err := json.Marshal(f)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(byt))
}

I need to output to look like this (it needs to be flat, not nested):

{"foo": "foo", "bar": "bar"}


问:
How use Xamarin.Forms MessagingCenter without tied it to the UI?
I have a long running task that need to be notified to the user using Toast-like messages. However, the user could move around the app freely.

Looking at https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/messaging-center/, it show that is necessary to bind to the UI to it to work?

```<code>MessagingCenter.Subscribe<MainPage> (this, "Hi", (sender) => {
    // do something whenever the "Hi" message is sent
});
MessagingCenter.Send<MainPage> (this, "Hi")
</code>```

I need to send notifications in the background, and I don't know from there to who.

答:
If you take a look it does not need to be bound to the UI but just to an Object which is the subscriber. so you could just get away with setting the subscriber to 'this' in code.

To Recieve something you could use this without the .

```<code>MessagingCenter.Subscribe(this, "Hi", (sender) =>
{
    // do something whenever the "Hi" message is sent
});
</code>```

To send something you could use this.

```<code>MessagingCenter.Send<MainPage> (this, "Hi")
</code>```

Body:
I have a long running task that need to be notified to the user using Toast-like messages. However, the user could move around the app freely.

Looking at https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/messaging-center/, it show that is necessary to bind to the UI to it to work?

MessagingCenter.Subscribe<MainPage> (this, "Hi", (sender) => {
    // do something whenever the "Hi" message is sent
});
MessagingCenter.Send<MainPage> (this, "Hi")

I need to send notifications in the background, and I don't know from there to who.

Body:
If you take a look it does not need to be bound to the UI but just to an Object which is the subscriber. so you could just get away with setting the subscriber to 'this' in code.

To Recieve something you could use this without the .

MessagingCenter.Subscribe(this, "Hi", (sender) =>
{
    // do something whenever the "Hi" message is sent
});

To send something you could use this.

MessagingCenter.Send<MainPage> (this, "Hi")


问:
resize row length proper using PrimeNG Datatable?
How can i solve this problem I want to resize row length proper using PrimeNG Datatable?
Now My Data Display Like These

And I want to change Like These

答:
Without a more elaborate setup, I would recommend utilizing the resizableColumns, expandableRows and expandedRows options on the p-dataTable and set your widths as percentages as well as make your columns manually adjustable (https://www.primefaces.org/primeng/#/datatable); for example, something like:

```<code><p-dataTable [value]="cars" [resizableColumns]="true" [expandableRows]="true" [expandedRows]="expandedItems">
    <p-column field="vin" header="Vin" [resizable]="true" [style]="{'width':'20%'}"></p-column>
    <p-column field="year" header="Year" [resizable]="true" [style]="{'width':'30%'}"></p-column>
    <p-column field="brand" header="Brand" [resizable]="true" [style]="{'width':'15%'}"></p-column>
    <p-column field="color" header="Color" [resizable]="true" [style]="{'width':'35%'}"></p-column>
</p-dataTable>
</code>```

For more detail, see this StackOverflow: How to expand row from datatable programmatically

Body:
Without a more elaborate setup, I would recommend utilizing the resizableColumns, expandableRows and expandedRows options on the p-dataTable and set your widths as percentages as well as make your columns manually adjustable (https://www.primefaces.org/primeng/#/datatable); for example, something like:

<p-dataTable [value]="cars" [resizableColumns]="true" [expandableRows]="true" [expandedRows]="expandedItems">
    <p-column field="vin" header="Vin" [resizable]="true" [style]="{'width':'20%'}"></p-column>
    <p-column field="year" header="Year" [resizable]="true" [style]="{'width':'30%'}"></p-column>
    <p-column field="brand" header="Brand" [resizable]="true" [style]="{'width':'15%'}"></p-column>
    <p-column field="color" header="Color" [resizable]="true" [style]="{'width':'35%'}"></p-column>
</p-dataTable>

For more detail, see this StackOverflow: How to expand row from datatable programmatically


问:
Azure Search - Using double quotes in a search string
I have a requirement that my application should be able to search a string having a double quote in it. For example 22" Wood Log. Currently, searching for this string returns an error of query being failed.

I understand that using quotes like "abc" will give me results for only abc. But in the case of 22" Wood Log, the double quote represent inches and user may search like "22" Wood Log" expecting to see results for 22" Wood Log.

What are my options in current scenario to get some results? I hope my question is not too ambiguous.

答:
The comment provided by Gaurav Mantri is correct. You should just escape the special characters in the search query with the backslash \ character.

For more details and for reference about the querying syntax, please visit: https://learn.microsoft.com/en-us/rest/api/searchservice/lucene-query-syntax-in-azure-search

(You particular query is answered under the Section: Escaping special characters)


问:
NFC/RFID module multiple cards
I have this NFC module. When i read ONE card at a moment everything works fine, but I need to read more that one card at a moment.

One card laying on a module - module reads it ok, when I move another card over the module, I get a mix of both card's numbers.

Is there any way to read both card at one moment correctly?

I read card like this. As a bord I use NodeMCU ESP8266 ESP-12E

```<code>SoftwareSerial rfid(RFID_RX, RFID_TX);
..
void loop()
{
    rfid.listen();
    delay(500);

    while (rfid.available() > 0) {
        Serial.println("Closest card number: " + rfid.readString());
    }

}
</code>```

答:
As the comments suggest this is quite hard.

If you want to read more cards you can maybe use the PN532, According to this thread with the board developer it can read 2 cards simultaneously.

Title: NFC/RFID module multiple cards

Body:
I have this NFC module. When i read ONE card at a moment everything works fine, but I need to read more that one card at a moment.

One card laying on a module - module reads it ok, when I move another card over the module, I get a mix of both card's numbers.

Is there any way to read both card at one moment correctly?

I read card like this. As a bord I use NodeMCU ESP8266 ESP-12E

SoftwareSerial rfid(RFID_RX, RFID_TX);
..
void loop()
{
    rfid.listen();
    delay(500);

    while (rfid.available() > 0) {
        Serial.println("Closest card number: " + rfid.readString());
    }

}


问:
C# Create an instance of a class from string
I am new in C# and I want to create an instance for MyTestClass in runtime. How can I do it ?

```<code>public class MyTestClass
{
    public int Value { get; set; }

    public MyTestClass()
    {
        Value = 5;
    }
}
</code>```

EDIT:
I just want to create an instance of MyTestClass from string variable like

```<code>string classInstance = "MyTestClass"
</code>```

I couldn't explain completely at first time, sorry for this.

答:
```<code>public static I CreateInstance<I>() where I : class
{
    string assemblyPath = Environment.CurrentDirectory + "\\MyTestClass.exe";

    Assembly assembly;

    assembly = Assembly.LoadFrom(assemblyPath);
    Type type = assembly.GetType("MyTestClass");
    return Activator.CreateInstance(type) as I;
}
</code>```

Body:
I am new in C# and I want to create an instance for MyTestClass in runtime. How can I do it ?

public class MyTestClass
{
    public int Value { get; set; }

    public MyTestClass()
    {
        Value = 5;
    }
}

EDIT:
I just want to create an instance of MyTestClass from string variable like

string classInstance = "MyTestClass"

I couldn't explain completely at first time, sorry for this.


问:
Calculate Time Remaining
What's a good algorithm for determining the remaining time for something to complete?  I know how many total lines there are, and how many have completed already, how should I estimate the time remaining?</p>

答:
If you know the percentage completed, and you can simply assume that the time scales linearly, something like

timeLeft = timeSoFar * (1/Percentage)

might work.

OwnerDisplayName: Aaron Smith

Title: Calculate Time Remaining

OwnerDisplayName: GWLlosa


问:
Displaying error message "Email not valid" but still saving to database file
can anyone help me for this problem. I have three text boxes in c# WPF (windows presentation foundation). I am displaying error message when Email text box not have valid email by pressing button but all the data from other text boxes including email text box is saving to my database file. What I should to do to stop saving data if error message pop up. Many thanks.</p>

```<code> Regex regMail = new Regex(@"^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$");

        if (regMail.IsMatch(mailID.Text))
        {

        }
        else
        {
            MessageBox.Show("Invalid Email ID, Please enter \nvalid Email ID.");

        }

        Email email = new Email();

        string emailAdd = mailID.Text;
        string phone =    phoneBox.Text;
        string messageEmail = email.Text;

        System.IO.StreamWriter file = new System.IO.StreamWriter(@"D:\Lia\mail.txt", true);
        file.WriteLine(emailAdd + phone + messageEmail);

        file.Close();
    }
</code>```

答:
Because all of your code is outside of your if block.  So it's going to execute every time, regardless of the condition.

Put the code in the if block:

```<code>Regex regMail = new Regex(@"^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$");

if (regMail.IsMatch(mailID.Text))
{
    Email email = new Email();

    string emailAdd = mailID.Text;
    string phone =    phoneBox.Text;
    string messageEmail = email.Text;

    System.IO.StreamWriter file = new System.IO.StreamWriter(@"D:\Lia\mail.txt", true);
    file.WriteLine(emailAdd + phone + messageEmail);

    file.Close();
}
else
{
    MessageBox.Show("Invalid Email ID, Please enter \nvalid Email ID.");
}
</code>```

Body:
can anyone help me for this problem. I have three text boxes in c# WPF (windows presentation foundation). I am displaying error message when Email text box not have valid email by pressing button but all the data from other text boxes including email text box is saving to my database file. What I should to do to stop saving data if error message pop up. Many thanks.

 Regex regMail = new Regex(@"^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$");

        if (regMail.IsMatch(mailID.Text))
        {

        }
        else
        {
            MessageBox.Show("Invalid Email ID, Please enter \nvalid Email ID.");

        }

        Email email = new Email();

        string emailAdd = mailID.Text;
        string phone =    phoneBox.Text;
        string messageEmail = email.Text;

        System.IO.StreamWriter file = new System.IO.StreamWriter(@"D:\Lia\mail.txt", true);
        file.WriteLine(emailAdd + phone + messageEmail);

        file.Close();
    }

Body:
Because all of your code is outside of your if block.  So it's going to execute every time, regardless of the condition.

Put the code in the if block:

Regex regMail = new Regex(@"^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$");

if (regMail.IsMatch(mailID.Text))
{
    Email email = new Email();

    string emailAdd = mailID.Text;
    string phone =    phoneBox.Text;
    string messageEmail = email.Text;

    System.IO.StreamWriter file = new System.IO.StreamWriter(@"D:\Lia\mail.txt", true);
    file.WriteLine(emailAdd + phone + messageEmail);

    file.Close();
}
else
{
    MessageBox.Show("Invalid Email ID, Please enter \nvalid Email ID.");
}


问:
When creating a class object, I get "error: linker command failed with exit code 1"
When ever I attempt to create a dgraph object, I get a compile error but I can link and compile the files perfectly fine when I omit the line that creates the dgraph object. Please help! Thanks.

This is main.cpp:

```<code>#include<iostream>
#include"dgraph.h"
using namespace std;
int main()
{
  string test;
  test = "Hello, world!";
  cout << test << endl;
  slist L1;
  L1.displayAll();
  dgraph L2; //offending line
  return 0;
}
</code>```

This is my dgraph.h:

```<code>#include <iostream>
#include <string>
#include "slist.h"

using namespace std;

const int SIZE = 20;
struct Gvertex
{
  char vertexName;      //the vertex Name
  int outDegree;    //the Out degree
  slist adjacentOnes;   //the adjecent vertices in an slist
  int visit;            // This will hold the visit number in HW7
};

class dgraph
{

private:
  Gvertex Gtable[SIZE];  // a table representing a dgraph
  int  countUsed; // how many slots of the Gtable are actually used

public:

  class BadVertex {};  // thrown when the vertex is not in the graph

  dgraph();
  ~dgraph();
  void fillTable();
  void displayGraph();
  int findOutDegree(char);
  slist findAdjacency(char);
};
</code>```

dgraph.cpp:

```<code>#include<iostream>
#include<fstream>
#include"dgraph.h"

void dgraph::fillTable()
{
  ifstream fin;
  fin.open("table.txt");
  while(fin >> Gtable[countUsed].vertexName) //if you can read the name
  {
    char x; //temp var
    fin >> Gtable[countUsed].outDegree;
    for (int i = 0; i < Gtable[countUsed].outDegree; ++i)
    {
      fin >> x;
      Gtable[countUsed].adjacentOnes.addRear(x);
    }
    countUsed++;
  }
  fin.close();
}
</code>```

I am compiling using g++ -c then using g++ -o to link all the files together.
Here is the exact error I get when I compile:

```<code>g++ -o run hw6Client.o dgraph.o llist.o slist.o
Undefined symbols for architecture x86_64:
"dgraph::~dgraph()", referenced from:
  _main in hw6Client.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see
invocation)
</code>```

答:
The header declares the dgraph object, but doesn't define the implementation. This is no problem as long as you don't actually create a dgraph object. The problem comes when you include the offending line which actually declares a dgraph object. When you do this, the linker will look for the actual implementation somewhere, but can't find it. You need to include the implementation of

```<code>void dgraph::filltable()
void dgraph::displayGraph()
int dgraph::findOutDegree(char)
slist dgraph::findAdjacency(char)
dgraph::dgraph()
dgraph::~dgraph()
</code>```

somewhere where the linker will find it. You need to explicitly define the constructor and destructor because you explicitly declared them.

Body:
When ever I attempt to create a dgraph object, I get a compile error but I can link and compile the files perfectly fine when I omit the line that creates the dgraph object. Please help! Thanks.

This is main.cpp:

#include<iostream>
#include"dgraph.h"
using namespace std;
int main()
{
  string test;
  test = "Hello, world!";
  cout << test << endl;
  slist L1;
  L1.displayAll();
  dgraph L2; //offending line
  return 0;
}

This is my dgraph.h:

#include <iostream>
#include <string>
#include "slist.h"

using namespace std;

const int SIZE = 20;
struct Gvertex
{
  char vertexName;      //the vertex Name
  int outDegree;    //the Out degree
  slist adjacentOnes;   //the adjecent vertices in an slist
  int visit;            // This will hold the visit number in HW7
};

class dgraph
{

private:
  Gvertex Gtable[SIZE];  // a table representing a dgraph
  int  countUsed; // how many slots of the Gtable are actually used

public:

  class BadVertex {};  // thrown when the vertex is not in the graph

  dgraph();
  ~dgraph();
  void fillTable();
  void displayGraph();
  int findOutDegree(char);
  slist findAdjacency(char);
};

dgraph.cpp:

#include<iostream>
#include<fstream>
#include"dgraph.h"

void dgraph::fillTable()
{
  ifstream fin;
  fin.open("table.txt");
  while(fin >> Gtable[countUsed].vertexName) //if you can read the name
  {
    char x; //temp var
    fin >> Gtable[countUsed].outDegree;
    for (int i = 0; i < Gtable[countUsed].outDegree; ++i)
    {
      fin >> x;
      Gtable[countUsed].adjacentOnes.addRear(x);
    }
    countUsed++;
  }
  fin.close();
}

I am compiling using g++ -c then using g++ -o to link all the files together.
Here is the exact error I get when I compile:

g++ -o run hw6Client.o dgraph.o llist.o slist.o
Undefined symbols for architecture x86_64:
"dgraph::~dgraph()", referenced from:
  _main in hw6Client.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see
invocation)

Body:
The header declares the dgraph object, but doesn't define the implementation. This is no problem as long as you don't actually create a dgraph object. The problem comes when you include the offending line which actually declares a dgraph object. When you do this, the linker will look for the actual implementation somewhere, but can't find it. You need to include the implementation of

void dgraph::filltable()
void dgraph::displayGraph()
int dgraph::findOutDegree(char)
slist dgraph::findAdjacency(char)
dgraph::dgraph()
dgraph::~dgraph()

somewhere where the linker will find it. You need to explicitly define the constructor and destructor because you explicitly declared them.


问:
SSL backend error when using OpenSSL
I was trying to install pycurl in a virtualenv using pip and I got this error

```<code>ImportError: pycurl: libcurl link-time ssl backend (openssl) is different from compile-time ssl backend (none/other)
</code>```

I read some documentation saying that "To fix this, you need to tell setup.py what SSL backend is used" (source) although I am not sure how to do this since I installed pycurl using pip.

How can I specify the SSL backend when installing pycurl with pip?

Thanks

答:
Error:

ImportError: pycurl: libcurl link-time ssl backend (openssl) is different from compile-time ssl backend (none/other)

This worked for me, Mac 10.13, python 3.5, pycurl import worked after installing like this

```<code>pip3 uninstall pycurl;

pip3 install --compile --install-option="--with-openssl" pycurl
</code>```

Title: SSL backend error when using OpenSSL

Body:
I was trying to install pycurl in a virtualenv using pip and I got this error

ImportError: pycurl: libcurl link-time ssl backend (openssl) is different from compile-time ssl backend (none/other)

I read some documentation saying that "To fix this, you need to tell setup.py what SSL backend is used" (source) although I am not sure how to do this since I installed pycurl using pip.

How can I specify the SSL backend when installing pycurl with pip?

Thanks

Body:
Error:

ImportError: pycurl: libcurl link-time ssl backend (openssl) is different from compile-time ssl backend (none/other)

This worked for me, Mac 10.13, python 3.5, pycurl import worked after installing like this

pip3 uninstall pycurl;

pip3 install --compile --install-option="--with-openssl" pycurl


问:
Django: How to manage development and production settings?
I have been developing a basic app. Now at the deployment stage it has become clear I have need for both a local settings and production settings.

It would be great to know the following:

How best to deal with development and production settings.

How to keep apps such as django-debug-toolbar only in a development environment.

Any other tips and best practices for development and deployment settings.

答:
I use the folloring file structure:

```<code>project/
   ...
   settings/
   settings/common.py
   settings/local.py
   settings/prod.py
   settings/__init__.py -> local.py
</code>```

So __init__.py is a link (ln in unix or mklink in windows) to local.py or can be to prod.py so the configuration is still in the project.settings module is clean and organized, and if you want to use a particular config you can use the environment variable DJANGO_SETTINGS_MODULE to project.settings.prod if you need to run a command for production environment.

In the files prod.py and local.py:

from .shared import *

DATABASE = {
    ...
}
```

and the shared.py file keeps as global without specific configs.

Body:
I use the folloring file structure:

project/
   ...
   settings/
   settings/common.py
   settings/local.py
   settings/prod.py
   settings/__init__.py -> local.py

So __init__.py is a link (ln in unix or mklink in windows) to local.py or can be to prod.py so the configuration is still in the project.settings module is clean and organized, and if you want to use a particular config you can use the environment variable DJANGO_SETTINGS_MODULE to project.settings.prod if you need to run a command for production environment.

In the files prod.py and local.py:

from .shared import *

DATABASE = {
    ...
}

and the shared.py file keeps as global without specific configs.


问:
How to dynamically autoSize a sharepoint modal dialog box?
I've created a web application in sharepoint which has a sign in link which loads a login webpart in the modal window on click. I haven't set the height of the modal pop through options but i have set its width only.

IE 7, 8 and 9 loads the webpart as per my need, and it automatically adjusts its height on load.  But Firefox (din't test in Chrome) loads the webpart but the height is not adjusted automatically to fit the login WP.

I tried using SP.UI.ModalDialog.get_childDialog().autoSize() explicitly like below

```<code>ExecuteOrDelayUntilScriptLoaded(function () {
SP.UI.ModalDialog.get_childDialog().autoSize();
}, "sp.ui.dialog.js");
</code>```

But this also does not work for Firefox. Calling autoSize in IE works great when I display the errors on login screen but on FF it returns height to be less than 20px and the modal popup seems to have a width but its height is less than 20.

How do I solve this issue?

Please help.

Sorry if I looked like a noob to all.

Thanks in advance

答:
I was just trying to work through a simliar problem myself. I wanted to override the width because my content was wrapping in an undesired behavior. I found that the following allows me to adjust the width after the dialog is presented.

```<code>ExecuteOrDelayUntilScriptLoaded(function () {
  var dialog = SP.UI.ModalDialog.get_childDialog();
  dialog.$2_0.autoSizeStartWidth = 1100;
  dialog.autoSize();
}, "sp.ui.dialog.js");
</code>```

I just added that into a script editor webpart as part of the display form part and it works like a dream.

Body:
I've created a web application in sharepoint which has a sign in link which loads a login webpart in the modal window on click. I haven't set the height of the modal pop through options but i have set its width only.

IE 7, 8 and 9 loads the webpart as per my need, and it automatically adjusts its height on load.  But Firefox (din't test in Chrome) loads the webpart but the height is not adjusted automatically to fit the login WP.

I tried using SP.UI.ModalDialog.get_childDialog().autoSize() explicitly like below

ExecuteOrDelayUntilScriptLoaded(function () {
SP.UI.ModalDialog.get_childDialog().autoSize();
}, "sp.ui.dialog.js");

But this also does not work for Firefox. Calling autoSize in IE works great when I display the errors on login screen but on FF it returns height to be less than 20px and the modal popup seems to have a width but its height is less than 20.

How do I solve this issue?

Please help.

Sorry if I looked like a noob to all.

Thanks in advance

Body:
I was just trying to work through a simliar problem myself. I wanted to override the width because my content was wrapping in an undesired behavior. I found that the following allows me to adjust the width after the dialog is presented.

ExecuteOrDelayUntilScriptLoaded(function () {
  var dialog = SP.UI.ModalDialog.get_childDialog();
  dialog.$2_0.autoSizeStartWidth = 1100;
  dialog.autoSize();
}, "sp.ui.dialog.js");

I just added that into a script editor webpart as part of the display form part and it works like a dream.


问:
why copy constructor is called when passing temporary by const reference?
I am passing an unnamed temporary object to a function defined with const ref parameter. The copy ctor of the class is private, and I get a compilation error. I don't understand why a copy constructor is called in this situation.

```<code>class A {
public:
  A(int i) {}
private:
  A(const A&) {}
};

void f(const A& a)
{
}

int main()
{
  f(A(1)); // <-- error here: 'A::A(const A&)' is private
}
</code>```

As expected, when I change the main to:

```<code>A a(1);
f(a);
</code>```

it works.

EDIT: the compiler is gcc 4.1.2

答:
The expression A(1) is an rvalue 5.2.3 [expr.type.conv].

In initializing a const reference (the function argument) with an expression that is an rvalue the compiler may create a temporary and copy the value of that expression to the temporary and bind that reference to that temporary. 8.5.3 [dcl.init.ref] / 5.

[...] The constructor that would be used to make the copy shall be callable whether or not the copy is actually done.

Note that this behaviour is due to change in the next version of C++. In the new standard a const reference initialized from a class prvalue must be bound directly to the reference object; no temporary is permitted to be created in this case and a copy constructor is not used or required.

Body:
I am passing an unnamed temporary object to a function defined with const ref parameter. The copy ctor of the class is private, and I get a compilation error. I don't understand why a copy constructor is called in this situation.

class A {
public:
  A(int i) {}
private:
  A(const A&) {}
};

void f(const A& a)
{
}

int main()
{
  f(A(1)); // <-- error here: 'A::A(const A&)' is private
}

As expected, when I change the main to:

A a(1);
f(a);

it works.

EDIT: the compiler is gcc 4.1.2


问:
Creating a word document (docx) with OpenXml
Let me start by saying that I have read other similar questions, but the solution (copied below) just doesn't work for me.

I am trying to create a word document (docx) with .net core and OpenXMl (using DocumentFormat.OpenXml 2.7.2 nuget package) .
Looks trivial, but somehow it doesn't work. When I try to open the document, I get the error that file is corrupted, truncated or in incorrect format.

Here is my code (I found it in the numerous tutorials):

```<code>using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.IO;

public Stream GetDocument()
        {
            var stream = new MemoryStream();

            using (WordprocessingDocument doc = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document, true))
            {
                MainDocumentPart mainPart = doc.AddMainDocumentPart();

                new Document(new Body()).Save(mainPart);

                Body body = mainPart.Document.Body;
                body.Append(new Paragraph(
                            new Run(
                                new Text("Hello World!"))));

                mainPart.Document.Save();

            }
            stream.Seek(0, SeekOrigin.Begin);

            return stream;

        }
</code>```

Ad save it like this:

```<code> public static void Test()
        {
            DocxWriter writer = new DocxWriter();

            string filepath = Directory.GetCurrentDirectory() + @"/test.docx";

            var stream = writer.GetDocument();

            using (var fileStream = new FileStream(filepath, FileMode.Create, FileAccess.Write))
            {
                stream.CopyTo(fileStream);
            }

            stream.Dispose();
        }
</code>```

EDIT:
After I extract the docx I can find an underlying xml looking like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
    <w:body>
        <w:p>
            <w:r>
                <w:t>Hello World!</w:t>
            </w:r>
        </w:p>
    </w:body>
</w:document>
</code>```

答:
For anyone else having this issue - it's a bug in open-xml-sdk, reported here:
https://github.com/OfficeDev/Open-XML-SDK/issues/249

Looks like there was a problem in the _rels/.rels hidden file with the paths, putting an extra backslash that caused problems on the mac.

My current fix/hack was to use an existing empty doc as a template.

Body:
Let me start by saying that I have read other similar questions, but the solution (copied below) just doesn't work for me.

I am trying to create a word document (docx) with .net core and OpenXMl (using DocumentFormat.OpenXml 2.7.2 nuget package) .
Looks trivial, but somehow it doesn't work. When I try to open the document, I get the error that file is corrupted, truncated or in incorrect format.

Here is my code (I found it in the numerous tutorials):

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.IO;

public Stream GetDocument()
        {
            var stream = new MemoryStream();

            using (WordprocessingDocument doc = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document, true))
            {
                MainDocumentPart mainPart = doc.AddMainDocumentPart();

                new Document(new Body()).Save(mainPart);

                Body body = mainPart.Document.Body;
                body.Append(new Paragraph(
                            new Run(
                                new Text("Hello World!"))));

                mainPart.Document.Save();

            }
            stream.Seek(0, SeekOrigin.Begin);

            return stream;

        }

Ad save it like this:

 public static void Test()
        {
            DocxWriter writer = new DocxWriter();

            string filepath = Directory.GetCurrentDirectory() + @"/test.docx";

            var stream = writer.GetDocument();

            using (var fileStream = new FileStream(filepath, FileMode.Create, FileAccess.Write))
            {
                stream.CopyTo(fileStream);
            }

            stream.Dispose();
        }

EDIT:
After I extract the docx I can find an underlying xml looking like this:

<?xml version="1.0" encoding="utf-8"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
    <w:body>
        <w:p>
            <w:r>
                <w:t>Hello World!</w:t>
            </w:r>
        </w:p>
    </w:body>
</w:document>


问:
How to add my own icon to ons-tab icon property
I want to add my own icon to the ons-tab icon property, the onsen page says that i need to create my own css with background img, i have tried that, but didnt work, here is what i have

```<code>     .home-icon{
     font-size: 40px;
     height: 1em;
     background-image: url('assets/icon-start-color.png')
     center/contain no-repeat;
     }
</code>```

and in my html file this is how i call this new "icon

```<code><ons-tabbar swipeable position="auto">
  <ons-tab page="inicio.html" label="Inicio" icon="home-icon" active>

  </ons-tab>
</ons-tabbar>
</code>```

but its not working, any idea in how to add my icon?

答:
assuming you have verified your icon works outside of tabbar, what could be happening here is the onsen autoprefix for icons.

Onsen auto-prefixes any icon that doesn't match 'md-', 'fa-' or 'ion-' with 'fa-', so you could check if this is the problem by using ons.disableIconAutoPrefix() as described in the documentation here:
https://onsen.io/v2/guide/faq.html#how-can-i-use-custom-icon-packs

If this isn't the problem, please update the question showing the import code for the icon.

Body:
I want to add my own icon to the ons-tab icon property, the onsen page says that i need to create my own css with background img, i have tried that, but didnt work, here is what i have

     .home-icon{
     font-size: 40px;
     height: 1em;
     background-image: url('assets/icon-start-color.png')
     center/contain no-repeat;
     }

and in my html file this is how i call this new "icon

<ons-tabbar swipeable position="auto">
  <ons-tab page="inicio.html" label="Inicio" icon="home-icon" active>

  </ons-tab>
</ons-tabbar>

but its not working, any idea in how to add my icon?


问:
Canvas update in tkinter
I am new to tkinter and writing a simple skeleton program that draws five lines on a canvas. I want the canvas to be updated after each new line. I am almost there(!), but the canvas does not update until all lines have been computed. All suggestions on how to fix my code would be much appreciated. Thanks!</p>

```<code>from tkinter import *
from time import sleep

class app():
    def __init__(self):
        self.root = Tk()
        self.canvas = Canvas(self.root, width=300, height=300)
        self.canvas.pack()

        self.go()
        self.root.mainloop()

    def go(self):
        for i in range(5):
            self.drawLine(i)
            sleep(1) # simulate computation of next value

    def drawLine(self, n):
        self.canvas.create_line(0, 0, 50, n * 50 + 10)
        # now I would like canvas to be updated with the new line added

app()
</code>```

答:
sleep is incompatible with tkinter because it block the event loop. Using them together will quite often cause your tkinter window to freeze. Sleeping for five seconds may or may not cause this on your computer, but still, it's very unreliable. If you later want to display 15 lines instead of just 5, your program is almost guaranteed to stop working.

The correct solution here would be to use the after method of your root object. after executes the specified function within a certain amount of time. Here is a working example of your code:

```<code>from tkinter import *

class app():
    def __init__(self):
        self.root = Tk()
        self.canvas = Canvas(self.root, width=300, height=300)
        self.canvas.pack()

        self.line_counter = 0
        self.draw_next_line()
        self.root.mainloop()

    def draw_next_line(self):
        self.canvas.create_line(0, 0, 50, self.line_counter * 50 + 10)
        self.line_counter += 1
        if self.line_counter != 5:
            # call this function again after 1000 milliseconds
            self.root.after(1000, self.draw_next_line)

app()
</code>```

Title: Canvas update in tkinter

Body:
I am new to tkinter and writing a simple skeleton program that draws five lines on a canvas. I want the canvas to be updated after each new line. I am almost there(!), but the canvas does not update until all lines have been computed. All suggestions on how to fix my code would be much appreciated. Thanks!

from tkinter import *
from time import sleep

class app():
    def __init__(self):
        self.root = Tk()
        self.canvas = Canvas(self.root, width=300, height=300)
        self.canvas.pack()

        self.go()
        self.root.mainloop()

    def go(self):
        for i in range(5):
            self.drawLine(i)
            sleep(1) # simulate computation of next value

    def drawLine(self, n):
        self.canvas.create_line(0, 0, 50, n * 50 + 10)
        # now I would like canvas to be updated with the new line added

app()

Body:
sleep is incompatible with tkinter because it block the event loop. Using them together will quite often cause your tkinter window to freeze. Sleeping for five seconds may or may not cause this on your computer, but still, it's very unreliable. If you later want to display 15 lines instead of just 5, your program is almost guaranteed to stop working.

The correct solution here would be to use the after method of your root object. after executes the specified function within a certain amount of time. Here is a working example of your code:

from tkinter import *

class app():
    def __init__(self):
        self.root = Tk()
        self.canvas = Canvas(self.root, width=300, height=300)
        self.canvas.pack()

        self.line_counter = 0
        self.draw_next_line()
        self.root.mainloop()

    def draw_next_line(self):
        self.canvas.create_line(0, 0, 50, self.line_counter * 50 + 10)
        self.line_counter += 1
        if self.line_counter != 5:
            # call this function again after 1000 milliseconds
            self.root.after(1000, self.draw_next_line)

app()