问:
Calling function object returned doesn't show same results? Python3.x
Why the calls to f()() not the same as h=f() then h()

when the id's are the same for f() and h?

Python program:

```<code>def f():
  c = [0]
  def g():
    c[0] += 1
    return c[0]
  return g

print (id(f()), id(f()))
print (f()(), f()())

h = f()
print (id(h))
print (h(), h())
</code>```

Output:

```<code>140383530386568 140383530386568
1 1
140383530386568
1 2
</code>```

EDIT:

and why does the value of c persist???

答:
There is a concept closure in python.

When you call f, the returned object contains an __closure__ attribute.
You can check it by calling h.__closure__, and in your case you can get
c by calling h.__closure__[0].cell_contents.

A closure is function that retains the bindings of the free variables that exist when the function is defined, so that they can be used later when the function is invoked and the defining scope is no longer available. -- Fluent Python

Body:
Why the calls to f()() not the same as h=f() then h()

when the id's are the same for f() and h?

Python program:

def f():
  c = [0]
  def g():
    c[0] += 1
    return c[0]
  return g

print (id(f()), id(f()))
print (f()(), f()())

h = f()
print (id(h))
print (h(), h())

Output:

140383530386568 140383530386568
1 1
140383530386568
1 2

EDIT:

and why does the value of c persist???


来源: stackexchange

问:
matweb.com: How to get source of page?
I have url like:

http://www.matweb.com/search/DataSheet.aspx?MatGUID=849e2916ab1541be9ff6a17b78f95c82

I want to download source code from that page using this code:

```<code>private static string urlTemplate = @"http://www.matweb.com/search/DataSheet.aspx?MatGUID=";

static string GetSource(string guid)
{
    try
    {
        Uri url = new Uri(urlTemplate + guid);

        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.Method = "GET";

        HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

        Stream responseStream = webResponse.GetResponseStream();
        StreamReader responseStreamReader = new StreamReader(responseStream);
        String result = responseStreamReader.ReadToEnd();

        return result;
    }
    catch (Exception ex)
    {
        return null;
    }
}
</code>```

When I do so I get:

You do not seem to have cookies enabled. MatWeb Requires cookies to be enabled.

Ok, that I understand, so I added lines:

```<code>CookieContainer cc = new CookieContainer();
webRequest.CookieContainer = cc;
</code>```

I got:

Your IP Address has been restricted due to excessive use. The problem may be compounded when an IP address may be shared by many people in a company or through an internet service provider. We apologize for any inconvenience.

I can understand this but I'm not getting this message when I try to visit this page using web browser. What can I do to get the source code? Some cookies or http headers?

答:
You are downloading pages too fast.

When you use a browser you might get up to one page per second. Using a application you can get several pages per second and that's probably what their web server is detecting. Hence the excessive usage.

ContentLicense: CC BY-SA 2.5

Title: matweb.com: How to get source of page?

Body:
I have url like:

http://www.matweb.com/search/DataSheet.aspx?MatGUID=849e2916ab1541be9ff6a17b78f95c82

I want to download source code from that page using this code:

private static string urlTemplate = @"http://www.matweb.com/search/DataSheet.aspx?MatGUID=";

static string GetSource(string guid)
{
    try
    {
        Uri url = new Uri(urlTemplate + guid);

        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.Method = "GET";

        HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

        Stream responseStream = webResponse.GetResponseStream();
        StreamReader responseStreamReader = new StreamReader(responseStream);
        String result = responseStreamReader.ReadToEnd();

        return result;
    }
    catch (Exception ex)
    {
        return null;
    }
}

When I do so I get:

You do not seem to have cookies enabled. MatWeb Requires cookies to be enabled.

Ok, that I understand, so I added lines:

CookieContainer cc = new CookieContainer();
webRequest.CookieContainer = cc;

I got:

Your IP Address has been restricted due to excessive use. The problem may be compounded when an IP address may be shared by many people in a company or through an internet service provider. We apologize for any inconvenience.

I can understand this but I'm not getting this message when I try to visit this page using web browser. What can I do to get the source code? Some cookies or http headers?


答:
To answer your second question, the reason for the inner function remembering the value of c is due to a concept in python called function closures.

```<code>>>> def print_msg(msg):
...     def foo():
...         print(msg)
...     return foo
...
>>> f = print_msg('hello')
>>> f()
hello
</code>```

This value in the enclosing scope is remembered even when the variable goes out of scope or the function itself is removed from the current namespace.

You may view the contents of your function's closure by accessing it's __closure__ hook: f._closure__[0].cell_contents.

To answer your first question, when you call f()() twice, you create and return the function on the fly. So each time the function is recreated with a fresh version c. The second time, when you assign it to a variable h, you keep a reference to the inner function, and so the value of c is retained because of why I mentioned earlier. So the second time you call that same function, c[0]'s value is incremented.

ContentLicense: CC BY-SA 3.0

Title: Calling function object returned doesn't show same results? Python3.x

Body:
To answer your second question, the reason for the inner function remembering the value of c is due to a concept in python called function closures.

>>> def print_msg(msg):
...     def foo():
...         print(msg)
...     return foo
...
>>> f = print_msg('hello')
>>> f()
hello

This value in the enclosing scope is remembered even when the variable goes out of scope or the function itself is removed from the current namespace.

You may view the contents of your function's closure by accessing it's __closure__ hook: f._closure__[0].cell_contents.

To answer your first question, when you call f()() twice, you create and return the function on the fly. So each time the function is recreated with a fresh version c. The second time, when you assign it to a variable h, you keep a reference to the inner function, and so the value of c is retained because of why I mentioned earlier. So the second time you call that same function, c[0]'s value is incremented.


问:
Create Assembly is successful, nothing found in sys.assembly_modules
First attempt at a CLR Integration, so I can use Regex tools.

I create the assembly:

```<code>CREATE ASSEMBLY SQLRegexTools
  FROM 'D:\CODE\SQLRegexTools\SQLRegexTools\bin\Release\SQLRegexTools.dll'
</code>```

This succeeds, and the assembly appears in SELECT @ FROM sys.assemblies.

But there are no records returned to SELECT * FROM sys.Assembly_modules.

And when I try to CREATE FUNCTION to call one of the methods,

```<code>CREATE FUNCTION RegExMatch(@pattern varchar(max)
                            , @SearchIn varchar(max)
                            , @options int)
RETURNS varchar
 EXTERNAL NAME SQLRegexTools.Functions.RegExMatch
</code>```

I get an error 'Msg 6505, Could not find Type "Functions" in assembly 'SQLRegexTools.'

The class name of the VB module is "Functions". Why is this called a type in the error, and why might I not be seeing anything in the modules?

答:
This error occurs when SQL Server is unable to resolve the name as provided. Try the snippet below to see if this resolves the issue.

```<code>CREATE FUNCTION RegExMatch(@pattern varchar(max)
                            , @SearchIn varchar(max)
                            , @options int)
RETURNS varchar
AS EXTERNAL NAME SQLRegexTools.[Functions].RegExMatch
</code>```

The resolution of individual functions/methods for accessing native code is relatively indistinguishable from a multipart object name (e.g. a type).

An additional note is that native code that utilizing nested namespaces must fully qualify nested namespaces within the same pair of quotes. For example, if RegExMatch were located at SQLRegexTools.A.B.C.RegExMatch, you would reference this as SQLRegexTools.[A.B.C].RegExMatch when using it with EXTERNAL NAME in SQL Server.

Body:
First attempt at a CLR Integration, so I can use Regex tools.

I create the assembly:

CREATE ASSEMBLY SQLRegexTools
  FROM 'D:\CODE\SQLRegexTools\SQLRegexTools\bin\Release\SQLRegexTools.dll'

This succeeds, and the assembly appears in SELECT @ FROM sys.assemblies.

But there are no records returned to SELECT * FROM sys.Assembly_modules.

And when I try to CREATE FUNCTION to call one of the methods,

CREATE FUNCTION RegExMatch(@pattern varchar(max)
                            , @SearchIn varchar(max)
                            , @options int)
RETURNS varchar
 EXTERNAL NAME SQLRegexTools.Functions.RegExMatch

I get an error 'Msg 6505, Could not find Type "Functions" in assembly 'SQLRegexTools.'

The class name of the VB module is "Functions". Why is this called a type in the error, and why might I not be seeing anything in the modules?

Body:
This error occurs when SQL Server is unable to resolve the name as provided. Try the snippet below to see if this resolves the issue.

CREATE FUNCTION RegExMatch(@pattern varchar(max)
                            , @SearchIn varchar(max)
                            , @options int)
RETURNS varchar
AS EXTERNAL NAME SQLRegexTools.[Functions].RegExMatch

The resolution of individual functions/methods for accessing native code is relatively indistinguishable from a multipart object name (e.g. a type).

An additional note is that native code that utilizing nested namespaces must fully qualify nested namespaces within the same pair of quotes. For example, if RegExMatch were located at SQLRegexTools.A.B.C.RegExMatch, you would reference this as SQLRegexTools.[A.B.C].RegExMatch when using it with EXTERNAL NAME in SQL Server.


问:
NiFi ifelse expression not working as expected with boolean
I am putting JSON values into a Postgres database, chaining InvokeHTTP, CovertJSONtoSQL, ReplaceText and PutSQL. The ReplaceText is adding an additional 'ON CONFLICT...'  clause to my SQL.

As part of the ReplaceText, I'm using one of the sql attributes of the flowfile, which as far as I can tell is being persisted as a boolean (attribute is shown as 't' or 'f' in the flowfile). I need to convert this boolean (t or f) to a string ("TRUE" or "FALSE") in order that it works in my query. My tactic was to try ifelse() as in

```<code>${sql.args.3.value:ifElse("TRUE","FALSE")}
</code>```

That always returns "FALSE" even when the attribute value it 't'.

I've made it work by casting it to a string first:

```<code>${sql.args.3.value:toString():equals('t'):ifElse("TRUE","FALSE")}
</code>```

but I'm frustrated that it doesn't seem to work as expected. Any ideas?

Thanks!

答:
This seems like expected behavior based on the documentation of ifelse:

