问:
Is the explanation for this disastrous declaration even correct?
I just started a new job where I'm part of the only team working on C projects. So I presented this picture:

which already decorated my desk on the old working place, where I just took the explanation as granted.

The idea of putting it next to our office's door case was well received. When I got asked, if I understand what this is doing and if I could explain it later this day, I agreed and prepared my self a little bit to explain it.

But I got stucked. Ignoring the additional hint which is semantically already wrong, I'm confused about the appearance of 2 empty argument-expression-list's.

Wouldn't that mean, void (*(*f[])())()is actually: f, identifying an array of unspecified size, of pointers to functions that return pointers to functions which return void?

Or am I just missing something since my C skills might have got a bit rusty?

答:
For starters in C such a function declaration like

```<code>void f();
</code>```

means that the number and types of parameters are defined based on the function call.

From the C Standard (6.7.6.3 Function declarators (including prototypes))

14 An identifier list declares only the identifiers of the parameters
  of the function. An empty list in a function declarator that is part
  of a definition of that function specifies that the function has no
  parameters. The empty list in a function declarator that is not part
  of a definition of that function specifies that no information about
  the number or types of the parameters is supplied

So if the function does not have parameters it is better to write

```<code>void f( void );
</code>```

Though it is not important nevertheless for clarity let's rewrite the declaration

```<code>void(*(*f[])( ))( )
</code>```

like

```<code>void(*(*f[])( void ))( void )
</code>```

This declaration declares an array of unspecified size (the size of the array is determinate from the number of initializers) of pointers to functions. The functions have no parameters and return pointers to functions that in turn have no parameters and have return type void.

Here is a demonstrative program

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

void func2(void)
{
    puts("Hello C");
}

void(*(func1)( void ))( void )
{
    return func2;
}

int main( void )
{
    void(*(*f[])( void ))( void) = { func1 };

    f[0]()();
}

void(*(*f[])())()
</code>```

Its output is

```<code>Hello C
</code>```

The declaration can be simplified by introducing a typedef.

For example

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

void func2(void)
{
    puts("Hello C");
}

typedef void(*FP)(void);

FP func1(void)
{
    return func2;
}

int main( void )
{
    FP ( *f[] )( void ) = { func1 };

    f[0]()();
}
</code>```

Body:
For starters in C such a function declaration like

void f();

means that the number and types of parameters are defined based on the function call.

From the C Standard (6.7.6.3 Function declarators (including prototypes))

14 An identifier list declares only the identifiers of the parameters
  of the function. An empty list in a function declarator that is part
  of a definition of that function specifies that the function has no
  parameters. The empty list in a function declarator that is not part
  of a definition of that function specifies that no information about
  the number or types of the parameters is supplied

So if the function does not have parameters it is better to write

void f( void );

Though it is not important nevertheless for clarity let's rewrite the declaration

void(*(*f[])( ))( )

like

void(*(*f[])( void ))( void )

This declaration declares an array of unspecified size (the size of the array is determinate from the number of initializers) of pointers to functions. The functions have no parameters and return pointers to functions that in turn have no parameters and have return type void.

Here is a demonstrative program

#include <stdio.h>

void func2(void)
{
    puts("Hello C");
}

void(*(func1)( void ))( void )
{
    return func2;
}

int main( void )
{
    void(*(*f[])( void ))( void) = { func1 };

    f[0]()();
}

void(*(*f[])())()

Its output is

Hello C

The declaration can be simplified by introducing a typedef.

For example

#include <stdio.h>

void func2(void)
{
    puts("Hello C");
}

typedef void(*FP)(void);

FP func1(void)
{
    return func2;
}

int main( void )
{
    FP ( *f[] )( void ) = { func1 };

    f[0]()();
}


来源: stackexchange

问:
How to get network provided date and time without internet connection?
I want to use network provided date and time in my android application even if network date and time is disable in device setting and there is no internet connectivity. Is there any possibility or any solution?

I referred this question but I didn't get perfect solution.

答:
You can try this:

```<code>String s1= android.provider.Settings.System.getString(this.getContentResolver(),
           android.provider.Settings.System.AUTO_TIME);
    if (s1.contentEquals("0")) {
        android.provider.Settings.System.putString(
                this.getContentResolver(),
                android.provider.Settings.System.AUTO_TIME, "1");
    }
    Date d1= new Date(System.currentTimeMillis());
    Log.e("finalvalue", d1.toString());
</code>```

Don't forget to give permission

