问:
How to make two buttons inline if each of them is in different form?
How can I make the submit buttons in two different forms inline ? The first form must be a block level element but the second one can be inline-block.</p>

```<code><form action="#">
     <div class="form-group">
        <label for="title">Title</label>
        <input type="text" name="title" class="form-control" id="title" placeholder="Enter title">
    </div>

    <div class="form-group">
        <label for="body">Body</label>
        <textarea class="form-control" name="body" id="body" rows="10"></textarea>
    </div>

    <button type="submit" class="btn btn-primary">Update</button>

</form>

<form action="#">
    <button type="submit" class="btn btn-danger">DELETE</button>
</form>
</code>```

答:
Float is a very good choice to use...But we can also use
the display: inline;  Property for form element...Like this..

Suggestion : -

```<code>   form{
       display: inline;
     }
</code>```

This is also the best option... And display inline carries
the gap between the elements...So delete and update
buttons will looking good.

Body:
How can I make the submit buttons in two different forms inline ? The first form must be a block level element but the second one can be inline-block.

<form action="#">

        Title
        <input type="text" name="title" class="form-control" id="title" placeholder="Enter title">

        Body
        <textarea class="form-control" name="body" id="body" rows="10"></textarea>

    <button type="submit" class="btn btn-primary">Update</button>

</form>

<form action="#">
    <button type="submit" class="btn btn-danger">DELETE</button>
</form>

Body:
Float is a very good choice to use...But we can also use
the display: inline;  Property for form element...Like this..

Suggestion : -

   form{
       display: inline;
     }

This is also the best option... And display inline carries
the gap between the elements...So delete and update
buttons will looking good.


来源: stackexchange

问:
IOS Export Compliance Info has Changed
Just before submitting my app, I realized that my export compliance info is incorrect. I used to get this warning where I always selected NO for test flight testing, but the correct answer should have been YES on the first question and on the second one that I am exempt because I only use https encryption.

Now I added <key>ITSAppUsesNonExemptEncryption</key><false/> to Info.plist, but I don't get the warning anymore. Before, I didn't "ALWAYS" get the warning. I think I only got it once in a while? I'm not sure if now I don't get the warning because I already added the nonExceptEncryption info to plist, if I'm supposed to update the encryption info elsewhere or if I should keep uploading builds until I get the warning again.

答: Uploading a new build brings you the dialogue back. Each build "asks" this question.</p>

ContentLicense: CC BY-SA 4.0

Title: IOS Export Compliance Info has Changed


Title: how to draw free hand line for given coordinates using drawcontours?

Body:
On image, i am trying to draw free hand line for given annotation data in json file. Line should be drawn by taking coordinates as a input and return image with free hand line.

import numpy as np
im = np.zeros([800, 1216],np.uint8)

points = [
[405.49313, 141.8587],[444.5172, 135.35468],
[444.5172, 135.35468],[ 509.44876, 128.50587],
[509.44876, 128.50587],[ 541.78784, 127.92772],
[541.78784, 127.92772],[ 561.9265, 129.86807],
[561.9265, 129.86807],[ 580.7606, 130.36917],
[580.7606, 130.36917],[ 605.0242, 127.64725],
[605.0242, 127.64725],[ 623.9638, 125.8712],
[623.9638, 125.8712],[ 638.4798, 122.56262],
[638.4798, 122.56262],[ 652.50616, 119.102554],
[652.50616, 119.102554],[ 666.3739, 116.87822],
[666.3739, 116.87822],[ 679.47644, 116.87822],
[679.47644, 116.87822],[ 695.8207, 116.87822],
[695.8207, 116.87822],[ 703.9951, 116.25368],
[703.9951, 116.25368],[ 713.08514, 114.554535],
[713.08514, 114.554535],[ 719.17285, 112.84549],
[719.17285, 112.84549],[ 724.0949, 110.882904],
[724.0949, 110.882904],[ 729.0887, 109.88368],
[729.0887, 109.88368],[ 736.0799, 105.88681]
]

cv2.drawContours(im, [points], 3, (0,255,0), 3)
cv2.imshow("",im)
cv2.waitKey(0)

I expect image with free hand line!where line is overlay not binding with image.

Body:
You can use polylines

Result:

Code:

import cv2
import numpy as np

# create the background, with 3 color channels
im = np.zeros([800, 1216, 3],np.uint8)

# create a numpy array with coordinates, dtype= np.uint32
points = np.array([
[405.49313, 141.8587],[444.5172, 135.35468],
[444.5172, 135.35468],[ 509.44876, 128.50587],
[509.44876, 128.50587],[ 541.78784, 127.92772],
[541.78784, 127.92772],[ 561.9265, 129.86807],
[561.9265, 129.86807],[ 580.7606, 130.36917],
[580.7606, 130.36917],[ 605.0242, 127.64725],
[605.0242, 127.64725],[ 623.9638, 125.8712],
[623.9638, 125.8712],[ 638.4798, 122.56262],
[638.4798, 122.56262],[ 652.50616, 119.102554],
[652.50616, 119.102554],[ 666.3739, 116.87822],
[666.3739, 116.87822],[ 679.47644, 116.87822],
[679.47644, 116.87822],[ 695.8207, 116.87822],
[695.8207, 116.87822],[ 703.9951, 116.25368],
[703.9951, 116.25368],[ 713.08514, 114.554535],
[713.08514, 114.554535],[ 719.17285, 112.84549],
[719.17285, 112.84549],[ 724.0949, 110.882904],
[724.0949, 110.882904],[ 729.0887, 109.88368],
[729.0887, 109.88368],[ 736.0799, 105.88681]
], np.int32)
# reshape array
points = points.reshape((-1,1,2))
# draw a line between coordinates
im = cv2.polylines(im,[points],True,(0,0,255))
# show image
cv2.imshow("",im)
cv2.waitKey(0)
cv2.destroyAllWindows()


问:
Is there any functions can access single value of smbios with protocol technique?
I am newbie to uefi and trying to access smbios values with protocol technique. I have checked up the UEFI and SMBIOS spec, but found nothing with them.

I know that there is one function called pci.read() which can access one value in the pci area of memory each time when using protocols to deal with pci devices. It seems that there is no alike function to read one value each time to deal with smbios protocols?

What I found in the specs which is similar is GetNext(), but this function only outputs three values of header. I am wonder if there is any way to read single value each time so I can instantly Print() the value? Or put memory values of smbios into an array?

答:
SMBIOS is nothing more to UEFI than a pointer to a configuration table (reachable through the UEFI System Table, and identified by the specified GUID).

There is an EFI_SMBIOS_PROTOCOL, but it is part of the PI (Platform Initialization) specification, not UEFI - so cannot be considered a portable interface. The latest version of the PI specification (currently 1.7) can be downloaded from https://uefi.org/specifications.

Otherwise, grab the pointer from the system table and parse the structure manually. The size of the structure table can be read from the SMBIOS entry point.


问:
How to pass two value from a link to another page using php?
I need to pass two value from a php page to another. I can pass one value but dont know about two.

```<code><a href="boardInsert.php?exam=<?php echo $row['year']; ?>">Delete</a>
</code>```

I need to pass another variable called 'year' with 'exam'.

答:
```<code><a href="boardInsert.php?exam=<?php echo $row['year']; ?>&year=<?php echo $variable;?>">Delete</a>
</code>```

Body:
I need to pass two value from a php page to another. I can pass one value but dont know about two.

<a href="boardInsert.php?exam=<?php echo $row['year']; ?>">Delete

I need to pass another variable called 'year' with 'exam'.


问:
How to authenticate app to respond to webhook events
I seem to be overlooking something quite fundamental regarding authentication when trying to automate an API request in response to receiving a webhook notification, and any help would be appreciated.

I am comfortable creating a custom app to work with the Exact Online API in my browser through oauth2 authorisation code authentication. I have also set up webhooks so that Exact Online sends notifications to a URL which then receives, validates and saves the data, and this takes place without a browser connection or oauth2 authentication. However, I would like to run API queries on receipt of webhook notifications so that they run automatically and I do not know how to obtain the oauth2 authorisation code.

Webhook data is easily received (without validating) as follows:

```<code>http_response_code(200); // Tell Exact I have received the data
$input = file_get_contents("php://input");
</code>```

I can easily capture the input data on a web page which does not have an open oauth2-authenticated channel to Exact Online, and the webhook notification takes place without opening a browser instance. Also, it is easy to open an oauth2-authenticated API link by sending

```<code>$authCodeRequest = "https://start.exactonline.co.uk/api/oauth2/auth?response_type=code&client_id=%-my-client-id-%7D&redirect_uri=my-site-redirect";
header('Location: ' . $authCodeRequest);
die('Request failed');
</code>```

and using a $_GET['code'] to get the authorisation code to use in the request for access token and refresh token.
But how can I run an API query on receipt of a webhook? - I cannot see how to allow for access between the page which is not open on the browser and Exact Online.

I have tried including an authorisation request on the page receiving the webhook:

```<code>$authCodeRequest = "https://start.exactonline.co.uk/api/oauth2/auth?response_type=code&client_id=%-my-client-id-%7D&redirect_uri=my-site-redirect";
header('Location: ' . $authCodeRequest);
die(fwrite('Request failed'));
</code>```

This makes sense, because the page could not magically open in a random browser to request user login.

I also tried making the API page the url for receipt of webhook notifications, and then authenticating the page before running a webhook event. This also did not work, as the webhook notification would be sent to a different instance of the page.