https://nifi.apache.org/docs/nifi-docs/html/expression-language-guide.html#ifelse

If sql.args.3.value contained the value "true" or "false" then it would be interpreted as a boolean, such as in the example in the docs where it has:

```<code>${bool:ifElse('a','b')}
</code>```

Which evaluates to 'a' when the value of bool is "true".

In your case the value of sql.args.3.value is 't' or 'f' so it needs an operation to be applied which results in "true" or "false", such as what you did with the equals('t') comparison.

Body:
I am putting JSON values into a Postgres database, chaining InvokeHTTP, CovertJSONtoSQL, ReplaceText and PutSQL. The ReplaceText is adding an additional 'ON CONFLICT...'  clause to my SQL.

As part of the ReplaceText, I'm using one of the sql attributes of the flowfile, which as far as I can tell is being persisted as a boolean (attribute is shown as 't' or 'f' in the flowfile). I need to convert this boolean (t or f) to a string ("TRUE" or "FALSE") in order that it works in my query. My tactic was to try ifelse() as in

${sql.args.3.value:ifElse("TRUE","FALSE")}

That always returns "FALSE" even when the attribute value it 't'.

I've made it work by casting it to a string first:

${sql.args.3.value:toString():equals('t'):ifElse("TRUE","FALSE")}

but I'm frustrated that it doesn't seem to work as expected. Any ideas?

Thanks!

Body:
This seems like expected behavior based on the documentation of ifelse:

https://nifi.apache.org/docs/nifi-docs/html/expression-language-guide.html#ifelse

If sql.args.3.value contained the value "true" or "false" then it would be interpreted as a boolean, such as in the example in the docs where it has:

${bool:ifElse('a','b')}

Which evaluates to 'a' when the value of bool is "true".

In your case the value of sql.args.3.value is 't' or 'f' so it needs an operation to be applied which results in "true" or "false", such as what you did with the equals('t') comparison.


问:
.forEach within async action creator not returning action when running unit test
I am using react/redux to generate a list of panels, each of which displays data on each list item. I set a 5 second interval that calls  refreshAppList(this.props.list) action creator that forEach loops through every item in the list and makes an async call which then dispatches the refreshed list item (using redux-thunk). So basically, every 5 seconds I am refreshing the list of panels with the most up-to-date data. This works great! Unfortunately, now that I am writing unit tests for this particular async action creator I have run into an issue. .forEach does not return anything so when I call it in my unit tests I am getting undefined. Does anyone know how to override this issue or maybe i need to use a different method to refresh the entire list of panels?

Here is the action creator that is looping through the array and making an async call on each array item.

```<code>export const refreshAppList = list => (dispatch) => {
  list.forEach((version, index) => {
    const url = `apiEndpoint/${version.data.app_id}/${version.data.version}`;
    return axios.get(url)
      .then(({ data }) => {
        data.uniqueId = version.uniqueId;
        data.refreshId = uuidv1();
        dispatch({ type: REFRESH_APP_LIST, payload: { index, data } });
      })
      .catch((e) => {
      console.log(e);
      });
   });
 };
</code>```

Here is the error i am receiving:

```<code> 1) async actions creates an action with type: REFRESH_APP_LIST:
 TypeError: Cannot read property 'then' of undefined
  at Context.<anonymous> (tests/asyncActions.js:140:12)
</code>```

Here is where I am calling the action creator within the test (using redux-mock-store):

```<code>return store.dispatch(refreshAppList(list)).then(() => {
  expect(store.getActions()).to.deep.equal(expectedActions);
});
</code>```

I think it is also worth mentioning that I am using axios-mock-adapter to mock the data returned from the async call within the action creator.

One last thing: I have written unit tests for two other async action creators within the same app and both pass. The big difference is that this particular action creator is chaining together multiple async calls using a forEach loop (that is not returning anything to the test).

答:
That doesn't work because the function that refreshAppList returns doesn't return anything. Also, .forEach doesn't return anything even though you do return axios.get. from inside. You could use .map instead and return everything inside Promise.all. Something like this

```<code>export const refreshAppList = list => (dispatch) => {
  return Promise.all(list.map((version, index) => {
    const url = `apiEndpoint/${version.data.app_id}/${version.data.version}`;
    return axios.get(url)
      .then(({ data }) => {
        data.uniqueId = version.uniqueId;
        data.refreshId = uuidv1();
        dispatch({ type: REFRESH_APP_LIST, payload: { index, data } });
      })
      .catch((e) => {
      console.log(e);
      });
   }));
 };
</code>```

Body:
I am using react/redux to generate a list of panels, each of which displays data on each list item. I set a 5 second interval that calls  refreshAppList(this.props.list) action creator that forEach loops through every item in the list and makes an async call which then dispatches the refreshed list item (using redux-thunk). So basically, every 5 seconds I am refreshing the list of panels with the most up-to-date data. This works great! Unfortunately, now that I am writing unit tests for this particular async action creator I have run into an issue. .forEach does not return anything so when I call it in my unit tests I am getting undefined. Does anyone know how to override this issue or maybe i need to use a different method to refresh the entire list of panels?

Here is the action creator that is looping through the array and making an async call on each array item.

export const refreshAppList = list => (dispatch) => {
  list.forEach((version, index) => {
    const url = `apiEndpoint/${version.data.app_id}/${version.data.version}`;
    return axios.get(url)
      .then(({ data }) => {
        data.uniqueId = version.uniqueId;
        data.refreshId = uuidv1();
        dispatch({ type: REFRESH_APP_LIST, payload: { index, data } });
      })
      .catch((e) => {
      console.log(e);
      });
   });
 };

Here is the error i am receiving:

 1) async actions creates an action with type: REFRESH_APP_LIST:
 TypeError: Cannot read property 'then' of undefined
  at Context.<anonymous> (tests/asyncActions.js:140:12)

Here is where I am calling the action creator within the test (using redux-mock-store):

return store.dispatch(refreshAppList(list)).then(() => {
  expect(store.getActions()).to.deep.equal(expectedActions);
});

I think it is also worth mentioning that I am using axios-mock-adapter to mock the data returned from the async call within the action creator.

One last thing: I have written unit tests for two other async action creators within the same app and both pass. The big difference is that this particular action creator is chaining together multiple async calls using a forEach loop (that is not returning anything to the test).

Body:
That doesn't work because the function that refreshAppList returns doesn't return anything. Also, .forEach doesn't return anything even though you do return axios.get. from inside. You could use .map instead and return everything inside Promise.all. Something like this

export const refreshAppList = list => (dispatch) => {
  return Promise.all(list.map((version, index) => {
    const url = `apiEndpoint/${version.data.app_id}/${version.data.version}`;
    return axios.get(url)
      .then(({ data }) => {
        data.uniqueId = version.uniqueId;
        data.refreshId = uuidv1();
        dispatch({ type: REFRESH_APP_LIST, payload: { index, data } });
      })
      .catch((e) => {
      console.log(e);
      });
   }));
 };


问:
How to create a date field for mm/yyyy
How do I create a date field in angular/html to force the user to input the date in a specific format like MM/yyyy without any validation?

For example: when the user enters the first two digits of month, he should see a slash '/' so that he can enter only 4 more digits for year.

I know it can be done with a simple regex validation, but that will allow the user to enter the date in any format and then validate to show the error.

答:
Instead of fiddling with Javascript and HTML code I would suggest you take a look at some of the baked-in date parser directives offered by angular-bootstrap as a starting point and tweak things from there.

Example 1:
Date parser

Example 2:
Date picker

Example 3:
Date picker with popup

As requested by OP. He is looking at inputting Month/Year only. This example might be more relevant;

Example 4

Title: How to create a date field for mm/yyyy


问:
Why HHVM and NGINX are used together?
I thought HHVM can already serve the website. Why do we need NGINX?

I used to install mediawiki on just Apache and MySQL and it worked fine.

答: NGINX is used as a reverse proxy with HHVM. Depending on what you're doing with it, HHVM might be a better processor for PHP than letting NGINX deal with PHP on its own. I'm not in a position to say which solution is best, only that those options exist.</p>

Title: Why HHVM and NGINX are used together?


问:
Java: Getting ExceptionInInitializerError for Enums
EDIT: Solved but I don't understand why

In PokemonEnum I had this line

```<code>private PokemonEnum[ ] pokemon = PokemonEnum.values();
</code>```

I changed it to:

```<code>private static PokemonEnum[ ] pokemon = PokemonEnum.values();
</code>```

and now it works. I never even used that array yet so I don't know why I was getting errors or why static fixed it.

I haven't really worked with Enums so I don't really know why I get an ExceptionInInitializerError when I run main (on line 28 when I try to create a new Pokemon). Anyone care to explain please? Thanks.

```<code>import java.awt.image.BufferedImage;
import java.util.ArrayList;

public class Pokemon {

    private PokemonEnum name;
    private int dexNumber;
    private BufferedImage sprite;
    private TypeEnum[] types = new TypeEnum[1];
    private ArrayList<AbilityEnum> abilities;
    private ArrayList<MoveEnum> moves;
    private short hp;
    private short attack;
    private short defense;
    private short special_attack;
    private short special_defense;
    private short speed;

    public Pokemon(PokemonEnum name)
    {
        this.name = name;
        this.dexNumber = name.getDexNum();
    }

    public static void main(String[] args)
    {
        Pokemon pikachu = new Pokemon(PokemonEnum.Pikachu);
        System.out.println(pikachu.dexNumber);
    }
}

   public enum PokemonEnum {
    Pikachu;

    public int getDexNum()
    {
        return ordinal()+1;
    }

    private PokemonEnum[ ] pokemon = PokemonEnum.values();
}

Stack Trace:

Exception in thread "main" java.lang.ExceptionInInitializerError
    at Pokemon.main(Pokemon.java:28)
Caused by: java.lang.NullPointerException
    at PokemonEnum.values(PokemonEnum.java:1)
    at PokemonEnum.<init>(PokemonEnum.java:722)
    at PokemonEnum.<clinit>(PokemonEnum.java:2)
    ... 1 more
</code>```

答:
What you are experiencing is 'like' a recursion.