```<code><uses-permission android:name="android.permission.WRITE_SETTINGS"/>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can try this:

String s1= android.provider.Settings.System.getString(this.getContentResolver(),
           android.provider.Settings.System.AUTO_TIME);
    if (s1.contentEquals("0")) {
        android.provider.Settings.System.putString(
                this.getContentResolver(),
                android.provider.Settings.System.AUTO_TIME, "1");
    }
    Date d1= new Date(System.currentTimeMillis());
    Log.e("finalvalue", d1.toString());

Don't forget to give permission

<uses-permission android:name="android.permission.WRITE_SETTINGS"/>


问:
Why wont my email validation work? PHP
I have used

```<code>if (!preg_match('/[a-z||0-9]@[a-z||0-9].[a-z]/', $email)) {
    [PRINT ERROR]
}
</code>```

&

```<code>if (!eregi( "^[0-9]+$", $email)) {
    [PRINT ERROR]
}
</code>```

&

```<code>if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    [PRINT ERROR]
}
</code>```

I have also tried taking out the ! and make it work backwards but for some reason NONE of those work to find out if it is valid. Any ideas why?...
I have it in an else if statement, Im not sure if that could be the cause..

I am using PHP

答:
Try this (from wordpress):</p>

```<code>// from wordpress code: wp-includes/formatting.php
function is_email($user_email)
{
    $chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";

    if (strpos($user_email, '@') !== false && strpos($user_email, '.') !== false)
    {
        if (preg_match($chars, $user_email)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Why wont my email validation work? PHP

Body:
I have used

if (!preg_match('/[a-z||0-9]@[a-z||0-9].[a-z]/', $email)) {
    [PRINT ERROR]
}

&

if (!eregi( "^[0-9]+$", $email)) {
    [PRINT ERROR]
}

&

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    [PRINT ERROR]
}

I have also tried taking out the ! and make it work backwards but for some reason NONE of those work to find out if it is valid. Any ideas why?...
I have it in an else if statement, Im not sure if that could be the cause..

I am using PHP

Body:
Try this (from wordpress):

// from wordpress code: wp-includes/formatting.php
function is_email($user_email)
{
    $chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";

    if (strpos($user_email, '@') !== false && strpos($user_email, '.') !== false)
    {
        if (preg_match($chars, $user_email)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}


问:
Why Android change 'compile' to 'implementation' configuration in Gradle dependencies?
As seen in Android Studio 3.0 (canary 3.0), we now add depedencies by declaring implementation instead of compile configuration.

```<code>// Before
compile 'com.android.support:appcompat-v7:25.3.1'

// Currently
implementation 'com.android.support:appcompat-v7:25.3.1'
</code>```

We can still use compile, but I would like to understand:

What is the difference between implementation and compile configuration?

Why do Android Gradle build change to use implementation as default?

答:
Thanks to the really useful link from @petter, I would like to add a summary as following.

It means that Android Gradle build starts to use the java-library plugin instead of its previous java plugin. This plugin introduces the exposed API concept with two configuration to declare dependencies.

api

should be used to declare dependencies which are exported by the
  library API

For example, in a case that you are building a Java (or Android) library which is used by other apps. If you use any third-party library and you want to expose its API to your library's consumer also, you should declare like this.

```<code>api 'commons-httpclient:commons-httpclient:3.1'
</code>```

implementation

should be used to declare dependencies which are internal to the
  component.

When developing Android app, our app module is the end point which does not need to expose any part externally. implementation should be used.

```<code>implementation 'org.apache.commons:commons-lang3:3.5'
</code>```

The previous compile configuration works the same as api. The implementation, however, brings the following benefits.

dependencies do not leak into the compile classpath of consumers
anymore, so you will never accidently depend on a transitive
dependency

faster compilation thanks to reduced classpath size

less recompilations when implementation dependencies change:
consumers would not need to be recompiled

cleaner publishing: when used in conjunction with the new
maven-publish plugin, Java libraries produce POM files that

distinguish exactly between what is required to compile against the

library and what is required to use the library at runtime (in other
words, don't mix what is needed to compile the library itself and

what is needed to compile against the library).

Body:
As seen in Android Studio 3.0 (canary 3.0), we now add depedencies by declaring implementation instead of compile configuration.

// Before
compile 'com.android.support:appcompat-v7:25.3.1'

// Currently
implementation 'com.android.support:appcompat-v7:25.3.1'

We can still use compile, but I would like to understand:

What is the difference between implementation and compile configuration?

Why do Android Gradle build change to use implementation as default?

Body:
Thanks to the really useful link from @petter, I would like to add a summary as following.

It means that Android Gradle build starts to use the java-library plugin instead of its previous java plugin. This plugin introduces the exposed API concept with two configuration to declare dependencies.

api

should be used to declare dependencies which are exported by the
  library API

For example, in a case that you are building a Java (or Android) library which is used by other apps. If you use any third-party library and you want to expose its API to your library's consumer also, you should declare like this.

api 'commons-httpclient:commons-httpclient:3.1'

implementation

should be used to declare dependencies which are internal to the
  component.

When developing Android app, our app module is the end point which does not need to expose any part externally. implementation should be used.

implementation 'org.apache.commons:commons-lang3:3.5'

The previous compile configuration works the same as api. The implementation, however, brings the following benefits.

dependencies do not leak into the compile classpath of consumers
anymore, so you will never accidently depend on a transitive
dependency

faster compilation thanks to reduced classpath size

less recompilations when implementation dependencies change:
consumers would not need to be recompiled

cleaner publishing: when used in conjunction with the new
maven-publish plugin, Java libraries produce POM files that

distinguish exactly between what is required to compile against the

library and what is required to use the library at runtime (in other
words, don't mix what is needed to compile the library itself and

what is needed to compile against the library).

ContentLicense: CC BY-SA 4.0


问:
Adding Global Password to Jenkins with init.groovy
How can I add a global passwords to Jenkins through the init.groovy that runs at startup?

To be clear, in the Manage Jenkins -> Configure Jenkins page, there is a section titled "Global Passwords". I would like to add entries in that section via Groovy code during the startup of Jenkins.

I am trying to provision my jenkins environment through groovy code by using the init.groovy. I need to add global passwords through the EnvInject plugin. I can successfully add path to a file for the same plugin using this code:

```<code>def instance = Jenkins.getInstance()

DescribableList<NodeProperty<?>, NodePropertyDescriptor> globalNodeProperties =
    instance.getGlobalNodeProperties();

globalNodeProperties.add(
    new EnvInjectNodeProperty(false, "/var/lib/jenkins/secret.properties")
);
</code>```

However, I am failing to understand the mechanics needed to programmatically add global passwords.

答:
https://github.com/jenkinsci/envinject-plugin/tree/master/src/main/java/org/jenkinsci/plugins/envinject

I did not try this plugin, but there is a class : EnvInjectGlobalPasswordEntry

i guess it could be like this:

```<code>globalNodeProperties.add(
    new EnvInjectGlobalPasswordEntry("pass-name", "the-password")
);
</code>```

Body:
How can I add a global passwords to Jenkins through the init.groovy that runs at startup?

To be clear, in the Manage Jenkins -> Configure Jenkins page, there is a section titled "Global Passwords". I would like to add entries in that section via Groovy code during the startup of Jenkins.

I am trying to provision my jenkins environment through groovy code by using the init.groovy. I need to add global passwords through the EnvInject plugin. I can successfully add path to a file for the same plugin using this code:

def instance = Jenkins.getInstance()

DescribableList<NodeProperty<?>, NodePropertyDescriptor> globalNodeProperties =
    instance.getGlobalNodeProperties();

globalNodeProperties.add(
    new EnvInjectNodeProperty(false, "/var/lib/jenkins/secret.properties")
);

However, I am failing to understand the mechanics needed to programmatically add global passwords.

Body:
https://github.com/jenkinsci/envinject-plugin/tree/master/src/main/java/org/jenkinsci/plugins/envinject

I did not try this plugin, but there is a class : EnvInjectGlobalPasswordEntry

i guess it could be like this:

globalNodeProperties.add(
    new EnvInjectGlobalPasswordEntry("pass-name", "the-password")
);


问:
Neo4J OGM Session.load(ID) returns null object for existing ID
I am conducting some Neo4J tests and running into the following peculiar problem. I created a small model which I'm intending to use with OGM. The model has a superclass Entity and a child class Child. They're both in package persistence.model. Entity has the required Long id; with matching getId() getter.

```<code>public abstract class Entity {
   private Long id;
   public Long getId() {
      return id;
   }
}

@NodeEntity
Child extends Entity {
   String name;
   public Child() {
   }
}
</code>```

Creating Child objects and persisting them through OGM works fine. I'm basing myself on the examples found in the documentation and using a Neo4jSessionFactory object, which initialises the SessionFactory with the package persistence.model. The resulting database contains objects with proper ID's filled in.

The problem arises when I try to fetch a Child for a given ID. I'm trying it with three methods, using two connection systems (bolt and ogm):

```<code>boltSession.run("MATCH (a:Child) WHERE id(a) = {id} RETURN a", parameters("id", childId));

ogmSession.query("MATCH (a:Child) WHERE id(a) = $id RETURN a", params);

ogmSession.load(Child.class, childId, 1);
</code>```

The first two methods actually return the correct data. The last one returns a null value. The last one, using OGM, has some obvious benefits, and I'd love to be able to use it properly. Can anyone point me in the right direction?

答:
In your test code you are doing a lookup by id of type int.

```<code>private int someIdInYourDatabase = 34617;
</code>```

The internal ids in Neo4j are of type Long.

If you change the type of the id to long or Long then it will work.

```<code>private long someIdInYourDatabase = 34617;
</code>```

Body:
I am conducting some Neo4J tests and running into the following peculiar problem. I created a small model which I'm intending to use with OGM. The model has a superclass Entity and a child class Child. They're both in package persistence.model. Entity has the required Long id; with matching getId() getter.

public abstract class Entity {
   private Long id;
   public Long getId() {
      return id;
   }
}

@NodeEntity
Child extends Entity {
   String name;
   public Child() {
   }
}

Creating Child objects and persisting them through OGM works fine. I'm basing myself on the examples found in the documentation and using a Neo4jSessionFactory object, which initialises the SessionFactory with the package persistence.model. The resulting database contains objects with proper ID's filled in.

The problem arises when I try to fetch a Child for a given ID. I'm trying it with three methods, using two connection systems (bolt and ogm):

boltSession.run("MATCH (a:Child) WHERE id(a) = {id} RETURN a", parameters("id", childId));

ogmSession.query("MATCH (a:Child) WHERE id(a) = $id RETURN a", params);

ogmSession.load(Child.class, childId, 1);

The first two methods actually return the correct data. The last one returns a null value. The last one, using OGM, has some obvious benefits, and I'd love to be able to use it properly. Can anyone point me in the right direction?

Body:
In your test code you are doing a lookup by id of type int.

private int someIdInYourDatabase = 34617;

The internal ids in Neo4j are of type Long.

If you change the type of the id to long or Long then it will work.

private long someIdInYourDatabase = 34617;


问:
How to zip two 1d numpy array to 2d numpy array
I have two numpy 1d arrays, e.g:

```<code>a = np.array([1,2,3,4,5])
b = np.array([6,7,8,9,10])
</code>```

Then how can I get one 2d array [[1,6], [2,7], [3,8], [4,9], [5, 10]]?

答:
The answer lies in your question:

```<code>np.array(list(zip(a,b)))
</code>```

Edit:

Although my post gives the answer as requested by the OP, the conversion to list and back to NumPy array takes some overhead (noticeable for large arrays).

Hence, dstack would be a computationally efficient alternative  (ref. @zipa's answer).  I was unaware of dstack at the time of posting this answer so credits to @zipa for introducing it to this post.

Edit 2:

As can be seen in the duplicate question, np.c_ is even shorter than np.dstack.

```<code>>>> import numpy as np
>>> a = np.arange(1, 6)
>>> b = np.arange(6, 11)
>>>
>>> a
array([1, 2, 3, 4, 5])
>>> b
array([ 6,  7,  8,  9, 10])
>>> np.c_[a, b]
array([[ 1,  6],
       [ 2,  7],
       [ 3,  8],
       [ 4,  9],
       [ 5, 10]])
</code>```

Body:
I have two numpy 1d arrays, e.g:

a = np.array([1,2,3,4,5])
b = np.array([6,7,8,9,10])

Then how can I get one 2d array [[1,6], [2,7], [3,8], [4,9], [5, 10]]?

Body:
The answer lies in your question:

np.array(list(zip(a,b)))

Edit:

Although my post gives the answer as requested by the OP, the conversion to list and back to NumPy array takes some overhead (noticeable for large arrays).

Hence, dstack would be a computationally efficient alternative  (ref. @zipa's answer).  I was unaware of dstack at the time of posting this answer so credits to @zipa for introducing it to this post.

Edit 2:

As can be seen in the duplicate question, np.c_ is even shorter than np.dstack.

>>> import numpy as np
>>> a = np.arange(1, 6)
>>> b = np.arange(6, 11)
>>>
>>> a
array([1, 2, 3, 4, 5])
>>> b
array([ 6,  7,  8,  9, 10])
>>> np.c_[a, b]
array([[ 1,  6],
       [ 2,  7],
       [ 3,  8],
       [ 4,  9],
       [ 5, 10]])


问:
Print text (disp, fprintf...) to the command MATLAB window in Labview
Is there a way I can print to the Labview MATLAB Command Windows?

disp and fprintf doesn't work.

Sample:

Create Labview vi

Add a "MATLAB script"

Write inside it: disp('Hello'); or MyFile; .m containg this same code.

Run code

Nothing is displayed in the "MATLAB Command Window"

答: MATLAB script window in LabVIEW dont support IDE functions of MATLAB. For example 'disp' is MATLAB own function to display some thing in command window. When calling from LabVIEW, we are not in MATLAB IDE.</p>


Title: How to zip two 1d numpy array to 2d numpy array

Body:
You can use zip

np.array(list(zip(a,b)))
array([[ 1,  6],
   [ 2,  7],
   [ 3,  8],
   [ 4,  9],
   [ 5, 10]])


问:
How can I make my icon
s show up next to each other, rather than underneath each other?
I have this

```<code><a href="#"><div class="iconFriends"></div></a>
<a href="#"><div class="iconFavorite"></div></a>
<a href="#"><div class="iconPM"></div></a>
<a href="#"><div class="iconShield"></div></a>
</code>```

and the css for the icons class looks all similiar to this:

```<code>.iconFriends{
background: url(../images/icons/friends_16x16.png) no-repeat;
width: 16px;
height: 16px;
border: none;
}
</code>```

Now the results is that there is like a
 when I do this. But if i remove the div and make a normal  It shows fine. How can i fix this?

答:
I would suggest reversing the order of your elements, as such:

```<code><div class="icon iconFriends"><a href="#"></a></div>
</code>```

Note the extra icon class on the div.

Then use this for your CSS:

```<code>.icon a
{
    display: block;
    width: 16px;
    height: 16px;
}

.iconFriends
{
    background: url(../images/icons/friends_16x16.png) no-repeat;
    width: 16px;
    height: 16px;
    border: none;
    float: left;
}
</code>```

Adding float: left; will put them all on the same line. Setting display: block; on the a will allow you to set the width and height (making the entire element clickable).

Title: How can I make my icon <div>s show up next to each other, rather than underneath each other?

Body:
I have this

and the css for the icons class looks all similiar to this:

.iconFriends{
background: url(../images/icons/friends_16x16.png) no-repeat;
width: 16px;
height: 16px;
border: none;
}

Now the results is that there is like a
 when I do this. But if i remove the div and make a normal  It shows fine. How can i fix this?

Body:
I would suggest reversing the order of your elements, as such:

<div class="icon iconFriends"><a href="#"></a></div>

Note the extra icon class on the div.

Then use this for your CSS:

.icon a
{
    display: block;
    width: 16px;
    height: 16px;
}

.iconFriends
{
    background: url(../images/icons/friends_16x16.png) no-repeat;
    width: 16px;
    height: 16px;
    border: none;
    float: left;
}

Adding float: left; will put them all on the same line. Setting display: block; on the a will allow you to set the width and height (making the entire element clickable).


问:
clang-format: how to prevent all function arguments on next line?
I have a C++ function call that I've manually and intentionally formatted like
this:

```<code>DoSomethingForAPurposeThatCausesALongFunctionName(
    arg_0,
    arg_1,
    arg_2);
</code>```

clang-format wants to re-format it like this:

```<code>DoSomethingForAPurposeThatCausesALongFunctionName(
    arg_0, arg_1, arg_2)
</code>```

I do not want this. AllowAllParametersOfDeclarationOnNextLine appears to
control this behavior for function declarations, but what about function calls?
Is there a corresponding setting?

My .clang-format looks like this:

```<code>BasedOnStyle: Google
BinPackArguments: false
BinPackParameters: false
AllowAllParametersOfDeclarationOnNextLine: false
AlignAfterOpenBracket: AlwaysBreak
</code>```

答:
I think you need

```<code>AllowAllParametersOfDeclarationOnNextLine: true
</code>```

It works for me unless the first argument is on the same line as the function call, in which case it puts them all on the same line.

I also have

```<code>ExperimentalAutoDetectBinPacking: false
</code>```

which may have some effect?

I'm using version 3.8.0.

Body:
I have a C++ function call that I've manually and intentionally formatted like
this:

DoSomethingForAPurposeThatCausesALongFunctionName(
    arg_0,
    arg_1,
    arg_2);

clang-format wants to re-format it like this:

DoSomethingForAPurposeThatCausesALongFunctionName(
    arg_0, arg_1, arg_2)

I do not want this. AllowAllParametersOfDeclarationOnNextLine appears to
control this behavior for function declarations, but what about function calls?
Is there a corresponding setting?

My .clang-format looks like this:

BasedOnStyle: Google
BinPackArguments: false
BinPackParameters: false
AllowAllParametersOfDeclarationOnNextLine: false
AlignAfterOpenBracket: AlwaysBreak

Body:
I think you need

AllowAllParametersOfDeclarationOnNextLine: true

It works for me unless the first argument is on the same line as the function call, in which case it puts them all on the same line.

I also have

ExperimentalAutoDetectBinPacking: false

which may have some effect?

I'm using version 3.8.0.


问:
Accessing Google Datastore from Google App engine via PHP
I'm really new to the whole GCP platform and I'm trying to create my first web app, specifically in PHP.
I've went through every thread, tutorials, etc. but they are too advance from me.

Could someone please let me know what are the most basic steps for querying a data in Cloud datastore using PHP from APP Engine?

This is my setup:
In my Datastore, there's 1 entry which basically has 2 properties called name and address, a PHP file on APP Engine that would just query the datastore.

I've enabled Datastore API access for my app. I've also deployed it.
But I can't make it to work.

This is my view.php file:

```<code><?php
use Google\Cloud\Datastore\DatastoreClient;

# Your Google Cloud Platform project ID
$projectId = '<my project id>';
# Instantiates a client
$datastore = new DatastoreClient(['projectId' => $projectId]);

$query = $datastore->query()
    ->kind('person');

$result = $datastore->runQuery($query);

foreach ($result as $entity) {
        echo 'Entity found: ' . $entity['name'] . PHP_EOL;
    }

?>
</code>```

note: I deployed my app with these 3 files:

app.yaml

index.php (hello world page)

view.php

app.yaml content:

```<code>runtime: php55
api_version: 1

handlers:
- url: /
  script: index.php

- url: /index\.html
  script: index.php

- url: /view
  script: view.php

- url: /view\.html
  script: view.php

- url: /.*
  script: not_found.php
</code>```

答:
If you are looking for a really easy to use library to access Datastore from PHP, I would recommend PHP-GDS by Tom Walder https://github.com/tomwalder/php-gds He has done a great job of making Datastore easy for PHP, without it can be a nightmare at times. He is continually updating the library as he uses it in his projects, and I have successfully used it in a few of my projects as well.

The library also has a heap of examples that show you how to do pretty much everything you will need. It is as simple as including the library manually or via composer, and defining your data-structures etc.

I have also created a tutorial/discussion on how to use php-gds on my site https://buziit.com.au/google-datastore-a-saas-experience/, but note this is a little out of date, as it was written before PHP was officially supported by Datastore. The main difference is in defining the Gateway, but Tom's documentation is up to date (you need to change 1 line).

You would most likely be better off using a library developed by someone who has felt your pain before, as Datastore can be a pain to get right for PHP (at least it was when it was not officially supported for PHP). I can't get away form the library now :)

Body:
I'm really new to the whole GCP platform and I'm trying to create my first web app, specifically in PHP.
I've went through every thread, tutorials, etc. but they are too advance from me.

Could someone please let me know what are the most basic steps for querying a data in Cloud datastore using PHP from APP Engine?

This is my setup:
In my Datastore, there's 1 entry which basically has 2 properties called name and address, a PHP file on APP Engine that would just query the datastore.

I've enabled Datastore API access for my app. I've also deployed it.
But I can't make it to work.

This is my view.php file:

<?php
use Google\Cloud\Datastore\DatastoreClient;

# Your Google Cloud Platform project ID
$projectId = '<my project id>';
# Instantiates a client
$datastore = new DatastoreClient(['projectId' => $projectId]);

$query = $datastore->query()
    ->kind('person');

$result = $datastore->runQuery($query);

foreach ($result as $entity) {
        echo 'Entity found: ' . $entity['name'] . PHP_EOL;
    }

?>

note: I deployed my app with these 3 files:

app.yaml

index.php (hello world page)

view.php

app.yaml content:

runtime: php55
api_version: 1

handlers:
- url: /
  script: index.php

- url: /index\.html
  script: index.php

- url: /view
  script: view.php

- url: /view\.html
  script: view.php

- url: /.*
  script: not_found.php


问:
Get window back on top
I started a new project with XAML based GUI, but I have the problem. When I open another window, message box or even call Get-Credential, the main windows disappears in the background (behind all other open windows).

Is there a possible easy way to get the windows back on top?
I found a lot of solutions with Get-Process, etc. but that seems to complicated for this simple issue.

答:
Might also be too complicated...

Nevertheless, using the SetWindowsPos function:

```<code>$User32 = Add-Type -Debug:$False -MemberDefinition '
    [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X,int Y, int cx, int cy, uint uFlags);
' -Name "User32Functions" -namespace User32Functions -PassThru

$Xaml = ...
$Window = [Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader($Xaml)))
$Handle = (New-Object System.Windows.Interop.WindowInteropHelper($Window)).Handle

[Void]$User32::SetWindowPos($Handle, -1, 0, 0, 0, 0, 0x53)
</code>```

Title: Get window back on top

Body:
Might also be too complicated...

Nevertheless, using the SetWindowsPos function:

$User32 = Add-Type -Debug:$False -MemberDefinition '
    [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X,int Y, int cx, int cy, uint uFlags);
' -Name "User32Functions" -namespace User32Functions -PassThru

$Xaml = ...
$Window = [Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader($Xaml)))
$Handle = (New-Object System.Windows.Interop.WindowInteropHelper($Window)).Handle

[Void]$User32::SetWindowPos($Handle, -1, 0, 0, 0, 0, 0x53)


问:
Streamreader initialization with a text file that has an empty line each other line
I'm facing a quite curious problem. I'm trying to initialize a streamreader with a file name and an encoding parameter but my code fails due to the fact the file has an empty line each other line contained.

What I'm trying to do is to read the lines in a list. If the file does not contain empty lines then the code executes sucessfuly.

i'm initalizing the reader like this

```<code>            using (StreamReader reader = new StreamReader(filename, encoding))
            {
               //do stuff...
            }
</code>```

Any thoughts as of how I could perform the operation mentioned above ? This is for an automated process, so no manual tampering with the file can be performed.

Thank you in advance

答:
It seems that the enconding of the file was messed up when I saved it using Notepad++ (without altering anything on the file, simply clicking save) and the Streamreader did not like it. I can parse it correctly now (if do not click on "save" accidentally) and i can handle the empty lines using

string.IsNullOrWhiteSpace

Thank you all for your time.

Body:
I'm facing a quite curious problem. I'm trying to initialize a streamreader with a file name and an encoding parameter but my code fails due to the fact the file has an empty line each other line contained.

What I'm trying to do is to read the lines in a list. If the file does not contain empty lines then the code executes sucessfuly.

i'm initalizing the reader like this

            using (StreamReader reader = new StreamReader(filename, encoding))
            {
               //do stuff...
            }

Any thoughts as of how I could perform the operation mentioned above ? This is for an automated process, so no manual tampering with the file can be performed.

Thank you in advance


问:
When I use f.write to write string, it only writes numbers/codes
I have a simple piece of code to write a bunch of strings to file:

```<code>    data = self.measure()
    f = open('output.txt', 'w')
    print data
    for line in data:
        print 'line:', line, type(line)
        f.write(str(line))
    f.close()
</code>```

But this gives me an output file looking like:

```<code>0034 0045 1056
0086 9078 0567...
</code>```

I thought my data was in unicode or something, so I tried a few things like changing to this:

```<code>f.write(unicode(line))
</code>```

Which resulted in the same file output
However when I use this:

```<code>f.write(str(line) + ';' + unicode(line))
</code>```

I get the correct and expected text in the file:

hal_init() for chip version 0x02c4;hal_init() for chip version
  0x02c4ram_prog, ed_list=  [edata(0x50000, 0x517c1)];ram_prog, ed_list=
  [edata(0x50000, 0x517c1)];Summary:;Summary:==== ....... etc

I dont understand why, or what I am doing wrong. Clearly I am missing something about the format/type of the variable 'line'. But type(line) just tells me its a string...

Can anyone explain?

答:
I figured it out.

SublimeText 3 encoded the output file as hexadecimal. There are a few hex values inside the string which I guess it spots and trys to be clever with the encoding... Blah

Not sure why the f.write(str(line) + ';' + unicode(line)) code made ST3 encode it different...

Thanks

Body:
I have a simple piece of code to write a bunch of strings to file:

    data = self.measure()
    f = open('output.txt', 'w')
    print data
    for line in data:
        print 'line:', line, type(line)
        f.write(str(line))
    f.close()

But this gives me an output file looking like:

0034 0045 1056
0086 9078 0567...

I thought my data was in unicode or something, so I tried a few things like changing to this:

f.write(unicode(line))

Which resulted in the same file output
However when I use this:

f.write(str(line) + ';' + unicode(line))

I get the correct and expected text in the file:

hal_init() for chip version 0x02c4;hal_init() for chip version
  0x02c4ram_prog, ed_list=  [edata(0x50000, 0x517c1)];ram_prog, ed_list=
  [edata(0x50000, 0x517c1)];Summary:;Summary:==== ....... etc

I dont understand why, or what I am doing wrong. Clearly I am missing something about the format/type of the variable 'line'. But type(line) just tells me its a string...

Can anyone explain?


问:
firebase authentication - does firebase differentiate facebook and google login accounts
I want to use firebase as my apps authentication method.  But I'd like my users to log in using Google or Facebook. I am a little confused what happens here.

Lets say a user successfully authenticates with Facebook only. Then I get a callback from Facebook with some token of success. Now I send that token to firebase for further authentication.
Firebase can return success or failure. This part I understand.

But what I am confused about is if the same user uses the Google account to login, will that not be considered a different login?  Will firebase know that the Facebook user is the same google user or will it create two different accounts? I don't want the user to have two different accounts because they chose a different login provider. I want firebase to be able to know its the same user. That is why I wanted to user firebase authentication as its a central place. Can someone advise me?

UPDATE:

Thanks. So if I understand correctly at least one account must already be currently logged into firebase inorder to link another one ? So that being the case ...imagine i am currently logged in with a google account. How would i ask the user to link there facebook account? I wish i could link the second account seamlessly but seems you cant. Therefore how doni prompt the user or under what condition can i link the second account effortlessly? I'm having trouble visualizing how this would work without me directly asking the user.

答: As long as the user uses the same email address for both providers, you can tell Firebase to link the two accounts together. See the section on linking providers in the Firebase documentation.</p>


问:
How to use events is jquery plugin?
Sorry this is my first time trying to create a plugin, so I might be way off. I have read the docs but got confused, and I decided to learn by trying....

I am trying to make a simple form validation plugin

```<code>(function($){
    $.fn.bluevalidate = function(options){

        var defaults = {
            errorMsg : 'You have an error',
            required : ''
        };

        var opt = $.extend(defaults,options);

        return this.each(function(index,element){
           var e = $(element);

           if(opt.required!='')
           {
                e.bind('blur',function(){
                    alert("required is here");
                });
           }
           else
           {
                alert("NOOOOOOOOO");
           }
        });
    };
</code>```

})( jQuery )

And I am calling it like

```<code>$('#username').bluevalidate({
     required:'This field is required';
})
</code>```

I want to get the alert when the user clicks off the field, but as you can guess, my method isn't working, please tell me what I am doing wrong....

答:
There's an extra ; in there, it should be:

```<code>$('#username').bluevalidate({
  required:'This field is required'
})
</code>```

When declaring an object literal, your properties should not be followed by a ; (you should however have a , between properties).  This is the main issue:

```<code>  required:'This field is required'; //the ; shouldn't be here
</code>```

You can test it out here.

Title: How to use events is jquery plugin?

Body:
Sorry this is my first time trying to create a plugin, so I might be way off. I have read the docs but got confused, and I decided to learn by trying....

I am trying to make a simple form validation plugin

(function($){
    $.fn.bluevalidate = function(options){

        var defaults = {
            errorMsg : 'You have an error',
            required : ''
        };

        var opt = $.extend(defaults,options);

        return this.each(function(index,element){
           var e = $(element);

           if(opt.required!='')
           {
                e.bind('blur',function(){
                    alert("required is here");
                });
           }
           else
           {
                alert("NOOOOOOOOO");
           }
        });
    };

})( jQuery )

And I am calling it like

$('#username').bluevalidate({
     required:'This field is required';
})

I want to get the alert when the user clicks off the field, but as you can guess, my method isn't working, please tell me what I am doing wrong....

Body:
There's an extra ; in there, it should be:

$('#username').bluevalidate({
  required:'This field is required'
})

When declaring an object literal, your properties should not be followed by a ; (you should however have a , between properties).  This is the main issue:

  required:'This field is required'; //the ; shouldn't be here

You can test it out here.


问:
How to convert [String : Any] to [NSAttributedStringKey : Any]
Dealing with some objC API, I receive an NSDictionary<NSString *, id> *> which translates to [String : Any] in Swift and which I was using for NSAttributedString.addAttributes:range:.

However, this method signature has now changed with Xcode 9 and now requires an [NSAttributedStringKey : Any].

```<code>let attr: [String : Any]? = OldPodModule.getMyAttributes()
// Cannot assign value of type '[String : Any]?' to type '[NSAttributedStringKey : Any]?'
let newAttr: [NSAttributedStringKey : Any]? = attr
if let newAttr = newAttr {
    myAttributedString.addAttributes(newAttr, range: range)
}
</code>```

How to convert a [String : Any] to a [NSAttributedStringKey : Any]?

答:
NSAttributedStringKey has an initialiser that takes a String, and you can use Dictionary's init(uniqueKeysWithValues:) initialiser in order to build a dictionary from a sequence of key-value tuples where each key is unique (such as is the case here).

We just have to apply a transform to attr that converts each String key into an NSAttributedStringKey prior to calling Dictionary's initialiser.

For example:

```<code>let attributes: [String : Any]? = // ...

let attributedString = NSMutableAttributedString(string: "hello world")
let range = NSRange(location: 0, length: attributedString.string.utf16.count)

if let attributes = attributes {
    let convertedAttributes = Dictionary(uniqueKeysWithValues:
        attributes.lazy.map { (NSAttributedStringKey($0.key), $0.value) }
    )
    attributedString.addAttributes(convertedAttributes, range: range)
}
</code>```

We're using lazy here to avoid the creation of an unnecessary intermediate array.

Body:
Dealing with some objC API, I receive an NSDictionary<NSString *, id> *> which translates to [String : Any] in Swift and which I was using for NSAttributedString.addAttributes:range:.

However, this method signature has now changed with Xcode 9 and now requires an [NSAttributedStringKey : Any].

let attr: [String : Any]? = OldPodModule.getMyAttributes()
// Cannot assign value of type '[String : Any]?' to type '[NSAttributedStringKey : Any]?'
let newAttr: [NSAttributedStringKey : Any]? = attr
if let newAttr = newAttr {
    myAttributedString.addAttributes(newAttr, range: range)
}

How to convert a [String : Any] to a [NSAttributedStringKey : Any]?

Body:
NSAttributedStringKey has an initialiser that takes a String, and you can use Dictionary's init(uniqueKeysWithValues:) initialiser in order to build a dictionary from a sequence of key-value tuples where each key is unique (such as is the case here).

We just have to apply a transform to attr that converts each String key into an NSAttributedStringKey prior to calling Dictionary's initialiser.

For example:

let attributes: [String : Any]? = // ...

let attributedString = NSMutableAttributedString(string: "hello world")
let range = NSRange(location: 0, length: attributedString.string.utf16.count)

if let attributes = attributes {
    let convertedAttributes = Dictionary(uniqueKeysWithValues:
        attributes.lazy.map { (NSAttributedStringKey($0.key), $0.value) }
    )
    attributedString.addAttributes(convertedAttributes, range: range)
}

We're using lazy here to avoid the creation of an unnecessary intermediate array.


问:
Angular Fullcalendar min and max time not working in month view
Full calendar min and max time not working in month view.
But it is working in week and day view </p>

```<code>minTime: "06:00:00",
maxTime: "30:00:00",
</code>```

答:
minTime:

Determines the starting time that will be displayed, even when the scrollbars have been scrolled all the way up.

Duration, default: "00:00:00"

The default "00:00:00" means the start time will be at the very beginning of the day (midnight).

maxTime:

Determines the end time (exclusively) that will be displayed, even when the scrollbars have been scrolled all the way down.

Duration, default: "24:00:00"

The default "24:00:00" means the end time will be at the very end of the day (midnight).

Basically it follows clock times, you can't just say the max time is 30 hours.

Body:
Full calendar min and max time not working in month view.
But it is working in week and day view

minTime: "06:00:00",
maxTime: "30:00:00",


问:
which data structure should I use in java to store duplicate values?
Which is the best data structure to store duplicate values in java? And how easy is to retrieve values from it!?

thanks
EDIT #1 I am reading contents from 1000 files, and I want to put each files content as tokens in some data structure. I used Hashtable but i am not able to view many words when I am doing that. thats why I want a data structure which can store the duplicate values.

答:
For just storing simple values, you should use an implementation of the List<E> interface.

To get data from a List<E> you can do the following:

```<code>list.get(index); // will get data at a given index
// or you can iterate over all of the items in the list
for(E item: list) {
    // use E
}
</code>```

Depending on your use either an ArrayList<E> or LinkedList<E> will do what you need.

Another option would be a Map<K, V> (it's implementation HashMap).  This will allow you to save duplicate values under unique keys.

You can get values out of a Map<K,V> in the following ways:

```<code>map.get(someKey); // will retrieve the value associated with a key
// or you can iterate through all of the entries in a map like so:
for(Entry<K,V> entry: map.entrySet()){
    // use entry
}
</code>```

Response to your edit:

You may want to use a Map<String, List<String>> where the key is the name of the file, and the value is a list of the words in the file.

Your code may look like this:

```<code>Map<String, List<String>> data = new HashMap<String, List<String>>();
for(File f: files) {
    List<String> words = new ArrayList<String();
    data.put(f.getName(), words);
    Scanner s = new Scanner(f);
    while(s.hasNext()) {
        words.add(s.next());
    }
}
</code>```

At the end of this snipit, data will be filled with lists of words from each file.

Body:
For just storing simple values, you should use an implementation of the List<E> interface.

To get data from a List<E> you can do the following:

list.get(index); // will get data at a given index
// or you can iterate over all of the items in the list
for(E item: list) {
    // use E
}

Depending on your use either an ArrayList<E> or LinkedList<E> will do what you need.

Another option would be a Map<K, V> (it's implementation HashMap).  This will allow you to save duplicate values under unique keys.

You can get values out of a Map<K,V> in the following ways:

map.get(someKey); // will retrieve the value associated with a key
// or you can iterate through all of the entries in a map like so:
for(Entry<K,V> entry: map.entrySet()){
    // use entry
}

Response to your edit:

You may want to use a Map<String, List<String>> where the key is the name of the file, and the value is a list of the words in the file.

Your code may look like this:

Map<String, List<String>> data = new HashMap<String, List<String>>();
for(File f: files) {
    List<String> words = new ArrayList<String();
    data.put(f.getName(), words);
    Scanner s = new Scanner(f);
    while(s.hasNext()) {
        words.add(s.next());
    }
}

At the end of this snipit, data will be filled with lists of words from each file.


问:
Need To Fetch Mails with SentOn Date
I've a below code that throwing up error. I need to fetch only mails that received today(current date). Please help to fix this. My other If cases are working fine. Except that Date (SentOn).

My script works like it fetch the email based on the user given time extract the file and created a consolidated sheet. Am trying fetch mail that received on current date.

```<code>Sub Unzip()
        Dim app As Object
        Dim NS As Object
        Dim InboX As Object
        Dim SubFolder As Object
        Dim MsG As Object
        Dim AtcHmt As Object
        Dim ReceivedHour As Date
        Dim oFrom As Date
        Dim oEnd As Date
        Dim f As Boolean
        '''Variables for unzipping
        Dim FSO As Object
        Dim ShellApp As Object
        Set FSO = CreateObject("Scripting.FileSystemObject")
        Set ShellApp = CreateObject("Shell.Application")
        Dim FileNameFolder As Variant
        Dim FileName As Variant
        Dim Ldate As String
        Dim myitem As Object
        Ldate
        On Error Resume Next
        Set app = GetObject(Class:="Outlook.Application")
        If app Is Nothing Then
            Set app = CreateObject(Class:="Outlook.Application")
            f = True
        End If
        On Error GoTo ErrHandler
        Set NS = app.GetNamespace("MAPI")
        Set InboX = NS.GetDefaultFolder(6) ' olFolderInbox
        Set SubFolder = InboX.Folders("TEST")
        Set myitem = Outlook.mailitem
        FileNameFolder = Environ$("USERPROFILE") & "\Documents\test\"
        oFrom = CDate(InputBox("Please give Start time" & vbCrLf & _
                                "Example: 9AM", ("Shadowserver report"), "9AM"))
        oEnd = CDate(InputBox("Please give End time" & vbCrLf & _
                                "Example: 6PM", ("Shadowserver report"), "6PM"))

        For Each MsG In SubFolder.Items
        If Ldate = DateValue(myitem.SentOn) Then
            MsG ("Yes")
            ReceivedHour = MsG.ReceivedTime
            If oFrom <= TimeValue(ReceivedHour) And _
                TimeValue(ReceivedHour) <= oEnd Then
                For Each AtcHmt In MsG.Attachments
                    FileName = AtcHmt.FileName
                    If LCase(Right(FileName, 3)) = "zip" Then
                        FileName = FileNameFolder & FileName
                        AtcHmt.SaveAsFile FileName

                        ShellApp.Namespace(FileNameFolder).CopyHere _
                                ShellApp.Namespace(FileName).Items

                        Kill FileName
                        On Error Resume Next
                        FSO.Deletefolder Environ$("Temp") & "\Temporary Directory*", True
                    End If
                Next AtcHmt
            End If
        End If
        Next MsG
    End Sub
</code>```

答:
Hi This is how i driven down to answer</p>

```<code>Dim Ldate As String

    Ldate = Date

    '''Define the Outlook folder you want to scan
    On Error Resume Next
    Set app = GetObject(Class:="Outlook.Application")
    If app Is Nothing Then
        Set app = CreateObject(Class:="Outlook.Application")
        f = True
    End If
    On Error GoTo ErrHandler
    Set NS = app.GetNamespace("MAPI")
    Set InboX = NS.PickFolder
    'Set SubFolder = InboX.Folders("Shadow Server Reports")
    'Dim myitem As Outlook.MailItems
    '''Define the folder where you want to save attachments
    FileNameFolder = Environ$("USERPROFILE") & "\Documents\test\"

    '''Define the hours in between which you want to apply the extraction
    oFrom = CDate(InputBox("Please give Start time" & vbCrLf & _
                            "Example: 9AM", ("Shadowserver report"), "9AM"))
    oEnd = CDate(InputBox("Please give End time" & vbCrLf & _
                            "Example: 6PM", ("Shadowserver report"), "6PM"))

    For Each MsG In InboX.Items
    If Ldate = DateValue(MsG.SentOn) Then
        ReceivedHour = MsG.ReceivedTime
        If oFrom <= TimeValue(ReceivedHour) And _
            TimeValue(ReceivedHour) <= oEnd Then
            For Each AtcHmt In MsG.Attachments
</code>```

Title: Need To Fetch Mails with SentOn Date

Body:
I've a below code that throwing up error. I need to fetch only mails that received today(current date). Please help to fix this. My other If cases are working fine. Except that Date (SentOn).

My script works like it fetch the email based on the user given time extract the file and created a consolidated sheet. Am trying fetch mail that received on current date.

Sub Unzip()
        Dim app As Object
        Dim NS As Object
        Dim InboX As Object
        Dim SubFolder As Object
        Dim MsG As Object
        Dim AtcHmt As Object
        Dim ReceivedHour As Date
        Dim oFrom As Date
        Dim oEnd As Date
        Dim f As Boolean
        '''Variables for unzipping
        Dim FSO As Object
        Dim ShellApp As Object
        Set FSO = CreateObject("Scripting.FileSystemObject")
        Set ShellApp = CreateObject("Shell.Application")
        Dim FileNameFolder As Variant
        Dim FileName As Variant
        Dim Ldate As String
        Dim myitem As Object
        Ldate
        On Error Resume Next
        Set app = GetObject(Class:="Outlook.Application")
        If app Is Nothing Then
            Set app = CreateObject(Class:="Outlook.Application")
            f = True
        End If
        On Error GoTo ErrHandler
        Set NS = app.GetNamespace("MAPI")
        Set InboX = NS.GetDefaultFolder(6) ' olFolderInbox
        Set SubFolder = InboX.Folders("TEST")
        Set myitem = Outlook.mailitem
        FileNameFolder = Environ$("USERPROFILE") & "\Documents\test\"
        oFrom = CDate(InputBox("Please give Start time" & vbCrLf & _
                                "Example: 9AM", ("Shadowserver report"), "9AM"))
        oEnd = CDate(InputBox("Please give End time" & vbCrLf & _
                                "Example: 6PM", ("Shadowserver report"), "6PM"))

        For Each MsG In SubFolder.Items
        If Ldate = DateValue(myitem.SentOn) Then
            MsG ("Yes")
            ReceivedHour = MsG.ReceivedTime
            If oFrom <= TimeValue(ReceivedHour) And _
                TimeValue(ReceivedHour) <= oEnd Then
                For Each AtcHmt In MsG.Attachments
                    FileName = AtcHmt.FileName
                    If LCase(Right(FileName, 3)) = "zip" Then
                        FileName = FileNameFolder & FileName
                        AtcHmt.SaveAsFile FileName

                        ShellApp.Namespace(FileNameFolder).CopyHere _
                                ShellApp.Namespace(FileName).Items

                        Kill FileName
                        On Error Resume Next
                        FSO.Deletefolder Environ$("Temp") & "\Temporary Directory*", True
                    End If
                Next AtcHmt
            End If
        End If
        Next MsG
    End Sub

Body:
Hi This is how i driven down to answer

Dim Ldate As String

    Ldate = Date

    '''Define the Outlook folder you want to scan
    On Error Resume Next
    Set app = GetObject(Class:="Outlook.Application")
    If app Is Nothing Then
        Set app = CreateObject(Class:="Outlook.Application")
        f = True
    End If
    On Error GoTo ErrHandler
    Set NS = app.GetNamespace("MAPI")
    Set InboX = NS.PickFolder
    'Set SubFolder = InboX.Folders("Shadow Server Reports")
    'Dim myitem As Outlook.MailItems
    '''Define the folder where you want to save attachments
    FileNameFolder = Environ$("USERPROFILE") & "\Documents\test\"

    '''Define the hours in between which you want to apply the extraction
    oFrom = CDate(InputBox("Please give Start time" & vbCrLf & _
                            "Example: 9AM", ("Shadowserver report"), "9AM"))
    oEnd = CDate(InputBox("Please give End time" & vbCrLf & _
                            "Example: 6PM", ("Shadowserver report"), "6PM"))

    For Each MsG In InboX.Items
    If Ldate = DateValue(MsG.SentOn) Then
        ReceivedHour = MsG.ReceivedTime
        If oFrom <= TimeValue(ReceivedHour) And _
            TimeValue(ReceivedHour) <= oEnd Then
            For Each AtcHmt In MsG.Attachments


问:
How to use PreparedAsync In ExoPlayer
I have an application that uses ExoPlayer. But it's done so before the start, I need to know Prepared is already ready or not.

I can not find PreparedAsync in ExoPlayer. Therefore, the application crashes

Running and training is 2 different things.

I need to find out when the preparation is over, To get the length of the video track.

I need any suggestions. Already 4 days I rack my brains. Help Developers ((

答:
You can try out the following code :</p>

```<code>// Measures bandwidth during playback. Can be null if not required.
        DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
// Produces DataSource instances through which media data is loaded.
        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this,
                Util.getUserAgent(this, "com.yourapp.appname"), bandwidthMeter);
// Produces Extractor instances for parsing the media data.
        ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
// This is the MediaSource representing the media to be played.
        MediaSource videoSource = new ExtractorMediaSource(uri,
                dataSourceFactory, extractorsFactory, null, null);
// Prepare the player with the source.
        exoPlayer.prepare(videoSource);
</code>```

Title: How to use PreparedAsync In ExoPlayer

Body:
You can try out the following code :

// Measures bandwidth during playback. Can be null if not required.
        DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
// Produces DataSource instances through which media data is loaded.
        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this,
                Util.getUserAgent(this, "com.yourapp.appname"), bandwidthMeter);
// Produces Extractor instances for parsing the media data.
        ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
// This is the MediaSource representing the media to be played.
        MediaSource videoSource = new ExtractorMediaSource(uri,
                dataSourceFactory, extractorsFactory, null, null);
// Prepare the player with the source.
        exoPlayer.prepare(videoSource);


问:
I have an input form with a prepaired statement that should input into sql and print the input but all I get is NULL printed on the page
I have an input form with a prepaired statement that should input into sql and print the input but all I get is a blank page with the input php address. Have i missed something? I have changed the code to below but all that appears is NULL. The date field is sql type date and the string i entered into it to test is "2008-11-11", without the quotes of course.

```<code>        <?php
function shutdown(){
  var_dump(error_get_last());
}

register_shutdown_function('shutdown');
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include("dbconfig.php");
$errorvar = "";
if (isset($_POST['submit'])) {
    if (empty($_POST['Title']) || empty($_POST["Date"]) || empty($_POST["Country"]) || empty($_POST["bloguser"]) || empty($_POST["Blogentry"])) {
        $errorvar = "You dun gooffed";
        echo $errorvar;
    } else {
        //defining and injection protecting data
        $title = $_POST['Title'];
        $date = $_POST['Date'];
        $country = $_POST['Country'];
        $bloguser = $_POST['bloguser'];
        $blogentry = $_POST['Blogentry'];

    $stmt = $mysqli->prepare("INSERT INTO blogs (BlogName,blogDate,country,bloguser,Blogdata) VALUES (?,?,?,?,?)");

        $stmt->bind_param('sssss', $title, $date, $country, $bloguser, $blogentry);

        if ($stmt->execute()) {
            echo "New records created successfully";
            printf("%d Row inserted.\n", $stmt->affected_rows);
            header("location:index.php");
        } else {
        header("location:index.php");
            echo $conn->error;
        }
        $stmt->close();
        $conn->close();
        header("location:index.php");
    }
}
?>
</code>```

The html form is below

```<code>   <fieldset style="width:45%"><legend>Blog data entry</legend>
        <form name="Blogentry" action="Inputform.php" method="POST">
            <label for="Title">Title: </label>
            <input type="text" name="Title" value="" size="40"/><br>
            <label for="Date">Date: </label>
            <input type="text" name="Date" value="" size="40"/><br>
            <label for="Country">Country: </label>
            <input type="text" name="Country" value="" size="40"/><br>
            <label for="bloguser">User: </label>
            <input type="text" name="bloguser" value="" size="40"/><br>
            <label for="Blogentry">Blog: </label>
            <textarea name="Blogentry" rows="4" cols="20">
            </textarea><br>
            <input id="button" type="submit" name="submitblog" value="submit-blog">
        </form>
            </fieldset>
    </body>
</html>
</code>```

答:
you don't need to escape anything since you are using bind
so drop the mysqli_real_escape

you have errors in your query as I point out in the code below

```<code>    $stmt = $mysqli->prepare("INSERT INTO blogs (BlogName,blogDate,country,bloguser,Blogdata) VALUES (?,?,?,?,?)");
    // question marks will be replaced with data - use question marks!
        $stmt->bind_param('sssss', $title, $date, $country, $bloguser, $blogentry);
    // number of bound parameters should match number and order of question marks

        $stmt->execute();
</code>```

Body:
I have an input form with a prepaired statement that should input into sql and print the input but all I get is a blank page with the input php address. Have i missed something? I have changed the code to below but all that appears is NULL. The date field is sql type date and the string i entered into it to test is "2008-11-11", without the quotes of course.

        <?php
function shutdown(){
  var_dump(error_get_last());
}

register_shutdown_function('shutdown');
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include("dbconfig.php");
$errorvar = "";
if (isset($_POST['submit'])) {
    if (empty($_POST['Title']) || empty($_POST["Date"]) || empty($_POST["Country"]) || empty($_POST["bloguser"]) || empty($_POST["Blogentry"])) {
        $errorvar = "You dun gooffed";
        echo $errorvar;
    } else {
        //defining and injection protecting data
        $title = $_POST['Title'];
        $date = $_POST['Date'];
        $country = $_POST['Country'];
        $bloguser = $_POST['bloguser'];
        $blogentry = $_POST['Blogentry'];

    $stmt = $mysqli->prepare("INSERT INTO blogs (BlogName,blogDate,country,bloguser,Blogdata) VALUES (?,?,?,?,?)");

        $stmt->bind_param('sssss', $title, $date, $country, $bloguser, $blogentry);

        if ($stmt->execute()) {
            echo "New records created successfully";
            printf("%d Row inserted.\n", $stmt->affected_rows);
            header("location:index.php");
        } else {
        header("location:index.php");
            echo $conn->error;
        }
        $stmt->close();
        $conn->close();
        header("location:index.php");
    }
}
?>

The html form is below

   <fieldset style="width:45%"><legend>Blog data entry</legend>
        <form name="Blogentry" action="Inputform.php" method="POST">
            Title:
            <input type="text" name="Title" value="" size="40"/>

            Date:
            <input type="text" name="Date" value="" size="40"/>

            Country:
            <input type="text" name="Country" value="" size="40"/>

            User:
            <input type="text" name="bloguser" value="" size="40"/>

            Blog:
            <textarea name="Blogentry" rows="4" cols="20">
            </textarea>

            <input id="button" type="submit" name="submitblog" value="submit-blog">
        </form>
            </fieldset>

Body:
you don't need to escape anything since you are using bind
so drop the mysqli_real_escape

you have errors in your query as I point out in the code below

    $stmt = $mysqli->prepare("INSERT INTO blogs (BlogName,blogDate,country,bloguser,Blogdata) VALUES (?,?,?,?,?)");
    // question marks will be replaced with data - use question marks!
        $stmt->bind_param('sssss', $title, $date, $country, $bloguser, $blogentry);
    // number of bound parameters should match number and order of question marks

        $stmt->execute();


问:
MySQL using "-" as different
It's not really a question, I already found out the answer the hard way.
The problem is with the following query.

```<code>delete from <table> where id - 145;
</code>```

Having minus instead of equals was clearly a typo. The database's autocommit was turned on and I ended up deleting all the entries in the table except those with the id = 145. So the minus over there acted as a "not equal" operator.

I searched for similar situations and looked for this operator in the MySQL docs and I couldn't find anything.

Is this supposed to happen this way? Is it normal or a MySQL bug?

答:
This is perfectly as expected.

Consider the following queries:

```<code>delete from <table>;
delete from <table> where true;
delete from <table> where 1;
</code>```

If you follow these, you can understand that any number not 0 is considered truthy. And 0 is considered falsy. So also:

```<code>delete from <table> where 3;
delete from <table> where 50;
delete from <table> where -1;
</code>```

All these queries will delete everything in the table.

Now in your query, you do did id - 145. This will return a non-zero for every row, except for the row with id 145, simply because 145 - 145 = 0.

That is why everything got deleted except the row with id 145.

Title: MySQL using "-" as different

Body:
It's not really a question, I already found out the answer the hard way.
The problem is with the following query.

delete from
 where id - 145;

Having minus instead of equals was clearly a typo. The database's autocommit was turned on and I ended up deleting all the entries in the table except those with the id = 145. So the minus over there acted as a "not equal" operator.

I searched for similar situations and looked for this operator in the MySQL docs and I couldn't find anything.

Is this supposed to happen this way? Is it normal or a MySQL bug?

Body:
This is perfectly as expected.

Consider the following queries:

delete from <table>;
delete from <table> where true;
delete from <table> where 1;

If you follow these, you can understand that any number not 0 is considered truthy. And 0 is considered falsy. So also:

delete from <table> where 3;
delete from <table> where 50;
delete from <table> where -1;

All these queries will delete everything in the table.

Now in your query, you do did id - 145. This will return a non-zero for every row, except for the row with id 145, simply because 145 - 145 = 0.

That is why everything got deleted except the row with id 145.


问:
Vectorizing multi categorical data with pandas
Hej, I'm trying to vectorize items that can belong to multiple categories and put them into a pandas dataframe. I already came up with a solution but it's very slow. So here's what I'm doing:

That's how my data looks like:

```<code>data = {
    'A':['c1','c2','c3'],
    'B':['c4','c5','c2'],
    'C':['c2','c1','c4']
}
</code>```

I have three items (A-C) that belong to five different categories (c1-c5).

So I create a an empty dataframe, iterate over the items turn them into boolean Series objects with the right index and append them:

```<code>df = pd.SparseDataFrame()
for k, v in data.items():
    s = pd.Series(np.ones_like(v, dtype=bool), index=v, name=k)
    df = df.append(s)
</code>```

My result looks like this:

Resulting Dataframe

I'm happy with this result but my real data has ~200k categories which makes this approach horribly slow. Do you have any suggestions how to speed up?

Remark: Extracting all categories and passing them as columns into the empty Dataframe doesn't help:

```<code>df = pd.SparseDataFrame(columns=all_categories)
</code>```

答:
You could try (source):

```<code>df = pd.DataFrame.from_dict(data, orient='index')
</code>```

and then

```<code>res = df.stack().reset_index().groupby(['level_0', 0]).size().unstack()
</code>```

Finally you can cast the output to a SparseDataFrame

```<code>result = pd.SparseDataFrame(res)
</code>```

With df.stack() you have :

```<code>A  0    c1
   1    c2
   2    c3
B  0    c4
   1    c5
   2    c2
C  0    c2
   1    c1
   2    c4
</code>```

Then you do the reset_index:

```<code>  level_0  level_1   0
0       A        0  c1
1       A        1  c2
2       A        2  c3
3       B        0  c4
4       B        1  c5
5       B        2  c2
6       C        0  c2
7       C        1  c1
8       C        2  c4
</code>```

You could change the column names to be cleaner.
The group by method make the count :

```<code>level_0  0
A        c1    1
         c2    1
         c3    1
B        c2    1
         c4    1
         c5    1
C        c1    1
         c2    1
         c4    1
</code>```

And finally :

```<code>0         c1   c2   c3   c4   c5
level_0
A        1.0  1.0  1.0  NaN  NaN
B        NaN  1.0  NaN  1.0  1.0
C        1.0  1.0  NaN  1.0  NaN
</code>```

Body:
Hej, I'm trying to vectorize items that can belong to multiple categories and put them into a pandas dataframe. I already came up with a solution but it's very slow. So here's what I'm doing:

That's how my data looks like:

data = {
    'A':['c1','c2','c3'],
    'B':['c4','c5','c2'],
    'C':['c2','c1','c4']
}

I have three items (A-C) that belong to five different categories (c1-c5).

So I create a an empty dataframe, iterate over the items turn them into boolean Series objects with the right index and append them:

df = pd.SparseDataFrame()
for k, v in data.items():
    s = pd.Series(np.ones_like(v, dtype=bool), index=v, name=k)
    df = df.append(s)

My result looks like this:

Resulting Dataframe

I'm happy with this result but my real data has ~200k categories which makes this approach horribly slow. Do you have any suggestions how to speed up?

Remark: Extracting all categories and passing them as columns into the empty Dataframe doesn't help:

df = pd.SparseDataFrame(columns=all_categories)

Body:
You could try (source):

df = pd.DataFrame.from_dict(data, orient='index')

and then

res = df.stack().reset_index().groupby(['level_0', 0]).size().unstack()

Finally you can cast the output to a SparseDataFrame

result = pd.SparseDataFrame(res)

With df.stack() you have :

A  0    c1
   1    c2
   2    c3
B  0    c4
   1    c5
   2    c2
C  0    c2
   1    c1
   2    c4

Then you do the reset_index:

  level_0  level_1   0
0       A        0  c1
1       A        1  c2
2       A        2  c3
3       B        0  c4
4       B        1  c5
5       B        2  c2
6       C        0  c2
7       C        1  c1
8       C        2  c4

You could change the column names to be cleaner.
The group by method make the count :

level_0  0
A        c1    1
         c2    1
         c3    1
B        c2    1
         c4    1
         c5    1
C        c1    1
         c2    1
         c4    1

And finally :

0         c1   c2   c3   c4   c5
level_0
A        1.0  1.0  1.0  NaN  NaN
B        NaN  1.0  NaN  1.0  1.0
C        1.0  1.0  NaN  1.0  NaN


问:
How to get network provided date and time without internet connection?
I want to use network provided date and time in my android application even if network date and time is disable in device setting and there is no internet connectivity. Is there any possibility or any solution?

I referred this question but I didn't get perfect solution.

答:
Add permission

```<code><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
</code>```

Check permission if ok get time.

```<code>     LocationManager locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
         if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
    }
    Location location=locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    if(location!=null){
        long time = location.getTime();
    }
</code>```

Body:
Add permission

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Check permission if ok get time.

     LocationManager locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
         if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
    }
    Location location=locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    if(location!=null){
        long time = location.getTime();
    }


问:
how to pass variable value to href attribute using javascript or jquery?
I'm trying to use JavaScript random function for pass the different value to href attribute
this is my code but it's not the jQuery part is not working:

jQuery:-

```<code>var numbers = ["22332233", "44455566", "12322122", "44455566", "12322122", "44455566", "12322122"];
var result = Math.floor(Math.random() * 5);
console.log(result);
console.log(numbers[result]);
$("#phone-tel").attr("href", numbers[result]);
</code>```

HTML:-

```<code><a id="phone-tel" href="">+353123456789</a>
</code>```

答:
Your code work fine,if:-

1.jQuery library added before your script code.

2.Wrap your script code inside $(document).ready(function(){..});,if it is on top of your page. If script code is on bottom of the page then wrapping is not necessary.

Working example:-

$(document).ready(function(){
  var numbers = ["22332233", "44455566", "12322122", "44455566", "12322122", "44455566", "12322122"];
  var result = Math.floor(Math.random() * 5);
  console.log(result);
  $("#phone-tel").attr("href",numbers[result]);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
+353123456789</code>```

Body:
I'm trying to use JavaScript random function for pass the different value to href attribute
this is my code but it's not the jQuery part is not working:

jQuery:-

var numbers = ["22332233", "44455566", "12322122", "44455566", "12322122", "44455566", "12322122"];
var result = Math.floor(Math.random() * 5);
console.log(result);
console.log(numbers[result]);
$("#phone-tel").attr("href", numbers[result]);

HTML:-

+353123456789

Body:
Your code work fine,if:-

1.jQuery library added before your script code.

2.Wrap your script code inside $(document).ready(function(){..});,if it is on top of your page. If script code is on bottom of the page then wrapping is not necessary.

Working example:-

$(document).ready(function(){
  var numbers = ["22332233", "44455566", "12322122", "44455566", "12322122", "44455566", "12322122"];
  var result = Math.floor(Math.random() * 5);
  console.log(result);
  $("#phone-tel").attr("href",numbers[result]);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="phone-tel" href="">+353123456789</a>


问:
ec2 stop working aws suddenly
I create t2.micro EC2 instance Amazon Linux AMI, then start to upload my work on it, I'm using WordPress. it's was working perfectly but just after I Install "woocommerce" & "woocommerce subcribe" plugins, the instance stopped working I can't log using FileZilla or SSH. If I disassociate and Re-associate the Elastic IP address to EC2 instance and reboot the instance start working. but when I try to test the "woocommerce" plugin by buying a product in my website, the instance fall again. The CPU Utilization of the instance doesn't go high than 30% </p>

答:
As you said in your comment

I see the "HTTP ERROR 503" in browser

So if you see 503 then it means the server is currently unable to handle the request due to a temporary overloading or maintenance of the server. Check if anything is causing it to be in some infinite loop or getting it stuck for some resource. But in this case I would primarily doubt the application rather than the infrastructure

Title: ec2 stop working aws suddenly


问:
How to get text inside href?
I'm trying to get the text inside an href link, in particular I've this:

```<code><a href="/matches/2015/02/07/italy/serie-a/juventus-fc/ac-milan/1836527/" class="form-icon form-win " title="Juventus - Milan 3 - 1">W</a>
</code>```

So I made this regex:

```<code>.giornata_1_casa_flag = Regex.Match(Casa_Rgx(0).Value, "/<a [^>]*href=""?([^"">]+)""?>/").Groups(2).ToString
</code>```

the pattern, however, don't get any value. I'm waiting a result like: W.
This character allow me to execute many control.

答:
using jQuery</p>

```<code>var link = "<a href=''>Text link</a>"
var textLink = $(link).text();
</code>```

Title: How to get text inside href?

Body:
I'm trying to get the text inside an href link, in particular I've this:

W

So I made this regex:

.giornata_1_casa_flag = Regex.Match(Casa_Rgx(0).Value, "/]*href=""?([^"">]+)""?>/").Groups(2).ToString

the pattern, however, don't get any value. I'm waiting a result like: W.
This character allow me to execute many control.

Body:
using jQuery

var link = "<a href=''>Text link</a>"
var textLink = $(link).text();


问:
How to execute shell script by double clicking in centos?
As the tile,I have a shell script needs to run every time I have to open a terminal and type "./ xxx.sh"  .it is annoying when it gets too frequent now how do I execute by double clicking like the way you do it in windows?

I know there is an option just for that in Ubuntu but I can't see that here in CentOS.

答:
I did a little bit of digging up and found these two links. Let me know if they were helpful
https://askubuntu.com/questions/286621/how-do-i-run-executable-scripts-in-nautilus
https://unix.stackexchange.com/questions/189777/how-to-launch-shell-script-with-double-click-in-centos-7

The first link is an askUbuntu link I know. But gnome uses nautilus as the file explorer program.

In my arch linux installation where I am running a cinnamon desktop environment, I just had to add a shebang (#!/usr/bin/bash) at the head of the file and use chmod to make the file an executable and I could run the script from by double clicking on it. I hope you have already tried this?


问:
(CSP) connect-src https://nikkomsgchannel
Hope someone can shed some light on this because I have searched for months for an answer but to no avail.

I use a Content Security Policy on all my sites and record policy violations but constantly see attempts using connect-src for https://nikkomsgchannel

The entries look like this:

```<code>https://nikkomsgchannel/e?001600500058005b00330035006f0050002d0059005c005f005c00090051004
</code>```

Does anyone else see this in their CSP violations?
What is nikkomsgchannel?
Should it be allowed connect-src access?

Thanks in advance.

答: Requests to nikkomsgchannel appear to be due to a browser extension related to Trusteer Rapport [1][2]. Do not add it to connect-src as you have no control over what content gets injected. Just ignore it in your CSP reports.

Body:
Hope someone can shed some light on this because I have searched for months for an answer but to no avail.

I use a Content Security Policy on all my sites and record policy violations but constantly see attempts using connect-src for https://nikkomsgchannel

The entries look like this:

https://nikkomsgchannel/e?001600500058005b00330035006f0050002d0059005c005f005c00090051004

Does anyone else see this in their CSP violations?
What is nikkomsgchannel?
Should it be allowed connect-src access?

Thanks in advance.


问:
Partial Specialization of Operator()
One of my classes declares a templated function:

```<code>template<class A, class B>
A do_something(const std::vector<B> &data)
</code>```

which I'd like to partially specialize on typename A. B is a family of types that implement a pretty minimal interface, and we use a lot of them, so I'd like my specialization to be generic on B. I suspect this is doubly vexing as typename A is used only as the return type.

From the internet, I've gleaned that I can't partially specialize a function, so I've created a class as follows:

```<code>template<class A, class B>
class do_something_implementation {
  public:
    do_something_implementation(const std::vector<B> &data_) {
      data = data_;
    }

  int do_something_implementation<int, B>::operator()() {
    /* Complicated algorithm goes here... */
  }

  double do_something_implementation<double, B>::operator()() {
    /* Different complicated algorithm goes here... */
  }

  private:
      std::vector<B> data;
}
</code>```

When I try to compile that (using Visual Studio 2008), the compiler crashes (!) and I get the following error:

```<code>fatal error C1001: An internal error has occurred in the compiler.
</code>```

I assume this is my problem and not the compiler's. Is there a better way to express the partial specialization I'm aiming for?

答:
Now that you've seen the classic forward to static method, there is actually another way when the type for which to specialize is "complete".

You may not be able to partially specialize a function, but you can perfectly overload it.

```<code>template <typename A, typename B>
A do(std::vector<B> const& data) { return this->doImpl(data, (A*)0); }

template <typename A, typename B>
A doImpl(std::vector<B> const& B, A*) { // generic implementation }

template <typename B>
int doImpl(std::vector<B> const& B, int*) { // int implementation }

template <typename B>
double doImpl(std::vector<B> const& B, double*) { // double implementation }
</code>```

The trick is to pass an "unused" argument to doImpl for the sole purpose of actually selecting the right implementation (thanks to overload resolution).

Here I simply chose to pass (A*)0, because this does not involve A's constructor (in case it's non trivial).

This dispatch idiom is what is used in the STL to implement some algorithm with better efficiency for some iterator categories (for example, std::distance is O(1) for random iterators).

I find it much more lightweight that using a helper class with static methods and partial specializations... but maybe that's just me :)

Title: Partial Specialization of Operator()

Body:
One of my classes declares a templated function:

template<class A, class B>
A do_something(const std::vector &data)

which I'd like to partially specialize on typename A. B is a family of types that implement a pretty minimal interface, and we use a lot of them, so I'd like my specialization to be generic on B. I suspect this is doubly vexing as typename A is used only as the return type.

From the internet, I've gleaned that I can't partially specialize a function, so I've created a class as follows:

template<class A, class B>
class do_something_implementation {
  public:
    do_something_implementation(const std::vector &data_) {
      data = data_;
    }

  int do_something_implementation<int, B>::operator()() {
    /* Complicated algorithm goes here... */
  }

  double do_something_implementation<double, B>::operator()() {
    /* Different complicated algorithm goes here... */
  }

  private:
      std::vector data;
}

When I try to compile that (using Visual Studio 2008), the compiler crashes (!) and I get the following error:

fatal error C1001: An internal error has occurred in the compiler.

I assume this is my problem and not the compiler's. Is there a better way to express the partial specialization I'm aiming for?

Body:
Now that you've seen the classic forward to static method, there is actually another way when the type for which to specialize is "complete".

You may not be able to partially specialize a function, but you can perfectly overload it.

template <typename A, typename B>
A do(std::vector<B> const& data) { return this->doImpl(data, (A*)0); }

template <typename A, typename B>
A doImpl(std::vector<B> const& B, A*) { // generic implementation }

template <typename B>
int doImpl(std::vector<B> const& B, int*) { // int implementation }

template <typename B>
double doImpl(std::vector<B> const& B, double*) { // double implementation }

The trick is to pass an "unused" argument to doImpl for the sole purpose of actually selecting the right implementation (thanks to overload resolution).

Here I simply chose to pass (A*)0, because this does not involve A's constructor (in case it's non trivial).

This dispatch idiom is what is used in the STL to implement some algorithm with better efficiency for some iterator categories (for example, std::distance is O(1) for random iterators).

I find it much more lightweight that using a helper class with static methods and partial specializations... but maybe that's just me :)


问:
how to check if bodymovin animation is complete?
I want the to destroy the animation when is complete animating. tried addEventListener that didn't work.

```<code>anim = bodymovin.loadAnimation(params);
animContainer.addEventListener("complete", myScript);

function myScript(){
      anim.destroy();
}
</code>```

答:
The following coded work...</p>

```<code>  anim.addEventListener("complete", function(){
      anim.destroy());
  });
</code>```

Body:
I want the to destroy the animation when is complete animating. tried addEventListener that didn't work.

anim = bodymovin.loadAnimation(params);
animContainer.addEventListener("complete", myScript);

function myScript(){
      anim.destroy();
}

Body:
The following coded work...

  anim.addEventListener("complete", function(){
      anim.destroy());
  });


问:
Using matplots 'axis' command makes my plot disappear
I have a list of prices that I want to plot using matplotlib, and if I just do so, everything is fine. Here is my code:

```<code>def plot_prices_and_events(prices, buy=None, sell=None):
    data = []
    max_price = 0
    min_price = sys.maxint
    values = prices.get_values()
    for price in values:
        current_price = price[1]
        data.append(current_price)
        if current_price > max_price:
            max_price = price[1]
        if current_price < min_price:
            min_price = current_price
    plt.ylabel('Bitcoin price in EUR')
    plt.xlabel('Date')
    start_date = datetime.datetime.fromtimestamp(values[0][0])
    end_date = datetime.datetime.fromtimestamp(values[-1][0])
    plt.plot(data)
    #plt.axis([start_date, end_date, min_price, max_price])
    if buy is not None:
        plt.plot(buy)
    if sell is not None:
        plt.plot(sell)
    plt.show()
</code>```

With the one line commented out, everything is fine:

Yet, if I try to set the scale for the x-axis, thus uncommenting the line, the axis are displayed correctly, but my plot disappears:

This is reproducible on two machines and by commenting and uncommenting the corresponding line. Am I missing something? I have already played around with the order of the commands, I checked the official tutorials and did some googling. The issue does not seem to be too far spread, so I hope for you people.

Thanks in advance and I hope I'm just stupid. ^^

EDIT: The issue is solved, but the solution is partly to be found in the comments. Bottom Line: The prices were not correctly ordered.

答:
As @Dmitri Chubarov said in a comment, by calling plt.plot(data), you are only providing vertical co-ordinates. matplotlib then has to assume that the horizontal co-ordinates are just [0:len(data)].

You later tell it to move the horizontal axis to [start_date, end_date]. However, none of your data points have a horizontal co-ordinate in this range, because the horizontal co-ordinates are [0:len(data)].

You'd have to provide horizontal co-ordinates to your data as well to make this work better. E.g. plt.plot(dates, data), where dates is a list of dates of equal length as data.

Body:
I have a list of prices that I want to plot using matplotlib, and if I just do so, everything is fine. Here is my code:

def plot_prices_and_events(prices, buy=None, sell=None):
    data = []
    max_price = 0
    min_price = sys.maxint
    values = prices.get_values()
    for price in values:
        current_price = price[1]
        data.append(current_price)
        if current_price > max_price:
            max_price = price[1]
        if current_price < min_price:
            min_price = current_price
    plt.ylabel('Bitcoin price in EUR')
    plt.xlabel('Date')
    start_date = datetime.datetime.fromtimestamp(values[0][0])
    end_date = datetime.datetime.fromtimestamp(values[-1][0])
    plt.plot(data)
    #plt.axis([start_date, end_date, min_price, max_price])
    if buy is not None:
        plt.plot(buy)
    if sell is not None:
        plt.plot(sell)
    plt.show()

With the one line commented out, everything is fine:

Yet, if I try to set the scale for the x-axis, thus uncommenting the line, the axis are displayed correctly, but my plot disappears:

This is reproducible on two machines and by commenting and uncommenting the corresponding line. Am I missing something? I have already played around with the order of the commands, I checked the official tutorials and did some googling. The issue does not seem to be too far spread, so I hope for you people.

Thanks in advance and I hope I'm just stupid. ^^

EDIT: The issue is solved, but the solution is partly to be found in the comments. Bottom Line: The prices were not correctly ordered.


问:
How to zip two 1d numpy array to 2d numpy array
I have two numpy 1d arrays, e.g:

```<code>a = np.array([1,2,3,4,5])
b = np.array([6,7,8,9,10])
</code>```

Then how can I get one 2d array [[1,6], [2,7], [3,8], [4,9], [5, 10]]?

Body:
I have two numpy 1d arrays, e.g:

a = np.array([1,2,3,4,5])
b = np.array([6,7,8,9,10])

Then how can I get one 2d array [[1,6], [2,7], [3,8], [4,9], [5, 10]]?

Body:
If you have numpy arrays you can use dstack():

import numpy as np

a = np.array([1,2,3,4,5])
b = np.array([6,7,8,9,10])

c = np.dstack((a,b))
#or
d = np.column_stack((a,b))

>>> c
array([[[ 1,  6],
        [ 2,  7],
        [ 3,  8],
        [ 4,  9],
        [ 5, 10]]])
>>> d
array([[ 1,  6],
       [ 2,  7],
       [ 3,  8],
       [ 4,  9],
       [ 5, 10]])

>>> c.shape
(1, 5, 2)
>>> d.shape
(5, 2)


问:
Are there any JavaScript library for cross browser desktop notification?
I know W3C just publish their draft version of Web Notification to notify user. So, there is no browser that implement this method in their current or latest build browser.

Web Notifications Overview

After I search a lot of webs for finding all possible desktop notification in most browser.I found any 2 major browser that should support this.

1.Google Chrome and Webkit-based browser

(source: google.com)

(source: google.com)

(source: google.com)

We can use native Desktop notification function to show message like the following picture.

More infomation: The Chromium Projects - Desktop Notifications

2.Internet Explorer

For IE 5.5+, we can use createPopup function to notify use like in Google Chrome but it's much flexible more that Google Chrome.

More information: CreatePopup Method on MSDN

Moreover, if we pin website to Windows 7 taskbar, we can use overlay icon to notify user too.

(source: microsoft.com)

More information: IE9, Site Specific Browsers, and adding your own Jump List Items to Pinned Tabs

Other browser

I think we can use Pines Notify jQuery plugin to create in-browser notification.

Or do you have any desktop notification library or idea for suggesting me?

Thanks,

PS. If it does not have fine library, I will create it with myself.

Update I

Since IE8, it does not allow us to display popup outside current browser. For example, when IE is minimized, all popups are not displayed. So, Google Chrome is only one browser that has fully web notification API (FF 4 also has non-documented web notification API but it not work for now).

答:
I don't know of a cross-browser lib; but desktop-notifications are coming to Mozilla Firefox post 4.0 as well.  They're implemented in trunk already: https://bugzilla.mozilla.org/show_bug.cgi?id=573588

Though apparently this new feature won't get included in FF 4.0: https://bugzilla.mozilla.org/show_bug.cgi?id=594543

But in the long term, an api related to but different from the webkit will be available.

Not sure about opera, however.


问:
Sublime Text 2: Error trying to parse settings
How do I fix this error?

Error trying to parse settings: No data in ~/Library/Application
  Support/Sublime Text 2/Packages/User/JavaScript.sublime-settings:1:1

答: Please go to ../Library/Application Support/Sublime Text 2/Packages/User/ location and delete JavaScript.sublime-settings:1:1 file which has been created by you or any process must have created that.This would surely work.</p>


问:
Checkbox in Datagrid MVVM WPF
The View ConfigRole has 2 columns, Name and IsEnabled(checkBox)with Button Edit for every row,

ConfigRole:

** If CheckBox is TRUE for a Row in ConfigRole View,when I click on Edit Button I get new View Button_Lists which has 2 columns Name_Button and IsEnabled(CheckBox)...and I modify TRUe or FALSe for every IsEnabled.

**My objectif is : When IsEnabled ConfigRole is FALSE, I want to get all the IsEnabled Button_Lists default to FALSE,

ButtonList:

this is my try code in Button_Lists Model:

```<code> // get all of ButtonsList
 public ObservableCollection<ButtonRoleMapClass> ButtonList
    {
        get { return _buttonList; }
        set
        {
            _buttonList = value;
            OnPropertyChanged("ButtonList");
        }
    }

    //viewRoleButton: the Name of selected row in ConfigRole
     public ButtonListViewModel(ViewRoleMapClass viewRoleButton)
    {

        //If IsEnabled for row in ConfigRole is FALSE
        if (viewRoleButton.IsEnabled==false)
        {
            ObservableCollection<ButtonRoleMapClass> butsList = new ObservableCollection<ButtonRoleMapClass>();
            foreach (ButtonRoleMapClass button in _buttonList)
            {
                button.IsEnabled = false;
                butsList.Add(button);
            }
            _buttonList = butsList;
        }
</code>```

I want to get all CheckBox in Datagrid for View Button_Lists default is FALSE,

But with my code, I have this  Error:

How can I fix it?

答:
Make sure that you have initialized the _buttonList by adding an if statement that check whether _buttonList is null. If you get rid of the exception, you know that the ObservableCollection hasn't been initialized

You probably also want to set the ButtonList property to the new collection:

```<code>public ButtonListViewModel(ViewRoleMapClass viewRoleButton)
{
    //If IsEnabled for row in ConfigRole is FALSE
    if (viewRoleButton.IsEnabled == false)
    {
        ObservableCollection<ButtonRoleMapClass> butsList = new ObservableCollection<ButtonRoleMapClass>();
        if (_buttonList != null)
        {
            foreach (ButtonRoleMapClass button in _buttonList)
            {
                button.IsEnabled = false;
                butsList.Add(button);
            }
        }
        ButtonList = butsList;
    }
}
</code>```

Title: Checkbox in Datagrid MVVM WPF

Body:
The View ConfigRole has 2 columns, Name and IsEnabled(checkBox)with Button Edit for every row,

ConfigRole:

** If CheckBox is TRUE for a Row in ConfigRole View,when I click on Edit Button I get new View Button_Lists which has 2 columns Name_Button and IsEnabled(CheckBox)...and I modify TRUe or FALSe for every IsEnabled.

**My objectif is : When IsEnabled ConfigRole is FALSE, I want to get all the IsEnabled Button_Lists default to FALSE,

ButtonList:

this is my try code in Button_Lists Model:

 // get all of ButtonsList
 public ObservableCollection<ButtonRoleMapClass> ButtonList
    {
        get { return _buttonList; }
        set
        {
            _buttonList = value;
            OnPropertyChanged("ButtonList");
        }
    }

    //viewRoleButton: the Name of selected row in ConfigRole
     public ButtonListViewModel(ViewRoleMapClass viewRoleButton)
    {

        //If IsEnabled for row in ConfigRole is FALSE
        if (viewRoleButton.IsEnabled==false)
        {
            ObservableCollection<ButtonRoleMapClass> butsList = new ObservableCollection<ButtonRoleMapClass>();
            foreach (ButtonRoleMapClass button in _buttonList)
            {
                button.IsEnabled = false;
                butsList.Add(button);
            }
            _buttonList = butsList;
        }

I want to get all CheckBox in Datagrid for View Button_Lists default is FALSE,

But with my code, I have this  Error:

How can I fix it?

Body:
Make sure that you have initialized the _buttonList by adding an if statement that check whether _buttonList is null. If you get rid of the exception, you know that the ObservableCollection hasn't been initialized

You probably also want to set the ButtonList property to the new collection:

public ButtonListViewModel(ViewRoleMapClass viewRoleButton)
{
    //If IsEnabled for row in ConfigRole is FALSE
    if (viewRoleButton.IsEnabled == false)
    {
        ObservableCollection<ButtonRoleMapClass> butsList = new ObservableCollection<ButtonRoleMapClass>();
        if (_buttonList != null)
        {
            foreach (ButtonRoleMapClass button in _buttonList)
            {
                button.IsEnabled = false;
                butsList.Add(button);
            }
        }
        ButtonList = butsList;
    }
}


答:
jQuery library is missing in your code

By adding jquery library, every thing is working fine with your code. The only issue is, there are only 7 element in the array. So most of th times random number generates the last generated number again and again. To remove this, hold the last value and generate the value other than that.

Title: how to pass variable value to href attribute using javascript or jquery?


问:
VarBinary vs Image SQL Server Data Type to Store Binary Data?
I need to store binary files to the SQL Server Database. Which is the better Data Type out of Varbinary and Image?</p>

答:
Since image is deprecated, you should use varbinary.

per Microsoft (thanks for the link @Christopher)

ntext , text, and image data types will be removed in a future
  version of Microsoft SQL Server. Avoid using these data types in new
  development work, and plan to modify applications that currently use
  them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

Fixed and variable-length data types for storing large non-Unicode and
  Unicode character and binary data. Unicode data uses the UNICODE UCS-2
  character set.

OwnerDisplayName: Yoann. B

OwnerDisplayName: cmsjr

LastEditorDisplayName: cmsjr