Exact Online does not allow for user credentials authentication - only for implicit and authorisation code authentication - and both of these require login. How do I authenticate to allow the processing of webhooks when I receive a notification? Or, is there some online resource I can look at to understand what it is that I am missing?

答:
You need to go through the OAuth flow once to fetch the tokens. Save the refresh token.
When you get a webhook notification, get new tokens with the previously saved refresh token. Don't forget to save the new refresh token as the old tokens are no longer valid.
Get the data.</p>

Body:
I seem to be overlooking something quite fundamental regarding authentication when trying to automate an API request in response to receiving a webhook notification, and any help would be appreciated.

I am comfortable creating a custom app to work with the Exact Online API in my browser through oauth2 authorisation code authentication. I have also set up webhooks so that Exact Online sends notifications to a URL which then receives, validates and saves the data, and this takes place without a browser connection or oauth2 authentication. However, I would like to run API queries on receipt of webhook notifications so that they run automatically and I do not know how to obtain the oauth2 authorisation code.

Webhook data is easily received (without validating) as follows:

http_response_code(200); // Tell Exact I have received the data
$input = file_get_contents("php://input");

I can easily capture the input data on a web page which does not have an open oauth2-authenticated channel to Exact Online, and the webhook notification takes place without opening a browser instance. Also, it is easy to open an oauth2-authenticated API link by sending

$authCodeRequest = "https://start.exactonline.co.uk/api/oauth2/auth?response_type=code&client_id=%-my-client-id-%7D&redirect_uri=my-site-redirect";
header('Location: ' . $authCodeRequest);
die('Request failed');

and using a $_GET['code'] to get the authorisation code to use in the request for access token and refresh token.
But how can I run an API query on receipt of a webhook? - I cannot see how to allow for access between the page which is not open on the browser and Exact Online.

I have tried including an authorisation request on the page receiving the webhook:

$authCodeRequest = "https://start.exactonline.co.uk/api/oauth2/auth?response_type=code&client_id=%-my-client-id-%7D&redirect_uri=my-site-redirect";
header('Location: ' . $authCodeRequest);
die(fwrite('Request failed'));

This makes sense, because the page could not magically open in a random browser to request user login.

I also tried making the API page the url for receipt of webhook notifications, and then authenticating the page before running a webhook event. This also did not work, as the webhook notification would be sent to a different instance of the page.

Exact Online does not allow for user credentials authentication - only for implicit and authorisation code authentication - and both of these require login. How do I authenticate to allow the processing of webhooks when I receive a notification? Or, is there some online resource I can look at to understand what it is that I am missing?


问:
How do I get a python module's version number through code?
I'm trying to get the version number of a specific few modules that I use. Something that I can store in a variable.</p>

答:
Starting Python 3.8, importlib.metadata can be used as a replacement for pkg_resources to extract the version of third-party packages installed via tools such as pip:

```<code>from importlib.metadata import version
version('wheel')
# '0.33.4'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Starting Python 3.8, importlib.metadata can be used as a replacement for pkg_resources to extract the version of third-party packages installed via tools such as pip:

from importlib.metadata import version
version('wheel')
# '0.33.4'


问:
I get Promise { <pending> } as returned value and also calling in async scope gives me undefined immediately
Im trying to return a value from a Promise in async-await form and use it in another function in another file, but I do have problem because my Promise doesnt return any value.
When im trying to console.log('website') it returns me undefined immediately (it's like the value is not being fetched at all from API services). I dont know what im doing wrong, I really love to learn about Promises and Async-Await but each time im trying to work with them im getting more confused.

```<code>const dns = require('dns')
const iplocation = require("iplocation").default;
const emojiFlags = require('emoji-flags');

const getServerIPAddress = async (server) => {
    return new Promise((resolve, reject) => {
        dns.lookup(server, (err, address) => {
            if (err) throw reject(err);
            resolve(address);
        });
    });
};

const getServerLocation = async (server) => {
    const ip = await getServerIPAddress(server)

    iplocation(ip).then((res) => {
        const country = emojiFlags.countryCode(res.countryCode)
        const result = `Location: ${country.emoji} ${country.name}`
        return result
    })
    .catch(err => {
        return `Location: Unknown`
    });
}

(async function() {
    console.log(await getServerLocation('www.google.com'))
})()

module.exports = {
    getServerLocation
}
</code>```

It is really important for me to get result from this function first, then use its value in another function. I wish you could give me tips on how to do tasks asynchronously.

答:
You're clearly using async so it's not apparent why you're using then as well. If you use then then you must return the promise as well in order to preserve the promise chain:

```<code>const getServerLocation = async (server) => {
    const ip = await getServerIPAddress(server)

    return iplocation(ip).then((res) => {
        const country = emojiFlags.countryCode(res.countryCode)
        const result = `Location: ${country.emoji} ${country.name}`
        return result
    })
    .catch(err => {
        return `Location: Unknown`
    });
}
</code>```

Otherwise just async this:

```<code>const getServerLocation = async (server) => {
    const ip = await getServerIPAddress(server)

    let res = await iplocation(ip);

    const country = emojiFlags.countryCode(res.countryCode)
    const result = `Location: ${country.emoji} ${country.name}`
    return result
}
</code>```

Body:
Im trying to return a value from a Promise in async-await form and use it in another function in another file, but I do have problem because my Promise doesnt return any value.
When im trying to console.log('website') it returns me undefined immediately (it's like the value is not being fetched at all from API services). I dont know what im doing wrong, I really love to learn about Promises and Async-Await but each time im trying to work with them im getting more confused.

const dns = require('dns')
const iplocation = require("iplocation").default;
const emojiFlags = require('emoji-flags');

const getServerIPAddress = async (server) => {
    return new Promise((resolve, reject) => {
        dns.lookup(server, (err, address) => {
            if (err) throw reject(err);
            resolve(address);
        });
    });
};

const getServerLocation = async (server) => {
    const ip = await getServerIPAddress(server)

    iplocation(ip).then((res) => {
        const country = emojiFlags.countryCode(res.countryCode)
        const result = `Location: ${country.emoji} ${country.name}`
        return result
    })
    .catch(err => {
        return `Location: Unknown`
    });
}

(async function() {
    console.log(await getServerLocation('www.google.com'))
})()

module.exports = {
    getServerLocation
}

It is really important for me to get result from this function first, then use its value in another function. I wish you could give me tips on how to do tasks asynchronously.

Body:
You're clearly using async so it's not apparent why you're using then as well. If you use then then you must return the promise as well in order to preserve the promise chain:

const getServerLocation = async (server) => {
    const ip = await getServerIPAddress(server)

    return iplocation(ip).then((res) => {
        const country = emojiFlags.countryCode(res.countryCode)
        const result = `Location: ${country.emoji} ${country.name}`
        return result
    })
    .catch(err => {
        return `Location: Unknown`
    });
}

Otherwise just async this:

const getServerLocation = async (server) => {
    const ip = await getServerIPAddress(server)

    let res = await iplocation(ip);

    const country = emojiFlags.countryCode(res.countryCode)
    const result = `Location: ${country.emoji} ${country.name}`
    return result
}


问:
How to do a group by on a count in powerbi
If I have a table called Data with the following rows:

```<code>UserID  action
1       went shopping
1       went shopping
2       cut grass
3       work
3       work
</code>```

I'm simply trying to create a bar chart that tells me how many actions each user took. When I select the bar chart and select the table's UserID column its counting basically the total row count and not the occurrences.

I'm looking for something like

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

What am I doing wrong here?

答:
You need to add UserId to the axis too:

You will get:

However, I will strongly recommend you to learn DAX language, and instead of dropping UserID into a value area directly, write a measure and then use it. For example, create a measure:

```<code>User Action Count = COUNTROWS(Data)
</code>```

and drop it into the values area.

More generally, read a good book on Power BI before jumping into it - it's not as simple as it seems.

Body:
If I have a table called Data with the following rows:

UserID  action
1       went shopping
1       went shopping
2       cut grass
3       work
3       work

I'm simply trying to create a bar chart that tells me how many actions each user took. When I select the bar chart and select the table's UserID column its counting basically the total row count and not the occurrences.

I'm looking for something like

1  2
2  1
3  2

What am I doing wrong here?

Body:
You need to add UserId to the axis too:

You will get:

However, I will strongly recommend you to learn DAX language, and instead of dropping UserID into a value area directly, write a measure and then use it. For example, create a measure:

User Action Count = COUNTROWS(Data)

and drop it into the values area.

More generally, read a good book on Power BI before jumping into it - it's not as simple as it seems.


问:
firestore using transaction twice in same function
I`m curious if there is no disadvantage when I use transaction method inside transaction method on Android.

like this

```<code>db.runTransaction(new Transaction.Function<Double>() {
@Override
public Double apply(Transaction transaction) throws
FirebaseFirestoreException {
    DocumentSnapshot snapshot = transaction.get(sfDocRef);
    double newPopulation = snapshot.getDouble("population") + 1;
    if (newPopulation <= 1000000) {

    db.runTransaction(new Transaction.Function<Double>() {
             ....
    }

    } else {
        throw new FirebaseFirestoreException("Population too high",
                FirebaseFirestoreException.Code.ABORTED);
    }
}
</code>```

