问:
Count number of appearances in JSON data for nested element
How I can get the appearance of elements in JSON data for nested element?

```<code>[
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'highestCurrent(scale(vcenter.*.*.*.*.cpu.usage_percent_average, 0.01), 5)'  -w 1 -c 6 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"vm_cpu_average",
                            "issued":1490774610,
                            "executed":1490774610,
                            "duration":0.142,
                            "output":"CheckGraphiteStat WARNING: No data from Graphite\n",
                            "status":3,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'collectd.*.*.system.memory.used.pct' -w 50 -c 75 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"mem_average",
                            "issued":1490774614,
                            "executed":1490774614,
                            "duration":0.223,
                            "output":"CheckGraphiteStat CRITICAL: collectd.DEMO.172_16_109_100.system.memory.used.pct is 94.44555555555556 \n",
                            "status":2,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'scale(vcenter.*.*.*.*.mem.usage_percent_average, 0.01)' -w 50 -c 75 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"vm_mem_average",
                            "issued":1490774614,
                            "executed":1490774614,
                            "duration":0.216,
                            "output":"CheckGraphiteStat WARNING: No data from Graphite\n",
                            "status":3,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'absolute(offset(collectd.*.*.system.cpu.idle.pct, -100))'  -c 7 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"cpu_average",
                            "issued":1490774613,
                            "executed":1490774613,
                            "duration":0.124,
                            "output":"CheckGraphiteStat CRITICAL: absolute(offset(collectd.DEMO.172_16_109_100.system.cpu.idle.pct,-100)) is 10.585147058823525 \n",
                            "status":2,
                            "type":"standard"
                    }
    }
</code>```

]

I need to count the number of appearances of WARNING and CRITICAL appeared, if it's appeared in output(check -> output).

Please excuse if this is a novice question. I'm new to this.

答:
you need to count the responses on the frontend?  You can use a regex to parse the json if you'd like.

```<code>var numMatches = (JSON.stringify(yourData).match(/(WARNING|CRITICAL)/g) || []).length;
</code>```

This should be faster than iterated over each item and running a separate regex on each attribute separately.  So if you are going to be running over a large data set I recommend this over the other solutions.

Body:
How I can get the appearance of elements in JSON data for nested element?

[
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'highestCurrent(scale(vcenter.*.*.*.*.cpu.usage_percent_average, 0.01), 5)'  -w 1 -c 6 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"vm_cpu_average",
                            "issued":1490774610,
                            "executed":1490774610,
                            "duration":0.142,
                            "output":"CheckGraphiteStat WARNING: No data from Graphite\n",
                            "status":3,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'collectd.*.*.system.memory.used.pct' -w 50 -c 75 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"mem_average",
                            "issued":1490774614,
                            "executed":1490774614,
                            "duration":0.223,
                            "output":"CheckGraphiteStat CRITICAL: collectd.DEMO.172_16_109_100.system.memory.used.pct is 94.44555555555556 \n",
                            "status":2,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'scale(vcenter.*.*.*.*.mem.usage_percent_average, 0.01)' -w 50 -c 75 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"vm_mem_average",
                            "issued":1490774614,
                            "executed":1490774614,
                            "duration":0.216,
                            "output":"CheckGraphiteStat WARNING: No data from Graphite\n",
                            "status":3,
                            "type":"standard"
                    }
    },
    {
            "client":"172.16.109.96",
            "check":
                    {
                            "command":"/var/lib/gems/1.9.1/gems/sensu-plugins-graphite-1.1.0/bin/check-graphite-stats.rb -h 172.16.109.96:8081 -t 'absolute(offset(collectd.*.*.system.cpu.idle.pct, -100))'  -c 7 -p -6hours",
                            "standalone":true,
                            "interval":5,
                            "name":"cpu_average",
                            "issued":1490774613,
                            "executed":1490774613,
                            "duration":0.124,
                            "output":"CheckGraphiteStat CRITICAL: absolute(offset(collectd.DEMO.172_16_109_100.system.cpu.idle.pct,-100)) is 10.585147058823525 \n",
                            "status":2,
                            "type":"standard"
                    }
    }

]

I need to count the number of appearances of WARNING and CRITICAL appeared, if it's appeared in output(check -> output).

Please excuse if this is a novice question. I'm new to this.

Body:
you need to count the responses on the frontend?  You can use a regex to parse the json if you'd like.

var numMatches = (JSON.stringify(yourData).match(/(WARNING|CRITICAL)/g) || []).length;

This should be faster than iterated over each item and running a separate regex on each attribute separately.  So if you are going to be running over a large data set I recommend this over the other solutions.


来源: stackexchange

问:
Github pull without a pull request
On github, how is it possible for the owner of an original repository to pull the changes that were made in a fork by another user, without a pull request? Or anyway include the fork's changes into the original repository, maintaining information about the fork's author?

Should I clone the fork and then push it to the original repository?
Or I could copy them manually, but that wouldn't be fair at all, because the project would lose any information about the fork's changes author.

答:
You would use the normal distributed workflow of Git here. That is, add the other repository as a second remote to your local repository, and then simply merge their changes in.

```<code>git remote add others-fork https://github.com/otheruser/fork.git
git fetch others-fork

git checkout master
git merge others-fork/master
</code>```

This would merge the changes from their master into your local master. Afterwards, you can push your changes to publish their commits in your repository.

ContentLicense: CC BY-SA 3.0

Title: Github pull without a pull request

Body:
You would use the normal distributed workflow of Git here. That is, add the other repository as a second remote to your local repository, and then simply merge their changes in.

git remote add others-fork https://github.com/otheruser/fork.git
git fetch others-fork

git checkout master
git merge others-fork/master

This would merge the changes from their master into your local master. Afterwards, you can push your changes to publish their commits in your repository.


问:
Can we create custom HTTP Status codes?
I have a REST and WCF service and want to send a custom status code based on the operation.

For example when some validation fails then I want to send HTTP 444 and when authorization fails I want to send HTTP 455

The question is how do we have it validated for both SOAP and REST web services.

On the client how does the error code act because when you send an HTTP 400/500 from a WCF Service (using SOAP) an exception is thrown on the client showing the status code?

Now if I send a new custom status code how does the client handle this?

答:
Some applications add their custom response codes in the range 600-799. Check for example the response code list from KeyNote here

Keynote Defined Error Codes (600-799)

```<code>600: CONNECTION ERROR - This indicates a general connection error
601: INCOMPLETE ERROR - This indicates sever sends an incomplete page/object (as indicated by Content-Length header)
602: UNEXPECTED CLOSE ERROR - This indicates socket connection has been closed unexpectedly
603: REFUSED ERROR - This indicates a request to connect to the server is refused
604: TIMEOUT ERROR - This indicates there is no activity in socket connection in 3 minutes
605: REDIRECT ERROR - This indicates an error in redirect HTTP header
606: SSL ERROR - This indicates a general error in SSL
607: HEADER ERROR - This indicates a malformed HTTP header
608: EMPTY RESPONSE ERROR - This indicates server doesn't send any response after a request is sent
609: UNKNOWN HOST ERROR - This indicates socket receives an unknown host error from DNS
610: NO ROUTE TO HOST ERROR - This indicates a no route to host error was received while attempting to open a socket
611: SOCKET ERROR - This indicates a general socket error
612: FRAME LOOP ERROR - This indicates a page has a frame loop (frame A includes Frame B that includes Frame A)
613: REDIRECT LOOP ERROR - This indicates a page has a redirect loop (page A redirects to page B that redirects to page A)
614: CONNECTION RESET ERROR - This indicates socket receive a reset signal from the server
615: SOCKET PROTOCOL ERROR - This indicates an error in socket protocol
616: SOCKET BIND ERROR - This indicates an error in binding the socket
617: CONNECTION ERROR - This indicates a general socket connection error
618: CHUNK ERROR - This indicates an error in chunked encoding
619: SSL TIMEOUT - This indicates a timeout during SSL handshake (2 minutes)
620: SSL END OF INPUT - This indicates an end-of-file is received during SSL handshake
621: SSL HANDSHAKE ERROR - This indicates a general error during SSL handshake
622: SSL CERTIFICATE ERROR - This indicates an error in SSL certificate verification
623: SSL AUTHENTICATION ERROR - This indicates an authentication error during SSL handshake
624: SSL BAD MAC ERROR - This indicates a bad MAC during SSL handshake
625: SSL CIPHER ERROR - This indicates a cipher error during SSL handshake
701: ERROR TEXT FOUND - This code is returned if any error text (such as, "Service Unavailable") are found in the main page (frame HTML contents included). Note that the error text must be defined in advance of the test. Error text means if the text is found, this session should be considered a failure.
702: REQUIRED TEXT NOT FOUND - This code is returned If not all required texts are found in the main page. Note that required text must be defined in advance of the test. Required text means if the text is not found, this session should be considered a failure.
703: HTML BODY EMPTY - This code is returned if the HTML body of the page is empty (only if error text or required text has been defined).
</code>```

Whether this is good practice I would not dare to say, but it is an interesting reference at least.

ContentLicense: CC BY-SA 4.0

Title: Can we create custom HTTP Status codes?

Body:
Some applications add their custom response codes in the range 600-799. Check for example the response code list from KeyNote here

Keynote Defined Error Codes (600-799)