This error occurs because the code PokemonEnum.values() is in the enum PokemonEnum and when this is compiling it reads values() and then using this internal function, the primitive data type enum references to itself. However due to the fact that the enum is still being compiled, the value of value() is null.

Note: Trying to use the value() inside of it's enum will result in an Error. Such that trying to use if(PokemonEnum.values()!=null) or even trying to catch the ExceptionInInitializerError will not work due to the values() being part of a primitive type(meaning the method being called is native).

The Solution would be to place private PokemonEnum[] pokemon = PokemonEnum.values(); outside and below the enum PokemonEnum.

I know this from personal experience as well as other sources on similar problems.

Similar Sources: here and here

Hope this helps.

Body:
EDIT: Solved but I don't understand why

In PokemonEnum I had this line

private PokemonEnum[ ] pokemon = PokemonEnum.values();

I changed it to:

private static PokemonEnum[ ] pokemon = PokemonEnum.values();

and now it works. I never even used that array yet so I don't know why I was getting errors or why static fixed it.

I haven't really worked with Enums so I don't really know why I get an ExceptionInInitializerError when I run main (on line 28 when I try to create a new Pokemon). Anyone care to explain please? Thanks.

import java.awt.image.BufferedImage;
import java.util.ArrayList;

public class Pokemon {

    private PokemonEnum name;
    private int dexNumber;
    private BufferedImage sprite;
    private TypeEnum[] types = new TypeEnum[1];
    private ArrayList<AbilityEnum> abilities;
    private ArrayList<MoveEnum> moves;
    private short hp;
    private short attack;
    private short defense;
    private short special_attack;
    private short special_defense;
    private short speed;

    public Pokemon(PokemonEnum name)
    {
        this.name = name;
        this.dexNumber = name.getDexNum();
    }

    public static void main(String[] args)
    {
        Pokemon pikachu = new Pokemon(PokemonEnum.Pikachu);
        System.out.println(pikachu.dexNumber);
    }
}

   public enum PokemonEnum {
    Pikachu;

    public int getDexNum()
    {
        return ordinal()+1;
    }

    private PokemonEnum[ ] pokemon = PokemonEnum.values();
}

Stack Trace:

Exception in thread "main" java.lang.ExceptionInInitializerError
    at Pokemon.main(Pokemon.java:28)
Caused by: java.lang.NullPointerException
    at PokemonEnum.values(PokemonEnum.java:1)
    at PokemonEnum.<init>(PokemonEnum.java:722)
    at PokemonEnum.<clinit>(PokemonEnum.java:2)
    ... 1 more


问:
MySQL InnoDB table with a Hash Index
I have a table like this.

```<code>ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
</code>```

Later i have created a HASH index like this.

```<code>CREATE INDEX index ON table (column) USING HASH;
</code>```

Latter i have try some explain queries.

Like

```<code>explain Select * from table where column=132;
</code>```

And i see the engine is using the index on possible_keys and in the key stuff says the name of the index!!

But in the docs says that InnoDB doesn't allow hash index now i wonder why my innoDB Supposedly allows the hash index?

答:
InnoDB silently changes "HASH" into "BTree".  A BTree index does what a HASH does, plus more.  Or do you think there is some good reason to want Hash?

"Good reason" -- MySQL was created many years ago.  It was designed to be 'lean and mean'.  Many features were boiled down to "one size fits all":  BTree for indexing; Nested Loop Join for JOINing, etc.

Meanwhile, for future expansion and pseudo compatibility, some common syntax variants were included -- HASH for indexing, DESC for index ordering, etc.  Even though those "lie" about what will happen, the database engine still gives you the 'right' answer.

Over time, the most glaring shortcuts have been remedied.

Replication (3.xx?)

Transactions (Adding InnoDB in 4.0) (MyISAM had LOCK TABLES, but that was not really adequate.)

information_schema (4.1?)  (versus a variety of SHOW commands)  Note:  8.0 overhauled it with the "data dictionary")

Character sets and collations (4.1) (vs "latin_swedish_ci", which was good enough for the implementor.)

Stored routines (vs client code) (5.0)

Subqueries (TEMPORARY TABLEs were not adequate)

Various JOIN optimizations  (5.6, 5,7, 8.0)

only_full_group_by (MariaDB 10.1?, 5.7)

ALTER not 'always' copying the table over (mostly 5.7)

"Generated" columns (5.7)

"Tablespaces" (5.7)

JSON datatype and functions

FULLTEXT and SPATIAL indexing in InnoDB (5.7, 8.0) (so MyISAM can be deprecated)

DESC in INDEXes (8.0) (very few use cases really need this)

"Windowing" functions  (MariaDB 10.2, then MySQL 8.0)

CTEs (MariaDB 10.2, then MySQL 8.0)

Security:  Better password handling (4.1?, 5.6, 8.0)

HA (High Availability) (MariaDB with Galera; 8.0 with InnoDB Cluster)

At-rest encryption (8.0?)

Notice how the list is somewhat ordered from "must have" to "nice to have".  Yet to come may include

Multi-threaded execution (Useless if you are I/O-bound anyway) (a very few use cases in 8.0)

HASH indexing (and other types) (MariaDB 10.4, only for UNIQUE on TEXT/BLOB)

Global UNIQUE and FOREIGN KEY for PARTITIONing.  (Not that partitioning is very useful.)

More syntax compatibility with standards and other vendors (MariaDB already does a much better job of this)

Meanwhile, some things are going away (or have already gone away -- either in MariaDB or MySQL)

Compiling for a large variety of computers -- such as Atari

The Query Cache -- Handy for benchmarking, but not really useful in Production environments.  And a major hassle to implement in any 'cluster' topology.

MyISAM has major deficiencies relative to InnoDB, and has very few benefits.  (Arguably, the only benefit is less disk space needed.)

Title: MySQL InnoDB table with a Hash Index

Body:
I have a table like this.

ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

Later i have created a HASH index like this.

CREATE INDEX index ON table (column) USING HASH;

Latter i have try some explain queries.

Like

explain Select * from table where column=132;

And i see the engine is using the index on possible_keys and in the key stuff says the name of the index!!

But in the docs says that InnoDB doesn't allow hash index now i wonder why my innoDB Supposedly allows the hash index?

ContentLicense: CC BY-SA 4.0


问:
Quick open new file on the current tab
I like to code using two panes and navigating my code with quick open as much as possible.

example

The problem is that every time I use Quick Open (Ctrl + P on Windows) it opens the file on another tab. I don't like tabs but there's no way to disable them as far as I know. You can only hide the tabs but that's not really useful since other tabs will be open in the background anyway.

Is there a way to make quick open use the current tab? Or disable tabs altogether and not just hide them?

Thanks

答:
To disable tabs, just add:

```<code>"workbench.editor.showTabs": false
</code>```

to your user settings.

Also note that VSCode normally opens files in preview mode. This is indicated by an italicized file name in the workbench. Files in preview mode are not kept open when you quick open another file. You can disable previews by setting:

```<code>"workbench.editor.enablePreview": false
</code>```

Title: Quick open new file on the current tab

Body:
To disable tabs, just add:

"workbench.editor.showTabs": false

to your user settings.

Also note that VSCode normally opens files in preview mode. This is indicated by an italicized file name in the workbench. Files in preview mode are not kept open when you quick open another file. You can disable previews by setting:

"workbench.editor.enablePreview": false


问:
Hexagon grid on sphere without pentagon
I wanted to make a tile-based world on a sphere. I would like to use hexagon-shaped tiles, though as far as I can figure out you need to have pentagons in there too to make it fit.

So, my question is, is it possible to make a hexagon grid on a sphere, without using pentagons? The hexagons don't have to be regular hexagons, if they are all close to regular that's more than enough.

答:
The author of this article was experiencing similar problems and wrote the aforementioned article on the subject, with some JavaScript source code.

Basically, the idea is, that since it is mathematically impossible to remove the Pentagons, the only valid solution is to modify and distort your hexagonal grid to make the occasional pentagon stand out less. To make odd tiles the normal occurrence. He did this by creating a voronoi diagram over the icosphere rather than a straight hexagonal grid, and to repeatedly run the Lloyd relaxation algorithm over the points until they were more or less in the Pentagon to Octagon range.

Title: Hexagon grid on sphere without pentagon


问:
How do I create a PHP array with 2 variables for each element without using an object?
I'm new to PHP and would require some assistance if possible.

I have the array

```<code>array("Name" => $userName, "Age" => $userAge);
</code>```

This works for one user but lets say I wanted to add multiple users that will all have a Name and Age how would I do that? Instead of passing is $userName would I have to pass it an array of user names and instead of $userage an array of user ages hence making it multidimesional?

Also for my purposes I cannot put the username and userage in an object and then simply add it to the array.

答:
Here is some sample code which should solve your problem given.  The two input array, names and ages, do not need to be the same size, and the output array will insert default values ('N/A' for names, -1 for ages) where a corresponding name or age is missing.

```<code>$userNames = ['name1', 'name2', 'name3', 'name4'];
$userAges = [26,14,99];
$userNamesAndAges = [];

for ($i=0; $i < max(count($userNames), count($userAges)); $i++) {
    if (isset($userNames[$i])) {
        $userName = $userNames[$i];
    } else {
        $userName = 'N/A';
    }

    if (isset($userAges[$i])) {
        $userAge = $userAges[$i];
    } else {
        $userAge = -1;
    }

    $userNamesAndAges[] = [
        'Name' => $userName,
        'Age' => $userAge
    ];
}

foreach ($userNamesAndAges as $obj) {
    $name = $obj['Name'];
    $age = $obj['Age'];
    echo("Name: $name, Age: $age<br>");
}
</code>```

Outputs:

Name: name1, Age: 26

Name: name2, Age: 14

Name: name3, Age: 99

Name: name4, Age: -1

Body:
I'm new to PHP and would require some assistance if possible.

I have the array

array("Name" => $userName, "Age" => $userAge);

This works for one user but lets say I wanted to add multiple users that will all have a Name and Age how would I do that? Instead of passing is $userName would I have to pass it an array of user names and instead of $userage an array of user ages hence making it multidimesional?

Also for my purposes I cannot put the username and userage in an object and then simply add it to the array.