答: I would strongly advise against this.  Transactions can be retried if there is a collision with another client also performing a transaction with any of the same documents.  You should expect that the transaction body could run more than once.  This means your inner transaction could be performed more than once, which is almost certainly not going to have the effect you want.  There could be other side effects that are unwanted.  For example, what do you think will happen if the inner transaction is trying transact with any of the same documents as the outer transaction?</p>

Body:
I`m curious if there is no disadvantage when I use transaction method inside transaction method on Android.

like this

db.runTransaction(new Transaction.Function<Double>() {
@Override
public Double apply(Transaction transaction) throws
FirebaseFirestoreException {
    DocumentSnapshot snapshot = transaction.get(sfDocRef);
    double newPopulation = snapshot.getDouble("population") + 1;
    if (newPopulation <= 1000000) {

    db.runTransaction(new Transaction.Function<Double>() {
             ....
    }

    } else {
        throw new FirebaseFirestoreException("Population too high",
                FirebaseFirestoreException.Code.ABORTED);
    }
}


问:
ruler control error: Uncaught SyntaxError: Unexpected identifier
I'm having this issue even though I've done what mapbox asks to be done, but maybe I've missed something.

This is the link with the usage: https://bravecow.github.io/mapbox-gl-controls/   (I'm only trying to add the ruler control)

I'm trying to add a ruler to mapbox-gl, in the usage of mapbox says that I have to do:

```<code>npm install mapbox-gl-controls
</code>```

and add

<link href="mapbox-gl-controls/theme.css" rel="stylesheet">

to the code, which I already did and added it to the main folder, I search more about the import and in some cases I need to add {} to the function that is going to be imported but it seems that there is something else.

```<code>import RulerControl from 'mapbox-gl-controls/lib/ruler';

map.addControl(new RulerControl(), 'top-right');

// events

map.on('ruler.on', () => console.log('ruler: on'));

map.on('ruler.off', () => console.log('ruler: off'));
</code>```

the error message I'm getting is

"Uncaught SyntaxError: Unexpected identifier"

答:
The error is due to the reason that you are not using {} in your import statement.

Try to change your import like this:

```<code>import { RulerControl } from 'mapbox-gl-controls/lib/ruler';
</code>```

Hope it helps

You can find the docs for import here

Body:
I'm having this issue even though I've done what mapbox asks to be done, but maybe I've missed something.

This is the link with the usage: https://bravecow.github.io/mapbox-gl-controls/   (I'm only trying to add the ruler control)

I'm trying to add a ruler to mapbox-gl, in the usage of mapbox says that I have to do:

npm install mapbox-gl-controls

and add

<link href="mapbox-gl-controls/theme.css" rel="stylesheet">

to the code, which I already did and added it to the main folder, I search more about the import and in some cases I need to add {} to the function that is going to be imported but it seems that there is something else.

import RulerControl from 'mapbox-gl-controls/lib/ruler';

map.addControl(new RulerControl(), 'top-right');

// events

map.on('ruler.on', () => console.log('ruler: on'));

map.on('ruler.off', () => console.log('ruler: off'));

the error message I'm getting is

"Uncaught SyntaxError: Unexpected identifier"

Body:
The error is due to the reason that you are not using {} in your import statement.

Try to change your import like this:

import { RulerControl } from 'mapbox-gl-controls/lib/ruler';

Hope it helps

You can find the docs for import here


问:
After choosing K-components in PCA how do we find out which components(names of the columns) have algorithm selected?
I am new to Data Science and I need some help to understand PCA.I know that each of columns constitute one axis,but when PCA is done and components are reduced to some k value,How to know which all columns got selected?</p>

答:
In PCA you compute the eigenvectors and eigenvalues of the covariance matrix to identify the principal components.

Principal components are new variables that are constructed as linear combinations or mixtures of the initial variables. These combinations are done in such a way that the new variables (i.e., principal components) are uncorrelated and most of the information within the initial variables is squeezed or compressed into the first components. So, the idea is 10-dimensional data gives you 10 principal components, but PCA tries to put maximum possible information in the first component, then maximum remaining information in the second and so on.

Geometrically speaking, principal components represent the directions of the data that explain a maximal amount of variance, that is to say, the lines that capture most information of the data. s there are as many principal components as there are variables in the data, principal components are constructed in such a manner that the first principal component accounts for the largest possible variance in the data set.

According to my experience, if the percentage of cumulative sum of Eigen values can over 80% or 90%, the transformed vectors will be enough to represent the old vectors.

To explain clearly lets use  @Nicholas M's code.

```<code>import numpy as np
from sklearn.decomposition import PCA
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
pca = PCA(n_components=1)
pca.fit(X)
</code>```

You must increase the n_components to get %90 variance.

Input:

```<code>pca.explained_variance_ratio_
</code>```

Output:

```<code>array([0.99244289])
</code>```

On this example just 1 component is enough.

I hope its all clear to understand.

Resources:

https://towardsdatascience.com/pca-using-python-scikit-learn-e653f8989e60
https://towardsdatascience.com/a-step-by-step-explanation-of-principal-component-analysis-b836fb9c97e2

Body:
In PCA you compute the eigenvectors and eigenvalues of the covariance matrix to identify the principal components.

Principal components are new variables that are constructed as linear combinations or mixtures of the initial variables. These combinations are done in such a way that the new variables (i.e., principal components) are uncorrelated and most of the information within the initial variables is squeezed or compressed into the first components. So, the idea is 10-dimensional data gives you 10 principal components, but PCA tries to put maximum possible information in the first component, then maximum remaining information in the second and so on.

Geometrically speaking, principal components represent the directions of the data that explain a maximal amount of variance, that is to say, the lines that capture most information of the data. s there are as many principal components as there are variables in the data, principal components are constructed in such a manner that the first principal component accounts for the largest possible variance in the data set.

According to my experience, if the percentage of cumulative sum of Eigen values can over 80% or 90%, the transformed vectors will be enough to represent the old vectors.

To explain clearly lets use  @Nicholas M's code.

import numpy as np
from sklearn.decomposition import PCA
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
pca = PCA(n_components=1)
pca.fit(X)

You must increase the n_components to get %90 variance.

Input:

pca.explained_variance_ratio_

Output:

array([0.99244289])

On this example just 1 component is enough.

I hope its all clear to understand.

Resources:

https://towardsdatascience.com/pca-using-python-scikit-learn-e653f8989e60
https://towardsdatascience.com/a-step-by-step-explanation-of-principal-component-analysis-b836fb9c97e2


问:
How to Convert Tuple to Dictionary?
i'm using Python 2.5 and Win XP. i have a tuple as below:

```<code>>>> a
(None, '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')
>>> a[1]
'{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}'
>>>
</code>```

i want to convert tuple a[1] to dictionary because i want to use the key and value. pls help to advise. tq

答:
If you trust the source of a[1] you can use eval:

```<code>dictionary = eval(a[1])
</code>```

Otherwise you can use json (or simplejson in Python 2.5: see here) :

```<code>import json
dictionay = json.loads(a[1])
</code>```

Note: it mostly depends on how you got the string: if it comes from a repr and cannot be hacked, eval may be good.
If it came from json.dumps (which would result in a different string), you should use json.loads.

Title: How to Convert Tuple to Dictionary?

Body:
i'm using Python 2.5 and Win XP. i have a tuple as below:

>>> a
(None, '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')
>>> a[1]
'{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}'
>>>

i want to convert tuple a[1] to dictionary because i want to use the key and value. pls help to advise. tq

Body:
If you trust the source of a[1] you can use eval:

dictionary = eval(a[1])

Otherwise you can use json (or simplejson in Python 2.5: see here) :

import json
dictionay = json.loads(a[1])

Note: it mostly depends on how you got the string: if it comes from a repr and cannot be hacked, eval may be good.
If it came from json.dumps (which would result in a different string), you should use json.loads.


问:
Limit of Freemium projects reached, but only 1 active project
I created an Here Freemium account a long time ago.
I'm using geocoding and map services.

I created some projects in the past and removed them a few months ago.

Today, I want to create new projects but I can't because :
"You've reached the limit of Freemium projects for this account.
Please visit your project page to see your existing projects.
Contact us if you need another project."

But We only have 1 active project on our account..
Here account page.

Cannot we be able to create 5 freemium project ?
We tried to contact the support but the support told us to find the answer here... Anyone can give us a clue ? :)

Thank you.

答:
Please note that you can have one Freemium plan per account

Source: email from HERE Developer.

It seems that the HERE Developer website does not cover this question, however the limit of one Freemium plan is implied in the answer of "How do I reactivate a cancelled plan?":

You may reactivate a cancelled Freemium as long as there is no other active Freemium or Pro plan on this account.


问:
How can I rerun a scrapy request object in Python?
I am using Scrapy, and in the response_is_ban function, I have two objects, a {Request} object, and a {Response} object.

```<code>from scrapy.http import Request
</code>```

For some reason, the Scrapy Request is returning different results than a standard Curl.

Is there a way I can rerun the {Request} object?

Something like:

```<code>response = request.get_again()
</code>```

The goal is to figure out exactly what is different between my Curl function and the Scrapy request object, and why they would be returning different results. Any suggestions would be welcomed.

Edit: Another question I have, where in the code does Scrapy actually execture the request? Is there a request.get() function somewhere I could put a debug point on?

答: For debugging, you could use fetch from a scrapy.shell session: https://docs.scrapy.org/en/latest/topics/shell.html#invoking-the-shell-from-spiders-to-inspect-responses

Body:
I am using Scrapy, and in the response_is_ban function, I have two objects, a {Request} object, and a {Response} object.

from scrapy.http import Request

For some reason, the Scrapy Request is returning different results than a standard Curl.

Is there a way I can rerun the {Request} object?

Something like:

response = request.get_again()

The goal is to figure out exactly what is different between my Curl function and the Scrapy request object, and why they would be returning different results. Any suggestions would be welcomed.

Edit: Another question I have, where in the code does Scrapy actually execture the request? Is there a request.get() function somewhere I could put a debug point on?


问:
How to give different divs a different height in the same line
I have 3 images with text next to it (Social media). And I want the text have a different padding or margin so it is in the center of the image. But when I use one of these, the images are going higher as well. I think this is because they all have display: inline-block;.

This is the html code;

```<code>    <footer>
        <div id="socialIcon"><img src="images/media/telefoon.png" width="30"></div>
        <div id="socialText">06-123456</div>
        <div id="socialIcon"><img src="images/media/mail.png" width="30"></div>
        <div id="socialText">example@gmail.com</div>
        <div id="socialIcon"><a class="socialIcon" href="https://www.instagram.com/example/"><img src="images/media/instagram.png" width="30px"</a></div>
        <div id="socialText"><a class="socialText" href="https://www.instagram.com/example/">@example</a></div>
    </footer>