600: CONNECTION ERROR - This indicates a general connection error
601: INCOMPLETE ERROR - This indicates sever sends an incomplete page/object (as indicated by Content-Length header)
602: UNEXPECTED CLOSE ERROR - This indicates socket connection has been closed unexpectedly
603: REFUSED ERROR - This indicates a request to connect to the server is refused
604: TIMEOUT ERROR - This indicates there is no activity in socket connection in 3 minutes
605: REDIRECT ERROR - This indicates an error in redirect HTTP header
606: SSL ERROR - This indicates a general error in SSL
607: HEADER ERROR - This indicates a malformed HTTP header
608: EMPTY RESPONSE ERROR - This indicates server doesn't send any response after a request is sent
609: UNKNOWN HOST ERROR - This indicates socket receives an unknown host error from DNS
610: NO ROUTE TO HOST ERROR - This indicates a no route to host error was received while attempting to open a socket
611: SOCKET ERROR - This indicates a general socket error
612: FRAME LOOP ERROR - This indicates a page has a frame loop (frame A includes Frame B that includes Frame A)
613: REDIRECT LOOP ERROR - This indicates a page has a redirect loop (page A redirects to page B that redirects to page A)
614: CONNECTION RESET ERROR - This indicates socket receive a reset signal from the server
615: SOCKET PROTOCOL ERROR - This indicates an error in socket protocol
616: SOCKET BIND ERROR - This indicates an error in binding the socket
617: CONNECTION ERROR - This indicates a general socket connection error
618: CHUNK ERROR - This indicates an error in chunked encoding
619: SSL TIMEOUT - This indicates a timeout during SSL handshake (2 minutes)
620: SSL END OF INPUT - This indicates an end-of-file is received during SSL handshake
621: SSL HANDSHAKE ERROR - This indicates a general error during SSL handshake
622: SSL CERTIFICATE ERROR - This indicates an error in SSL certificate verification
623: SSL AUTHENTICATION ERROR - This indicates an authentication error during SSL handshake
624: SSL BAD MAC ERROR - This indicates a bad MAC during SSL handshake
625: SSL CIPHER ERROR - This indicates a cipher error during SSL handshake
701: ERROR TEXT FOUND - This code is returned if any error text (such as, "Service Unavailable") are found in the main page (frame HTML contents included). Note that the error text must be defined in advance of the test. Error text means if the text is found, this session should be considered a failure.
702: REQUIRED TEXT NOT FOUND - This code is returned If not all required texts are found in the main page. Note that required text must be defined in advance of the test. Required text means if the text is not found, this session should be considered a failure.
703: HTML BODY EMPTY - This code is returned if the HTML body of the page is empty (only if error text or required text has been defined).

Whether this is good practice I would not dare to say, but it is an interesting reference at least.


问:
Couldn't get Apple Photos details - C# macOS Sierra 10.12 Xamarin Application
I'm developing an iMac desktop application which is able to upload normal photos as well as Photos library (Previously iPhotos library) to online services like Flickr,SmugMug. Before upgrading to Sierra i was able to get details of iPhotos and could upload too but after upgradation those files/directories doesn't exist.

Below is the block by which i was getting files:

```<code>string PhotosLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Photos Library.photoslibrary/Database/apdb/Library.apdb");
</code>```

But above is not working anymore in Sierra 10.12, if i go to finder itself to locate above mentioned path then i find 'Database' directory but no 'apdb' is there by which i can get Library.apdb

I have googled but no luck, can anybody please show me some pointers on how to get Photos Library files using C#.

Please tell me if i missed any information to share.
Thanks.

答:
The Media Library Framework is the place to go if your situation permit.

```<code>NSDictionary<NSString, NSObject> options = new NSDictionary<NSString, NSObject>(
    new[] { MLMediaLibrary.MediaLoadSourceTypesKey, MLMediaLibrary.MediaLoadIncludeSourcesKey },
    new[] { new NSString(MLMediaSourceType.Image.ToString()), MLMediaSource.MediaSourcePhotosIdentifier }
);
var ml = new MLMediaLibrary(options);
ml.AddObserver("mediaSources", 0, (obj) => Console.WriteLine("Loaded"));
var src = ml.MediaSources; // returns null first time
</code>```

In order to access MLMediaLibrary, your application has to be sandboxed and codesigned.

See also https://stackoverflow.com/a/29626032 to learn how to deal with entitlements.plist.

Body:
I'm developing an iMac desktop application which is able to upload normal photos as well as Photos library (Previously iPhotos library) to online services like Flickr,SmugMug. Before upgrading to Sierra i was able to get details of iPhotos and could upload too but after upgradation those files/directories doesn't exist.

Below is the block by which i was getting files:

string PhotosLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Photos Library.photoslibrary/Database/apdb/Library.apdb");

But above is not working anymore in Sierra 10.12, if i go to finder itself to locate above mentioned path then i find 'Database' directory but no 'apdb' is there by which i can get Library.apdb

I have googled but no luck, can anybody please show me some pointers on how to get Photos Library files using C#.

Please tell me if i missed any information to share.
Thanks.

Body:
The Media Library Framework is the place to go if your situation permit.

NSDictionary<NSString, NSObject> options = new NSDictionary<NSString, NSObject>(
    new[] { MLMediaLibrary.MediaLoadSourceTypesKey, MLMediaLibrary.MediaLoadIncludeSourcesKey },
    new[] { new NSString(MLMediaSourceType.Image.ToString()), MLMediaSource.MediaSourcePhotosIdentifier }
);
var ml = new MLMediaLibrary(options);
ml.AddObserver("mediaSources", 0, (obj) => Console.WriteLine("Loaded"));
var src = ml.MediaSources; // returns null first time

In order to access MLMediaLibrary, your application has to be sandboxed and codesigned.

See also https://stackoverflow.com/a/29626032 to learn how to deal with entitlements.plist.


问:
Unable to fetch commit from github
The following commands fail to check out this commit:

```<code>$ git clone git@github.com:DefinitelyTyped/DefinitelyTyped.git
$ cd DefinitelyTyped
$ git checkout e90424c424ef9087d0589234e9e9cd0140bab0d7
fatal: reference is not a tree: e90424c424ef9087d0589234e9e9cd0140bab0d7
</code>```

Attempting to follow the advice given here results in the following:

```<code>$ git fetch origin e90424c424ef9087d0589234e9e9cd0140bab0d7
$ echo $?
1
</code>```

Is this failure something specific to GitHub / large repos on GitHub?  My git version is 2.10.1.

** edit **

```<code>$ git fetch origin e90424c424ef9087d0589234e9e9cd0140bab0d7:refs/remotes/origin/foo-commit
$ echo $?
1
$ git cat-file -p e90424c424ef9087d0589234e9e9cd0140bab0d7
fatal: Not a valid object name e90424c424ef9087d0589234e9e9cd0140bab0d7
$ git branch -a --contains e90424c424ef9087d0589234e9e9cd0140bab0d7
error: no such commit e90424c424ef9087d0589234e9e9cd0140bab0d7
$ git reset e90424c424ef9087d0589234e9e9cd0140bab0d7
fatal: Could not parse object 'e90424c424ef9087d0589234e9e9cd0140bab0d7'.
</code>```

答:
The behavior you are seeing can happen if a repository is rebased.  You can replicate this yourself by pushing a commit to a remote repository, then updating it with git commit --amend and (force) pushing the updated repository.

The old commit id will continue to exist in the remote repository until some sort of garbage collection runs, but because it is unreachable from any existing reference it will not be included in a git clone operation.

Title: Unable to fetch commit from github

Body:
The following commands fail to check out this commit:

$ git clone git@github.com:DefinitelyTyped/DefinitelyTyped.git
$ cd DefinitelyTyped
$ git checkout e90424c424ef9087d0589234e9e9cd0140bab0d7
fatal: reference is not a tree: e90424c424ef9087d0589234e9e9cd0140bab0d7

Attempting to follow the advice given here results in the following:

$ git fetch origin e90424c424ef9087d0589234e9e9cd0140bab0d7
$ echo $?
1

Is this failure something specific to GitHub / large repos on GitHub?  My git version is 2.10.1.

** edit **

$ git fetch origin e90424c424ef9087d0589234e9e9cd0140bab0d7:refs/remotes/origin/foo-commit
$ echo $?
1
$ git cat-file -p e90424c424ef9087d0589234e9e9cd0140bab0d7
fatal: Not a valid object name e90424c424ef9087d0589234e9e9cd0140bab0d7
$ git branch -a --contains e90424c424ef9087d0589234e9e9cd0140bab0d7
error: no such commit e90424c424ef9087d0589234e9e9cd0140bab0d7
$ git reset e90424c424ef9087d0589234e9e9cd0140bab0d7
fatal: Could not parse object 'e90424c424ef9087d0589234e9e9cd0140bab0d7'.


问:
What is the biggest drawback of <your favorite database>?
We all have our favourite database. If you look objectively at your chosen database, what drawbacks does it have and what could be improved?

The rules:

One reply per drawback with;

a short description of the limitation, followed by;

a more detailed description, an explanation of how it could be done better or an example of another technology that does not have the same limitation.

Do not diss any database that you haven't used extensively.  It is easy to take potshots at other technologies but we want to learn form your experience, not your prejudice.

答:
Any SQL DBMS

Defect: Duplicate rows

One of the virtues of the relational model is that it represents everything without duplicate tuples, i.e. using relations, which have keys and no duplicates. Unfortunately SQL isn't built that way. This makes the database developer's life needlessly difficult. SQL developers have to deal with tables without keys and debug queries that return duplicate rows.

OwnerDisplayName: pappes

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Sklivvz


问:
Magento translations ok in online program but not run as cronjob
I created a module (extends Mage_Core_Model_Abstract) and an admin controller.

When I run this module online translations are going right.

When I run this module as cronjob, everything goes allright but translations are not done, I specified translation file in config.xml in as well frontend as adminhtml.

What I am doing wrong?

答:
I see this is a very old question. I've posted here to future reference and others.

Quick and dirty solution

```<code>// Fix unitialized translator
Mage::app()->getTranslator()->init('frontend', true);
</code>```

just after

```<code>$initialEnvironmentInfo = $appEmulation>startEnvironmentEmulation($storeId);
</code>```

for instance. Or in a foreach loop of your own, which is called via cron/admin. Since you're talking about crons, I assume that you know what you are doing.

The real problem

In Magento 1.9 in Mage_Core_Model_App_Emulation (in app/code/core/Mage/Core/Model/App/Emulation.php), there's this function:

```<code>/**
 * Apply locale of the specified store
 *
 * @param integer $storeId
 * @param string $area
 *
 * @return string initial locale code
 */
protected function _emulateLocale($storeId, $area = Mage_Core_Model_App_Area::AREA_FRONTEND)
{
    $initialLocaleCode = $this->_app->getLocale()->getLocaleCode();
    $newLocaleCode = $this->_getStoreConfig(Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE, $storeId);
    if ($initialLocaleCode != $newLocaleCode) {
        $this->_app->getLocale()->setLocaleCode($newLocaleCode);
        $this->_factory->getSingleton('core/translate')->setLocale($newLocaleCode)->init($area, true);
    }
    return $initialLocaleCode;
}
</code>```

The $initialLocaleCode != $newLocaleCode seems to be the issue here. When iteration orders/customers/subscribers/*, the locale could stay the same, which then prevents executing the code in the statement. And the locale is thus not set in the Translator (Mage::app()->getTranslator()).

We've yet to fix the issue, but you could change if ($initialLocaleCode != $newLocaleCode) { to if (true) { straight in the core source. Off course, this is ugly. I suggest something like extending the class and then :

```<code>/**
 * Apply locale of the specified store. Extended
 * to fix Magento's uninitialized translator.
 *
 * @see http://stackoverflow.com/questions/19940733/magento-translations-ok-in-online-program-but-not-run-as-cronjob#
 * @param integer $storeId
 * @param string $area
 *
 * @return string initial locale code
 */