Body:
Here is some sample code which should solve your problem given.  The two input array, names and ages, do not need to be the same size, and the output array will insert default values ('N/A' for names, -1 for ages) where a corresponding name or age is missing.

$userNames = ['name1', 'name2', 'name3', 'name4'];
$userAges = [26,14,99];
$userNamesAndAges = [];

for ($i=0; $i < max(count($userNames), count($userAges)); $i++) {
    if (isset($userNames[$i])) {
        $userName = $userNames[$i];
    } else {
        $userName = 'N/A';
    }

    if (isset($userAges[$i])) {
        $userAge = $userAges[$i];
    } else {
        $userAge = -1;
    }

    $userNamesAndAges[] = [
        'Name' => $userName,
        'Age' => $userAge
    ];
}

foreach ($userNamesAndAges as $obj) {
    $name = $obj['Name'];
    $age = $obj['Age'];
    echo("Name: $name, Age: $age<br>");
}

Outputs:

Name: name1, Age: 26

Name: name2, Age: 14

Name: name3, Age: 99

Name: name4, Age: -1


问:
Too many open files in python
I wrote kind of a test suite which is heavily file intensive. After some time (2h) I get an IOError: [Errno 24] Too many open files: '/tmp/tmpxsqYPm'. I double checked all file handles whether I close them again. But the error still exists.

I tried to figure out the number of allowed file descriptors using resource.RLIMIT_NOFILE and the number of currently opened file desciptors:

```<code>def get_open_fds():

    fds = []
    for fd in range(3,resource.RLIMIT_NOFILE):
            try:
                    flags = fcntl.fcntl(fd, fcntl.F_GETFD)
            except IOError:
                    continue

            fds.append(fd)

    return fds
</code>```

So if I run the following test:

```<code>print get_open_fds()
for i in range(0,100):
    f = open("/tmp/test_%i" % i, "w")
    f.write("test")
    print get_open_fds()
</code>```

I get this output:

```<code>[]
/tmp/test_0
[3]
/tmp/test_1
[4]
/tmp/test_2
[3]
/tmp/test_3
[4]
/tmp/test_4
[3]
/tmp/test_5
[4] ...
</code>```

That's strange, I expected an increasing number of opened file descriptors. Is my script correct?

I'm using python's logger and subprocess. Could that be the reason for my fd leak?

Thanks,
Daniel

答: resource.RLIMIT_NOFILE is indeed 7, but that's an index into resource.getrlimit(), not the limit itself... resource.getrlimit(resource.RLIMIT_NOFILE) is what you want your top range() to be</p>

Title: Too many open files in python

Body:
I wrote kind of a test suite which is heavily file intensive. After some time (2h) I get an IOError: [Errno 24] Too many open files: '/tmp/tmpxsqYPm'. I double checked all file handles whether I close them again. But the error still exists.

I tried to figure out the number of allowed file descriptors using resource.RLIMIT_NOFILE and the number of currently opened file desciptors:

def get_open_fds():

    fds = []
    for fd in range(3,resource.RLIMIT_NOFILE):
            try:
                    flags = fcntl.fcntl(fd, fcntl.F_GETFD)
            except IOError:
                    continue

            fds.append(fd)

    return fds

So if I run the following test:

print get_open_fds()
for i in range(0,100):
    f = open("/tmp/test_%i" % i, "w")
    f.write("test")
    print get_open_fds()

I get this output:

[]
/tmp/test_0
[3]
/tmp/test_1
[4]
/tmp/test_2
[3]
/tmp/test_3
[4]
/tmp/test_4
[3]
/tmp/test_5
[4] ...

That's strange, I expected an increasing number of opened file descriptors. Is my script correct?

I'm using python's logger and subprocess. Could that be the reason for my fd leak?

Thanks,
Daniel


问:
How do I detect a touch in navigationController.view?
I was implementing this function.

```<code>override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let point = touches.first?.location(in: self.view) else { return }

    for i in 0..<paths.count {
        if paths[i].contains(point) { addViews(selectedView: i); break }
    }
}
</code>```

My designers decided they want to make a small part of the views I add to overlay the navigationBar. The problem is that after I add the views to the navigationController.view instead, I am no longer able to detect the touches. I have tried location(in: self.navigationController.view) and that didn't work. Before I go down the rabbit hole of endless different things that might work, does anyone have an easy answer for me?

答:
While navigationController is nominally a ViewController, it's 'view' outlet is usually not used, and probably not put in the responder chain.

My solution was to create a custom view (in the storyboard) as outlet for navigationItem.titleView for the UIViewController.

You can set up the custom view in viewDidLoad() (instead of storyboard)

```<code>self.navigationItem.titleView = myCustomView;
</code>```

In viewDidLoad I set up a gesture like:

```<code>UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleStatusTap:)];
[chatTitleView addGestureRecognizer:singleTap];
</code>```

Body:
I was implementing this function.

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let point = touches.first?.location(in: self.view) else { return }

    for i in 0..<paths.count {
        if paths[i].contains(point) { addViews(selectedView: i); break }
    }
}

My designers decided they want to make a small part of the views I add to overlay the navigationBar. The problem is that after I add the views to the navigationController.view instead, I am no longer able to detect the touches. I have tried location(in: self.navigationController.view) and that didn't work. Before I go down the rabbit hole of endless different things that might work, does anyone have an easy answer for me?

Body:
While navigationController is nominally a ViewController, it's 'view' outlet is usually not used, and probably not put in the responder chain.

My solution was to create a custom view (in the storyboard) as outlet for navigationItem.titleView for the UIViewController.

You can set up the custom view in viewDidLoad() (instead of storyboard)

self.navigationItem.titleView = myCustomView;

In viewDidLoad I set up a gesture like:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleStatusTap:)];
[chatTitleView addGestureRecognizer:singleTap];


问:
Invalid runtimeconfig.json error when trying to run netcore app on linux
I have developed .net core console application. It connects with Azure table storage and downloads from azure to a local database. Application is working w/o any issues on a Windows 10 PC. However when I publish it to a PC running Lubuntu and try to run I receive "Invalid runtimeconfig.json error".

Content of runtimeconfig.json is:

```<code>{
  "runtimeOptions": {
    "framework": {
      "name": "Microsoft.NETCore.App",
      "version": "1.1.2"
    }
  }
}
</code>```

and output of dotnet --info is:

```<code>NET Command Line Tools (1.0.4)
Product Information:
Version: 1.0.4
Commit SHA-1 hash: af1e6684fd
Runtime Environment:
OS Name: ubuntu
OS Version: 17.04
OS Platform: Linux
RID: ubuntu.16.10-x64
Base Path: /usr/share/dotnet/sdk/1.0.4
</code>```

SDK for Linux is the latest version. Anybody have any ideas what might be wrong and how to fix it?

答:
After some trial and error I have resolved the issue. Problem is not really a invalid configuration file. When dotnet runs the dll file it creates a xxxx.runtimeconfig.dev.json, xxxx being the name of dll. However in my case due to missing folder and file access rights in Lubuntu, dotnet was not able to create the runtimeconfig.dev.json file.

I have modified access rights to folder holding my application by executing following terminal command (run this from parent directory of folderholdingmyapp)

chmod -R 1744 folderholdingmyapp

Body:
I have developed .net core console application. It connects with Azure table storage and downloads from azure to a local database. Application is working w/o any issues on a Windows 10 PC. However when I publish it to a PC running Lubuntu and try to run I receive "Invalid runtimeconfig.json error".

Content of runtimeconfig.json is:

{
  "runtimeOptions": {
    "framework": {
      "name": "Microsoft.NETCore.App",
      "version": "1.1.2"
    }
  }
}

and output of dotnet --info is:

NET Command Line Tools (1.0.4)
Product Information:
Version: 1.0.4
Commit SHA-1 hash: af1e6684fd
Runtime Environment:
OS Name: ubuntu
OS Version: 17.04
OS Platform: Linux
RID: ubuntu.16.10-x64
Base Path: /usr/share/dotnet/sdk/1.0.4

SDK for Linux is the latest version. Anybody have any ideas what might be wrong and how to fix it?


问:
How to make two columns line up to top
Not sure why this is happening but when I scale down my page my right column (the one in yellow) moves down. It looks fine when I'm full screen but not sure what to do to the CSS to make sure the column contents always line up to the top of the div container. Here's my css for that section

```<code>.wrapper-cols {
margin-top:0px;
margin-left: auto;
margin-right:auto;
max-width: 900px;
}

.contact-col1 {
margin-top:0px;
padding-right:5px;
background-color:blue;
 height: 200px;
}

.contact-col2 {
padding-left:5px;
background-color:yellow;
height: 200px;
}
</code>```

here's the url:

link

答:
The styles that are causing this to happen don't have anything to do with the code you've shared with us. There's a combination of stylesheets affecting everything in your website:

Wordpress includes it's own CSS.

The Beaver Builder Wordpress Page Builder you used includes it's own CSS.

The Wordpress themes you're using (Avada and Fusion) each include their own CSS.

Bootstrap is also mixed in.

So you've got all of these CSS huge libraries combining themselves, and the HTML you're using clearly uses their classes. At this point, the only practical way to make the website look exactly how you want it to, is to write the HTML and CSS code by yourself (instead of using a generator).

The non-practical way? Spend a few hours resetting all of the styles of the HTML tags involved, overwriting them with !important to make them behave as default. Be warned that this involves using some advanced CSS concepts to go against the libraries you're including (probably easier to write the code from scratch).

Title: How to make two columns line up to top

Body:
Not sure why this is happening but when I scale down my page my right column (the one in yellow) moves down. It looks fine when I'm full screen but not sure what to do to the CSS to make sure the column contents always line up to the top of the div container. Here's my css for that section

.wrapper-cols {
margin-top:0px;
margin-left: auto;
margin-right:auto;
max-width: 900px;
}

.contact-col1 {
margin-top:0px;
padding-right:5px;
background-color:blue;
 height: 200px;
}

.contact-col2 {
padding-left:5px;
background-color:yellow;
height: 200px;
}

here's the url:

link