</code>```

This is the css code:

```<code>footer {
    background: #222222;
    position: fixed;
    bottom: 0;
    width: 100%;
    color: white;
    font-family: proxima-nova, sans-serif;
    text-align: center;
    font-size: 20px;
}
#socialText{
    display: inline-block;
    margin-bottom: 10px;

}
#socialIcon{
    display: inline-block;
    margin-left: 10px;
    margin-right: 3px;
    margin-bottom: 0px;
    margin-top: 0px;
    padding-bottom: 0px;
    height: 30px;
}
</code>```

But right now not only the socialText goes 10px up, the socialIcon as well.

答:
Flexbox is your best friend for this kind of layout. Just give the footer wrapper display:flex and these two other additional rules to center the items in the footer vertically and horizontally:

```<code>footer {
  display: flex;
  align-items: center; // centers items vertically
  justify-content: center; // centers items horizontally
}
</code>```

Now you can remove all the padding & margin rules you were using to bump items up and down. Notice I added padding to the footer as well to give consistent space around the edges.

Final bit of advice, it is invalid to use id property with the same value on more than one item. The moment you want to reuse CSS, reach for classes instead. Cheers!

footer {
  display: flex;
  align-items: center;
  justify-content: center;
    background: #222222;
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 10px;
    color: white;
    font-family: proxima-nova, sans-serif;
    font-size: 20px;
}
.socialIcon {
    margin: 0 10px;
    height: 30px;
    width: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
  <div class="socialIcon"><img src="https://picsum.photos/30" width="30"></div>
  <div class="socialText">06-123456</div>
  <div class="socialIcon"><img src="https://picsum.photos/31" width="30"></div>
  <div class="socialText">example@gmail.com</div>
  <div class="socialIcon"><img src="https://picsum.photos/32" width="30px" /></div>
  <div class="socialText">@example</div>
</footer></code>```

Body:
I have 3 images with text next to it (Social media). And I want the text have a different padding or margin so it is in the center of the image. But when I use one of these, the images are going higher as well. I think this is because they all have display: inline-block;.

This is the html code;

06-123456

example@gmail.com

<img src="images/media/instagram.png" width="30px"

@example

This is the css code:

footer {
    background: #222222;
    position: fixed;
    bottom: 0;
    width: 100%;
    color: white;
    font-family: proxima-nova, sans-serif;
    text-align: center;
    font-size: 20px;
}
#socialText{
    display: inline-block;
    margin-bottom: 10px;

}
#socialIcon{
    display: inline-block;
    margin-left: 10px;
    margin-right: 3px;
    margin-bottom: 0px;
    margin-top: 0px;
    padding-bottom: 0px;
    height: 30px;
}

But right now not only the socialText goes 10px up, the socialIcon as well.

Body:
Flexbox is your best friend for this kind of layout. Just give the footer wrapper display:flex and these two other additional rules to center the items in the footer vertically and horizontally:

footer {
  display: flex;
  align-items: center; // centers items vertically
  justify-content: center; // centers items horizontally
}

Now you can remove all the padding & margin rules you were using to bump items up and down. Notice I added padding to the footer as well to give consistent space around the edges.

Final bit of advice, it is invalid to use id property with the same value on more than one item. The moment you want to reuse CSS, reach for classes instead. Cheers!

footer {
  display: flex;
  align-items: center;
  justify-content: center;
    background: #222222;
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 10px;
    color: white;
    font-family: proxima-nova, sans-serif;
    font-size: 20px;
}
.socialIcon {
    margin: 0 10px;
    height: 30px;
    width: auto;
}

<footer>
  <div class="socialIcon"><img src="https://picsum.photos/30" width="30"></div>
  <div class="socialText">06-123456</div>
  <div class="socialIcon"><img src="https://picsum.photos/31" width="30"></div>
  <div class="socialText">example@gmail.com</div>
  <div class="socialIcon"><a class="socialIcon" href="https://www.instagram.com/example/"><img src="https://picsum.photos/32" width="30px" /></a></div>
  <div class="socialText"><a class="socialText" href="https://www.instagram.com/example/">@example</a></div>
</footer>


问:
How to write a test case for password and Confirm password PasswordMatching validation Directive
I am working on writing Unit test cases for the Password Mismatch Validator. How can I write a test spec for below method?

I tried searching the internet but was not able to set the value for the form control

export class PasswordMatchingValidation {

  constructor() {}

  static MatchPassword(AC: FormControl) {

    const password = AC.get('password').value; // to get value in input tag
    const confirmPassword = AC.get('confirmPassword').value; // to get value in

    if (password !== confirmPassword) {

      AC.get('confirmPassword').setErrors({
        MatchPassword: true
      });

    } else {
      return null;
    }
  }

  /**
   * validate if the passwords are matching
   * @param ctrl Takes Form Control
   */
  validate(ctrl: FormControl) {
    return PasswordMatchingValidation.MatchPassword(ctrl);
  }
}
```

答:
Well, first you should initialize a new FormControl with some dummy data and the call the PasswordMatchingValidation.MatchPassword with the control you previously made as an argument and assert the outcome.

```<code>const control = new FormControl({password: 'whatever'});
describe('PasswordMatchingValidation', () => {
  it('should validate two identical passwords', () => {
    const validation = PasswordMatchingValidation.MatchPassword(control);
    expect(validation).toEqual({ MatchPassword: true });
  });
});
</code>```

Make your FormControl like it's supposed to be and of course assert the opposite case as well

Body:
Well, first you should initialize a new FormControl with some dummy data and the call the PasswordMatchingValidation.MatchPassword with the control you previously made as an argument and assert the outcome.

const control = new FormControl({password: 'whatever'});
describe('PasswordMatchingValidation', () => {
  it('should validate two identical passwords', () => {
    const validation = PasswordMatchingValidation.MatchPassword(control);
    expect(validation).toEqual({ MatchPassword: true });
  });
});

Make your FormControl like it's supposed to be and of course assert the opposite case as well


问:
Inline switch statement java?
Is there a way to implement an inline switch statement in java?

Right now, i'm using the following:

    private static String BaseURL = (lifeCycle == LifeCycle.Production)
        ? prodUrl
        : ( (lifeCycle == LifeCycle.Development)
            ? devUrl
            : ( (lifeCycle == LifeCycle.LocalDevelopment)
                  ? localDevUrl
                  : null
            )
        );
```

<p>I would much prefer it if I could do something like:</p>

<pre class="lang-java prettyprint-override"><code>    private static String BaseURL = switch (lifeCycle) {
        case Production: return prodUrl;
        case Development: return devUrl;
        case LocalDevelopment: return localDevUrl;
    }
</code>```

I do know you could achieve this by moving the BaseURL variable into a function GetBaseURL where the switch occurs (see below), however I'm more so just curious if this feature even exists in Java.

static String GetBaseURL() {
    switch(lifeCycle) {
        case Production: return prodUrl;
        case Development: return devUrl;
        case LocalDevelopment: return localDevUrl;
    }

    return null;
}
```

<hr>

<p>I'm transitioning from Swift, and in Swift I know you could do this:</p>

<pre class="lang-swift prettyprint-override"><code>private static var BaseURL:String {
    switch (API.LifeCycle) {
        case .Production:
            return prodUrl
        case .Development:
            return devUrl
        case .LocalDevelopment:
            return localDevUrl
    }
}
</code>```

答:
Assuming LifeCycle is an enum, then you're in luck, as switch expressions were introduced as a preview feature in JDK 12. By using them, your code would look like the following:

```<code>LifeCycle lifeCycle = ...;