protected function _emulateLocale($storeId, $area = Mage_Core_Model_App_Area::AREA_FRONTEND)
{
    $initialLocaleCode = $this->_app->getLocale()->getLocaleCode();
    $newLocaleCode = $this->_getStoreConfig(Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE, $storeId);

    $this->_app
        ->getLocale()
        ->setLocaleCode($newLocaleCode);

    $this->_factory
        ->getSingleton('core/translate')
        ->setLocale($newLocaleCode)
        ->init($area, true);

    return $initialLocaleCode;
}
</code>```

Magento 2

I guess the developers became aware it was borked and they changed the code in Magento 2. The _emulateLocale() function is gone all together and they added this line to the startEnvironmentEmulation() function, without any conditional around it:

```<code>$this->_localeResolver->setLocale($newLocaleCode);
</code>```

Body:
I see this is a very old question. I've posted here to future reference and others.

Quick and dirty solution

// Fix unitialized translator
Mage::app()->getTranslator()->init('frontend', true);

just after

$initialEnvironmentInfo = $appEmulation>startEnvironmentEmulation($storeId);

for instance. Or in a foreach loop of your own, which is called via cron/admin. Since you're talking about crons, I assume that you know what you are doing.

The real problem

In Magento 1.9 in Mage_Core_Model_App_Emulation (in app/code/core/Mage/Core/Model/App/Emulation.php), there's this function:

/**
 * Apply locale of the specified store
 *
 * @param integer $storeId
 * @param string $area
 *
 * @return string initial locale code
 */
protected function _emulateLocale($storeId, $area = Mage_Core_Model_App_Area::AREA_FRONTEND)
{
    $initialLocaleCode = $this->_app->getLocale()->getLocaleCode();
    $newLocaleCode = $this->_getStoreConfig(Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE, $storeId);
    if ($initialLocaleCode != $newLocaleCode) {
        $this->_app->getLocale()->setLocaleCode($newLocaleCode);
        $this->_factory->getSingleton('core/translate')->setLocale($newLocaleCode)->init($area, true);
    }
    return $initialLocaleCode;
}

The $initialLocaleCode != $newLocaleCode seems to be the issue here. When iteration orders/customers/subscribers/*, the locale could stay the same, which then prevents executing the code in the statement. And the locale is thus not set in the Translator (Mage::app()->getTranslator()).

We've yet to fix the issue, but you could change if ($initialLocaleCode != $newLocaleCode) { to if (true) { straight in the core source. Off course, this is ugly. I suggest something like extending the class and then :

/**
 * Apply locale of the specified store. Extended
 * to fix Magento's uninitialized translator.
 *
 * @see http://stackoverflow.com/questions/19940733/magento-translations-ok-in-online-program-but-not-run-as-cronjob#
 * @param integer $storeId
 * @param string $area
 *
 * @return string initial locale code
 */
protected function _emulateLocale($storeId, $area = Mage_Core_Model_App_Area::AREA_FRONTEND)
{
    $initialLocaleCode = $this->_app->getLocale()->getLocaleCode();
    $newLocaleCode = $this->_getStoreConfig(Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE, $storeId);

    $this->_app
        ->getLocale()
        ->setLocaleCode($newLocaleCode);

    $this->_factory
        ->getSingleton('core/translate')
        ->setLocale($newLocaleCode)
        ->init($area, true);

    return $initialLocaleCode;
}

Magento 2

I guess the developers became aware it was borked and they changed the code in Magento 2. The _emulateLocale() function is gone all together and they added this line to the startEnvironmentEmulation() function, without any conditional around it:

$this->_localeResolver->setLocale($newLocaleCode);


问:
Having an array receive its own value
I am trying to have an array receive its own value plus a specific cell value:

```<code>myarray(1) = myarray(1) + Cells(2,4)
</code>```

But I get error "13": Incompatible types (translated from Portuguese)

I have verified that if I make it:

```<code>myarray(1) = Cells(2,4)
</code>```

It works.

The array has been declared as string.

Please help me out figuring out how to do this.
Best regards,

答:
Thank you, declaring the array as Long did the job. I wanted to add numeric values but was confused with all variable types. I thought String would cover all. Beginner...
Best regards,</p>

Title: Having an array receive its own value

Body:
I am trying to have an array receive its own value plus a specific cell value:

myarray(1) = myarray(1) + Cells(2,4)

But I get error "13": Incompatible types (translated from Portuguese)

I have verified that if I make it:

myarray(1) = Cells(2,4)

It works.

The array has been declared as string.

Please help me out figuring out how to do this.
Best regards,


问:
TestNG Reporting, how to quickly identify Retry-d Tests?
Hello: When a @Test fails and a Retry happens, is there a direct way in TestNG to distinguish between a Test that has been Retried and a test that has not been retried - such as through a NG context method or variable?

Case 1: If a Test not been retried then the 1st test is a test that has not been retried.

Case 2: If a Test that has been retried 2 times then the 3rd test is a test that has not been retried.

Some options i have found such as http://www.seleniumeasy.com/testng-tutorials/retry-listener-failed-tests-count-update - but wanted to check if the community has other means and/or recommendations.

答:
Currently, there is no easy way to know if the test is a retry or not.

Maybe you can to collect every run methods in a testng listener, and then you can determine if the method was retried if you already find it in the list of run methods.

BTW, you should ask for the feature on http://github.com/cbeust/testng/issues


问:
Uncaught Error: Error serializing unrecognized object about a date in react
i use a react-datepicker which i adjust to be compatible with redux form. My Datepicker component is like this:

```<code>const MyDatePicker = ({ input, meta: { touched, error } }) => (
  <div>
    <DatePicker
      {...input} dateFormat="YYYY-MM-DD"
      selected={input.value ? moment(input.value, 'YYYY-MM-DD') : null}
    />
    {
      touched && error &&
      <span className="error">
        {error}
      </span>
    }
  </div>
);
</code>```

By the way it does not show the validation messages when i trigger a validation.
When i enter a date in a date input like the screenshot above:

an error is shown multiple times (5789 to be more accurate). That has the impact of making my app slow when i use dates. I google it but i didn't find a proper solution. Do you have any idea how to handle this? The error is:

```<code>Uncaught Error: Error serializing unrecognized object Sun Mar 26 2017 00:00:00 GMT+0200
    at b.rep (index.js:143)
    at Object.com.cognitect.transit.impl.writer.marshal (transit.js:2912)
    at Object.com.cognitect.transit.impl.writer.emitObjects (transit.js:2755)
    at Object.com.cognitect.transit.impl.writer.emitArray (transit.js:2765)
    at Object.com.cognitect.transit.impl.writer.marshal (transit.js:2930)
    at Object.com.cognitect.transit.impl.writer.emitTaggedMap (transit.js:2892)
    at Object.com.cognitect.transit.impl.writer.emitEncoded (transit.js:2909)
    at Object.com.cognitect.transit.impl.writer.marshal (transit.js:2934)
    at Object.com.cognitect.transit.impl.writer.emitObjects (transit.js:2755)
    at Object.com.cognitect.transit.impl.writer.emitArray
</code>```

Last but not least i use REDUX-FORM/IMMUTABLE

答:
I am too getting same issue. My code look like. </p>

```<code><Container>
  {label && <Label icon={icon}>{label}</Label>}
  <DatePickerPure
    onBlur={() => input.onBlur()}
    // onChange={(val) => input.onChange(val ? val.toDate(val) : null)}
    onChange={(val) => input.onChange(val ? moment(val) : null)}
    selected={dateValue}
    id={`field_${input.name}`}
    placeholder={placeholder}
  />
  <FieldError touched={touched} error={error} warning={warning} />
 </Container>
</code>```

<p>In beginning date Filed was not picking correct date for the very 1st time. It was always picking 1 previous day. As soon as I use momnet(val), date field picking correct date but i m getting this error in my console.
If any body can help </p>

Body:
i use a react-datepicker which i adjust to be compatible with redux form. My Datepicker component is like this:

const MyDatePicker = ({ input, meta: { touched, error } }) => (

    <DatePicker
      {...input} dateFormat="YYYY-MM-DD"
      selected={input.value ? moment(input.value, 'YYYY-MM-DD') : null}
    />
    {
      touched && error &&

        {error}

    }

);

By the way it does not show the validation messages when i trigger a validation.
When i enter a date in a date input like the screenshot above:

an error is shown multiple times (5789 to be more accurate). That has the impact of making my app slow when i use dates. I google it but i didn't find a proper solution. Do you have any idea how to handle this? The error is:

Uncaught Error: Error serializing unrecognized object Sun Mar 26 2017 00:00:00 GMT+0200
    at b.rep (index.js:143)
    at Object.com.cognitect.transit.impl.writer.marshal (transit.js:2912)
    at Object.com.cognitect.transit.impl.writer.emitObjects (transit.js:2755)
    at Object.com.cognitect.transit.impl.writer.emitArray (transit.js:2765)
    at Object.com.cognitect.transit.impl.writer.marshal (transit.js:2930)
    at Object.com.cognitect.transit.impl.writer.emitTaggedMap (transit.js:2892)
    at Object.com.cognitect.transit.impl.writer.emitEncoded (transit.js:2909)
    at Object.com.cognitect.transit.impl.writer.marshal (transit.js:2934)
    at Object.com.cognitect.transit.impl.writer.emitObjects (transit.js:2755)
    at Object.com.cognitect.transit.impl.writer.emitArray

Last but not least i use REDUX-FORM/IMMUTABLE

Body:
I am too getting same issue. My code look like.

<Container>
  {label && <Label icon={icon}>{label}</Label>}
  <DatePickerPure
    onBlur={() => input.onBlur()}
    // onChange={(val) => input.onChange(val ? val.toDate(val) : null)}
    onChange={(val) => input.onChange(val ? moment(val) : null)}
    selected={dateValue}
    id={`field_${input.name}`}
    placeholder={placeholder}
  />
  <FieldError touched={touched} error={error} warning={warning} />
 </Container>

In beginning date Filed was not picking correct date for the very 1st time. It was always picking 1 previous day. As soon as I use momnet(val), date field picking correct date but i m getting this error in my console.
If any body can help


问:
Button links to page in wordpress
Currently I am working on a website where people could take courses from external websites. On the course page there is a button which would take you to that website. I made a meta_box which should hold an URL and use that URL for the button, it looks like this:
link to form picture

But right now it does not take in this URL which I submit in this form. What part am I doing wrong? Here's my code:

This is in functions.php:

```<code>add_action('add_meta_boxes', 'mp_add_custom_metabox');
function mp_meta_callback( $post ) {
    echo "Add the link for the course button here:<br/>";
    echo "<form method='get'>";
    echo "<input type='text' name='buttonurl' placeholder='add a URL here'>";
    echo "<input type='submit' value='Add'>";
    echo "</form>";
}
</code>```

This is in the course single page:

```<code><a href="<?php $_GET['buttonurl'];?>">
    <p>
        <div class="btn btn-primary take-course">
            Go to the course!
        </div>
    </p>