问:
Is it possible to trigger a lambda on creation from CloudFormation template
I tried creating a set of lambdas using cloudformation. I want the lambdas to get triggered once they are created. I saw at various blogs to create a trigger to s3 or sns but none seems to be a option to trigger lambda once it has been created. Any options?

答:
For who looking the similar workaround.

CloudWatch is able to capture API calls of CloudFormation, which is "CreateStack", "UpdateStack" and "DeleteStack", stack states like "Create_complete" or "Complete_Rollback" are uncapturable, which means such state changes not be able to trigger lambda.

The workaround is SNS, stacks are able to send notifications to SNS (In advance settings when you creating stack) and SNS can choose to trigger lambda, however, you can't choose for specific states. So, lambda function takes the job to find out what state in "Message" content of an event. Everyone, just coding.


问:
Cannot retrieve Boolean value from User class in parse server
Hi (I'm new so you'll have to forgive me)

I'm trying to retrieve a boolean value from the column "isSignedIn" from the current User in the User class in parse server.

The issue I have is that every time I try to retrieve it, the Boolean value always returns as false even though I have manually set it to true in the parse front end:

This is the code I am using to retrieve the value:

```<code> public boolean isSignedIn(){
    ParseUser user = ParseUser.getCurrentUser();
    Boolean signedInStatus = Boolean.valueOf(user.getBoolean("isSignedIn"));
    Log.i("isSignedIn", signedInStatus.toString());

    return signedInStatus;

}
</code>```

I thought that a parse query may work but I'm not sure if it would be as efficient as if I fixed the code above.

Any ideas on what I can do to fix this?

答: You probably need to call fetch()  on your user before getting the value so you have the latest up to date value from the server!

Body:
Hi (I'm new so you'll have to forgive me)

I'm trying to retrieve a boolean value from the column "isSignedIn" from the current User in the User class in parse server.

The issue I have is that every time I try to retrieve it, the Boolean value always returns as false even though I have manually set it to true in the parse front end:

This is the code I am using to retrieve the value:

 public boolean isSignedIn(){
    ParseUser user = ParseUser.getCurrentUser();
    Boolean signedInStatus = Boolean.valueOf(user.getBoolean("isSignedIn"));
    Log.i("isSignedIn", signedInStatus.toString());

    return signedInStatus;

}

I thought that a parse query may work but I'm not sure if it would be as efficient as if I fixed the code above.

Any ideas on what I can do to fix this?


问:
grails/gorm/mysql/hibernate
I have a simples question. I have been trying to learn Grails by my own, and i managed to do a simple application using Grails/Gorm.

1 ) Later, i decided to use Mysql instead of Gorm - i just needed to configure the 'DataSource' and download the driver.

2 )So if i want to use hibernate between both (Grails and MYSQL) like this:
http://www.grails.org/doc/latest/guide/15.%20Grails%20and%20Hibernate.html, i need to make an 'hibernate.cfg.xml' file, and specify my mysql database url, user, pw etc .. and i have to map each Class in Grails for MySql columns.

So what is the diference between 1) and 2) ? and what exactly hibernate does. Give examples if possible

PS. Please correct me if i said something wrong, im kinda new to this

答:
I think you are a bit confused here.

GORM is not a database, it is a ORM that maps you Groovy classes to database tables. It uses Hibernate under the covers to achieve this (Hibernate is also an ORM).

The default database Grails uses is an in-memory HSQL DB. If you want to use MySQL instead of that, all you need to do is change the settings in conf/DataSource.groovy.

You don't need to create any Hibernate xml files. That part of the documentation you've linked to is to allow people with existing Hibernate domain models to easily re-use them.

Hope this helps clear things up.

cheers

Lee

Title: grails/gorm/mysql/hibernate


问:
How to resolve issue about Privacy Violation in HPE?
We use HPE to check the code potential risks, i got one critical issue below in Log util class
"The method d() in LogUtil.java mishandles confidential information, which can compromise user privacy and is often illegal".
how can i do to fix this?</p>

答: Are you logging sensitive information, such as credit card numbers, session ids, or names and birth dates?  You should not do so.  You fix the issue by not logging it.</p>


问:
Upload base64 image to amazon s3
I'm having some issues when trying to upload an image to AWS S3. It seems to upload the file correctly but, whenever I try to download or preview, it can't be opened. Currently, this is the upload code I'm using:

```<code><?php
require_once 'classes/amazon.php';
require_once 'includes/aws/aws-autoloader.php';
use Aws\S3\S3Client;

$putdata = file_get_contents("php://input");
$request = json_decode($putdata);

$image_parts = explode(";base64,", $request->image);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = $image_parts[1];

$dateTime = new DateTime();
$fileName = $dateTime->getTimestamp() . "." . $image_type;

$s3Client = S3Client::factory(array(
    'region' => 'eu-west-1',
    'version' => '2006-03-01',
    'credentials' => array(
        'key'    => Amazon::getAccessKey(),
        'secret' => Amazon::getSecretKey(),
    )
));

try {
    $result = $s3Client->putObject(array(
        'Bucket'          => Amazon::getBucket(),
        'Key'             => 'banners/' . $fileName,
        'Body'            => $image_base64,
        'ContentType'     => 'image/' . $image_type,
        'ACL'             => 'public-read'
    ));
    echo $result['ObjectURL'] . "\n";
} catch(S3Exception $e) {
    echo $e->getMessage() . "\n";
}
?>
</code>```

So, when I check the console after uploading the image file, it has the expected size, permissions and headers but, as I said, whenever I try to open the file, it fails.

What could be the problem here? Thanks in advance.

答:
I use silex php 2.0  and the following code fount</p>

```<code>    $s3 = $app['aws']->createS3();
    $putdata = file_get_contents("php://input");
    $data = json_decode($request->getContent(), true);
    $data = (object) $data;
    $image_parts = explode(";base64,", $data->image);
    $image_type_aux = explode("image/", $image_parts[0]);
    $image_type = $image_type_aux[1];
    $image_base64 = base64_decode($image_parts[1]);
    $result = $s3->putObject([
        'ACL' => 'public-read',
        'Body' => $image_base64,
        'Bucket' => 'name-bucket',
        'Key' => 'test_img.jpeg',
        'ContentType' => 'image/' . $image_type,
    ]);
    var_dump($result['ObjectURL']);
</code>```

Title: Upload base64 image to amazon s3

Body:
I'm having some issues when trying to upload an image to AWS S3. It seems to upload the file correctly but, whenever I try to download or preview, it can't be opened. Currently, this is the upload code I'm using:

<?php
require_once 'classes/amazon.php';
require_once 'includes/aws/aws-autoloader.php';
use Aws\S3\S3Client;

$putdata = file_get_contents("php://input");
$request = json_decode($putdata);

$image_parts = explode(";base64,", $request->image);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = $image_parts[1];

$dateTime = new DateTime();
$fileName = $dateTime->getTimestamp() . "." . $image_type;

$s3Client = S3Client::factory(array(
    'region' => 'eu-west-1',
    'version' => '2006-03-01',
    'credentials' => array(
        'key'    => Amazon::getAccessKey(),
        'secret' => Amazon::getSecretKey(),
    )
));

try {
    $result = $s3Client->putObject(array(
        'Bucket'          => Amazon::getBucket(),
        'Key'             => 'banners/' . $fileName,
        'Body'            => $image_base64,
        'ContentType'     => 'image/' . $image_type,
        'ACL'             => 'public-read'
    ));
    echo $result['ObjectURL'] . "\n";
} catch(S3Exception $e) {
    echo $e->getMessage() . "\n";
}
?>

So, when I check the console after uploading the image file, it has the expected size, permissions and headers but, as I said, whenever I try to open the file, it fails.

What could be the problem here? Thanks in advance.

Body:
I use silex php 2.0  and the following code fount

    $s3 = $app['aws']->createS3();
    $putdata = file_get_contents("php://input");
    $data = json_decode($request->getContent(), true);
    $data = (object) $data;
    $image_parts = explode(";base64,", $data->image);
    $image_type_aux = explode("image/", $image_parts[0]);
    $image_type = $image_type_aux[1];
    $image_base64 = base64_decode($image_parts[1]);
    $result = $s3->putObject([
        'ACL' => 'public-read',
        'Body' => $image_base64,
        'Bucket' => 'name-bucket',
        'Key' => 'test_img.jpeg',
        'ContentType' => 'image/' . $image_type,
    ]);
    var_dump($result['ObjectURL']);


问:
How to let people collaborate on my open source project?
A while ago I started an open-source project, which for me meant (until now) I simply pushed my source code to a public repository (Mercurial on Google Code). Recently though, I've received requests from other people to collaborate on my project. Having never collaborated on an open-source project before, I'm not sure how to proceed:

Do I just give them access to the repository so they can push changes? If they push something I don't like I can always roll back and if they get on my nerves I can always revoke their access to the repository.

Do I tell them to send in patches (via the issue tracker) and then apply the ones I like and revoke the ones I don't?

Now:

I don't want to lose ownership of my project. It's a pretty nice project and it's good resume material. I think this is what I am most afraid of. However, I want to give proper credit to my collaborators.

I know this is the whole point of open-source: collaboration, so I don't want to be an idiot and say no to these people who want to help.

Lately I haven't had much time to code on my project, so it could use some help.

Also, I'm a bit reluctant to let just anyone work on my project. What if they're, pardon the expression, noobs? I suppose I can just rollback they're changes and tell them to, pardon the expression, gtfo, but that wouldn't be particularly nice.

How is this usually done?

答:
The good point to mention here, is that other developers want to contribute to your project, because they need to change/modify/upgrade it a little bit based on their needs. If they don't have the changes committed into your project, they won't be able to easily migrate to next version.
These developers won't want you to share credit or anything. They just want their modifications/upgrades be committed.

The more developers are committing the higher chance is there that the project will be alive for a long time. The credit will be yours.


问:
Unexpectedly needed to give input value to an irrelevant placeholder in the graph
https://gist.github.com/Wermarter/466e9585579ef65927fa934fe4e0ffd4
Here I'm trying to implement Variational AutoEncoder in Tensorflow with TFLearn.

I build the computations for training, encoding, generating in one big graph in self.training_model.session. The self.generating_model and self.recognition_model share the same session as self.training_model.