String baseURL = switch (lifeCycle) {
    case Production -> prodUrl;
    case Development -> devUrl;
    case LocalDevelopment -> localDevUrl;
};
</code>```

If the LifeCycle enum contains more than those three values, then you'll need to add a default case; otherwise, it will be a compile-time error.

Title: Inline switch statement java?

Body:
Is there a way to implement an inline switch statement in java?

Right now, i'm using the following:

    private static String BaseURL = (lifeCycle == LifeCycle.Production)
        ? prodUrl
        : ( (lifeCycle == LifeCycle.Development)
            ? devUrl
            : ( (lifeCycle == LifeCycle.LocalDevelopment)
                  ? localDevUrl
                  : null
            )
        );

I would much prefer it if I could do something like:

    private static String BaseURL = switch (lifeCycle) {
        case Production: return prodUrl;
        case Development: return devUrl;
        case LocalDevelopment: return localDevUrl;
    }

I do know you could achieve this by moving the BaseURL variable into a function GetBaseURL where the switch occurs (see below), however I'm more so just curious if this feature even exists in Java.

static String GetBaseURL() {
    switch(lifeCycle) {
        case Production: return prodUrl;
        case Development: return devUrl;
        case LocalDevelopment: return localDevUrl;
    }

    return null;
}

I'm transitioning from Swift, and in Swift I know you could do this:

private static var BaseURL:String {
    switch (API.LifeCycle) {
        case .Production:
            return prodUrl
        case .Development:
            return devUrl
        case .LocalDevelopment:
            return localDevUrl
    }
}

Body:
Assuming LifeCycle is an enum, then you're in luck, as switch expressions were introduced as a preview feature in JDK 12. By using them, your code would look like the following:

LifeCycle lifeCycle = ...;

String baseURL = switch (lifeCycle) {
    case Production -> prodUrl;
    case Development -> devUrl;
    case LocalDevelopment -> localDevUrl;
};

If the LifeCycle enum contains more than those three values, then you'll need to add a default case; otherwise, it will be a compile-time error.


答:
First split the string on comma.
Iterate over all parts.
Split each part on colon.
Convert the strings into integers.
Add the second integer as value for the first integer as key.</p>

Title: How to Convert Tuple to Dictionary?


问:
Array as new and non new
I would like to understand if the a diffrent between 2 types of writing arrays.

I tried to check here but did not find any similar question.

What are the differences between:

```<code>String[] arr = new String[]{"ab","axc"};
</code>```

AND

```<code>String[] arr2 ={"ab","axc"};
</code>```

答:
There's no difference. String[] arr2 = { "ab", "axc" } is just syntactic sugar.

According to the Java Language Specification § 10.6:

An array initializer may be specified in a field declaration (§8.3, §9.3) or local variable declaration (§14.4), or as part of an array creation expression (§15.10.1), to create an array and provide some initial values.

Omitting new String[] is only possible on field declaration or local variable declaration:

Each variable initializer must be assignment-compatible (§5.2) with the array's component type, or a compile-time error occurs.

Examples:

```<code>// This works:
String[] array = { "abc", "def" };

// This does not:
String[] array2;
array2 = { "abc", "def" };
</code>```

Title: Array as new and non new

Body:
I would like to understand if the a diffrent between 2 types of writing arrays.

I tried to check here but did not find any similar question.

What are the differences between:

String[] arr = new String[]{"ab","axc"};

AND

String[] arr2 ={"ab","axc"};

Body:
There's no difference. String[] arr2 = { "ab", "axc" } is just syntactic sugar.

According to the Java Language Specification § 10.6:

An array initializer may be specified in a field declaration (§8.3, §9.3) or local variable declaration (§14.4), or as part of an array creation expression (§15.10.1), to create an array and provide some initial values.

Omitting new String[] is only possible on field declaration or local variable declaration:

Each variable initializer must be assignment-compatible (§5.2) with the array's component type, or a compile-time error occurs.

Examples:

// This works:
String[] array = { "abc", "def" };

// This does not:
String[] array2;
array2 = { "abc", "def" };


问:
put data in List thenn insert it its values into database
I have to store questions in session afterward in List then insert them all into database by one click

my servlet

```<code>Question question = new Question(title, content, idExam);
        request.getSession().setAttribute("question", question);
        int quizKey = ExamDAO.add_question(question);
        ArrayList<Question> ques = new ArrayList<Question>();
        ques.add(question);
</code>```

my dao

```<code>cnx = Connect.getConnection();
        String req = "insert into question(title, content, id_examen) values(?,?,?)";
        PreparedStatement st = cnx.prepareStatement(req, Statement.RETURN_GENERATED_KEYS);
        st.setString(1, question.getTitre());
        st.setString(2, question.getContenu());
        st.setInt(3, question.getIdExamen());
        st.executeBatch();

        ResultSet rs = st.getGeneratedKeys();

        if (rs.next()) {

quizKey = rs.getInt(1);
            }
</code>```

how to do that ?

答:
If you have a List<Question> and you wish to insert all in one go then you have to utilize what is called as - batching or batch update. Refer here for more details

You will be iterating your list of questions and setting parameters for each question then adding that statement to batch (by using st.addBatch()) &  then finally call - st.executeBatch().

In your code sample, you are executing a batch but there is only one prepared statement in that batch. You need as many prepared statements as number of questions in the list.

```<code>    String req = "insert into question(title, content, id_examen) values(?,?,?)";
    PreparedStatement st = cnx.prepareStatement(req, Statement.RETURN_GENERATED_KEYS);
    for(Question question : ques){
     st.setString(1, question.getTitre());
        st.setString(2, question.getContenu());
        st.setInt(3, question.getIdExamen());
       st.addBatch();
    }
st.executeBatch();
</code>```

With this approach, you might have issues in collecting generated keys as illustrated in this SO question  so if you really need those ids , you will have to turn off auto commit, execute updates in loop without batching, collected generated ids in a map or list for each insert statement and then finally commit your connection in the end.

Body:
I have to store questions in session afterward in List then insert them all into database by one click

my servlet

Question question = new Question(title, content, idExam);
        request.getSession().setAttribute("question", question);
        int quizKey = ExamDAO.add_question(question);
        ArrayList<Question> ques = new ArrayList<Question>();
        ques.add(question);

my dao

cnx = Connect.getConnection();
        String req = "insert into question(title, content, id_examen) values(?,?,?)";
        PreparedStatement st = cnx.prepareStatement(req, Statement.RETURN_GENERATED_KEYS);
        st.setString(1, question.getTitre());
        st.setString(2, question.getContenu());
        st.setInt(3, question.getIdExamen());
        st.executeBatch();

        ResultSet rs = st.getGeneratedKeys();

        if (rs.next()) {

quizKey = rs.getInt(1);
            }

how to do that ?

Body:
If you have a List<Question> and you wish to insert all in one go then you have to utilize what is called as - batching or batch update. Refer here for more details

You will be iterating your list of questions and setting parameters for each question then adding that statement to batch (by using st.addBatch()) &  then finally call - st.executeBatch().

In your code sample, you are executing a batch but there is only one prepared statement in that batch. You need as many prepared statements as number of questions in the list.

    String req = "insert into question(title, content, id_examen) values(?,?,?)";
    PreparedStatement st = cnx.prepareStatement(req, Statement.RETURN_GENERATED_KEYS);
    for(Question question : ques){
     st.setString(1, question.getTitre());
        st.setString(2, question.getContenu());
        st.setInt(3, question.getIdExamen());
       st.addBatch();
    }
st.executeBatch();

With this approach, you might have issues in collecting generated keys as illustrated in this SO question  so if you really need those ids , you will have to turn off auto commit, execute updates in loop without batching, collected generated ids in a map or list for each insert statement and then finally commit your connection in the end.


答:
```<code>const getServerLocation = async (server) => {
    const ip = await getServerIPAddress(server)

   //you need to return
    return iplocation(ip).then((res) => {
        const country = emojiFlags.countryCode(res.countryCode)
        const result = `Location: ${country.emoji} ${country.name}`
        return result
    })
    .catch(err => {
        return `Location: Unknown`
    });
}
</code>```

Title: I get Promise { <pending> } as returned value and also calling in async scope gives me undefined immediately

Body:
Im trying to return a value from a Promise in async-await form and use it in another function in another file, but I do have problem because my Promise doesnt return any value.
When im trying to console.log('website') it returns me undefined immediately (it's like the value is not being fetched at all from API services). I dont know what im doing wrong, I really love to learn about Promises and Async-Await but each time im trying to work with them im getting more confused.

const dns = require('dns')
const iplocation = require("iplocation").default;
const emojiFlags = require('emoji-flags');

const getServerIPAddress = async (server) => {
    return new Promise((resolve, reject) => {
        dns.lookup(server, (err, address) => {
            if (err) throw reject(err);
            resolve(address);
        });
    });
};

const getServerLocation = async (server) => {
    const ip = await getServerIPAddress(server)

    iplocation(ip).then((res) => {
        const country = emojiFlags.countryCode(res.countryCode)
        const result = `Location: ${country.emoji} ${country.name}`
        return result
    })
    .catch(err => {
        return `Location: Unknown`
    });
}

(async function() {
    console.log(await getServerLocation('www.google.com'))
})()

module.exports = {
    getServerLocation
}

It is really important for me to get result from this function first, then use its value in another function. I wish you could give me tips on how to do tasks asynchronously.


问:
Program not working as well - C
The following code gives me a zero value for 'count' all the time...

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

#define SIZE 128

int main ()

{
    char mychar , string [SIZE];
    int i;
    int count =0 ;

    printf ("Please enter your string: \n\n");
    fgets (string, SIZE, stdin);

    printf ("Please enter char to find: ");
    mychar = getchar();

    for (i=0 ; (string[i] == '\0') ; i++ )
        if ( string[i]  == mychar )
            count++;

    printf ("The char %c appears %d times" ,mychar ,count);

    return 0;
}
</code>```

Thanks !

答:
```<code> for (i=0 ; (string[i] == '\0') ; i++ )
        if ( string[i]  == mychar )
            count++;
</code>```