</a>
</code>```

Thank you in advance for the help!

答:
Try like this:

```<code><?php
add_action( 'add_meta_boxes', 'cd_meta_box_add' );
function cd_meta_box_add()
{
    add_meta_box( 'my-meta-box-id', 'My First Meta Box', 'cd_meta_box_cb', 'post', 'normal', 'high' );
}

function cd_meta_box_cb()
{
    global $post;
    $values = get_post_custom( $post->ID );
    $button = isset( $values['buttonurl'] ) ? $values['buttonurl'] : '';?>
    <p>
        <label for="my_meta_box_text">Add the link for the course button here:</label>
        <input type='text' name='buttonurl' placeholder='add a URL here' value='<?php echo $button[0];?>'>
    </p>  <?php
}
add_action( 'save_post', 'cd_meta_box_save' );
function cd_meta_box_save( $post_id )
{
    // Make sure your data is set before trying to save it
    if( isset( $_POST['buttonurl'] ) )
        update_post_meta( $post_id, 'buttonurl', esc_url( $_POST['buttonurl']) );
}
</code>```

You can then use the value in frontend like:

```<code>$button=get_post_meta( $post_id, 'buttonurl', true );

 <a href="<?php echo $button;?>">
    <p>
        <div class="btn btn-primary take-course">
            Go to the course!
        </div>
    </p>
</a>
</code>```

Take a reference to : https://code.tutsplus.com/tutorials/how-to-create-custom-wordpress-writemeta-boxes--wp-20336

Title: Button links to page in wordpress

Body:
Currently I am working on a website where people could take courses from external websites. On the course page there is a button which would take you to that website. I made a meta_box which should hold an URL and use that URL for the button, it looks like this:
link to form picture

But right now it does not take in this URL which I submit in this form. What part am I doing wrong? Here's my code:

This is in functions.php:

add_action('add_meta_boxes', 'mp_add_custom_metabox');
function mp_meta_callback( $post ) {
    echo "Add the link for the course button here:
";
    echo "<form method='get'>";
    echo "<input type='text' name='buttonurl' placeholder='add a URL here'>";
    echo "<input type='submit' value='Add'>";
    echo "</form>";
}

This is in the course single page:

<a href="<?php $_GET['buttonurl'];?>">

            Go to the course!

Thank you in advance for the help!

Body:
Try like this:

<?php
add_action( 'add_meta_boxes', 'cd_meta_box_add' );
function cd_meta_box_add()
{
    add_meta_box( 'my-meta-box-id', 'My First Meta Box', 'cd_meta_box_cb', 'post', 'normal', 'high' );
}

function cd_meta_box_cb()
{
    global $post;
    $values = get_post_custom( $post->ID );
    $button = isset( $values['buttonurl'] ) ? $values['buttonurl'] : '';?>
    <p>
        <label for="my_meta_box_text">Add the link for the course button here:</label>
        <input type='text' name='buttonurl' placeholder='add a URL here' value='<?php echo $button[0];?>'>
    </p>  <?php
}
add_action( 'save_post', 'cd_meta_box_save' );
function cd_meta_box_save( $post_id )
{
    // Make sure your data is set before trying to save it
    if( isset( $_POST['buttonurl'] ) )
        update_post_meta( $post_id, 'buttonurl', esc_url( $_POST['buttonurl']) );
}

You can then use the value in frontend like:

$button=get_post_meta( $post_id, 'buttonurl', true );

 <a href="<?php echo $button;?>">
    <p>
        <div class="btn btn-primary take-course">
            Go to the course!
        </div>
    </p>
</a>

Take a reference to : https://code.tutsplus.com/tutorials/how-to-create-custom-wordpress-writemeta-boxes--wp-20336


问:
Is there a way to reset the app between tests in Swift XCTest UI?
Is there an API call within XCTest that I can put into the setUP() or tearDown() to reset the app between tests? I looked in the dot syntax of XCUIApplication and all I saw was the .launch()

OR is there a way to call a shell script in Swift? I could then call xcrun in-between test methods to reset the simulator.

答:
Updated for swift 3.1 / xcode 8.3

create bridging header in test target:

```<code>#import <XCTest/XCUIApplication.h>
#import <XCTest/XCUIElement.h>

@interface XCUIApplication (Private)
- (id)initPrivateWithPath:(NSString *)path bundleID:(NSString *)bundleID;
- (void)resolve;
@end
</code>```

updated Springboard class

```<code>class Springboard {
   static let springboard = XCUIApplication(privateWithPath: nil, bundleID: "com.apple.springboard")!
   static let settings = XCUIApplication(privateWithPath: nil, bundleID: "com.apple.Preferences")!

/**
Terminate and delete the app via springboard
*/

class func deleteMyApp() {
   XCUIApplication().terminate()

// Resolve the query for the springboard rather than launching it

   springboard.resolve()

// Force delete the app from the springboard
   let icon = springboard.icons["{MyAppName}"] /// change to correct app name
   if icon.exists {
     let iconFrame = icon.frame
     let springboardFrame = springboard.frame
     icon.press(forDuration: 1.3)

  // Tap the little "X" button at approximately where it is. The X is not exposed directly

    springboard.coordinate(withNormalizedOffset: CGVector(dx: (iconFrame.minX + 3) / springboardFrame.maxX, dy: (iconFrame.minY + 3) / springboardFrame.maxY)).tap()

     springboard.alerts.buttons["Delete"].tap()

     // Press home once make the icons stop wiggling

     XCUIDevice.shared().press(.home)
     // Press home again to go to the first page of the springboard
     XCUIDevice.shared().press(.home)
     // Wait some time for the animation end
     Thread.sleep(forTimeInterval: 0.5)

      let settingsIcon = springboard.icons["Settings"]
      if settingsIcon.exists {
       settingsIcon.tap()
       settings.tables.staticTexts["General"].tap()
       settings.tables.staticTexts["Reset"].tap()
       settings.tables.staticTexts["Reset Location & Privacy"].tap()
       settings.buttons["Reset Warnings"].tap()
       settings.terminate()
      }
     }
    }
   }
</code>```

Body:
Updated for swift 3.1 / xcode 8.3

create bridging header in test target:

#import <XCTest/XCUIApplication.h>
#import <XCTest/XCUIElement.h>

@interface XCUIApplication (Private)
- (id)initPrivateWithPath:(NSString *)path bundleID:(NSString *)bundleID;
- (void)resolve;
@end

updated Springboard class

class Springboard {
   static let springboard = XCUIApplication(privateWithPath: nil, bundleID: "com.apple.springboard")!
   static let settings = XCUIApplication(privateWithPath: nil, bundleID: "com.apple.Preferences")!

/**
Terminate and delete the app via springboard
*/

class func deleteMyApp() {
   XCUIApplication().terminate()

// Resolve the query for the springboard rather than launching it

   springboard.resolve()

// Force delete the app from the springboard
   let icon = springboard.icons["{MyAppName}"] /// change to correct app name
   if icon.exists {
     let iconFrame = icon.frame
     let springboardFrame = springboard.frame
     icon.press(forDuration: 1.3)

  // Tap the little "X" button at approximately where it is. The X is not exposed directly

    springboard.coordinate(withNormalizedOffset: CGVector(dx: (iconFrame.minX + 3) / springboardFrame.maxX, dy: (iconFrame.minY + 3) / springboardFrame.maxY)).tap()

     springboard.alerts.buttons["Delete"].tap()

     // Press home once make the icons stop wiggling

     XCUIDevice.shared().press(.home)
     // Press home again to go to the first page of the springboard
     XCUIDevice.shared().press(.home)
     // Wait some time for the animation end
     Thread.sleep(forTimeInterval: 0.5)

      let settingsIcon = springboard.icons["Settings"]
      if settingsIcon.exists {
       settingsIcon.tap()
       settings.tables.staticTexts["General"].tap()
       settings.tables.staticTexts["Reset"].tap()
       settings.tables.staticTexts["Reset Location & Privacy"].tap()
       settings.buttons["Reset Warnings"].tap()
       settings.terminate()
      }
     }
    }
   }


问:
JavaScript file not loading in .jsp file
Currently I'm programming in the front end and I have run into a problem where my javascript files dont load. My files are .jsp becauase of scala/scalatra backend. I have my index.jsp where I include my header file in the top and in the bottom I include my footer.

I include them like this:

```<code><jsp:include page="header.jsp"/>
// CODE //
<jsp:include page="footer.jsp"/>
</code>```

My header looks like this:

```<code><!-- HEADER -->
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="styles/cssfile.css">
    <link rel="stylesheet" href="css/cssfile.css">
</head>
<body>
</code>```

And my footer looks like this:

```<code>  <!-- FOOTER -->
      <script type="text/javascript" src="js/jquery.js"></script>
      <script type="text/javascript" src="js/main.js"></script>