Everything went fine when I ran the generating_model to generate MNIST 2D Latent space. But error appeared when I ran self.recognition_model to encode the given input_data, it required me to given input value to the self.train_data which belongs to the self.training_model.

Here's the full error:

```<code>Traceback (most recent call last):
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1039, in _do_call
    return fn(*args)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1021, in _run_fn
    status, run_metadata)
  File "/home/wermarter/anaconda3/lib/python3.5/contextlib.py", line 66, in __exit__
    next(self.gen)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/errors_impl.py", line 466, in raise_exception_on_not_ok_status
    pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'train_data/X' with dtype float
     [[Node: train_data/X = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
     [[Node: add_5/_47 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_8_add_5", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/wermarter/Desktop/vae.py", line 178, in <module>
    main()
  File "/home/wermarter/Desktop/vae.py", line 172, in main
    vae.img_transition(trainX[4], trainX[100])
  File "/home/wermarter/Desktop/vae.py", line 130, in img_transition
    enc_A = self.encode(A)[0]
  File "/home/wermarter/Desktop/vae.py", line 121, in encode
    return self.recognition_model.predict({self.input_data: input_data})
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tflearn/models/dnn.py", line 257, in predict
    return self.predictor.predict(feed_dict)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tflearn/helpers/evaluator.py", line 69, in predict
    return self.session.run(self.tensors[0], feed_dict=feed_dict)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 778, in run
    run_metadata_ptr)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 982, in _run
    feed_dict_string, options, run_metadata)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1032, in _do_run
    target_list, options, run_metadata)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1052, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'train_data/X' with dtype float
     [[Node: train_data/X = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
     [[Node: add_5/_47 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_8_add_5", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

Caused by op 'train_data/X', defined at:
  File "/home/wermarter/Desktop/vae.py", line 178, in <module>
    main()
  File "/home/wermarter/Desktop/vae.py", line 169, in main
    vae = VAE()
  File "/home/wermarter/Desktop/vae.py", line 28, in __init__
    self._build_training_model()
  File "/home/wermarter/Desktop/vae.py", line 78, in _build_training_model
    self.train_data = tflearn.input_data(shape=[None, *self.img_shape], name='train_data')
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tflearn/layers/core.py", line 81, in input_data
    placeholder = tf.placeholder(shape=shape, dtype=dtype, name="X")
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/ops/array_ops.py", line 1507, in placeholder
    name=name)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/ops/gen_array_ops.py", line 1997, in _placeholder
    name=name)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'train_data/X' with dtype float
     [[Node: train_data/X = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
     [[Node: add_5/_47 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_8_add_5", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
</code>```

答:
This is a code-specific error. My self.recognition_model is actually linked to the placeholder self.train_data through self.curr_batch_size in self._sample_z(). My solution is to re-link self.curr_batch_size to the size of self.input_data.

That's it. Happy Coding

Body:
https://gist.github.com/Wermarter/466e9585579ef65927fa934fe4e0ffd4
Here I'm trying to implement Variational AutoEncoder in Tensorflow with TFLearn.

I build the computations for training, encoding, generating in one big graph in self.training_model.session. The self.generating_model and self.recognition_model share the same session as self.training_model.

Everything went fine when I ran the generating_model to generate MNIST 2D Latent space. But error appeared when I ran self.recognition_model to encode the given input_data, it required me to given input value to the self.train_data which belongs to the self.training_model.

Here's the full error:

Traceback (most recent call last):
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1039, in _do_call
    return fn(*args)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1021, in _run_fn
    status, run_metadata)
  File "/home/wermarter/anaconda3/lib/python3.5/contextlib.py", line 66, in __exit__
    next(self.gen)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/errors_impl.py", line 466, in raise_exception_on_not_ok_status
    pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'train_data/X' with dtype float
     [[Node: train_data/X = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
     [[Node: add_5/_47 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_8_add_5", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/wermarter/Desktop/vae.py", line 178, in <module>
    main()
  File "/home/wermarter/Desktop/vae.py", line 172, in main
    vae.img_transition(trainX[4], trainX[100])
  File "/home/wermarter/Desktop/vae.py", line 130, in img_transition
    enc_A = self.encode(A)[0]
  File "/home/wermarter/Desktop/vae.py", line 121, in encode
    return self.recognition_model.predict({self.input_data: input_data})
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tflearn/models/dnn.py", line 257, in predict
    return self.predictor.predict(feed_dict)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tflearn/helpers/evaluator.py", line 69, in predict
    return self.session.run(self.tensors[0], feed_dict=feed_dict)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 778, in run
    run_metadata_ptr)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 982, in _run
    feed_dict_string, options, run_metadata)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1032, in _do_run
    target_list, options, run_metadata)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1052, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'train_data/X' with dtype float
     [[Node: train_data/X = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
     [[Node: add_5/_47 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_8_add_5", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

Caused by op 'train_data/X', defined at:
  File "/home/wermarter/Desktop/vae.py", line 178, in <module>
    main()
  File "/home/wermarter/Desktop/vae.py", line 169, in main
    vae = VAE()
  File "/home/wermarter/Desktop/vae.py", line 28, in __init__
    self._build_training_model()
  File "/home/wermarter/Desktop/vae.py", line 78, in _build_training_model
    self.train_data = tflearn.input_data(shape=[None, *self.img_shape], name='train_data')
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tflearn/layers/core.py", line 81, in input_data
    placeholder = tf.placeholder(shape=shape, dtype=dtype, name="X")
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/ops/array_ops.py", line 1507, in placeholder
    name=name)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/ops/gen_array_ops.py", line 1997, in _placeholder
    name=name)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/home/wermarter/anaconda3/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'train_data/X' with dtype float
     [[Node: train_data/X = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
     [[Node: add_5/_47 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_8_add_5", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]


问:
How to Run R Script from ASP.NET C#
I want to create some plots using R. Save them as .png or .jpg image in R. And then display the image on the web page.

can you please tell me how to call an R script from c#, asp.net. I have found that R.NET has issues, so I am trying to avoid using it.

Here is my R script:

```<code>library(stats)
library(ggplot2)
getwd()
setwd("C:\\Users\\..................")
mydatadata <- read.csv(file = "boxplot_test_data.csv", header = TRUE, sep = ",")
ggplot(mydata, aes(y=Y, x=X, fill=fillFactor)) +    geom_boxplot(outlier.color=NA) + geom_point(aes(size=AXI, shape=FA), color="gold", position=position_jitter(width=0.1, height=0))
ggsave("myggplot2.png")
</code>```

答:
R has command line executables. There are a few different SO threads with various answers on the best way to do this. For example, see How to run a R language(.r) file using Batch file?

From within C# you can use `System.Diagnositics.Process' to start the executable using your chosen method and wait for the process to exit.:

```<code>var myRProcess = new Process {StartInfo = new ProcessStartInfo(processPath)};
myRProcess.Start();
myRProcess.WaitForExit();
</code>```

Once it has completes your image will be in the the location you saved it to.

From there you can serve the image as you would any image.

Title: How to Run R Script from ASP.NET C#

Body:
I want to create some plots using R. Save them as .png or .jpg image in R. And then display the image on the web page.

can you please tell me how to call an R script from c#, asp.net. I have found that R.NET has issues, so I am trying to avoid using it.

Here is my R script:

library(stats)
library(ggplot2)
getwd()
setwd("C:\\Users\\..................")
mydatadata <- read.csv(file = "boxplot_test_data.csv", header = TRUE, sep = ",")
ggplot(mydata, aes(y=Y, x=X, fill=fillFactor)) +    geom_boxplot(outlier.color=NA) + geom_point(aes(size=AXI, shape=FA), color="gold", position=position_jitter(width=0.1, height=0))
ggsave("myggplot2.png")

Body:
R has command line executables. There are a few different SO threads with various answers on the best way to do this. For example, see How to run a R language(.r) file using Batch file?

From within C# you can use `System.Diagnositics.Process' to start the executable using your chosen method and wait for the process to exit.:

var myRProcess = new Process {StartInfo = new ProcessStartInfo(processPath)};
myRProcess.Start();
myRProcess.WaitForExit();

Once it has completes your image will be in the the location you saved it to.

From there you can serve the image as you would any image.


问:
Capture Click event of button with image in WPF
I'm new to WPF and created a draggable button with an image inside - which works nicely...but I can't seem to capture the onClick of the button which contains the image?

```<code><Window x:Class="PAD.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:PAD"
    mc:Ignorable="d"
    Title="C2D" Height="134" Width="134" WindowStyle="None" Background="Transparent" Foreground="Transparent" BorderBrush="Transparent" BorderThickness="0" ResizeMode="NoResize" AllowsTransparency="True">
<Grid x:Name="ClickIcon" Background="Transparent" >

    <Button x:Name="dialButton" HorizontalAlignment="Left" VerticalAlignment="Top" Width="130" Height="130" Foreground="Transparent" Background="Transparent" BorderThickness="0" BorderBrush="Transparent" >
        <Button.Template>
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid>
                    <Ellipse Fill="Transparent"/>
                    <ContentPresenter Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    <Image x:Name="phoneIcon"  Width="128" Height="128" Source="c:\users\chapmd1\documents\visual studio 2015\Projects\PAD\PAD\red-phone-icon_300205.png" MouseDown="image_MouseDown" />
                </Grid>
            </ControlTemplate>
        </Button.Template>

    </Button>

 private void image_MouseDown(object sender, MouseButtonEventArgs e)
    {
            this.DragMove();

    }
</code>```

I tried the onClick on the Button, but nothing got captured?

答:
Your problem is probably somewhere else. This works as expected:

XAML:

```<code><Grid x:Name="ClickIcon" Background="Transparent" >
    <Button
        Click="dialButton_Click"
        x:Name="dialButton"
        HorizontalAlignment="Left"
        VerticalAlignment="Top" Width="130" Height="130"
        Foreground="Transparent"
        Background="Transparent"
        BorderThickness="0"
        BorderBrush="Transparent">
        <Button.Template>
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid >
                    <Ellipse Fill="Transparent"/>
                    <ContentPresenter
                        Content="{TemplateBinding Content}"
                        HorizontalAlignment="Center"
                        VerticalAlignment="Center"/>
                    <Image x:Name="phoneIcon"
                           Width="128" Height="128"
                           Source="..."
                           MouseDown="phoneIcon_MouseDown"/>
                </Grid>
            </ControlTemplate>
        </Button.Template>
    </Button>
</Grid>
</code>```

C#:

```<code>private void phoneIcon_MouseDown(object sender, MouseButtonEventArgs e)
{
    System.Diagnostics.Trace.WriteLine("phoneIcon_MouseDown");
}

private void dialButton_Click(object sender, RoutedEventArgs e)
{
    System.Diagnostics.Trace.WriteLine("dialButton_Click");
}
</code>```

Body:
I'm new to WPF and created a draggable button with an image inside - which works nicely...but I can't seem to capture the onClick of the button which contains the image?

<Window x:Class="PAD.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:PAD"
    mc:Ignorable="d"
    Title="C2D" Height="134" Width="134" WindowStyle="None" Background="Transparent" Foreground="Transparent" BorderBrush="Transparent" BorderThickness="0" ResizeMode="NoResize" AllowsTransparency="True">
<Grid x:Name="ClickIcon" Background="Transparent" >

    <Button x:Name="dialButton" HorizontalAlignment="Left" VerticalAlignment="Top" Width="130" Height="130" Foreground="Transparent" Background="Transparent" BorderThickness="0" BorderBrush="Transparent" >
        <Button.Template>
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid>
                    <Ellipse Fill="Transparent"/>
                    <ContentPresenter Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    <Image x:Name="phoneIcon"  Width="128" Height="128" Source="c:\users\chapmd1\documents\visual studio 2015\Projects\PAD\PAD\red-phone-icon_300205.png" MouseDown="image_MouseDown" />
                </Grid>
            </ControlTemplate>
        </Button.Template>

    </Button>

 private void image_MouseDown(object sender, MouseButtonEventArgs e)
    {
            this.DragMove();

    }

I tried the onClick on the Button, but nothing got captured?

Body:
Your problem is probably somewhere else. This works as expected:

XAML:

<Grid x:Name="ClickIcon" Background="Transparent" >
    <Button
        Click="dialButton_Click"
        x:Name="dialButton"
        HorizontalAlignment="Left"
        VerticalAlignment="Top" Width="130" Height="130"
        Foreground="Transparent"
        Background="Transparent"
        BorderThickness="0"
        BorderBrush="Transparent">
        <Button.Template>
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid >
                    <Ellipse Fill="Transparent"/>
                    <ContentPresenter
                        Content="{TemplateBinding Content}"
                        HorizontalAlignment="Center"
                        VerticalAlignment="Center"/>
                    <Image x:Name="phoneIcon"
                           Width="128" Height="128"
                           Source="..."
                           MouseDown="phoneIcon_MouseDown"/>
                </Grid>
            </ControlTemplate>
        </Button.Template>
    </Button>
</Grid>

C#:

private void phoneIcon_MouseDown(object sender, MouseButtonEventArgs e)
{
    System.Diagnostics.Trace.WriteLine("phoneIcon_MouseDown");
}

private void dialButton_Click(object sender, RoutedEventArgs e)
{
    System.Diagnostics.Trace.WriteLine("dialButton_Click");
}


问:
why does comparing three array elements return false
My question might sound silly but it is fundamental. I am trying to compare the elements of an array and I am getting inaccurate result.

$(document).ready(function(){
   var array =["a","a","a"]

   console.log(array[0]===array[1]===array[2])
})```
<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></code>```

why does it return false? What can I do to get the right result?

答:
Cause of the problem:

Because:

```<code>a === b === c
</code>```

is the same as:

```<code>(a === b) === c
</code>```

thus you are comparing the result of one comparaison (between a and b) (which will be either true or false) with the last item c.

Solution:

To compare the three items use a logical and operator like this:

```<code>a === b && b === c
</code>```

using logical and to check if a is eqaul to b and if b is equal to c (or if a is equal to c). If one comparaison fail, then the whole test fail, If not then the three items are equal.

Body:
My question might sound silly but it is fundamental. I am trying to compare the elements of an array and I am getting inaccurate result.

$(document).ready(function(){
   var array =["a","a","a"]

   console.log(array[0]===array[1]===array[2])
})

why does it return false? What can I do to get the right result?

Body:
Cause of the problem:

Because:

a === b === c

is the same as:

(a === b) === c

thus you are comparing the result of one comparaison (between a and b) (which will be either true or false) with the last item c.

Solution:

To compare the three items use a logical and operator like this:

a === b && b === c

using logical and to check if a is eqaul to b and if b is equal to c (or if a is equal to c). If one comparaison fail, then the whole test fail, If not then the three items are equal.


答:
Let's break this down...

```<code>'a'==='a'==='a'
('a'==='a')==='a'
true==='a'
false
</code>```

If you want to compare multiple elements in an array to a specific value, I'd recommend the every() method:

var array = ['a', 'a', 'a'];

console.log(array.every((value) => value === 'a'));```

Title: why does comparing three array elements return false

Body:
Let's break this down...

'a'==='a'==='a'
('a'==='a')==='a'
true==='a'
false

If you want to compare multiple elements in an array to a specific value, I'd recommend the every() method:

var array = ['a', 'a', 'a'];

console.log(array.every((value) => value === 'a'));


答:
array[0]===array[1] returns true. You then essentially say true===array[2], which is false.

You could say array[0] === array[1] && array[0] === array[2] which I think is logically the same.


问:
Add_action inside of another add_action
I'd like to have this hook be used

```<code>foreach($admin_page_hooks as $hook){
    add_action('admin_head-'.$hook, 'add_headernew');
}
</code>```

but I want to have it be called after the wp side menu has been uploaded any ideas?

答:
I ended up switching

```<code>add_action('admin_head-'.$hook, 'add_headernew');
</code>```

With

```<code>add_action('in_admin_header'.$hook, 'add_headernew');
</code>```

It was being called before the wpwrap div and now its called inside of the wrapper.

Title: Add_action inside of another add_action

Body:
I'd like to have this hook be used

foreach($admin_page_hooks as $hook){
    add_action('admin_head-'.$hook, 'add_headernew');
}

but I want to have it be called after the wp side menu has been uploaded any ideas?

Body:
I ended up switching

add_action('admin_head-'.$hook, 'add_headernew');

With

add_action('in_admin_header'.$hook, 'add_headernew');

It was being called before the wpwrap div and now its called inside of the wrapper.


问:
javascript test if div has text in it
```<code>1. <div id="div_Msg"> Test the div </div>
2. <div id="div_Msg"> </div>
</code>```

In  the first instance there is the text  in the div. In the second instance there is no text. Using javascript how can it be tested if a div has text in it.

答:
If you are using jQuery, you can do it like this:

```<code>if($.trim($('#div_Msg').text()) != "") {
    // Code here
}
</code>```

In just plain JavaScript, do this:

```<code>if(document.getElementById("div_Msg").innerHTML.replace(/^\s*/, "").replace(/\s*$/, "") != "") {
    // Code here
}
</code>```

Both cases get the text and trim whitespace off the beginning and end of the string, then compare it to an empty string.

Title: javascript test if div has text in it

Body:
1.
 Test the div

2.

In  the first instance there is the text  in the div. In the second instance there is no text. Using javascript how can it be tested if a div has text in it.

Body:
If you are using jQuery, you can do it like this:

if($.trim($('#div_Msg').text()) != "") {
    // Code here
}

In just plain JavaScript, do this:

if(document.getElementById("div_Msg").innerHTML.replace(/^\s*/, "").replace(/\s*$/, "") != "") {
    // Code here
}

Both cases get the text and trim whitespace off the beginning and end of the string, then compare it to an empty string.


问:
Create JavaScript Array From MSSQL Query
I am attempting to create a JavaScript array from a MSSQL query results.  Below is my syntax that I attempt to use, but the array is not created.  How should this be set-up so that the JavaScript array is properly assigned?</p>

```<code><?php
    $mssql = new mssql("localhost", "user", "password", "testdb");
    $data=mssql_query($mssql,"SELECT * FROM test");
?>
<script>
    var firstNames=[<?php
        while($info=mssql_fetch_array($data))
            echo $info['f_name'].',';
?>];
<?php
    $data=mssql_query($mssql,"SELECT * FROM test");
?>
var lastNames=[<?php
        while($info=myssql_fetch_array($data))
            echo '"'.$info['l_name'].'",';
?>];
</script>
<?php
    $mysqli->close();
?>
</code>```

答:
A good approach here would be to get the query (after correcting the deficiencies in the code as noted below your post, then casting the whole array to JSON using json_encode($data); and then echo $data in to your javascript.

This is not the only way to do it. I'm sure others will suggest other things.

Body:
I am attempting to create a JavaScript array from a MSSQL query results.  Below is my syntax that I attempt to use, but the array is not created.  How should this be set-up so that the JavaScript array is properly assigned?

<?php
    $mssql = new mssql("localhost", "user", "password", "testdb");
    $data=mssql_query($mssql,"SELECT * FROM test");
?>

<?php
    $mysqli->close();
?>


问:
many Tomcat Threads sleeping - org.apache.catalina.connector.CoyoteAdapter.postParseRequest
While my tomcat server was up and working, it was not able to server requests from one specific app -  the browser would just keep spinning (just at the simple login page itself). No errors. From multiple thread dumps, i see only one this suspicious. There are 100's of the threads sleeping, all same stack trace.

Why would so all these be threads be sleeping at CoyoteAdapter.postParseRequest ?

```<code>http-nio-8080-exec-159 - priority:6 - threadId:0x000000000f5f5000 - nativeId:0x658 - state:TIMED_WAITING
stackTrace:
java.lang.Thread.State: TIMED_WAITING (sleeping)
at java.lang.Thread.sleep(Native Method)
at org.apache.catalina.connector.CoyoteAdapter.postParseRequest(CoyoteAdapter.java:754)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:344)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
- locked <0x00000007dcc67fe8> (a org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
</code>```

答:
Looking at the tomcat source code, the postParseRequest will sleep if the context is paused, the context gets paused while it is being reloaded.

Looking through your thread dump to see which one is reloading the context, should shed some more light on the issue.

Body:
While my tomcat server was up and working, it was not able to server requests from one specific app -  the browser would just keep spinning (just at the simple login page itself). No errors. From multiple thread dumps, i see only one this suspicious. There are 100's of the threads sleeping, all same stack trace.

Why would so all these be threads be sleeping at CoyoteAdapter.postParseRequest ?

http-nio-8080-exec-159 - priority:6 - threadId:0x000000000f5f5000 - nativeId:0x658 - state:TIMED_WAITING
stackTrace:
java.lang.Thread.State: TIMED_WAITING (sleeping)
at java.lang.Thread.sleep(Native Method)
at org.apache.catalina.connector.CoyoteAdapter.postParseRequest(CoyoteAdapter.java:754)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:344)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
- locked <0x00000007dcc67fe8> (a org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)


问:
OSX Photos video play/pause Applescript shortcut
There is currently no keyboard shortcut to play videos in the new Mac Photos application.https://discussions.apple.com/thread/6996731?start=0&tstart=0

Rather than be frustrated in manually clicking the "play" button hundreds of times, I would like to run an Applescript to play/pause with a keyboard shortcut. I tried with no success:
tell application "photos"
"play" video
end tell
Any help advice on this would be appreciated.
Thanks

答: Just to update Paul's response, in Photos 2.0 (3150.4.120), you need to hit TAB twice, then spacebar will start playback.  Similarly you need to hit TAB twice once you are done playing it, and then (and only then) spacebar will take you back to the grid view of your thumbnails.


问:
How to trigger scroll event in acceptance test
I need to trigger window scroll event to test infinite scrolling, I've tried to use triggerEvent, but it seems that I missing something and it doesn't work. I'm using Ember 2.0 and list is rendered inside the component if it matters. Test fails on last 2 assertions, scroll position doesn't change after triggering event

```<code>test 'loads more items when scrolling', (assert) ->
  visit '/locations/1'
  andThen ->
    assert.equal(find('.items-list li').length, 30)

    find(window).scrollTop(10000)
    triggerEvent(window, 'scroll')

    andThen ->
      assert.ok(find(window).scrollTop() > 0, 'window should scroll')
      assert.ok(find('.items-list li').length > 30, 'should load more items after reaching threshold')
</code>```

Has anyone successfully triggered scroll event in their tests?

答:
Finally I could make it work! Used #ember-testing-container instead window.

The code below was what worked for me:

```<code>andThen(() => {
  Ember.$('#ember-testing-container').scrollTop(10000);
});

triggerEvent(Ember.$('#ember-testing-container'), 'scroll');

andThen(() => {
  assert.ok(Ember.$('#ember-testing-container').scrollTop() > 0, 'window should scroll')
});
</code>```

With ember-infinity you also need to scroll down the body before starting the test:

```<code>Ember.$('body').scrollTop(2000);
</code>```

Body:
I need to trigger window scroll event to test infinite scrolling, I've tried to use triggerEvent, but it seems that I missing something and it doesn't work. I'm using Ember 2.0 and list is rendered inside the component if it matters. Test fails on last 2 assertions, scroll position doesn't change after triggering event

test 'loads more items when scrolling', (assert) ->
  visit '/locations/1'
  andThen ->
    assert.equal(find('.items-list li').length, 30)

    find(window).scrollTop(10000)
    triggerEvent(window, 'scroll')

    andThen ->
      assert.ok(find(window).scrollTop() > 0, 'window should scroll')
      assert.ok(find('.items-list li').length > 30, 'should load more items after reaching threshold')

Has anyone successfully triggered scroll event in their tests?

Body:
Finally I could make it work! Used #ember-testing-container instead window.

The code below was what worked for me:

andThen(() => {
  Ember.$('#ember-testing-container').scrollTop(10000);
});

triggerEvent(Ember.$('#ember-testing-container'), 'scroll');

andThen(() => {
  assert.ok(Ember.$('#ember-testing-container').scrollTop() > 0, 'window should scroll')
});

With ember-infinity you also need to scroll down the body before starting the test:

Ember.$('body').scrollTop(2000);


问:
how to combine two LPCWSTRs?
I have two variables that are LPCWSTRs. I want to create a new variable that will have the values of the first and second variable.

I tried this but it didn't work.

```<code>LPCWSTR d = L"sd";
LPCWSTR f = L"f";
LPCWSTR df = d + f;
</code>```

I get this error when i try that.

```<code>1   IntelliSense: expression must have integral or enum type
</code>```

Is there a function that can combine two LPCWSTRs?

答:
In C++ it is usually a good idea to use std::string for manipulations with strings. In your case it could look like:

```<code>LPCWSTR d = L"sd";
LPCWSTR f = L"f";
std::wstring df = std::wstring(d) + f;
LPCWSTR dfc = df.c_str(); // if you are really need this
</code>```

Title: how to combine two LPCWSTRs?

Body:
I have two variables that are LPCWSTRs. I want to create a new variable that will have the values of the first and second variable.

I tried this but it didn't work.

LPCWSTR d = L"sd";
LPCWSTR f = L"f";
LPCWSTR df = d + f;

I get this error when i try that.

1   IntelliSense: expression must have integral or enum type

Is there a function that can combine two LPCWSTRs?

Body:
In C++ it is usually a good idea to use std::string for manipulations with strings. In your case it could look like:

LPCWSTR d = L"sd";
LPCWSTR f = L"f";
std::wstring df = std::wstring(d) + f;
LPCWSTR dfc = df.c_str(); // if you are really need this


问:
gSoap fault SOAP-ENV:MustUnderstand[no subcode]
I am building a web service for ONVIF camera using gSoap.
I have generated the header and the source files using the core wdsl provided by ONVIF at https://www.onvif.org/profiles/specifications/.

However, every time i make a request from the client i get the below error in the function soap_begin_serve(soap):

```<code>SOAP 1.2 fault SOAP-ENV:MustUnderstand[no subcode]
"The data in element 'Security' must be understood but cannot be processed"
</code>```

What does the above error means and how can i fix it?

EDIT: This is what i receive at the camera side:

```<code>POST / HTTP/1.1
Content-Type: application/soap+xml; charset=utf-8; action="http://www.onvif.org/ver10/device/wsdl/GetSystemDateAndTime"
Host: localhost:8090
Content-Length: 261
Accept-Encoding: gzip, deflate
Connection: Close

<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"><s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><GetSystemDateAndTime xmlns="http://www.onvif.org/ver10/device/wsdl"/></s:Body></s:Envelope>POST / HTTP/1.1
Content-Type: application/soap+xml; charset=utf-8; action="http://www.onvif.org/ver10/device/wsdl/GetScopes"
Host: localhost:8090
Content-Length: 905
Accept-Encoding: gzip, deflate
Connection: Close

<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"><s:Header><Security s:mustUnderstand="1" xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"><UsernameToken><Username>admin</Username><Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">WFz21zL8rch8LRoxAPzgHRMBbr0=</Password><Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">9y79ka0xD02oCIw6GAoIPwEAAAAAAA==</Nonce><Created xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2017-05-21T08:15:58.902Z</Created></UsernameToken></Security></s:Header><s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><GetScopes xmlns="http://www.onvif.org/ver10/device/wsdl"/></s:Body></s:Envelope>
</code>```

答:
SOAP 1.2 fault SOAP-ENV:MustUnderstand[no subcode]
  "The data in element 'Security' must be understood but cannot be processed"

This means that you will need to enable WS-Security to authenticate:

add #import "wsse.h" to the .h header file (aka. service and data binding "interface file") for soapcpp2 to process.

in your source code, #include "plugin/wsseapi.h"

in your source code, provide the user credentials before sending the request with soap_wsse_add_UsernameTokenDigest(soap, NULL, "username", "password");

compile the source code with compiler flag -DWITH_OPENSSL and compile your application code base together with plugin/wsseapi.c, plugin/smdevp.c, and plugin/mecevp.c (the plugin directory is in the gSOAP distro path), and of course also compile stdsoap2.c or stdsoap2.cpp and other generated files;

link with OpenSSL -lssl -lcrypto, and perhaps -lz if compression is desired;

when using the full WS-Security plugin capabilities with gSOAP (digital signature and/or encryption), you should compile all your source code with compiler option -DWITH_OPENSSL -DWITH_DOM -DWITH_GZIP and also compile dom.c or dom.cpp together with your code.

See also the WS-Security plugin for gSOAP.

Hope this helps.

Body:
I am building a web service for ONVIF camera using gSoap.
I have generated the header and the source files using the core wdsl provided by ONVIF at https://www.onvif.org/profiles/specifications/.

However, every time i make a request from the client i get the below error in the function soap_begin_serve(soap):

SOAP 1.2 fault SOAP-ENV:MustUnderstand[no subcode]
"The data in element 'Security' must be understood but cannot be processed"

What does the above error means and how can i fix it?

EDIT: This is what i receive at the camera side:

POST / HTTP/1.1
Content-Type: application/soap+xml; charset=utf-8; action="http://www.onvif.org/ver10/device/wsdl/GetSystemDateAndTime"
Host: localhost:8090
Content-Length: 261
Accept-Encoding: gzip, deflate
Connection: Close

<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"><s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><GetSystemDateAndTime xmlns="http://www.onvif.org/ver10/device/wsdl"/></s:Body></s:Envelope>POST / HTTP/1.1
Content-Type: application/soap+xml; charset=utf-8; action="http://www.onvif.org/ver10/device/wsdl/GetScopes"
Host: localhost:8090
Content-Length: 905
Accept-Encoding: gzip, deflate
Connection: Close

<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"><s:Header><Security s:mustUnderstand="1" xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"><UsernameToken><Username>admin</Username><Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">WFz21zL8rch8LRoxAPzgHRMBbr0=</Password><Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">9y79ka0xD02oCIw6GAoIPwEAAAAAAA==</Nonce><Created xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2017-05-21T08:15:58.902Z</Created></UsernameToken></Security></s:Header><s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><GetScopes xmlns="http://www.onvif.org/ver10/device/wsdl"/></s:Body></s:Envelope>