This means run the loop for as long as string[i] == '\0', but string[i] can't also be mychar (unless mychar is \0) so you never increment count.

I think you meant:

```<code>for (i = 0; string[i] != '\0'; i++)
   if (string[i]  == mychar)
      count++;
</code>```

Title: Program not working as well - C

Body:
The following code gives me a zero value for 'count' all the time...

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 128

int main ()

{
    char mychar , string [SIZE];
    int i;
    int count =0 ;

    printf ("Please enter your string: \n\n");
    fgets (string, SIZE, stdin);

    printf ("Please enter char to find: ");
    mychar = getchar();

    for (i=0 ; (string[i] == '\0') ; i++ )
        if ( string[i]  == mychar )
            count++;

    printf ("The char %c appears %d times" ,mychar ,count);

    return 0;
}

Thanks !

Body:
 for (i=0 ; (string[i] == '\0') ; i++ )
        if ( string[i]  == mychar )
            count++;

This means run the loop for as long as string[i] == '\0', but string[i] can't also be mychar (unless mychar is \0) so you never increment count.

I think you meant:

for (i = 0; string[i] != '\0'; i++)
   if (string[i]  == mychar)
      count++;


问:
Python ctypes and void const pointers
I have an numpy array of uint8, that I would like to pass as a void const pointer to a C++ library through SWIG.

I use this python code:

print(arr.ctypes.data_as(ctypes.c_void_p))
display.GetImageDisplay().SetImage(arr.ctypes.data_as(ctypes.c_void_p),arr.shape[0],arr.shape[1],1,1)
display.GetImageDisplay().Update()
```

<p>To call the SetImage method of the ImageDisplay class, in the mvIMPACT aquire library:</p>

```void SetImage   (   const void *    pData,
        int     width,
        int     height,
        int     bitsPerPixel,
        int     pitch
    )
```

<p>I get the following error:</p>

```c_void_p(193598576)
Traceback (most recent call last):
  File ".\mvIMPACT test.py", line 137, in <module>
    display.GetImageDisplay().SetImage(arr.ctypes.data_as(ctypes.c_void_p),arr.shape[0],arr.shape[1],1,1)
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\mvIMPACT\acquire.py", line 7101, in SetImage
    def SetImage(self, *args): return lib_mvIMPACT_acquire.ImageDisplay_SetImage(self, *args)
TypeError: in method 'ImageDisplay_SetImage', argument 2 of type 'void const *'
```

<p>I think the type of pData is wrong. I checked the SWIG wrapper, and I'm quite sure I'm calling the correct function, and the first type matches</p>

```SWIGINTERN PyObject *_wrap_ImageDisplay_SetImage__SWIG_0(PyObject *SWIGUNUSEDPARM(self), int nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0; mvIMPACT::acquire::display::ImageDisplay *arg1 = (mvIMPACT::acquire::display::ImageDisplay *) 0 ;
  void *arg2 = (void *) 0 ; int arg3 ; int arg4 ; int arg5 ; int arg6 ; void *argp1 = 0 ; int res1 = 0 ; int res2 ; int val3 ;
  int ecode3 = 0 ; int val4 ; int ecode4 = 0 ; int val5 ; int ecode5 = 0 ; int val6 ; int ecode6 = 0 ;
  if ((nobjs < 6) || (nobjs > 6)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_mvIMPACT__acquire__display__ImageDisplay, 0 |  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImageDisplay_SetImage" "', argument " "1"" of type '" "mvIMPACT::acquire::display::ImageDisplay *""'");  }
   arg1 = reinterpret_cast< mvIMPACT::acquire::display::ImageDisplay * >(argp1);
  res2 = SWIG_ConvertPtr(swig_obj[1],SWIG_as_voidptrptr(&arg2), 0, 0); if (!SWIG_IsOK(res2)) {
    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ImageDisplay_SetImage" "', argument " "2"" of type '" "void const *""'");  }
   ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); if (!SWIG_IsOK(ecode3)) {
    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "ImageDisplay_SetImage" "', argument " "3"" of type '" "int""'"); }
    arg3 = static_cast< int >(val3); ecode4 = SWIG_AsVal_int(swig_obj[3], &val4); if (!SWIG_IsOK(ecode4)) {
    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "ImageDisplay_SetImage" "', argument " "4"" of type '" "int""'"); }
    arg4 = static_cast< int >(val4); ecode5 = SWIG_AsVal_int(swig_obj[4], &val5); if (!SWIG_IsOK(ecode5)) {
    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "ImageDisplay_SetImage" "', argument " "5"" of type '" "int""'"); }
    arg5 = static_cast< int >(val5); ecode6 = SWIG_AsVal_int(swig_obj[5], &val6); if (!SWIG_IsOK(ecode6)) {
    SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "ImageDisplay_SetImage" "', argument " "6"" of type '" "int""'"); }
    arg6 = static_cast< int >(val6); { try { { SWIG_PYTHON_THREAD_BEGIN_ALLOW;
        (arg1)->SetImage((void const *)arg2,arg3,arg4,arg5,arg6); SWIG_PYTHON_THREAD_END_ALLOW; }  }
    catch(const mvIMPACT::acquire::ImpactAcquireException &e) { handleImpactAcquireException(e); SWIG_fail; }
    catch(const std::exception &e) { SWIG_SetErrorMsg(PyExc_RuntimeError, e.what()); SWIG_fail; }  catch(...) {
      SWIG_SetErrorMsg(PyExc_RuntimeError, "unknown C++ exception"); SWIG_fail; }  }  resultobj = SWIG_Py_Void();
  return resultobj; fail: return NULL; }
```

Am I running into issues because my pointer is not constant?

Can I make a constant pointer with ctypes?

Do I need to make a copy of my numpy array with another library?
I know that the C++ code is not using the array once I return form that call.

答:
I have made a small example demonstrating why you cannot use ctypes.c_void_p together with a function wrapped with SWIG and provided two alternative solutions.

The example is given for a C library - for C++ you need to find the mangled names for the first part.

test.h

```<code>#pragma once

void SetImage(const void* pData,
              int width,
              int height,
              int hitsPerPixel,
              int pitch);
</code>```

test.c

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

#include <stdio.h>

void SetImage(const void* pData,
              int width,
              int height,
              int hitsPerPixel,
              int pitch) {
  double* _pData = (double*)pData;
  printf("%f\n",_pData[0]);
}
</code>```

To compile

```<code>swig3.0 -python -includeall -Wall test.i
gcc -shared -o _example.so test.c test_wrap.c -Wall -Wextra -fPIC -I/usr/include/python2.7/ -DSWIGRUNTIME=extern
</code>```

In Python, you can do the following

```<code>import ctypes
import example
import numpy as np

arr = np.ones(10,dtype=np.float64)

arg = arr.ctypes.data_as(ctypes.c_void_p)

# Using the C functions
libexample = ctypes.cdll.LoadLibrary("_example.so")

libexample.SetImage(arg, 0,0,0,0)

n = 20
a = example.doubleArray(n)
a[0] = 37.0

# Using the SWIG wrapping
example.SetImage(a,0,0,0,0)
</code>```

Title: Python ctypes and void const pointers

Body:
I have an numpy array of uint8, that I would like to pass as a void const pointer to a C++ library through SWIG.

I use this python code:

print(arr.ctypes.data_as(ctypes.c_void_p))
display.GetImageDisplay().SetImage(arr.ctypes.data_as(ctypes.c_void_p),arr.shape[0],arr.shape[1],1,1)
display.GetImageDisplay().Update()

To call the SetImage method of the ImageDisplay class, in the mvIMPACT aquire library:

void SetImage   (   const void *    pData,
        int     width,
        int     height,
        int     bitsPerPixel,
        int     pitch
    )

I get the following error:

c_void_p(193598576)
Traceback (most recent call last):
  File ".\mvIMPACT test.py", line 137, in <module>
    display.GetImageDisplay().SetImage(arr.ctypes.data_as(ctypes.c_void_p),arr.shape[0],arr.shape[1],1,1)
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\mvIMPACT\acquire.py", line 7101, in SetImage
    def SetImage(self, *args): return lib_mvIMPACT_acquire.ImageDisplay_SetImage(self, *args)
TypeError: in method 'ImageDisplay_SetImage', argument 2 of type 'void const *'

I think the type of pData is wrong. I checked the SWIG wrapper, and I'm quite sure I'm calling the correct function, and the first type matches