</body>
</html>
</code>```

My main.js looks like this:

```<code>$(document).ready(function () {
'use strict';
$(function() {

    $('a[href*=#]:not([href=#])').click(function () {

          if (
                  location.pathname.replace(/^//,'') == this.pathname.replace(/^//,'')
                || location.hostname == this.hostname
            ) {

            var target = $(this.hash);

            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

            if ( target.length ) {

                  $('html,body').animate({
                    scrollTop: target.offset().top
                  }, 1000);
                  return false;

            }

          }

    });

});
</code>```

});

My file structure is like this:

```<code>css
  -cssfile1
  -cssfile2
js
  -jquery.js
  -main.js
header.jsp
index.jsp
footer.jsp
</code>```

Mr src route shoulde be correct and when I insepect the source code of the site I can see the main.js file and click on it and it is the correct js.
I have tried console.log("test"); and nothing appears, so it does not load.
I added the jquery.js with the jquery javascript in it and added it first in the footer as you can see.

So what I want is that my main.js should load.

Thanks in advance :)

答:
JSP EL provides a variable (${pageContext.request.contextPath}) that can be used at design-time to help resolve to the proper path at runtime. Try this might help, are you using the correct jquery libary?</p>

```<code><script type="text/javascript" src="${pageContext.request.contextPath}/js/main.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js">
</code>```

Body:
Currently I'm programming in the front end and I have run into a problem where my javascript files dont load. My files are .jsp becauase of scala/scalatra backend. I have my index.jsp where I include my header file in the top and in the bottom I include my footer.

I include them like this:

<jsp:include page="header.jsp"/>
// CODE //
<jsp:include page="footer.jsp"/>

My header looks like this:

<!doctype html>

    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="styles/cssfile.css">
    <link rel="stylesheet" href="css/cssfile.css">

And my footer looks like this:

My main.js looks like this:

$(document).ready(function () {
'use strict';
$(function() {

    $('a[href*=#]:not([href=#])').click(function () {

          if (
                  location.pathname.replace(/^//,'') == this.pathname.replace(/^//,'')
                || location.hostname == this.hostname
            ) {

            var target = $(this.hash);

            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

            if ( target.length ) {

                  $('html,body').animate({
                    scrollTop: target.offset().top
                  }, 1000);
                  return false;

            }

          }

    });

});

});

My file structure is like this:

css
  -cssfile1
  -cssfile2
js
  -jquery.js
  -main.js
header.jsp
index.jsp
footer.jsp

Mr src route shoulde be correct and when I insepect the source code of the site I can see the main.js file and click on it and it is the correct js.
I have tried console.log("test"); and nothing appears, so it does not load.
I added the jquery.js with the jquery javascript in it and added it first in the footer as you can see.

So what I want is that my main.js should load.

Thanks in advance :)

Body:
JSP EL provides a variable (${pageContext.request.contextPath}) that can be used at design-time to help resolve to the proper path at runtime. Try this might help, are you using the correct jquery libary?

<script type="text/javascript" src="${pageContext.request.contextPath}/js/main.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js">


问:
Should I use std::list or is there a better method?
I am currently coding in a 2D geometry editor in c++. I am having the user place nodes. Lines and arcs can be drawn by selecting 2 nodes.

Right now, I am storing the nodes in a std::deque container (same thing for the lines and arcs) because I would like to store the address of the node into each line/arc. This makes things very convenient coding wise when I implement a feature to move the node. If I were to store the actual node inside of each line/arc, then when I want to move a node, then I would have to iterate through the entire line and arc stucture to find the node that I just moved and update the parameters. This option isn't an option on the table. Hence, the need to be able to store the address of the node inside each line/arc.

However, I am running into some issue where I need to delete the node. Looking on the reference manual, it seems that for all pointer, these are invalidated when you erase an element from the deque (unless that element is at the beginning or the end. For the sake of discussion, I will not be considering this case). This causes issue with the erasing because now, all of my lines/arc reconnect themselves to different nodes or are not drawn at all when a node is erased and the program eventually crashes.

Continuing to look online, I come across std::list which (from my understanding of reading the documentation) does not invalidate any pointers or references when one of the elements is erased. This seems to be a very nice solution to my problem.

However, I have been looking a little bit on stack overflow to see what are the benefits/disadvantages of using a list vs a deque. And it seems like there is more of a preference to use a deque then a list. It seems as though the list is slower to access then the deque. This is not good because I am not sure how many nodes a user would like to draw. For all I know, there could be 10,000+ nodes in the geometry and if the user wants to move a node, I don't want the user have to wait 30 sec for the program to iterate through all of the elements to find the node(s) to erase.

So on one hand, deque are alot faster but as soon as an element is removed, all of the pointers and references are invalidated. On the other hand, std::list allows me to erase whatever element I want without invalidating any of the pointers and references but is slower compared to a deque.

I am considering to switch to a list because even if the list is slower, if I can't erase an element without invalidating the pointers and references, then there isn't much of a benefit speed wise if the program doesn't work.

However, is using a list the best choice in my situation? Is there any way to use a deque? Or is there a third option that I haven't considered?

Edit:

I forgot to mention. One thing that I am not to fond of with lists is the inability to get an element's data directly (in std::deque and vector, I can use the at function to access elements). This isn't a huge deal breaker with my code. But it does makes things convenient. For example, when a user selects a node when they want to create a line/arc, the code iterates over the entire node list to find out which one was selected and then, for the first selection, stores the index into a variable (called firstNodeIndex). For the second node, it does the same thing but when both variables (firstNodeIndex and secondNodeIndex) are viable numbers, then the function for creating the line/arc is called and the function uses the two stored indexes to re-access the node list to grab an address to the node. If I were to use the list, I would have to store the address of the two nodes in variables and then create some additional logic to make sure that the two variables containing the addresses to the two nodes are viable options.

Another alternate solution would be to reiterate through the entire node list again to grab the nodes that are selected (I would have a variable inside each node to indicate that it is selected). But I am afraid that this might not be a good idea given std::list limitations.

I am kind of in favor of my first way but I am open to change if need be or if there is a better method

答:
A rule of thumb:

will I want to add and delete items at random?

```<code>set, list, map, multimap and unordered versions of same
</code>```

will I want to be able to name individual items and find them quickly?

```<code>map, set, multimap and unordered versions of same
</code>```

does the thing I am storing have mutable data, or is it more detailed than just its name (key)?

```<code>map, multimap, unordered versions thereof
</code>```

do I need the items to say in order?

```<code>yes: map, no: unordered_map
</code>```

Body:
A rule of thumb:

will I want to add and delete items at random?

set, list, map, multimap and unordered versions of same

will I want to be able to name individual items and find them quickly?

map, set, multimap and unordered versions of same

does the thing I am storing have mutable data, or is it more detailed than just its name (key)?

map, multimap, unordered versions thereof

do I need the items to say in order?

yes: map, no: unordered_map


问:
Tensorflow Inception FeedInputs: unable to find feed output input
I tried the inception tutorial in tensorflow site:
https://www.tensorflow.org/versions/r0.12/how_tos/image_retraining/
the bazel build is done successfully but when I try to predict an image class wth this command:

```<code>bazel build tensorflow/examples/label_image:label_image && \
bazel-bin/tensorflow/examples/label_image/label_image \
--graph=/tmp/output_graph.pb --labels=/tmp/output_labels.txt \
--output_layer=final_result \
--image=$HOME/flower_photos/daisy/21652746_cc379e0eea_m.jpg
</code>```

I have this error:
tensorflow/examples/label_image/main.cc:305] Running model failed: Not found: FeedInputs: unable to find feed output input

How can I solve this problem

答:
This thread helped me to fix this issue.

It seems that we need to provide --input_layer with Tensorflow 1.0+.

In your case, this should fix the problem:

```<code>bazel build tensorflow/examples/label_image:label_image && \
bazel-bin/tensorflow/examples/label_image/label_image \
--graph=/tmp/output_graph.pb --labels=/tmp/output_labels.txt \
--output_layer=final_result \
--image=$HOME/flower_photos/daisy/21652746_cc379e0eea_m.jpg \
--input_layer=Mul
</code>```

Body:
I tried the inception tutorial in tensorflow site:
https://www.tensorflow.org/versions/r0.12/how_tos/image_retraining/
the bazel build is done successfully but when I try to predict an image class wth this command:

bazel build tensorflow/examples/label_image:label_image && \
bazel-bin/tensorflow/examples/label_image/label_image \
--graph=/tmp/output_graph.pb --labels=/tmp/output_labels.txt \
--output_layer=final_result \
--image=$HOME/flower_photos/daisy/21652746_cc379e0eea_m.jpg

I have this error:
tensorflow/examples/label_image/main.cc:305] Running model failed: Not found: FeedInputs: unable to find feed output input

How can I solve this problem

Body:
This thread helped me to fix this issue.

It seems that we need to provide --input_layer with Tensorflow 1.0+.

In your case, this should fix the problem:

bazel build tensorflow/examples/label_image:label_image && \
bazel-bin/tensorflow/examples/label_image/label_image \
--graph=/tmp/output_graph.pb --labels=/tmp/output_labels.txt \
--output_layer=final_result \
--image=$HOME/flower_photos/daisy/21652746_cc379e0eea_m.jpg \
--input_layer=Mul


问:
Import a git repo into an empty branch
Lets say a project has been developed in one repo, and the project website was developed in another.

Is there a way to import the website repo, with full history, into an empty branch of the project repo?

答:
```
git remote add rweb git://whereever
git fetch rweb
```

And voilà, you have it in one repository. Perhaps you then also want to create a branch out of it, to make it accessible and pushable:

```git branch website rweb/master
git push origin website```

Starting with an empty branches and dumping the website tree instead would have the drawback of losing all the history.

Title: Import a git repo into an empty branch

Body:
git remote add rweb git://whereever
git fetch rweb

And voilà, you have it in one repository. Perhaps you then also want to create a branch out of it, to make it accessible and pushable:

git branch website rweb/master
git push origin website

Starting with an empty branches and dumping the website tree instead would have the drawback of losing all the history.


问:
Warning about SSL connection when connecting to MySQL database
With the two classes below, I've tried connect to a MySQL database. However, I always get this error:

Wed Dec 09 22:46:52 CET 2015 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

This is the test class with the main method:

```<code>public class TestDatabase {

    public static void main(String[] args) {
        Database db = new Database();
        try {
            db.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        db.close();
    }
}
</code>```

This is the Database class:

```<code>import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Database {

    private Connection con;

    public void connect() throws Exception{

        if(con != null) return;

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new Exception("No database");
        }

        String connectionURL = "jdbc:mysql://localhost:3306/Peoples";

        con = DriverManager.getConnection(connectionURL, "root", "milos23");
    }

    public void close(){
        if(con != null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
</code>```

答:
you need to user your mysql path like this: </p>

```<code><property name="url" value="jdbc:mysql://localhost:3306/world?useSSL=true"/>
</code>```

Body:
With the two classes below, I've tried connect to a MySQL database. However, I always get this error:

Wed Dec 09 22:46:52 CET 2015 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

This is the test class with the main method:

public class TestDatabase {

    public static void main(String[] args) {
        Database db = new Database();
        try {
            db.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        db.close();
    }
}

This is the Database class:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Database {

    private Connection con;

    public void connect() throws Exception{

        if(con != null) return;

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new Exception("No database");
        }

        String connectionURL = "jdbc:mysql://localhost:3306/Peoples";

        con = DriverManager.getConnection(connectionURL, "root", "milos23");
    }

    public void close(){
        if(con != null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

Body:
you need to user your mysql path like this:

<property name="url" value="jdbc:mysql://localhost:3306/world?useSSL=true"/>


问:
how to write a custom panel displaying categories in magento
I have a category called "Top Products". I wish to display this in a panel on my home page. What is the best way to do this in magento.

** edit **

Thanks sdek, i now have the following. In Home Page / Design.

```<code><block type="catalog/product_list" category_id="13"  template="catalog/product/featured.phtml"/>
</code>```

And it is displaying products. However i have the following issues.
- it's not displaying products from category_id 13, It seems like this value is not being passed thru
- it's only display 2 products. I wish to display all.

featured.phtml

```<code><?php
    $_productCollection=$this->getLoadedProductCollection();
    $_helper = $this->helper('catalog/output');
?>
<?php if(!$_productCollection->count()): ?>
<p class="note-msg"><?php echo $this->__('There are no products matching the selection.') ?></p>
<?php else: ?>
<h2>Featured Products </h2>
    <?php $_collectionSize = $_productCollection->count() ?>
    <?php $_columnCount = $this->getColumnCount(); ?>
    <?php $i=0; foreach ($_productCollection as $_product): ?>
        <?php if ($i++%$_columnCount==0): ?>
        <ul class="product-grid">
        <?php endif ?>
            <li class="<?php if(($i-1)%$_columnCount==0): ?> first<?php else: ?> last<?php endif; ?>">
            <a class="product-image" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" >
            <img src="<?php echo $this->helper('catalog/image')->init($_product, 'thumbnail')->resize(85); ?>" class="product-img" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" style="padding-bottom:20px; margin-bottom:20px;" />
            </a>
           <p><strong><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?></strong>
           <?php echo $_product->getShortDescription(); ?></p>

            <?php echo $this->getPriceHtml($_product, true) ?>
            <a href="<?php echo $_product->getProductUrl() ?>" class="more">More details</a>
            </li>
        <?php if ($i%$_columnCount==0 || $i==$_collectionSize): ?>
        </ul>
        <?php endif ?>
        <?php endforeach ?>
    <?php endif; ?
</code>```

答:
The Featured Products extension mentioned by clockworkgeek is a good idea.  But if you don't like that option the easiest thing to do is to add this in your home page cms
{{block type="catalog/product_list" category_id="YOUR_CAT_ID" template="catalog/product/YOUR_MODIFIED_COPY_OF_LIST.phtml"}}

And then make a copy of app/design/frontend///template/catalog/product/list.phtml (I refered to it above as YOUR_MODIFIED_COPY_OF_LIST.phtml) and remove the two lines that say

```<code><?php echo $this->getToolbarHtml() ?>
</code>```

and remove the entire if-block that outputs the "list mode"... basically the if statement

```<code>    <?php // List mode ?>
    <?php if($this->getMode()!='grid'): ?>
</code>```

and you should only have the "grid mode" code in there.

Body:
I have a category called "Top Products". I wish to display this in a panel on my home page. What is the best way to do this in magento.

** edit **

Thanks sdek, i now have the following. In Home Page / Design.

<block type="catalog/product_list" category_id="13"  template="catalog/product/featured.phtml"/>

And it is displaying products. However i have the following issues.
- it's not displaying products from category_id 13, It seems like this value is not being passed thru
- it's only display 2 products. I wish to display all.

featured.phtml

<?php
    $_productCollection=$this->getLoadedProductCollection();
    $_helper = $this->helper('catalog/output');
?>
<?php if(!$_productCollection->count()): ?>

<?php echo $this->__('There are no products matching the selection.') ?>

<?php else: ?>

Featured Products

    <?php $_collectionSize = $_productCollection->count() ?>
    <?php $_columnCount = $this->getColumnCount(); ?>
    <?php $i=0; foreach ($_productCollection as $_product): ?>
        <?php if ($i++%$_columnCount==0): ?>

        <?php endif ?>
            <li class="<?php if(($i-1)%$_columnCount==0): ?> first<?php else: ?> last<?php endif; ?>">
            <a class="product-image" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" >
            <img src="<?php echo $this->helper('catalog/image')->init($_product, 'thumbnail')->resize(85); ?>" class="product-img" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" style="padding-bottom:20px; margin-bottom:20px;" />

<?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?>
           <?php echo $_product->getShortDescription(); ?>

            <?php echo $this->getPriceHtml($_product, true) ?>
            <a href="<?php echo $_product->getProductUrl() ?>" class="more">More details

        <?php if ($i%$_columnCount==0 || $i==$_collectionSize): ?>

        <?php endif ?>
        <?php endforeach ?>
    <?php endif; ?

Body:
The Featured Products extension mentioned by clockworkgeek is a good idea.  But if you don't like that option the easiest thing to do is to add this in your home page cms
{{block type="catalog/product_list" category_id="YOUR_CAT_ID" template="catalog/product/YOUR_MODIFIED_COPY_OF_LIST.phtml"}}

And then make a copy of app/design/frontend///template/catalog/product/list.phtml (I refered to it above as YOUR_MODIFIED_COPY_OF_LIST.phtml) and remove the two lines that say

<?php echo $this->getToolbarHtml() ?>

and remove the entire if-block that outputs the "list mode"... basically the if statement

    <?php // List mode ?>
    <?php if($this->getMode()!='grid'): ?>

and you should only have the "grid mode" code in there.


问:
Where does <input type="file"> store the path of the last file uploaded?
I would like to access this property and hopefully change it, so that my event listener, that listens to the event change, gets invoked on two consecutive uploads of the same file.

答:
Are you looking for something like this?

var $c  = $("#container");
var $f1 = $("#container .f1");

function FChange() {
    alert("f1 changed");

    $(this).remove();
    $("<input type='file' class='f1' />").change(FChange).appendTo($c);
}

$f1.change(FChange);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.f1 { z-index: 2 }</code>```

    <input type="file" class="f1">

```

Body:
Are you looking for something like this?

var $c  = $("#container");
var $f1 = $("#container .f1");

function FChange() {
    alert("f1 changed");

    $(this).remove();
    $("<input type='file' class='f1' />").change(FChange).appendTo($c);
}

$f1.change(FChange);

.f1 { z-index: 2 }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
    <input type="file" class="f1">
</div>


问:
How to invoke a function and pass parameter when you have function name as string?
How to invoke a function when you have function name as string? e.g.</p>

```<code>$scope.ExecuteFunction = function (func,val) {
  // here func="GetActivityInfo" and val="ERF000000000A6543"
  // How to Invoke function named in variable func and pass val as parameter ?
  // GetActivityInfo(val) to be invoked.
}

var GetActivityInfo = function (elementId) {
  // some code
};
</code>```

答:
GetActivityInfo is a private property of its parent function. It can only be accessed by closure. It can not be accessed by a property accessor. It needs to be made a property of an accessible object:

```<code>var accessibleObj = { GetActivityInfo: GetActivityInfo };

$scope.ExecuteFunction = function (func,val) {
  // here func="GetActivityInfo" and val="ERF000000000A6543"
  // How to Invoke function named in variable func and pass val as parameter ?
  // GetActivityInfo(val) to be invoked.
  accessibleObj[func](val);
}

//var GetActivityInfo = function (elementId) {
function GetActivityInfo (elementId) {
  // some code
};
</code>```

In the above example the private variable (initialized to an anonymous function) was changed to a private function so that it could be hoisted.

Body:
How to invoke a function when you have function name as string? e.g.

$scope.ExecuteFunction = function (func,val) {
  // here func="GetActivityInfo" and val="ERF000000000A6543"
  // How to Invoke function named in variable func and pass val as parameter ?
  // GetActivityInfo(val) to be invoked.
}

var GetActivityInfo = function (elementId) {
  // some code
};

Body:
GetActivityInfo is a private property of its parent function. It can only be accessed by closure. It can not be accessed by a property accessor. It needs to be made a property of an accessible object:

var accessibleObj = { GetActivityInfo: GetActivityInfo };

$scope.ExecuteFunction = function (func,val) {
  // here func="GetActivityInfo" and val="ERF000000000A6543"
  // How to Invoke function named in variable func and pass val as parameter ?
  // GetActivityInfo(val) to be invoked.
  accessibleObj[func](val);
}

//var GetActivityInfo = function (elementId) {
function GetActivityInfo (elementId) {
  // some code
};

In the above example the private variable (initialized to an anonymous function) was changed to a private function so that it could be hoisted.


问:
Expression brain fade
I'm having brain fade trying to write a single logical expression that suits the question's comment

```<code>// **Don't do xyz between 10.00pm and 7:30am**
//
if(hour > 22 || (hour < 7 && minutes < 30)
    output("too early or too late");
</code>```

Without coming up with something god awful like:

```<code>if (hour > 20)
    "Too late";

if (hour < 7)
    "Too early"
else
if (hour == 7 && minute < 30)
          "Too early"
</code>```

Please put me out of my misery.

答:
|| is your friend here.  If you have multiple conditions and if any of them are true you want to do something then instead of using

```<code>if (condition1)
    do_something();
if (condition2)
    do_something();
if (condition3)
    do_something();
</code>```

You can use

```<code>if (condition1 || condition2 || condition3)
    do_something();
</code>```

So to relate that to what you have your single if statement would be

```<code>if(hour > 21 || hour < 7 || (hour == 7 && minute < 30))
    output("too early or too late");
</code>```

Title: Expression brain fade

Body:
I'm having brain fade trying to write a single logical expression that suits the question's comment

// **Don't do xyz between 10.00pm and 7:30am**
//
if(hour > 22 || (hour < 7 && minutes < 30)
    output("too early or too late");

Without coming up with something god awful like:

if (hour > 20)
    "Too late";

if (hour < 7)
    "Too early"
else
if (hour == 7 && minute < 30)
          "Too early"

Please put me out of my misery.

Body:
|| is your friend here.  If you have multiple conditions and if any of them are true you want to do something then instead of using

if (condition1)
    do_something();
if (condition2)
    do_something();
if (condition3)
    do_something();

You can use

if (condition1 || condition2 || condition3)
    do_something();

So to relate that to what you have your single if statement would be

if(hour > 21 || hour < 7 || (hour == 7 && minute < 30))
    output("too early or too late");


问:
Conditionally trigger a full page postback from a link button inside an update panel
How do I conditionally trigger a full page postback from a link button inside of an update panel?

I have a custom control that contains its own updatepanel with a link button nested inside of  it. When the link button is pressed I want its event handler to have the option of either letting the control update as normal or doing a full postback on the page.

Here is the control hierarchy:

```<code>Page
  Custom Control
    UpdatePanel
      LinkButton
</code>```

Event handler Pseudo code:

```<code>LinkButton Click Handler Begin
    If is a partial post back AND a full postback is needed
        Page.DoFullPostback
    End If
End Handler
</code>```

Note: I aways need the partial postback to happen. I was considering injecting a __DoPostback in the controls markup but this seems hacky to me.

Thanks for your help!

答:
Sorry, I'm not familiar with the VB, so my example source will be written in C#:

```<code>protected void btnLink_Click(object sender, EventArgs e)
{
    bool isAsync = ScriptManager.GetCurrent(Page).IsInAsyncPostBack;
    bool postBackIsNeeded = true;

    if (isAsync && postBackIsNeeded)
    {
        ScriptManager.GetCurrent(Page).RegisterPostBackControl(btnClick);
        string postback = Page.ClientScript.GetPostBackEventReference(
            btnClick,
            string.Empty
        );
        ScriptManager.RegisterStartupScript(
            btnClick,
            btnClick.GetType(),
            "postback",
            postback,
            true
       );
}
</code>```

}

The main idea is to change the type of postback of your LinkButton control. If neccessary it should be changed to full postback instead of partial during the async postback event. Right after this, another postback script should be generated and it should be executed as soon as the page will be returned to client.

And the last thing - use loop detection condition (if (isAsync && postBackIsNeeded) in my case) otherwise postback will be infinite.

Body:
How do I conditionally trigger a full page postback from a link button inside of an update panel?

I have a custom control that contains its own updatepanel with a link button nested inside of  it. When the link button is pressed I want its event handler to have the option of either letting the control update as normal or doing a full postback on the page.

Here is the control hierarchy:

Page
  Custom Control
    UpdatePanel
      LinkButton

Event handler Pseudo code:

LinkButton Click Handler Begin
    If is a partial post back AND a full postback is needed
        Page.DoFullPostback
    End If
End Handler

Note: I aways need the partial postback to happen. I was considering injecting a __DoPostback in the controls markup but this seems hacky to me.

Thanks for your help!

Body:
Sorry, I'm not familiar with the VB, so my example source will be written in C#:

protected void btnLink_Click(object sender, EventArgs e)
{
    bool isAsync = ScriptManager.GetCurrent(Page).IsInAsyncPostBack;
    bool postBackIsNeeded = true;

    if (isAsync && postBackIsNeeded)
    {
        ScriptManager.GetCurrent(Page).RegisterPostBackControl(btnClick);
        string postback = Page.ClientScript.GetPostBackEventReference(
            btnClick,
            string.Empty
        );
        ScriptManager.RegisterStartupScript(
            btnClick,
            btnClick.GetType(),
            "postback",
            postback,
            true
       );
}

}

The main idea is to change the type of postback of your LinkButton control. If neccessary it should be changed to full postback instead of partial during the async postback event. Right after this, another postback script should be generated and it should be executed as soon as the page will be returned to client.

And the last thing - use loop detection condition (if (isAsync && postBackIsNeeded) in my case) otherwise postback will be infinite.


问:
casting a function back to the original signature using variadic args
I've found this interesting code here on stackoverflow from:
Using a STL map of function pointers

```<code>template<typename T,typename... Args>
    T searchAndCall(std::string s1, Args&&... args){

// ....
        // auto typeCastedFun = reinterpret_cast<T(*)(Args ...)>(mapVal.first);
        auto typeCastedFun = (T(*)(Args ...))(mapVal.first);

        //compare the types is equal or not
        assert(mapVal.second == std::type_index(typeid(typeCastedFun)));
        return typeCastedFun(std::forward<Args>(args)...);
    }
};
</code>```

Basically, mapVal is a map of function pointers casted to void(*)(void) that will be casted back to their original type with this function. What I would like to do know is how typeCastedFun will be deduced when you don't specify the template parameters.

For instance, let's suppose that you had:

```<code>int f(const MyClass& a, MyClass b) {...}
</code>```

... if you have:

```<code>MyClass first, second;
searchAndCall<int>(first, second);
</code>```

What Args... parameter will be deduced? if I recall correctly, using the function casted back to a function with a different signature compared to the original one, should yield undefined behavior. Is there any other alternative?

What I would like to do is a way to store the type of the function somewhere and use this information to do the correct cast. Everything in the most efficient way.

Thanks

[edit1]
More specifically, I'm trying to build a kind of generic function dispatcher, able to call functions (templated with an enum class value) with different signatures using a lookup table for efficiency reasons. No boost::any as it internally uses a new

[edit2] Use of macros is not allowed

答:
The key problem is that by taking the calling argument types directly, and attempting to cast the function pointer, you are losing all implicit conversions.

Your function signature has to match exactly, or you will get UB if you try to call it. And there is generally no way to get the signature from the args without manually specifying it at the call site.

One workaround to try would be to add a wrapper lambda which takes standardized args with pre-specified implicit coversions applied, e.g. T -> const T&, and possibly numeric types -> double.

Then, when you look up the function, you can cast it to use these standardized args, and the calling args will be implicitly converted.

This would rule out functions taking rvalue refs and non-const references, but I don't thing this is unreasonable for a function that you don't know the signature of, unless you want to disregard const-correctness completely.

Also, other implicit conversions wouldn't happen, e.g. Derived& -> Base&, or char* -> std::string, and I don't think there would be an easy way to make that happen without creating extra limitations.

Overall, it's definitely a tricky thing to do in c++, and anything you try will be hacky. This way should be decent enough. The performance overhead of one extra function call (which can be inlined), and possibly some extraneous argument conversions will be overshadowed by the unavoidable RTTI checking.

Here is a sample implementation (also here on ideone):

```<code>#include <unordered_map>
#include <typeinfo>
#include <typeindex>
#include <string>
#include <type_traits>
#include <iostream>
#include <assert.h>
#include <cxxabi.h>
#include <sstream>

#include <stdexcept>

template <typename Func, Func f>
struct store_func_helper;

// unix-specific
std::string demangle(const std::string& val) {
  int     status;
  char   *realname;

  std::string strname = realname = abi::__cxa_demangle(val.c_str(), 0, 0, &status);
  free(realname);
  return strname;
}

// args will be implicitly converted to arg<T>::type before calling function
// default: convert to const Arg&
template <typename Arg, typename snifae=void>
struct arg {
  using type = const Arg&;
};

// numeric types: convert to double.
template <typename Arg>
struct arg <Arg, typename std::enable_if<std::is_arithmetic<Arg>::value, void>::type> {
    using type = double;
};

// set more special arg types here.

// Functions stored in the map are first wrapped in a lambda with this signature.
template <typename Ret, typename... Arg>
using func_type = Ret(*)(typename arg<Arg>::type...);

class func_map {
  template <typename Func, Func f>
  friend class store_func_helper;

public:
template <typename Func, Func f>
void store(const std::string& name){
  store_func_helper<Func, f>::call(this, name );
}

template<typename Ret, typename... Args>
Ret call(std::string func, Args... args){
  using new_func_type = func_type<Ret, Args...>;
  auto& mapVal = m_func_map.at(func);

  if (mapVal.second != std::type_index(typeid(new_func_type))){
    std::ostringstream ss;
    ss << "Error calling function " << func << ", function type: "
      << demangle(mapVal.second.name())
      << ", attempted to call with " << demangle(typeid(new_func_type).name());
    throw std::runtime_error(ss.str());
  }
  auto typeCastedFun = (new_func_type)(mapVal.first);

  //args will be implicitly converted to match standardized args
  return typeCastedFun(std::forward<Args>(args)...);
};

private:
std::unordered_map<std::string, std::pair<void(*)(),std::type_index> > m_func_map;
};

#define FUNC_MAP_STORE(map, func) (map).store<decltype(&func),&func>(#func);

  template <typename Ret, typename... Args, Ret(*f)(Args...)>
  struct store_func_helper<Ret(*)(Args...), f> {
    static void call (func_map* map, const std::string& name) {
      using new_func_type = func_type<Ret, Args...>;

      // add a wrapper function, which takes standardized args.
      new_func_type lambda = [](typename arg<Args>::type... args) -> Ret {
        return (*f)(args...);
      };
      map->m_func_map.insert(std::make_pair(
        name,
        std::make_pair((void(*)()) lambda, std::type_index(typeid(lambda)))
        ));
    }
  };

//examples

long add (int i, long j){
  return i + j;
}

int total_size(std::string arg1, const std::string& arg2) {
    return arg1.size() + arg2.size();
}

int  main() {
  func_map map;
  FUNC_MAP_STORE(map, total_size);
  FUNC_MAP_STORE(map, add);

  std::string arg1="hello", arg2="world";
  std::cout << "total_size: "  << map.call<int>("total_size", arg1, arg2) << std::endl;
  std::cout << "add: " << map.call<long>("add", 3, 4) << std::endl;
}
</code>```

Body:
I've found this interesting code here on stackoverflow from:
Using a STL map of function pointers

template<typename T,typename... Args>
    T searchAndCall(std::string s1, Args&&... args){

// ....
        // auto typeCastedFun = reinterpret_cast<T(*)(Args ...)>(mapVal.first);
        auto typeCastedFun = (T(*)(Args ...))(mapVal.first);

        //compare the types is equal or not
        assert(mapVal.second == std::type_index(typeid(typeCastedFun)));
        return typeCastedFun(std::forward<Args>(args)...);
    }
};

Basically, mapVal is a map of function pointers casted to void(*)(void) that will be casted back to their original type with this function. What I would like to do know is how typeCastedFun will be deduced when you don't specify the template parameters.

For instance, let's suppose that you had:

int f(const MyClass& a, MyClass b) {...}

... if you have:

MyClass first, second;
searchAndCall<int>(first, second);

What Args... parameter will be deduced? if I recall correctly, using the function casted back to a function with a different signature compared to the original one, should yield undefined behavior. Is there any other alternative?

What I would like to do is a way to store the type of the function somewhere and use this information to do the correct cast. Everything in the most efficient way.

Thanks

[edit1]
More specifically, I'm trying to build a kind of generic function dispatcher, able to call functions (templated with an enum class value) with different signatures using a lookup table for efficiency reasons. No boost::any as it internally uses a new

[edit2] Use of macros is not allowed

Body:
The key problem is that by taking the calling argument types directly, and attempting to cast the function pointer, you are losing all implicit conversions.

Your function signature has to match exactly, or you will get UB if you try to call it. And there is generally no way to get the signature from the args without manually specifying it at the call site.

One workaround to try would be to add a wrapper lambda which takes standardized args with pre-specified implicit coversions applied, e.g. T -> const T&, and possibly numeric types -> double.

Then, when you look up the function, you can cast it to use these standardized args, and the calling args will be implicitly converted.

This would rule out functions taking rvalue refs and non-const references, but I don't thing this is unreasonable for a function that you don't know the signature of, unless you want to disregard const-correctness completely.

Also, other implicit conversions wouldn't happen, e.g. Derived& -> Base&, or char* -> std::string, and I don't think there would be an easy way to make that happen without creating extra limitations.

Overall, it's definitely a tricky thing to do in c++, and anything you try will be hacky. This way should be decent enough. The performance overhead of one extra function call (which can be inlined), and possibly some extraneous argument conversions will be overshadowed by the unavoidable RTTI checking.

Here is a sample implementation (also here on ideone):

#include <unordered_map>
#include <typeinfo>
#include <typeindex>
#include <string>
#include <type_traits>
#include <iostream>
#include <assert.h>
#include <cxxabi.h>
#include <sstream>

#include <stdexcept>

template <typename Func, Func f>
struct store_func_helper;

// unix-specific
std::string demangle(const std::string& val) {
  int     status;
  char   *realname;

  std::string strname = realname = abi::__cxa_demangle(val.c_str(), 0, 0, &status);
  free(realname);
  return strname;
}

// args will be implicitly converted to arg<T>::type before calling function
// default: convert to const Arg&
template <typename Arg, typename snifae=void>
struct arg {
  using type = const Arg&;
};

// numeric types: convert to double.
template <typename Arg>
struct arg <Arg, typename std::enable_if<std::is_arithmetic<Arg>::value, void>::type> {
    using type = double;
};

// set more special arg types here.

// Functions stored in the map are first wrapped in a lambda with this signature.
template <typename Ret, typename... Arg>
using func_type = Ret(*)(typename arg<Arg>::type...);

class func_map {
  template <typename Func, Func f>
  friend class store_func_helper;

public:
template <typename Func, Func f>
void store(const std::string& name){
  store_func_helper<Func, f>::call(this, name );
}

template<typename Ret, typename... Args>
Ret call(std::string func, Args... args){
  using new_func_type = func_type<Ret, Args...>;
  auto& mapVal = m_func_map.at(func);

  if (mapVal.second != std::type_index(typeid(new_func_type))){
    std::ostringstream ss;
    ss << "Error calling function " << func << ", function type: "
      << demangle(mapVal.second.name())
      << ", attempted to call with " << demangle(typeid(new_func_type).name());
    throw std::runtime_error(ss.str());
  }
  auto typeCastedFun = (new_func_type)(mapVal.first);

  //args will be implicitly converted to match standardized args
  return typeCastedFun(std::forward<Args>(args)...);
};

private:
std::unordered_map<std::string, std::pair<void(*)(),std::type_index> > m_func_map;
};

#define FUNC_MAP_STORE(map, func) (map).store<decltype(&func),&func>(#func);

  template <typename Ret, typename... Args, Ret(*f)(Args...)>
  struct store_func_helper<Ret(*)(Args...), f> {
    static void call (func_map* map, const std::string& name) {
      using new_func_type = func_type<Ret, Args...>;

      // add a wrapper function, which takes standardized args.
      new_func_type lambda = [](typename arg<Args>::type... args) -> Ret {
        return (*f)(args...);
      };
      map->m_func_map.insert(std::make_pair(
        name,
        std::make_pair((void(*)()) lambda, std::type_index(typeid(lambda)))
        ));
    }
  };

//examples

long add (int i, long j){
  return i + j;
}

int total_size(std::string arg1, const std::string& arg2) {
    return arg1.size() + arg2.size();
}

int  main() {
  func_map map;
  FUNC_MAP_STORE(map, total_size);
  FUNC_MAP_STORE(map, add);

  std::string arg1="hello", arg2="world";
  std::cout << "total_size: "  << map.call<int>("total_size", arg1, arg2) << std::endl;
  std::cout << "add: " << map.call<long>("add", 3, 4) << std::endl;
}


问:
Quartz: Does not implement interface member
I am using Quartz and using sample code and get the error:

CS0738 'EmailJob' does not implement interface member
  IJob.Execute(IJobExecutionContext). EmailJob.Execute(IJobExecutionContext) cannot implement IJob.Execute(IJobExecutionContext) because it does not > have the matching return type of Task.

This is my first go at Quartz so any help would be kindly appreciated.

```<code>public class EmailJob : IJob  // <<<--- Error on this line
{
    public void Execute(IJobExecutionContext context)
    {
        using (var message = new MailMessage("user@gmail.com", "user@live.co.uk"))
        {
            message.Subject = "Test";
            message.Body = "Test at " + DateTime.Now;
            using (SmtpClient client = new SmtpClient
            {
                EnableSsl = true,
                Host = "smtp.gmail.com",
                Port = 587,
                Credentials = new NetworkCredential("user@gmail.com", "password")
            })
            {
                client.Send(message);
            }
        }
    }

 public class JobScheduler
    {
        public static void Start()
        {
            IScheduler scheduler = (IScheduler)StdSchedulerFactory.GetDefaultScheduler();
            scheduler.Start();

            IJobDetail job = JobBuilder.Create<EmailJob>().Build();

            ITrigger trigger = TriggerBuilder.Create()
                .WithDailyTimeIntervalSchedule
                  (s =>
                     s.WithIntervalInHours(24)
                    .OnEveryDay()
                    .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(0, 0))
                  )
                .Build();

            scheduler.ScheduleJob(job, trigger);
        }
    }
</code>```

I got the code directly from this wonderful article:  http://www.mikesdotnetting.com/article/254/scheduled-tasks-in-asp-net-with-quartz-net

答:
I had the same error.

Fixed it by running Install-Package Quartz -Version 3.0.0-alpha1 -Pre in the Package Manager Console.

Body:
I am using Quartz and using sample code and get the error:

CS0738 'EmailJob' does not implement interface member
  IJob.Execute(IJobExecutionContext). EmailJob.Execute(IJobExecutionContext) cannot implement IJob.Execute(IJobExecutionContext) because it does not > have the matching return type of Task.

This is my first go at Quartz so any help would be kindly appreciated.

public class EmailJob : IJob  // <<<--- Error on this line
{
    public void Execute(IJobExecutionContext context)
    {
        using (var message = new MailMessage("user@gmail.com", "user@live.co.uk"))
        {
            message.Subject = "Test";
            message.Body = "Test at " + DateTime.Now;
            using (SmtpClient client = new SmtpClient
            {
                EnableSsl = true,
                Host = "smtp.gmail.com",
                Port = 587,
                Credentials = new NetworkCredential("user@gmail.com", "password")
            })
            {
                client.Send(message);
            }
        }
    }

 public class JobScheduler
    {
        public static void Start()
        {
            IScheduler scheduler = (IScheduler)StdSchedulerFactory.GetDefaultScheduler();
            scheduler.Start();

            IJobDetail job = JobBuilder.Create<EmailJob>().Build();

            ITrigger trigger = TriggerBuilder.Create()
                .WithDailyTimeIntervalSchedule
                  (s =>
                     s.WithIntervalInHours(24)
                    .OnEveryDay()
                    .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(0, 0))
                  )
                .Build();

            scheduler.ScheduleJob(job, trigger);
        }
    }

I got the code directly from this wonderful article:  http://www.mikesdotnetting.com/article/254/scheduled-tasks-in-asp-net-with-quartz-net


问:
Autohotkey - Different commands when different programs are active
I am trying to write a script that when clicking "SHIFT+ALT+I" it sends a particular command when Microsft Word is active and another command if Microsoft PowerPoint is Active (both programs are running at the same time).

The code should be something like:

```<code>"if Microsoft Word is open"
+!i::
MouseMove, 300,50,0
MouseClick, left

"if Microsoft Powerpoint is open"
+!i::
MouseMove, 600,100,0
MouseClick, left
</code>```

Is there any (easy) way of doing that?

答:
Yes, this is quite straightforward.

First off:
The structure you propose is possible, but not with a standard hotkey trigger. You can have a timer running which checks if a window is open and that then detects keypresses and then takes action. Or you can indeed use what @user already linked to.
I would consider it more neat and efficiënt to have one hotkey trigger a window check and then take action accordingly.

The code would then look like:

```<code>+!i::
IfWinActive, Microsoft Word
{
MouseMove, 300,50,0
MouseClick, left
}

IfWinActive, Microsoft Powerpoint
{
MouseMove, 600,100,0
MouseClick, left
}

Return
</code>```

Do note that this function checks the window title, so there has in this example to be "Microsoft Word" literally in the window title. Read up on this function here: https://autohotkey.com/docs/commands/WinActive.htm

Body:
I am trying to write a script that when clicking "SHIFT+ALT+I" it sends a particular command when Microsft Word is active and another command if Microsoft PowerPoint is Active (both programs are running at the same time).

The code should be something like:

"if Microsoft Word is open"
+!i::
MouseMove, 300,50,0
MouseClick, left

"if Microsoft Powerpoint is open"
+!i::
MouseMove, 600,100,0
MouseClick, left

Is there any (easy) way of doing that?

Body:
Yes, this is quite straightforward.

First off:
The structure you propose is possible, but not with a standard hotkey trigger. You can have a timer running which checks if a window is open and that then detects keypresses and then takes action. Or you can indeed use what @user already linked to.
I would consider it more neat and efficiënt to have one hotkey trigger a window check and then take action accordingly.

The code would then look like:

+!i::
IfWinActive, Microsoft Word
{
MouseMove, 300,50,0
MouseClick, left
}

IfWinActive, Microsoft Powerpoint
{
MouseMove, 600,100,0
MouseClick, left
}

Return

Do note that this function checks the window title, so there has in this example to be "Microsoft Word" literally in the window title. Read up on this function here: https://autohotkey.com/docs/commands/WinActive.htm


问:
What's the difference between console.log and response.write?
With the exception of using console.log to print what's received from a request and response.write to echo a request back, these two seem to essentially do the same thing (echo data back to me). Thanks in advance!</p>

答:
console.log puts the data on the standard output (file descriptor number 1).

response.write write the data on the response object, whatever it is. In your case it seems to be a response to an HTTP request, but it may be any other stream (including standard output).

The results of both of those commands can end up in the same place - like your screen - but taking a different path to the same destination: console.log doesn't use the network in the process but response.write (most likely) does. I say "most likely" because it is not clear from your question what this response is a response to.