SWIGINTERN PyObject *_wrap_ImageDisplay_SetImage__SWIG_0(PyObject *SWIGUNUSEDPARM(self), int nobjs, PyObject **swig_obj) {
  PyObject *resultobj = 0; mvIMPACT::acquire::display::ImageDisplay *arg1 = (mvIMPACT::acquire::display::ImageDisplay *) 0 ;
  void *arg2 = (void *) 0 ; int arg3 ; int arg4 ; int arg5 ; int arg6 ; void *argp1 = 0 ; int res1 = 0 ; int res2 ; int val3 ;
  int ecode3 = 0 ; int val4 ; int ecode4 = 0 ; int val5 ; int ecode5 = 0 ; int val6 ; int ecode6 = 0 ;
  if ((nobjs < 6) || (nobjs > 6)) SWIG_fail;
  res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_mvIMPACT__acquire__display__ImageDisplay, 0 |  0 );
  if (!SWIG_IsOK(res1)) {
    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ImageDisplay_SetImage" "', argument " "1"" of type '" "mvIMPACT::acquire::display::ImageDisplay *""'");  }
   arg1 = reinterpret_cast< mvIMPACT::acquire::display::ImageDisplay * >(argp1);
  res2 = SWIG_ConvertPtr(swig_obj[1],SWIG_as_voidptrptr(&arg2), 0, 0); if (!SWIG_IsOK(res2)) {
    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "ImageDisplay_SetImage" "', argument " "2"" of type '" "void const *""'");  }
   ecode3 = SWIG_AsVal_int(swig_obj[2], &val3); if (!SWIG_IsOK(ecode3)) {
    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "ImageDisplay_SetImage" "', argument " "3"" of type '" "int""'"); }
    arg3 = static_cast< int >(val3); ecode4 = SWIG_AsVal_int(swig_obj[3], &val4); if (!SWIG_IsOK(ecode4)) {
    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "ImageDisplay_SetImage" "', argument " "4"" of type '" "int""'"); }
    arg4 = static_cast< int >(val4); ecode5 = SWIG_AsVal_int(swig_obj[4], &val5); if (!SWIG_IsOK(ecode5)) {
    SWIG_exception_fail(SWIG_ArgError(ecode5), "in method '" "ImageDisplay_SetImage" "', argument " "5"" of type '" "int""'"); }
    arg5 = static_cast< int >(val5); ecode6 = SWIG_AsVal_int(swig_obj[5], &val6); if (!SWIG_IsOK(ecode6)) {
    SWIG_exception_fail(SWIG_ArgError(ecode6), "in method '" "ImageDisplay_SetImage" "', argument " "6"" of type '" "int""'"); }
    arg6 = static_cast< int >(val6); { try { { SWIG_PYTHON_THREAD_BEGIN_ALLOW;
        (arg1)->SetImage((void const *)arg2,arg3,arg4,arg5,arg6); SWIG_PYTHON_THREAD_END_ALLOW; }  }
    catch(const mvIMPACT::acquire::ImpactAcquireException &e) { handleImpactAcquireException(e); SWIG_fail; }
    catch(const std::exception &e) { SWIG_SetErrorMsg(PyExc_RuntimeError, e.what()); SWIG_fail; }  catch(...) {
      SWIG_SetErrorMsg(PyExc_RuntimeError, "unknown C++ exception"); SWIG_fail; }  }  resultobj = SWIG_Py_Void();
  return resultobj; fail: return NULL; }

Am I running into issues because my pointer is not constant?

Can I make a constant pointer with ctypes?

Do I need to make a copy of my numpy array with another library?
I know that the C++ code is not using the array once I return form that call.

Body:
I have made a small example demonstrating why you cannot use ctypes.c_void_p together with a function wrapped with SWIG and provided two alternative solutions.

The example is given for a C library - for C++ you need to find the mangled names for the first part.

test.h

#pragma once

void SetImage(const void* pData,
              int width,
              int height,
              int hitsPerPixel,
              int pitch);

test.c

#include "test.h"

#include <stdio.h>

void SetImage(const void* pData,
              int width,
              int height,
              int hitsPerPixel,
              int pitch) {
  double* _pData = (double*)pData;
  printf("%f\n",_pData[0]);
}

To compile

swig3.0 -python -includeall -Wall test.i
gcc -shared -o _example.so test.c test_wrap.c -Wall -Wextra -fPIC -I/usr/include/python2.7/ -DSWIGRUNTIME=extern

In Python, you can do the following

import ctypes
import example
import numpy as np

arr = np.ones(10,dtype=np.float64)

arg = arr.ctypes.data_as(ctypes.c_void_p)

# Using the C functions
libexample = ctypes.cdll.LoadLibrary("_example.so")

libexample.SetImage(arg, 0,0,0,0)

n = 20
a = example.doubleArray(n)
a[0] = 37.0

# Using the SWIG wrapping
example.SetImage(a,0,0,0,0)


问:
PHP scheduling a task on webhosting without SSH/Console
I have a php website that has a script that executes an update for my database with data from an external API. The script itself works perfectly fine but i need to time it so that it executes it every monday at 2:30 AM. I am using a webhosting where SSH is not available neither is any form of command execution such as exec() or passthru(). I've also looked at CRON jobs but i can't use that either because i have no access to a console.

An other option i found was using threads with phthreads. But it seemed that i need an extra libary (PECL) to use it, but again because i can't use any console i can't install that dependency.

So another solution i came up with myself is the idea of stealing a request of the first user that visits the website. I know it's not a beautiful solution that's why i want to ask if there are some other options for me where i can schedule a task. Or is stealing the request the only option here? Or did i make a mistake in my assumptions?

Also a VPS is no option for me.

Sorry for my bad english, it's not my native language.

答:
One way to do it is to let your visitors trigger the update.

The advantage to this is you are not exposing your updating script to the world.

The disadvantage is that your database will not be updated until the visit of your first user after 2:30 am on Mondays, and that first user will have to wait for the database to be updated.

Add this to your script:

```<code>/**
 * Checks if the database's last update was before
 * Monday at 02:30
 *
 * @param \DateTime Time of last update.  Must be converted to DateTime object
 * @return boolean
 */
function databaseIsOutOfDate(DateTime $createDate) {

  // find the last Monday at 2:30 am.
  $monday = (new DateTime())->modify('tomorrow')->modify('previous monday')->format('Y-m-d 02:30:00');
  $lastUpdated = $createDate->format('Y-m-d H:i:s');

  return ($lastUpdated < $monday);
}

$date_time_from_database = '2019-05-27 02:30:00'; // this date value comes from your database
$last_updated = new DateTime($date_time_from_database);

if(databaseIsOutOfDate($last_updated)) {
  print "Updating database, please try again later";
  // trigger your update script
  die; // if you continue, you'll have race condition.
}

print "continue with script";
</code>```

Body:
One way to do it is to let your visitors trigger the update.

The advantage to this is you are not exposing your updating script to the world.

The disadvantage is that your database will not be updated until the visit of your first user after 2:30 am on Mondays, and that first user will have to wait for the database to be updated.

Add this to your script:

/**
 * Checks if the database's last update was before
 * Monday at 02:30
 *
 * @param \DateTime Time of last update.  Must be converted to DateTime object
 * @return boolean
 */
function databaseIsOutOfDate(DateTime $createDate) {

  // find the last Monday at 2:30 am.
  $monday = (new DateTime())->modify('tomorrow')->modify('previous monday')->format('Y-m-d 02:30:00');
  $lastUpdated = $createDate->format('Y-m-d H:i:s');

  return ($lastUpdated < $monday);
}

$date_time_from_database = '2019-05-27 02:30:00'; // this date value comes from your database
$last_updated = new DateTime($date_time_from_database);

if(databaseIsOutOfDate($last_updated)) {
  print "Updating database, please try again later";
  // trigger your update script
  die; // if you continue, you'll have race condition.
}

print "continue with script";


问:
React router dom params issue
I tried to Routing the params ":id" in react with a sub Route ":id/history" and the route link not render the component on clicking</p>

```<code><Switch>
     <Route path="/patients/:id" exact component={GeneralData} />
     <Route path="/patients/:id/history" component={History} />
</Switch>
</code>```

答:
The Switch component renders the first route that matches the URL you entered

Because you are using a wildcard for your GeneralData Route like so

```<code><Route path="/patients/:id" component={GeneralData}/>
</code>```

No matter what you enter after /patients, it gets captured in that wildcard definition of that Route because it accepts literally anything. So even if you navigate to /patients/4834834/history it still satisfies the GeneralData route which was found first in the list of routes.

To fix this, simply move your History Route above your GeneralData Route. This makes it so the GeneralData route will not get rendered for anything that just satisfies /patients/:id. Switch will look to see if your URL matches History first.

```<code><Switch>
     <Route path="/patients/:id/history" component={History} />
     <Route path="/patients/:id" component={GeneralData} />
</Switch>
</code>```

Title: React router dom params issue

Body:
I tried to Routing the params ":id" in react with a sub Route ":id/history" and the route link not render the component on clicking

<Switch>
     <Route path="/patients/:id" exact component={GeneralData} />
     <Route path="/patients/:id/history" component={History} />
</Switch>

Body:
The Switch component renders the first route that matches the URL you entered

Because you are using a wildcard for your GeneralData Route like so

<Route path="/patients/:id" component={GeneralData}/>

No matter what you enter after /patients, it gets captured in that wildcard definition of that Route because it accepts literally anything. So even if you navigate to /patients/4834834/history it still satisfies the GeneralData route which was found first in the list of routes.

To fix this, simply move your History Route above your GeneralData Route. This makes it so the GeneralData route will not get rendered for anything that just satisfies /patients/:id. Switch will look to see if your URL matches History first.

<Switch>
     <Route path="/patients/:id/history" component={History} />
     <Route path="/patients/:id" component={GeneralData} />
</Switch>


问:
How do I install Spring Boot CLI in Ubuntu?
I am trying to install Spring Boot CLI in Ubuntu. I am new to spring boot and was trying to learn it. I have already installed Gradle and groovy but did not find anything online to install Spring boot CLI.</p>

答: Here is detailed instruction on how to do it, much more useful than official one, at least for manual installation. One more thing - to make path change permanent you might need to logout - login, as "source /etc/profile" will be effective only for currently opened terminal.</p>


问:
How can I create a "tooltip tail" using pure CSS?
I just came across a neat CSS trick. Check out the fiddle...

.tooltiptail {
  display: block;
  border-color: #ffffff #a0c7ff #ffffff #ffffff;
  border-style: solid;
  border-width: 20px;
  width: 0px;
  height: 0px;
}
.anothertail {
  background-image: url(http://static.jqueryfordesigners.com/demo/images/coda/bubble-tail2.png);
  display: block;
  height: 29px;
  width: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>Cool Trick:
  <br />
  <div class="tooltiptail"></div>
</div>
<br />

<div>How do I get this effect with only CSS?
  <br />
  <div class="anothertail"></div>
</div></code>```

This creates a little arrow/triangle-like effect, a "tooltip tail". This blows my mind! I'm really interested in knowing how this works?!

Further, is there a way to extend this CSS trick to create an effect as follows:

This is an interesting problem. Can this be done using only CSS, ignoring the shadow for now?

UPDATE 1

I figured out a solution to my initial question. Here's the fiddle...

http://jsfiddle.net/duZAx/7/

HTML

```<code><div style="position: relative;">Cool Trick:<br />
    <div class="tooltiptail"></div>
    <div class="tooltiptail2"></div>
</div>
</code>```

CSS

```<code>.tooltiptail {
    display: block;
    border-color: #ffffff #a0c7ff #ffffff #ffffff;
    border-style: solid;
    border-width: 20px;
    width: 0px;
    height: 0px;
}
.tooltiptail2 {
    display: block;
    border-color: transparent #ffffff transparent transparent;
    border-style: solid;
    border-width: 18px;
    width: 0px;
    height: 0px;
    position: relative;
    left: 4px;
    top: -38px;
}
</code>```

Now, how do I exactly mimic the little picture above using pure CSS, including the shadow and having it cross-browser compatible?

UPDATE 2

Here's my solution after a combination of the answers below. I haven't tested it across multiple browsers, but it looks great in Chrome.

http://jsfiddle.net/UnsungHero97/MZXCj/688/

HTML

```<code><div id="toolTip">
    <p>i can haz css tooltip</p>
    <div id="tailShadow"></div>
    <div id="tail1"></div>
    <div id="tail2"></div>
</div>
</code>```

CSS

```<code>#toolTip {
    background-color: #ffffff;
    border: 1px solid #73a7f0;
    width: 200px;
    height: 100px;
    margin-left: 32px;
    position:relative;
    border-radius: 4px;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
    box-shadow: 0px 0px 8px -1px black;
    -moz-box-shadow: 0px 0px 8px -1px black;
    -webkit-box-shadow: 0px 0px 8px -1px black;
}

#toolTip p {
    padding:10px;
}

#tailShadow {
    background-color: transparent;
    width: 4px;
    height: 4px;
    position: absolute;
    top: 16px;
    left: -8px;
    z-index: -10;
    box-shadow: 0px 0px 8px 1px black;
    -moz-box-shadow: 0px 0px 8px 1px black;
    -webkit-box-shadow: 0px 0px 8px 1px black;
}

#tail1 {
    width: 0px;
    height: 0px;
    border: 10px solid;
    border-color: transparent #73a7f0 transparent transparent;
    position:absolute;
    top: 8px;
    left: -20px;
}

#tail2 {
    width: 0px;
    height: 0px;
    border: 10px solid;
    border-color: transparent #ffffff transparent transparent;
    position:absolute;
    left: -18px;
    top: 8px;
}
</code>```

答:
I do this tooltip with only one div element.

HTML:

```<code><div class="tooltip">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent augue justo, venenatis non tincidunt sit amet, suscipit eget ligula.</div>
</code>```

CSS:

```<code>.tooltip{
    position: relative;
    border: 1px solid #73a7f0;
    width: 200px;
    margin-left: 20px;
    padding: 5px 14px;
    border-radius: 4px;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    box-shadow: 0px 0px 6px rgba(0, 0, 0, .7);
    -webkit-box-shadow: -0px 0px 6px rgba(0, 0, 0, .7);
    -moz-box-shadow: 0px 0px 6px rgba(0, 0, 0, .7);
}
.tooltip:before{
    content: ' ';
    display: block;
    position: absolute;
    left: -8px;
    top: 15px;
    width: 14px;
    height: 14px;
    border-color: #73a7f0;
    border-width: 1px;
    border-style: none none solid solid;
    background-color: #fff;
    box-shadow: -2px 2px 3.5px rgba(0, 0, 0, .5);
    -webkit-box-shadow: -2px 2px 3.5px rgba(0, 0, 0, .5);
    -moz-box-shadow: -2px 2px 3.5px rgba(0, 0, 0, .5);
    transform: rotate(45deg);
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
}
</code>```

Demo

Explanation:

I have my normal div with border just like other example. The tail is a simple combination of CSS :

I use the pseudo selector :before (:after works fine too)

I force the content with a white space to make the tail visible.

I rotate my box from 45deg to fix the corner in the side of the tooltip

No surprise for the size and the positioning.

I add a border on the 2 sides i want.

And finally i add the shadows to the outside border.

Body:
I just came across a neat CSS trick. Check out the fiddle...

.tooltiptail {
  display: block;
  border-color: #ffffff #a0c7ff #ffffff #ffffff;
  border-style: solid;
  border-width: 20px;
  width: 0px;
  height: 0px;
}
.anothertail {
  background-image: url(http://static.jqueryfordesigners.com/demo/images/coda/bubble-tail2.png);
  display: block;
  height: 29px;
  width: 30px;
}

Cool Trick:

How do I get this effect with only CSS?

This creates a little arrow/triangle-like effect, a "tooltip tail". This blows my mind! I'm really interested in knowing how this works?!

Further, is there a way to extend this CSS trick to create an effect as follows:

This is an interesting problem. Can this be done using only CSS, ignoring the shadow for now?

UPDATE 1

I figured out a solution to my initial question. Here's the fiddle...

http://jsfiddle.net/duZAx/7/

HTML

Cool Trick:

CSS

.tooltiptail {
    display: block;
    border-color: #ffffff #a0c7ff #ffffff #ffffff;
    border-style: solid;
    border-width: 20px;
    width: 0px;
    height: 0px;
}
.tooltiptail2 {
    display: block;
    border-color: transparent #ffffff transparent transparent;
    border-style: solid;
    border-width: 18px;
    width: 0px;
    height: 0px;
    position: relative;
    left: 4px;
    top: -38px;
}

Now, how do I exactly mimic the little picture above using pure CSS, including the shadow and having it cross-browser compatible?

UPDATE 2

Here's my solution after a combination of the answers below. I haven't tested it across multiple browsers, but it looks great in Chrome.

http://jsfiddle.net/UnsungHero97/MZXCj/688/

HTML

i can haz css tooltip

CSS

#toolTip {
    background-color: #ffffff;
    border: 1px solid #73a7f0;
    width: 200px;
    height: 100px;
    margin-left: 32px;
    position:relative;
    border-radius: 4px;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
    box-shadow: 0px 0px 8px -1px black;
    -moz-box-shadow: 0px 0px 8px -1px black;
    -webkit-box-shadow: 0px 0px 8px -1px black;
}

#toolTip p {
    padding:10px;
}

#tailShadow {
    background-color: transparent;
    width: 4px;
    height: 4px;
    position: absolute;
    top: 16px;
    left: -8px;
    z-index: -10;
    box-shadow: 0px 0px 8px 1px black;
    -moz-box-shadow: 0px 0px 8px 1px black;
    -webkit-box-shadow: 0px 0px 8px 1px black;
}

#tail1 {
    width: 0px;
    height: 0px;
    border: 10px solid;
    border-color: transparent #73a7f0 transparent transparent;
    position:absolute;
    top: 8px;
    left: -20px;
}

#tail2 {
    width: 0px;
    height: 0px;
    border: 10px solid;
    border-color: transparent #ffffff transparent transparent;
    position:absolute;
    left: -18px;
    top: 8px;
}

Body:
I do this tooltip with only one div element.

HTML:

<div class="tooltip">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent augue justo, venenatis non tincidunt sit amet, suscipit eget ligula.</div>

CSS:

.tooltip{
    position: relative;
    border: 1px solid #73a7f0;
    width: 200px;
    margin-left: 20px;
    padding: 5px 14px;
    border-radius: 4px;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    box-shadow: 0px 0px 6px rgba(0, 0, 0, .7);
    -webkit-box-shadow: -0px 0px 6px rgba(0, 0, 0, .7);
    -moz-box-shadow: 0px 0px 6px rgba(0, 0, 0, .7);
}
.tooltip:before{
    content: ' ';
    display: block;
    position: absolute;
    left: -8px;
    top: 15px;
    width: 14px;
    height: 14px;
    border-color: #73a7f0;
    border-width: 1px;
    border-style: none none solid solid;
    background-color: #fff;
    box-shadow: -2px 2px 3.5px rgba(0, 0, 0, .5);
    -webkit-box-shadow: -2px 2px 3.5px rgba(0, 0, 0, .5);
    -moz-box-shadow: -2px 2px 3.5px rgba(0, 0, 0, .5);
    transform: rotate(45deg);
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
}

Demo

Explanation:

I have my normal div with border just like other example. The tail is a simple combination of CSS :

I use the pseudo selector :before (:after works fine too)

I force the content with a white space to make the tail visible.

I rotate my box from 45deg to fix the corner in the side of the tooltip

No surprise for the size and the positioning.

I add a border on the 2 sides i want.

And finally i add the shadows to the outside border.