问:
Possibility of store object type for std::any
In c++17 we have the std::any which stores variable type of object in memory. Good part is I can create a vector of std::any to simulate a container for arbitrary type of object.

Whenever to query back the object from the container one will use  std::any_cast with the exact same type when calling std::make_any to create the any object. Here is the snippet of how I achieve this

```<code>#include <any>
#include <iostream>
#include <unordered_map>
#include <vector>
#include <set>

int main()
{
    /* create some objects */
    std::set<int> mySet = { 1, 2, 3 };
    std::vector<int> myVec = { 3, 4, 5 };
    std::unordered_map<int, std::vector<int>> myHash = { std::make_pair(1, myVec) };
    /* create any store */
    std::vector<std::any> anyStore;
    anyStore.push_back(std::make_any<decltype(mySet)>(mySet));
    anyStore.push_back(std::make_any<decltype(myVec)>(myVec));
    anyStore.push_back(std::make_any<decltype(myHash)>(myHash));
    /* get object back */
    auto newSet = std::any_cast<decltype(mySet)>(anyStore[0]);
    auto newVec = std::any_cast<decltype(myVec)>(anyStore[1]);
    auto newHash = std::any_cast<decltype(myHash)>(anyStore[2]);

    /* Question is can we store the decltype(mySet) in memory so that
     * it can be read back while query from the vector to do any_cast?
     */

    return 0;
}
</code>```

The question is as follows:
Is it possible to store the decltype(mySet) as run time variable so that we can use it in any_cast to auto resolve the type we want to get? I know probably you cannot store the type in memory since it is compile time variable, but is there workaround like using std::type_index or std::type_info to achieve goal?

Edit:

Per @KerrekSB 's request. Here is an example usage of this dynamic sized container of std::any to create a class with dynamic properties.

```<code>#include <any>
#include <iostream>
#include <unordered_map>
#include <vector>
#include <set>
#include <string>

class FooWithDynamic
{
public:
    FooWithDynamic() = default;

    template <class T>
    void RegisterProperty(const std::string &key, const T &obj)
    {
        m_store.emplace(key, std::make_any<T>(obj));
    }

    template <class T>
    T GetProperty(const std::string &key)
    {
        if (m_store.find(key) == m_store.end())
            throw;
        return std::any_cast<T>(m_store[key]);
    }
private:
    std::unordered_map<std::string, std::any> m_store;
};

int main()
{
    /* create some objects */
    FooWithDynamic foo;
    foo.RegisterProperty("mySet", std::set<int>{ 1, 2, 3 });
    foo.RegisterProperty("myVec", std::vector<int>{ 1, 2, 3 });
    foo.RegisterProperty("myHash", std::unordered_map<int, int>{ std::make_pair(1, 2) });
    /* query back object */
    auto mySet = foo.GetProperty<std::set<int>>("mySet");
    auto myVec = foo.GetProperty<std::vector<int>>("myVec");
    auto myHash = foo.GetProperty<std::unordered_map<int, int>>("myHash");
    return 0;
}
</code>```

Thanks everyone to let me know this is not possible because it is in contrast of C++'s static typed philosophy.

答:
If your operations and/or types are enumerable in certain ways (finite, for example), then you can solve this problem.

Here is an example of some systems that pack an any with operations on it.  Then whenever you store a value in the any, the operations are automatically written and stored.

At a later time you can invoke the operations on the object stored in the any without ever knowing what the type is.

This does require knowing what operations you need to be able to perform on the contents of the any before you store them.  Alternatively, if you find partial functions acceptable, you can store have it only work on a subset of possible types stored.

You can store a map from typeindex to some operation, check if an any has a type matching any of the keys, if so, invoke the operation, if not, flag an error.

C++ does not have runtime reification, barring shipping a C++ compiler with your product, compiling a custom DLL, then dynamically loading it.  (And no, don't do this)  But you can often solve problems that naively would be solved via reification through various type erasure techniques.

Body:
In c++17 we have the std::any which stores variable type of object in memory. Good part is I can create a vector of std::any to simulate a container for arbitrary type of object.

Whenever to query back the object from the container one will use  std::any_cast with the exact same type when calling std::make_any to create the any object. Here is the snippet of how I achieve this

#include <any>
#include <iostream>
#include <unordered_map>
#include <vector>
#include <set>

int main()
{
    /* create some objects */
    std::set<int> mySet = { 1, 2, 3 };
    std::vector<int> myVec = { 3, 4, 5 };
    std::unordered_map<int, std::vector<int>> myHash = { std::make_pair(1, myVec) };
    /* create any store */
    std::vector<std::any> anyStore;
    anyStore.push_back(std::make_any<decltype(mySet)>(mySet));
    anyStore.push_back(std::make_any<decltype(myVec)>(myVec));
    anyStore.push_back(std::make_any<decltype(myHash)>(myHash));
    /* get object back */
    auto newSet = std::any_cast<decltype(mySet)>(anyStore[0]);
    auto newVec = std::any_cast<decltype(myVec)>(anyStore[1]);
    auto newHash = std::any_cast<decltype(myHash)>(anyStore[2]);

    /* Question is can we store the decltype(mySet) in memory so that
     * it can be read back while query from the vector to do any_cast?
     */

    return 0;
}

The question is as follows:
Is it possible to store the decltype(mySet) as run time variable so that we can use it in any_cast to auto resolve the type we want to get? I know probably you cannot store the type in memory since it is compile time variable, but is there workaround like using std::type_index or std::type_info to achieve goal?

Edit:

Per @KerrekSB 's request. Here is an example usage of this dynamic sized container of std::any to create a class with dynamic properties.

#include <any>
#include <iostream>
#include <unordered_map>
#include <vector>
#include <set>
#include <string>

class FooWithDynamic
{
public:
    FooWithDynamic() = default;

    template <class T>
    void RegisterProperty(const std::string &key, const T &obj)
    {
        m_store.emplace(key, std::make_any<T>(obj));
    }

    template <class T>
    T GetProperty(const std::string &key)
    {
        if (m_store.find(key) == m_store.end())
            throw;
        return std::any_cast<T>(m_store[key]);
    }
private:
    std::unordered_map<std::string, std::any> m_store;
};

int main()
{
    /* create some objects */
    FooWithDynamic foo;
    foo.RegisterProperty("mySet", std::set<int>{ 1, 2, 3 });
    foo.RegisterProperty("myVec", std::vector<int>{ 1, 2, 3 });
    foo.RegisterProperty("myHash", std::unordered_map<int, int>{ std::make_pair(1, 2) });
    /* query back object */
    auto mySet = foo.GetProperty<std::set<int>>("mySet");
    auto myVec = foo.GetProperty<std::vector<int>>("myVec");
    auto myHash = foo.GetProperty<std::unordered_map<int, int>>("myHash");
    return 0;
}

Thanks everyone to let me know this is not possible because it is in contrast of C++'s static typed philosophy.


来源: stackexchange

问:
PHP Security - Sanitize & Clean
I have a built a script around class.upload from http://www.verot.net/php_class_upload.htm

Basically what it is that all my images are stored on the server in a directory called /images/

The script I built basically takes some parameters from my website such as /xyzDir/tomnjerry.jpg?w=100&h=100&fill=1&color=fff

Then I have mod_rewrite which reads the file from /xyzDir/ into a php script which then translates the width and height and returns the image.

Lately I have noticed some idiots from Turkey trying to input weird characters into the parameters w= and h=

On my script I do check to make sure only integer is allowed in width and heigh and fill can be either 1 or 2 and color can only be certain values which i check via array.

I just want to see if there is anything else I should be doing in order to avoid getting hacked.

Thanks

答:
No one's mentioned the filter extension here which provides great filtering natively implemented in the PHP engine. IMHO this is a great extension and should always be used before rolling your own filtering code. For example, checking for an integer is as simple as:

```<code><?php
if (filter_var($value, FILTER_VALIDATE_INT)) {
    //Valid Integer.
}
?>
</code>```

Validating a hex number can be done with:

```<code><?php
if (filter_var($value, FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX)) {
    //Valid Hex number
}
?>
</code>```

ContentLicense: CC BY-SA 2.5

Title: PHP Security - Sanitize & Clean

Body:
No one's mentioned the filter extension here which provides great filtering natively implemented in the PHP engine. IMHO this is a great extension and should always be used before rolling your own filtering code. For example, checking for an integer is as simple as:

<?php
if (filter_var($value, FILTER_VALIDATE_INT)) {
    //Valid Integer.
}
?>

Validating a hex number can be done with:

<?php
if (filter_var($value, FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX)) {
    //Valid Hex number
}
?>


问:
fgets from stdin with unpredictable input size
I'm trying to read a line from stdin but I don't know to properly handle the cases when input size is at least equal to the limit. Example code:

```<code>void myfun() {
    char buf[5];
    char somethingElse;

    printf("\nInsert string (max 4 characters): ");
    fgets (buf, 5, stdin);

    ...

    printf("\nInsert char: ");
    somethingElse = getchar();
}
</code>```

Now, the user can do three things:

Input less than 4 characters (plus newline): in this case there's nothing left in stdin and the subsequent getchar() correctly waits for user input;

Input exactly 4 characters (plus newline): in this case there's a newline left in stdin and the subsequent getchar() reads it;

Input more than 4 characters (plus newline): in this case there's at least another character left in stdin and the subsequent getchar() reads it, leaving at least a newline in.

Cases 2 and 3 would require emptying stdin using something like while(getchar() != '\n'), whereas case 1 doesn't require any additional action. As I understand from reading answers to similar questions and c-faq, there's no standard/portable way to know whether the actual scenario is the one described in 1 or not.

Did I get it well? Or there actually is a portable way to do it? Or maybe a totally different approach?

答:
The fgets function will store the newline in the buffer if there is room for it.  So if the last character in the string is not a newline, you know you need to flush the buffer.

```<code>fgets (buf, 5, stdin);
if (strrchr(buf, '\n') == NULL) {
    // flush buffer
    int c;
    while ((c = getchar()) != '\n') && (c != EOF));
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to read a line from stdin but I don't know to properly handle the cases when input size is at least equal to the limit. Example code:

void myfun() {
    char buf[5];
    char somethingElse;

    printf("\nInsert string (max 4 characters): ");
    fgets (buf, 5, stdin);

    ...

    printf("\nInsert char: ");
    somethingElse = getchar();
}

Now, the user can do three things:

Input less than 4 characters (plus newline): in this case there's nothing left in stdin and the subsequent getchar() correctly waits for user input;

Input exactly 4 characters (plus newline): in this case there's a newline left in stdin and the subsequent getchar() reads it;

Input more than 4 characters (plus newline): in this case there's at least another character left in stdin and the subsequent getchar() reads it, leaving at least a newline in.

Cases 2 and 3 would require emptying stdin using something like while(getchar() != '\n'), whereas case 1 doesn't require any additional action. As I understand from reading answers to similar questions and c-faq, there's no standard/portable way to know whether the actual scenario is the one described in 1 or not.

Did I get it well? Or there actually is a portable way to do it? Or maybe a totally different approach?

Body:
The fgets function will store the newline in the buffer if there is room for it.  So if the last character in the string is not a newline, you know you need to flush the buffer.

fgets (buf, 5, stdin);
if (strrchr(buf, '\n') == NULL) {
    // flush buffer
    int c;
    while ((c = getchar()) != '\n') && (c != EOF));
}


问:
Having real images on top of svg
I am working on svg rectangles which represent a farmer's field. Is it possible to have an image of a field on it, just to give it a true sense and view.
Here's a sample code of one of the rectangles</p>

```<code><!DOCTYPE html>
 <html>
 <body>

<svg width="400" height="110">
<rect width="300" height="100" style="fill:green; stroke: black; stroke-width:3;" />
</svg>

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

答:
I used clipPath to cut and place the picture in a rectangle.

<svg width="600" height="200" viewBox="0 0 600 200" >
<defs>
<clipPath id="field">
 <rect x="25" y="5" width="550" height="190" rx="25" ry="25" style="fill:none; stroke: black; stroke-width:1;" />
 </clipPath>
</defs>
<image xlink:href=" https://i.stack.imgur.com/MJkK0.jpg" width="600" height="200" clip-path="url(#field)" />
</svg>```
</div>
</div>
</p>

<p>If you want to use a different border form instead of a rectangle, for example a circle, then this will be easy to do, replacing the rectangle with a circle in the <code>clipPath</code>.    </p>

<p><em>Option, as suggested by Paulie_D, but it needs a little refinement</em>  </p>

<p>If you need a frame around the picture, you will need to add a second transparent rectangle with a border    </p>

<p><code><rect width="300" height="100" style="fill:none;  stroke: black; stroke-width:3;" /></code>      </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg width="400" height="110">

<defs>
  <pattern id="field" patternUnits="userSpaceOnUse" width="300" height="100">
    <image xlink:href=" https://i.stack.imgur.com/MJkK0.jpg" x="-20" y="0" width="350" height="130" />
  </pattern>
</defs>
<rect width="300" height="100"  fill="url(#field)" />
<rect width="300" height="100" style="fill:none;  stroke: black; stroke-width:3;" />
</svg></code>```

UPDATE

With a black frame looks grim, let's replace it with a shadow.

To create a shadow, the Gauss filter is used, blurring the edges of the bottom rectangle

```<code><filter id="filtershadow" width="120%" height="120%">
      <feGaussianBlur in="SourceAlpha" stdDeviation="4"/>
</filter>
</code>```

 <svg width="400" height="110">

<defs>

  <filter id="filtershadow" width="120%" height="120%">
      <feGaussianBlur in="SourceAlpha" stdDeviation="4"/>
</filter>
  <pattern id="field" patternUnits="userSpaceOnUse" width="300" height="100">
    <image xlink:href=" https://i.stack.imgur.com/MJkK0.jpg" x="0" y="0" width="350" height="130" />
  </pattern>
</defs>
<rect class="rect-shadow" x="10" y="14" width="290" height="90" filter="url(#filtershadow)" style="fill:black; " />
 <rect width="300" height="100"  fill="url(#field)" />

</svg>

```

Title: Having real images on top of svg

Body:
I am working on svg rectangles which represent a farmer's field. Is it possible to have an image of a field on it, just to give it a true sense and view.
Here's a sample code of one of the rectangles

<!DOCTYPE html>

<svg width="400" height="110">
<rect width="300" height="100" style="fill:green; stroke: black; stroke-width:3;" />
</svg>

Body:
I used clipPath to cut and place the picture in a rectangle.

<svg width="600" height="200" viewBox="0 0 600 200" >
<defs>
<clipPath id="field">
 <rect x="25" y="5" width="550" height="190" rx="25" ry="25" style="fill:none; stroke: black; stroke-width:1;" />
 </clipPath>
</defs>
<image xlink:href=" https://i.stack.imgur.com/MJkK0.jpg" width="600" height="200" clip-path="url(#field)" />
</svg>

If you want to use a different border form instead of a rectangle, for example a circle, then this will be easy to do, replacing the rectangle with a circle in the clipPath.

Option, as suggested by Paulie_D, but it needs a little refinement

If you need a frame around the picture, you will need to add a second transparent rectangle with a border

<rect width="300" height="100" style="fill:none;  stroke: black; stroke-width:3;" />

<svg width="400" height="110">

<defs>
  <pattern id="field" patternUnits="userSpaceOnUse" width="300" height="100">
    <image xlink:href=" https://i.stack.imgur.com/MJkK0.jpg" x="-20" y="0" width="350" height="130" />
  </pattern>
</defs>
<rect width="300" height="100"  fill="url(#field)" />
<rect width="300" height="100" style="fill:none;  stroke: black; stroke-width:3;" />
</svg>

UPDATE

With a black frame looks grim, let's replace it with a shadow.

To create a shadow, the Gauss filter is used, blurring the edges of the bottom rectangle

<filter id="filtershadow" width="120%" height="120%">
      <feGaussianBlur in="SourceAlpha" stdDeviation="4"/>
</filter>

<body>
 <svg width="400" height="110">

<defs>

  <filter id="filtershadow" width="120%" height="120%">
      <feGaussianBlur in="SourceAlpha" stdDeviation="4"/>
</filter>
  <pattern id="field" patternUnits="userSpaceOnUse" width="300" height="100">
    <image xlink:href=" https://i.stack.imgur.com/MJkK0.jpg" x="0" y="0" width="350" height="130" />
  </pattern>
</defs>
<rect class="rect-shadow" x="10" y="14" width="290" height="90" filter="url(#filtershadow)" style="fill:black; " />
 <rect width="300" height="100"  fill="url(#field)" />

</svg>

</body>


问:
Check if a file exists with Lua
How can I check if a file exists using Lua?</p>

答:
If you're using Premake and LUA version 5.3.4:</p>

```<code>if os.isfile(path) then
    ...
end
</code>```

ContentLicense: CC BY-SA 4.0

Title: Check if a file exists with Lua

Body:
If you're using Premake and LUA version 5.3.4:

if os.isfile(path) then
    ...
end


问:
Mysql: Get data from multiple tables
I have 4 tables.

post: id, title

tag: id, name

post_tag: id, post_id, tag_id

user_read_activity: id, user_id, post_id

User_read_activity contains posts that user has read. Post_tag contains post that are linked to tags. one post can have more than one tag. I need to fetch user unread posts based on certain tags that the user follows and also remove certain posts which the user may not like.

I have come up with this code. But this is wrong. This also gives me user read posts. But based on tags these are correct. Just need to correct the unread part. Please help me with this.

Please also help me with the code correction if the code is wrong by any means.

```<code>SELECT DISTINCT post.* FROM post

INNER JOIN post_tag ON post.id = post_tag.post_id

INNER JOIN tag

WHERE tag.id = 21 OR tag.id = 26 OR tag.id = 63 OR tag.id = 86 OR tag.id = 11

AND post.id != 1088 AND post.id != 338 AND post.id != 1396

AND post.id NOT IN (SELECT post_id from user_read_activity WHERE user_id = 70)

ORDER BY post.likes DESC LIMIT 5
</code>```

答:
You just need brackets around your conditions to be explicit about order of precedence. You should also have a proper join between post_tag and tag:

```<code>SELECT DISTINCT post.* FROM post

INNER JOIN post_tag ON post.id = post_tag.post_id

INNER JOIN tag ON post_tag.tag_id = tag.id

WHERE (tag.id = 21 OR tag.id = 26 OR tag.id = 63 OR tag.id = 86 OR tag.id = 11)

AND post.id != 1088 AND post.id != 338 AND post.id != 1396

AND post.id NOT IN (SELECT post_id from user_read_activity WHERE user_id = 70)

ORDER BY post.likes DESC LIMIT 5
</code>```

Alternatively the IN criteria advised by @dimwittedanimal would work.

```<code>SELECT DISTINCT post.* FROM post

INNER JOIN post_tag ON post.id = post_tag.post_id

INNER JOIN tag ON post_tag.tag_id = tag.id

WHERE tag.id IN (21, 26, 63, 86, 11)

AND post.id NOT IN (1088, 338, 1396)

AND post.id NOT IN (SELECT post_id from user_read_activity WHERE user_id = 70)

ORDER BY post.likes DESC LIMIT 5
</code>```

Title: Mysql: Get data from multiple tables

Body:
I have 4 tables.

post: id, title

tag: id, name

post_tag: id, post_id, tag_id

user_read_activity: id, user_id, post_id

User_read_activity contains posts that user has read. Post_tag contains post that are linked to tags. one post can have more than one tag. I need to fetch user unread posts based on certain tags that the user follows and also remove certain posts which the user may not like.

I have come up with this code. But this is wrong. This also gives me user read posts. But based on tags these are correct. Just need to correct the unread part. Please help me with this.

Please also help me with the code correction if the code is wrong by any means.

SELECT DISTINCT post.* FROM post

INNER JOIN post_tag ON post.id = post_tag.post_id

INNER JOIN tag

WHERE tag.id = 21 OR tag.id = 26 OR tag.id = 63 OR tag.id = 86 OR tag.id = 11

AND post.id != 1088 AND post.id != 338 AND post.id != 1396

AND post.id NOT IN (SELECT post_id from user_read_activity WHERE user_id = 70)

ORDER BY post.likes DESC LIMIT 5

Body:
You just need brackets around your conditions to be explicit about order of precedence. You should also have a proper join between post_tag and tag:

SELECT DISTINCT post.* FROM post

INNER JOIN post_tag ON post.id = post_tag.post_id

INNER JOIN tag ON post_tag.tag_id = tag.id

WHERE (tag.id = 21 OR tag.id = 26 OR tag.id = 63 OR tag.id = 86 OR tag.id = 11)

AND post.id != 1088 AND post.id != 338 AND post.id != 1396

AND post.id NOT IN (SELECT post_id from user_read_activity WHERE user_id = 70)

ORDER BY post.likes DESC LIMIT 5

Alternatively the IN criteria advised by @dimwittedanimal would work.

SELECT DISTINCT post.* FROM post

INNER JOIN post_tag ON post.id = post_tag.post_id

INNER JOIN tag ON post_tag.tag_id = tag.id

WHERE tag.id IN (21, 26, 63, 86, 11)

AND post.id NOT IN (1088, 338, 1396)

AND post.id NOT IN (SELECT post_id from user_read_activity WHERE user_id = 70)

ORDER BY post.likes DESC LIMIT 5


问:
Is xmatters open source? is there any documentation or a website where it explicitly says that xmatters is or isn't open source?
I am a part of a dev team and the company requires us to work only with non open source software, but I am unable to find out if xmatters is open source or not.</p>

答:
Full disclosure, I work for xMatters.
xMatters as a product is a closed source solution, but our integrations are "open source" under various licenses. More info can be found at https://xmatters.com</p>


问:
Django writing view with sudomain
With my (Django v 1.17) project I am using django-subdomains.
I have no problem to call index view and when I open my url https://subdomain.domain.com I will get index.html.
My issue that I wrote a new view called example for the sub-domain but when I open the url  https://subdomain.domain.com/exmaple I will get error Page not found (404).
Hete is my code:

settings.py

```<code>INSTALLED_APPS = [
   'subdomain'
]
SUBDOMAIN_URLCONFS = {

    'subdomain': 'subdomain.urls',

}
</code>```

subdomain/urls.py

```<code> from django.conf.urls import url, include

from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^$example', views.example, name='example'),
]
</code>```

subdomain/views.py

```<code>from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse

def index(request):
    template = loader.get_template('subdomain/index.html')
    return HttpResponse(template.render())

def example(request):
    template = loader.get_template('subdomain/example.html')
    return HttpResponse(template.render())
</code>```

Error:

```<code>    Page not found (404)
    Request Method: GET
    Request URL:    https://subdomain.domain.com/example
    Using the URLconf defined in subdomain.urls, Django tried these URL patterns, in this order:
   1. ^$ [name='index']
   2. ^$example [name='example']

    The current path, econ, didn't match any of these.
</code>```

Please advise how to fix this issue and write view for sub-domain.

答:
This is unrelated to django-subdomains. The dollar should be at the end of the regex.

```<code>url(r'^example$', views.example, name='example'),
</code>```

The dollar matches the end of the string, so if you have it at the beginning then it's not going to match.

Title: Django writing view with sudomain

Body:
With my (Django v 1.17) project I am using django-subdomains.
I have no problem to call index view and when I open my url https://subdomain.domain.com I will get index.html.
My issue that I wrote a new view called example for the sub-domain but when I open the url  https://subdomain.domain.com/exmaple I will get error Page not found (404).
Hete is my code:

settings.py

INSTALLED_APPS = [
   'subdomain'
]
SUBDOMAIN_URLCONFS = {

    'subdomain': 'subdomain.urls',

}

subdomain/urls.py

 from django.conf.urls import url, include

from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^$example', views.example, name='example'),
]

subdomain/views.py

from django.shortcuts import render
from django.template import loader
from django.http import HttpResponse

def index(request):
    template = loader.get_template('subdomain/index.html')
    return HttpResponse(template.render())

def example(request):
    template = loader.get_template('subdomain/example.html')
    return HttpResponse(template.render())

Error:

    Page not found (404)
    Request Method: GET
    Request URL:    https://subdomain.domain.com/example
    Using the URLconf defined in subdomain.urls, Django tried these URL patterns, in this order:
   1. ^$ [name='index']
   2. ^$example [name='example']

    The current path, econ, didn't match any of these.

Please advise how to fix this issue and write view for sub-domain.

Body:
This is unrelated to django-subdomains. The dollar should be at the end of the regex.

url(r'^example$', views.example, name='example'),

The dollar matches the end of the string, so if you have it at the beginning then it's not going to match.


问:
Why are no Amazon S3 authentication handlers ready?
I have my $AWS_ACCESS_KEY_ID and $AWS_SECRET_ACCESS_KEY environment variables set properly, and I run this code:

```<code>import boto
conn = boto.connect_s3()
</code>```

and get this error:

```<code>boto.exception.NoAuthHandlerFound: No handler was ready to authenticate. 1 handlers were checked. ['HmacAuthV1Handler']
</code>```

What's happening? I don't know where to start debugging.

It seems boto isn't taking the values from my environment variables. If I pass in the key id and secret key as arguments to the connection constructor, this works fine.

答:
I was having this issue with a flask application on ec2. I didn't want to put credentials in the application, but managed permission via IAM roles. That way can avoid hard-coding keys into code. Then I set a policy in the AWS console (I didn't even code it, I just used the policy generator)

My code is exactly like OP's. The other solutions here are good but there is a way to grand permission without hard-coding access keys.

Create an IAM security group that grants access to the S3 resource

Give the policy to the EC2 instance

Connect using nothing but boto.connect_s3() #no keys needed

Body:
I have my $AWS_ACCESS_KEY_ID and $AWS_SECRET_ACCESS_KEY environment variables set properly, and I run this code:

import boto
conn = boto.connect_s3()

and get this error:

boto.exception.NoAuthHandlerFound: No handler was ready to authenticate. 1 handlers were checked. ['HmacAuthV1Handler']

What's happening? I don't know where to start debugging.

It seems boto isn't taking the values from my environment variables. If I pass in the key id and secret key as arguments to the connection constructor, this works fine.


问:
Don't Overwrite Azure Blob Storage
I have a method which adds files to a Azure Blob Storage the problem is i'm trying to specify a condition in which it DOES NOT overwrite the blob but simply adds to it. I am trying to use the parameter access condition however VS is saying this method cannot take two parameters-
       async void archiveNewImportedImages(List imageFiles)
        {

```<code>        // Saving the images
        // Retrieve reference to a blob named "myblob".

        // Create or overwrite the "myblob" blob with contents from a local file.

        using (var fileStream = System.IO.File.OpenRead(@"C:\Users\rahulchawla\Desktop\FilezilleIMGS\FilezilleIMGS\MTO_Image\CR01-1-20170623-1327.jpg"))
        {

            await blockBlob.UploadFromStreamAsync(fileStream, accessCondition: AccessCondition.GenerateIfNoneMatchCondition("*"));
        }

        // save url of the image into a variable and later to the database
        ///  fileURL = blockBlob.Uri.ToString();

    }
</code>```

Any suggestions?

end goal:  dont overwrite container - keep adding distinct files ex. img1.jpg, img2.jpg to blob

Additional Details: Want to append the images to a container (in other words keep on adding images to the container). If the file exists, then would not want to overwrite the existing file)

答:
By design, Azure Blob Storage will overwrite the contents of a blob if you're trying to upload new content with same blob name.

If you want to don't want to override the contents, there are certain things you could do but then you will have to write code for it.

Check if blob exists before uploading and fail the upload operation and notify the user to either pick another name for the blob or assign a new name in your code. You could check for blob's existence by calling blob.ExistsAsync or perform the operation using an access condition like you're doing currently. In the 1st case, you will get a true/false value back and based on that you decide what you want to do. In the 2nd case, the uploading operation will fail with PreConditionNotMet (412 Status Code) so you will need to catch the exception and decide what you want to do.

If your intention is to keep a history of all the changes, then you should look at blob snapshot feature available in Azure Blob Storage. When you take a blob's snapshot, it creates a read-only copy of the blob. However please do keep in mind that in this case, there will just one blob and many snapshots. Each snapshot is uniquely identified by the date/time when it was snapshotted. You can fetch a blob and its snapshots to see the history of the changes done to that blob.

Title: Don't Overwrite Azure Blob Storage

Body:
I have a method which adds files to a Azure Blob Storage the problem is i'm trying to specify a condition in which it DOES NOT overwrite the blob but simply adds to it. I am trying to use the parameter access condition however VS is saying this method cannot take two parameters-
       async void archiveNewImportedImages(List imageFiles)
        {

        // Saving the images
        // Retrieve reference to a blob named "myblob".

        // Create or overwrite the "myblob" blob with contents from a local file.

        using (var fileStream = System.IO.File.OpenRead(@"C:\Users\rahulchawla\Desktop\FilezilleIMGS\FilezilleIMGS\MTO_Image\CR01-1-20170623-1327.jpg"))
        {

            await blockBlob.UploadFromStreamAsync(fileStream, accessCondition: AccessCondition.GenerateIfNoneMatchCondition("*"));
        }

        // save url of the image into a variable and later to the database
        ///  fileURL = blockBlob.Uri.ToString();

    }

Any suggestions?

end goal:  dont overwrite container - keep adding distinct files ex. img1.jpg, img2.jpg to blob

Additional Details: Want to append the images to a container (in other words keep on adding images to the container). If the file exists, then would not want to overwrite the existing file)


问:
How to get actual color value of text view in espresso
I am trying to verify color of text view in android app.

healthHistoryPage.allergies.check(matches(hasTextColor(android.R.color.black))))

I am getting an error saying:

android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'has color with ID 17170444' doesn't match the selected view.

Expected: has color with ID android:color/black

But I dont see the whats the actual color value anywhere in error message. Is there a way I can fetch the actual color value if I dont have access to source code.

答:
See here the adjusted hasTextColor matcher of the original: https://android.googlesource.com/platform/frameworks/testing/+/android-support-test/espresso/core/src/main/java/android/support/test/espresso/matcher/ViewMatchers.java

```<code>public static Matcher<View> hasTextColor(final int colorResId) {
    return new BoundedMatcher<View, TextView>(TextView.class) {
        private Context context;

        @Override
        protected boolean matchesSafely(TextView textView) {
            context = textView.getContext();
            int textViewColor = textView.getCurrentTextColor();
            int expectedColor;

            if (Build.VERSION.SDK_INT <= 22) {
                expectedColor = context.getResources().getColor(colorResId);
            } else {
                expectedColor = context.getColor(colorResId);
            }

            return textViewColor == expectedColor;
        }

        @Override
        public void describeTo(Description description) {
            String colorId = String.valueOf(colorResId);
            String colorCode = "";
            if (context != null) {
                colorId = context.getResources().getResourceName(colorResId);

                //added get color hex code
                @ColorInt int colorInt = context.getResources().getColor(colorResId);
                colorCode = String.format("#%06X", (0xFFFFFF & colorInt));
            }
            description.appendText("has color with ID " + colorId);

            //added output color code in error msg
            description.appendText(" and color code: " +
                    colorCode);
        }
    };
}
</code>```

Note: the //added comments with the modifications for the color hex code

This will log an error similar to:

...
  Expected: has color with ID com.appham.sandbox:color/colorAccent and
  color code: #FF4081
  ...

Body:
See here the adjusted hasTextColor matcher of the original: https://android.googlesource.com/platform/frameworks/testing/+/android-support-test/espresso/core/src/main/java/android/support/test/espresso/matcher/ViewMatchers.java

public static Matcher<View> hasTextColor(final int colorResId) {
    return new BoundedMatcher<View, TextView>(TextView.class) {
        private Context context;

        @Override
        protected boolean matchesSafely(TextView textView) {
            context = textView.getContext();
            int textViewColor = textView.getCurrentTextColor();
            int expectedColor;

            if (Build.VERSION.SDK_INT <= 22) {
                expectedColor = context.getResources().getColor(colorResId);
            } else {
                expectedColor = context.getColor(colorResId);
            }

            return textViewColor == expectedColor;
        }

        @Override
        public void describeTo(Description description) {
            String colorId = String.valueOf(colorResId);
            String colorCode = "";
            if (context != null) {
                colorId = context.getResources().getResourceName(colorResId);

                //added get color hex code
                @ColorInt int colorInt = context.getResources().getColor(colorResId);
                colorCode = String.format("#%06X", (0xFFFFFF & colorInt));
            }
            description.appendText("has color with ID " + colorId);

            //added output color code in error msg
            description.appendText(" and color code: " +
                    colorCode);
        }
    };
}

Note: the //added comments with the modifications for the color hex code

This will log an error similar to:

...
  Expected: has color with ID com.appham.sandbox:color/colorAccent and
  color code: #FF4081
  ...


问:
jquery function unexpected token error
So I am trying to write a reusable function in jquery for a style guide I'm creating.  The goal of the function is to hide/show a number of divs based on the value of a range slider.

The html code looks like this

```<code><div class="primary-colors">
    <h3>Primary Colors</h3>
    <div class="primary-range-container">
        <input type="range" min="1" max="15" value ="5" class="primary-slider"><span class="value">0</span>
    </div>
    <hr>
    <div class="color-container">
        <div class="color primary-color-1"></div>
        <div class="color primary-color-2"></div>
        <div class="color primary-color-3"></div>
        <div class="color primary-color-4"></div>
        <div class="color primary-color-5"></div>
        <div class="color primary-color-6"></div>
        <div class="color primary-color-7"></div>
        <div class="color primary-color-8"></div>
        <div class="color primary-color-9"></div>
        <div class="color primary-color-10"></div>
        <div class="color primary-color-11"></div>
    </div>
</div>
</code>```

And the javascript code looks like this

```<code>var primarySlider = $(".primary-slider");
var primaryColorContainer = $(".primary-colors .color");
var primaryValue = $('.primary-range-container .value');

$.fn.colorBlocks(colorContainer, rangeSlider) {
    this.change(function() {
        var number = $(rangeSlider).val();
        $(colorContainer).hide();
        $(colorContainer).hide().slice( 0, number ).show();
    }
    this.change();
}

primarySlider.colorBlocks(primaryColorContainer, primaryValue);
</code>```

The expected result in my head would be that the function would work, but so far I'm just not seeing anything and instead the compiler is giving me Parsing error: Unexpected Token {.

Any advice or better methods would be incredibly helpful.

答:
Please try this JS</p>

```<code>    var primarySlider = $(".primary-slider");
    var primaryColorContainer = $(".primary-colors .color");
    var primaryValue = $('.primary-range-container input');
    var primaryValueDisplay = $('.primary-range-container .value');

    $.fn.colorBlocks = function(colorContainer, rangeSlider) {
        this.change(function() {
            var number = $(rangeSlider).val();
            $(colorContainer).hide();
            $(colorContainer).hide().slice(0, number).show();
            primaryValueDisplay.html(number)

        })
        this.change();
    }

    primarySlider.colorBlocks(primaryColorContainer, primaryValue);
</code>```

Title: jquery function unexpected token error

Body:
So I am trying to write a reusable function in jquery for a style guide I'm creating.  The goal of the function is to hide/show a number of divs based on the value of a range slider.

The html code looks like this

Primary Colors

        <input type="range" min="1" max="15" value ="5" class="primary-slider">0

And the javascript code looks like this

var primarySlider = $(".primary-slider");
var primaryColorContainer = $(".primary-colors .color");
var primaryValue = $('.primary-range-container .value');

$.fn.colorBlocks(colorContainer, rangeSlider) {
    this.change(function() {
        var number = $(rangeSlider).val();
        $(colorContainer).hide();
        $(colorContainer).hide().slice( 0, number ).show();
    }
    this.change();
}

primarySlider.colorBlocks(primaryColorContainer, primaryValue);

The expected result in my head would be that the function would work, but so far I'm just not seeing anything and instead the compiler is giving me Parsing error: Unexpected Token {.

Any advice or better methods would be incredibly helpful.

Body:
Please try this JS

    var primarySlider = $(".primary-slider");
    var primaryColorContainer = $(".primary-colors .color");
    var primaryValue = $('.primary-range-container input');
    var primaryValueDisplay = $('.primary-range-container .value');

    $.fn.colorBlocks = function(colorContainer, rangeSlider) {
        this.change(function() {
            var number = $(rangeSlider).val();
            $(colorContainer).hide();
            $(colorContainer).hide().slice(0, number).show();
            primaryValueDisplay.html(number)

        })
        this.change();
    }

    primarySlider.colorBlocks(primaryColorContainer, primaryValue);


问:
How to apply a function to mulitple columns of a pandas DataFrame in parallel
I have a pandas DataFrame with hundreds of thousands of rows, and I want to apply a time-consuming function on multiple columns of that DataFrame in parallel.

I know how to apply the function serially. For example:

```<code>import hashlib

import pandas as pd

df = pd.DataFrame(
    {'col1': range(100_000), 'col2': range(100_000, 200_000)},
    columns=['col1', 'col2'])

def foo(col1, col2):
    # This function is actually much more time consuming in real life
    return hashlib.md5(f'{col1}-{col2}'.encode('utf-8')).hexdigest()

df['md5'] = df.apply(lambda row: foo(row.col1, row.col2), axis=1)

df.head()
# Out[5]:
#    col1    col2                               md5
# 0     0  100000  92e2a2c7a6b7e3ee70a1c5a5f2eafd13
# 1     1  100001  01d14f5020a8ba2715cbad51fd4c503d
# 2     2  100002  c0e01b86d0a219cd71d43c3cc074e323
# 3     3  100003  d94e31d899d51bc00512938fc190d4f6
# 4     4  100004  7710d81dc7ded13326530df02f8f8300
</code>```

But how would I apply function foo parallel, utilizing all available cores on my machine?

答:
The easiest way to do this is using concurrent.futures.

```<code>import concurrent.futures

with concurrent.futures.ProcessPoolExecutor(16) as pool:
    df['md5'] = list(pool.map(foo, df['col1'], df['col2'], chunksize=1_000))

df.head()
# Out[10]:
#    col1    col2                               md5
# 0     0  100000  92e2a2c7a6b7e3ee70a1c5a5f2eafd13
# 1     1  100001  01d14f5020a8ba2715cbad51fd4c503d
# 2     2  100002  c0e01b86d0a219cd71d43c3cc074e323
# 3     3  100003  d94e31d899d51bc00512938fc190d4f6
# 4     4  100004  7710d81dc7ded13326530df02f8f8300
</code>```

Specifying chunksize=1_000 makes this run faster because each process will process 1000 rows at a time (i.e. you will pay the overhead of initializing a process only once per 1000 rows).

Note that this will only work in Python 3.2 or newer.

Body:
I have a pandas DataFrame with hundreds of thousands of rows, and I want to apply a time-consuming function on multiple columns of that DataFrame in parallel.

I know how to apply the function serially. For example:

import hashlib

import pandas as pd

df = pd.DataFrame(
    {'col1': range(100_000), 'col2': range(100_000, 200_000)},
    columns=['col1', 'col2'])

def foo(col1, col2):
    # This function is actually much more time consuming in real life
    return hashlib.md5(f'{col1}-{col2}'.encode('utf-8')).hexdigest()

df['md5'] = df.apply(lambda row: foo(row.col1, row.col2), axis=1)

df.head()
# Out[5]:
#    col1    col2                               md5
# 0     0  100000  92e2a2c7a6b7e3ee70a1c5a5f2eafd13
# 1     1  100001  01d14f5020a8ba2715cbad51fd4c503d
# 2     2  100002  c0e01b86d0a219cd71d43c3cc074e323
# 3     3  100003  d94e31d899d51bc00512938fc190d4f6
# 4     4  100004  7710d81dc7ded13326530df02f8f8300

But how would I apply function foo parallel, utilizing all available cores on my machine?

Body:
The easiest way to do this is using concurrent.futures.

import concurrent.futures

with concurrent.futures.ProcessPoolExecutor(16) as pool:
    df['md5'] = list(pool.map(foo, df['col1'], df['col2'], chunksize=1_000))

df.head()
# Out[10]:
#    col1    col2                               md5
# 0     0  100000  92e2a2c7a6b7e3ee70a1c5a5f2eafd13
# 1     1  100001  01d14f5020a8ba2715cbad51fd4c503d
# 2     2  100002  c0e01b86d0a219cd71d43c3cc074e323
# 3     3  100003  d94e31d899d51bc00512938fc190d4f6
# 4     4  100004  7710d81dc7ded13326530df02f8f8300

Specifying chunksize=1_000 makes this run faster because each process will process 1000 rows at a time (i.e. you will pay the overhead of initializing a process only once per 1000 rows).

Note that this will only work in Python 3.2 or newer.


问:
Java : save data from UTF-8 file into Sql Server 2008
I failed to save data with accents from utf8 file into my SQL Server 2008 table - SQL collation = SQL_Latin1_General_CP1_CI_AS - (when I do a System.out.print of my insert statement : the accents are OK).

Here's the steps I'm doing :

1) Convert file to String :

```<code>        File f = new File(file);
        byte[] buffer = new byte[(int) f.length()];
        in = new DataInputStream(new FileInputStream(f));
        in.readFully(buffer);
        result = new String(buffer);
</code>```

2) Execute insert :

```<code>            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            Properties properties = new Properties();
            properties.put("charSet", "ISO-8859-1");
            properties.put("user", user);
            properties.put("password", password);
            connection = DriverManager.getConnection("jdbc:jtds:sqlserver://" + serverName + ":1433;DatabaseName=" + dbName + "", properties);

            statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            statement.executeUpdate(sqlInsert, Statement.RETURN_GENERATED_KEYS);
</code>```

Thanks for your help

答:
No matter which collation you use,
it is important to use "N" before  unicode data strings.

Like:

insert into table(somecolumn) values(N'unicode string')
```

Body:
I failed to save data with accents from utf8 file into my SQL Server 2008 table - SQL collation = SQL_Latin1_General_CP1_CI_AS - (when I do a System.out.print of my insert statement : the accents are OK).

Here's the steps I'm doing :

1) Convert file to String :

        File f = new File(file);
        byte[] buffer = new byte[(int) f.length()];
        in = new DataInputStream(new FileInputStream(f));
        in.readFully(buffer);
        result = new String(buffer);

2) Execute insert :

            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            Properties properties = new Properties();
            properties.put("charSet", "ISO-8859-1");
            properties.put("user", user);
            properties.put("password", password);
            connection = DriverManager.getConnection("jdbc:jtds:sqlserver://" + serverName + ":1433;DatabaseName=" + dbName + "", properties);

            statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            statement.executeUpdate(sqlInsert, Statement.RETURN_GENERATED_KEYS);

Thanks for your help


问:
Recording events(request & response) in an MVC application
Ok, so I have quite a task here:

The background of this project is very complex and fully covered by NDA's so I'll just state what I am trying to do without the background.

So what I need is a way to record every request made to an MVC application and every response from it.

Furthermore, I also need a way to "reply" the requests exactly as they were sent.

I was hoping that I could create some solution that "loads" the MVC application, Self hosts or runs in IIS, get requests, records them and passed them verbatim to the MVC application which would then act exactly like any other MVC app.

I could then create a second solution that "loads" the MVC app but instead of opening it up to request it would read the events from the event store and "replays" them in the MVC app.

Now I have no clue where to even start.  This kinda thing is way out of my comfort zone.

If there is another solution for how I can record and replay request (and responses) then please let me know.

Even if there is a way to intercept a request in MVC before it starts doing all of its authentication and routing malarkey then that would be a great starting point.  I would also need to know where I can capture the response at the very last second before it is sent.

Many thanks for your time
Andy

答:
A HttpModule would work just fine for your scenario:

```<code>using System;
using System.Web;
public class HelloWorldModule : IHttpModule
{
   public HelloWorldModule()
   {
   }

   public String ModuleName
   {
       get { return "HelloWorldModule"; }
   }

   // In the Init function, register for HttpApplication
   // events by adding your handlers.
   public void Init(HttpApplication application)
   {
      application.BeginRequest +=
          (new EventHandler(this.Application_BeginRequest));
      application.EndRequest +=
          (new EventHandler(this.Application_EndRequest));
   }
   private void Application_BeginRequest(Object source,
        EventArgs e)
   {
      // Create HttpApplication and HttpContext objects to access
      // request and response properties.
      HttpApplication application = (HttpApplication)source;
      HttpContext context = application.Context;
      /*...*/
   }

   private void Application_EndRequest(Object source, EventArgs e)
   {
      HttpApplication application = (HttpApplication)source;
      HttpContext context = application.Context;
      /*...*/
   }

   public void Dispose() { }
}
</code>```

The code and more information available here.

Body:
A HttpModule would work just fine for your scenario:

using System;
using System.Web;
public class HelloWorldModule : IHttpModule
{
   public HelloWorldModule()
   {
   }

   public String ModuleName
   {
       get { return "HelloWorldModule"; }
   }

   // In the Init function, register for HttpApplication
   // events by adding your handlers.
   public void Init(HttpApplication application)
   {
      application.BeginRequest +=
          (new EventHandler(this.Application_BeginRequest));
      application.EndRequest +=
          (new EventHandler(this.Application_EndRequest));
   }
   private void Application_BeginRequest(Object source,
        EventArgs e)
   {
      // Create HttpApplication and HttpContext objects to access
      // request and response properties.
      HttpApplication application = (HttpApplication)source;
      HttpContext context = application.Context;
      /*...*/
   }

   private void Application_EndRequest(Object source, EventArgs e)
   {
      HttpApplication application = (HttpApplication)source;
      HttpContext context = application.Context;
      /*...*/
   }

   public void Dispose() { }
}

The code and more information available here.


问:
Jetty HTTP Client - reconnect after N requests?
I'm using the Jetty HTTP Client and I want to force the client to close the connection to the server after a certain number of requests (regardless of their status) - this is basically an implementation of the "max" value for the HTTP Keep-Alive header.

Is this possible in Jetty? Digging through the docs there does not appear to be an option for it, and I can't find a place where I can get access to the connection that a request used and kill it after the request is done.

答:
There is no such thing as a max value for the Keep-Alive header.

The Keep-Alive header is a HTTP/1.0 only feature, and has no meaning outside of HTTP/1.0 (such as HTTP/1.1 or HTTP/2).

The Jetty HTTP Client is a HTTP/1.1 (and optionally a HTTP/2 client as well).

What you are seeking is a maximum number of requests per connection.

Or said another way, a maximum number of requests per pipelined HTTP/1.1 connection.

This desired behavior will only exist on HTTP/1.1 (Jetty HTTP Client doesn't talk HTTP/1.0, so that's out.  And HTTP/2 has no such concept)

Look at the various HttpClient.set*Connection() methods, and you'll see a variety of options that might suite you.

If you fail to find one that matches your needs, please file an issue at https://github.com/eclipse/jetty.project/issues/new


问:
Convert DataTable field from String to double
I'm trying to retrieve data from my SQL base to a DataTable and make some decimal operations on some fields.

Since I can get strings, ints and doubles in my DataTable is initialize like this new DataTable();.<s> So the default type is set to string </s>update: This is wrong, it is decimal. So no need to convert.

Imagine I want to sum a field from my DataTable

```<code>myRow = 2;
double sum = 0;
foreach (DataRow row in data.Rows)
{
    if (row.Field<String>(myRow) != "")
        sum = sum + double.Parse(row.Field<String>(myRow), CultureInfo.InvariantCulture.NumberFormat);
}
</code>```

I prevent empty fields to be added. So I don't try to convert an empty string.

Unable to cast object of type 'System.Decimal' to type 'System.String'.

If there is no "good" way to convert this, I can change my DataTable to get only decimals, but how do i Fill with Decimals?

Update
Since the default type is decimal, I can do

```<code>sum = sum + (double) row.Field<decimal>(myRow);
</code>```

One work around would be making my database do the sum.

答:
```<code>if(row.Field<String>(myRow) != ""){
    var stringToDouble = Convert.ToDouble(row.Field<String>(myRow));
    //Or you can do Convert.ToDecimal(row.Field<String>(myRow));
}
</code>```

Body:
I'm trying to retrieve data from my SQL base to a DataTable and make some decimal operations on some fields.

Since I can get strings, ints and doubles in my DataTable is initialize like this new DataTable();.<s> So the default type is set to string </s>update: This is wrong, it is decimal. So no need to convert.

Imagine I want to sum a field from my DataTable

myRow = 2;
double sum = 0;
foreach (DataRow row in data.Rows)
{
    if (row.Field<String>(myRow) != "")
        sum = sum + double.Parse(row.Field<String>(myRow), CultureInfo.InvariantCulture.NumberFormat);
}

I prevent empty fields to be added. So I don't try to convert an empty string.

Unable to cast object of type 'System.Decimal' to type 'System.String'.

If there is no "good" way to convert this, I can change my DataTable to get only decimals, but how do i Fill with Decimals?

Update
Since the default type is decimal, I can do

sum = sum + (double) row.Field<decimal>(myRow);

One work around would be making my database do the sum.


问:
Firestore update is crashing app
```<code>let dataRef = database.collection("stores").document(store.id).collection("data").document("storeData")

var storeData: [String:Any] = [:]
storeData["seq"] = store.seq + 1
storeData["shiftSeq"] = store.shiftSeq + 1
dataRef.updateData(storeData)
</code>```

I am receiving the following error when executing the above code. It was working fine until I upgraded to the latest version of Firebase/Firestore

* Assertion failure in -[FSTWriteStream startWithDelegate:], third_party/firebase/ios/Source/Firestore/Source/Remote/FSTStream.m:244
2017-12-08 10:48:47.819586-0500 centroOne[1833:473631] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'FIRESTORE INTERNAL ASSERTION FAILED: Delegate must be nil'

答: I removed a rule set that was attached to this document and the problem went away. The ruleset referenced a value in another document to make sure it existed.</p>

Title: Firestore update is crashing app

Body:
let dataRef = database.collection("stores").document(store.id).collection("data").document("storeData")

var storeData: [String:Any] = [:]
storeData["seq"] = store.seq + 1
storeData["shiftSeq"] = store.shiftSeq + 1
dataRef.updateData(storeData)

I am receiving the following error when executing the above code. It was working fine until I upgraded to the latest version of Firebase/Firestore

* Assertion failure in -[FSTWriteStream startWithDelegate:], third_party/firebase/ios/Source/Firestore/Source/Remote/FSTStream.m:244
2017-12-08 10:48:47.819586-0500 centroOne[1833:473631] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'FIRESTORE INTERNAL ASSERTION FAILED: Delegate must be nil'


问:
Javascript listening for data changes & trigger reload
I have a server sent event in PHP that displays inventory information client side and updates in real time. That part works great. The challenge is that I want to trigger a reload when the inventory = 0. Note: I'm using jQuery Mobile 1.4.5

Here's my code:

```<code>var source = new EventSource('listener.php');
source.onmessage = function(msg) {
document.getElementById('inv').innerHTML = msg.data;
};

source.addEventListener('msg', onMessageHandler,false);

function onMessageHandler(msg) {
var inventory = msg.data;
};

// Trying to Fire Something like this //
//if (inventory = 0) {
//setTimeout(function() {
//location.reload(true)
//},5000);
</code>```

Thanks for any suggestions : )

答:
Watch the scoping:</p>

```<code>var source = new EventSource('listener.php');
source.onmessage = function(msg) {
  document.getElementById('inv').innerHTML = msg.data;
};

source.addEventListener('msg', onMessageHandler,false);

function onMessageHandler(msg) {
var inventory = msg.data;
 if (inventory === 0) {
    setTimeout(function() {
      location.reload(true);
    }, 5000);
  }
};
</code>```

Body:
I have a server sent event in PHP that displays inventory information client side and updates in real time. That part works great. The challenge is that I want to trigger a reload when the inventory = 0. Note: I'm using jQuery Mobile 1.4.5

Here's my code:

var source = new EventSource('listener.php');
source.onmessage = function(msg) {
document.getElementById('inv').innerHTML = msg.data;
};

source.addEventListener('msg', onMessageHandler,false);

function onMessageHandler(msg) {
var inventory = msg.data;
};

// Trying to Fire Something like this //
//if (inventory = 0) {
//setTimeout(function() {
//location.reload(true)
//},5000);

Thanks for any suggestions : )

Body:
Watch the scoping:

var source = new EventSource('listener.php');
source.onmessage = function(msg) {
  document.getElementById('inv').innerHTML = msg.data;
};

source.addEventListener('msg', onMessageHandler,false);

function onMessageHandler(msg) {
var inventory = msg.data;
 if (inventory === 0) {
    setTimeout(function() {
      location.reload(true);
    }, 5000);
  }
};


问:
iPhone app update while still in background
I was wondering what happens if a user updates an app (through the app store/update) while the app is still in the background on iOS 4.x

I am planning a big update for my next release and I wanted to know if it is a special case I have to handle to avoid a crash.

Or can I trust the OS to restart the application on the next launch (or to kill the background process during the update), detecting that the application has changed instead of just doing a "applicationWillEnterForeground"?

答: Any app in suspended in the iOS "background" can get terminated by the OS at any time.  The OS knows to do the "right thing" when the app's icon is tapped on again next.  An app update would just be another case of that same thing happening.</p>


问:
How to set maximum execution time for a Promise await?
How would you wait for a Promise to resolve/reject, for a maximum execution time ? The code below is obviously wrong, it's just to explain what I'm trying to achieve. I'm clueless.

```<code>await doSomething();
if ( executionTime > maxExecutionTime ) {
    doSomethingElse();
}
</code>```

This is not for a bluebird promise.

答:
In ECMA6 You can do something like this:</p>

```<code>let promise = new Promise((resolve, reject) => {
  let wait = setTimeout(() => {
    clearTimeout(wait);
    resolve('Timed out after 200 ms..');
  }, 200)
})
</code>```

Body:
How would you wait for a Promise to resolve/reject, for a maximum execution time ? The code below is obviously wrong, it's just to explain what I'm trying to achieve. I'm clueless.

await doSomething();
if ( executionTime > maxExecutionTime ) {
    doSomethingElse();
}

This is not for a bluebird promise.

Body:
In ECMA6 You can do something like this:

let promise = new Promise((resolve, reject) => {
  let wait = setTimeout(() => {
    clearTimeout(wait);
    resolve('Timed out after 200 ms..');
  }, 200)
})


问:
Ruby variables and pointers
I am practicing with different design patterns in Ruby and am trying to figure out the innards of Ruby. Right now I am practicing with Proxy patterns. If I have my main object:

```<code>class BankAccount
  attr_reader :balance

  def initialize(starting_balance = 0)
    @balance = starting_balance
  end

  def deposit(amount)
    @balance += amount
  end

  # other code
end
</code>```

And my Proxy object:

```<code>class BankAccountProxy

  def initialize(real_object)
    @real_object = real_object
  end

  def balance
    @real_object.balance
  end

  def deposit(amount)
    @real_object.deposit(amount)
  end

  # other code
end
</code>```

And I initialize the main and proxy object:

```<code>main = BankAccount.new(100)
proxy = BankAccountProxy.new(main)
</code>```

Does Ruby make a copy of the main object within the proxy object, and therefore take up memory OR does Ruby simply point to main object from the proxy, and therefore not take up additional space?

答: Reference to that object. "Immediate values" are just integer and symbols in Ruby.</p>

Title: Ruby variables and pointers

Body:
I am practicing with different design patterns in Ruby and am trying to figure out the innards of Ruby. Right now I am practicing with Proxy patterns. If I have my main object:

class BankAccount
  attr_reader :balance

  def initialize(starting_balance = 0)
    @balance = starting_balance
  end

  def deposit(amount)
    @balance += amount
  end

  # other code
end

And my Proxy object:

class BankAccountProxy

  def initialize(real_object)
    @real_object = real_object
  end

  def balance
    @real_object.balance
  end

  def deposit(amount)
    @real_object.deposit(amount)
  end

  # other code
end

And I initialize the main and proxy object:

main = BankAccount.new(100)
proxy = BankAccountProxy.new(main)

Does Ruby make a copy of the main object within the proxy object, and therefore take up memory OR does Ruby simply point to main object from the proxy, and therefore not take up additional space?


问:
Is it possible to get singleton mentions by stanford-nlp software?
We want to detect the mentions in our data by using the stanford-nlp coref annotator. It seems that the coref annotator does not create singleton chains (i.e. chains with only one mention) by default. Is it possible to configure the annotator so that the resulting annotation contains the signleton chains in addition to the non-singleton ones.

Thank you.

答: Depending on how you define entities, you can use the POS tagger or the phrase chunker to get the outstanding "1-member" coref chains.</p>


问:
Connecting 2 drop down lists in Peoplesoft
on a specific page that I am developping; I have 2 drop down lists that I have to connect, the first one shows XLAT operands ( equals, different, greater than...) and the second shows values (0,1,2,3,4). The problem is how  can I translate the operands mathematically, so that when I choose 'greater than 2' for example the system gets it (>2)? It should be done with peoplecode? schema
 Thanks!</p>

答:
You would need to do an Evaluate or If/Else over the XLAT from the operands.
What do you want to achieve? Post your code so I can suggest if you go to a SQL statement or PeopleCode.</p>


问:
Google Column Chart display the vert value in the column bar?
How do i display the vertical number in a column bar??

This a simple Google Column Chart, how do i display the numbers in the column bars on top???

```<code>      var data = new google.visualization.DataTable();
      data.addColumn('string', 'Period Incident');
      data.addColumn('number', '# of Incidents');
      data.addRows([
        ['Mushrooms', 3],
        ['Onions', 4],
        ['Olives', 5],
        ['Zucchini', 11],
        ['Pepper', 7],
        ['Avocado', 4],
        ['Tomato', 5],
        ['Pepperoni', 2]
      ]);

      // Set chart options
      var options = {
          'title':'How Much Pizza I Ate Last Night',
          legend: { position: 'top', alignment: 'start' },
                    'width':570,
                    'height':420};

            var chart = new google.visualization.ColumnChart(
                    document.getElementById('columnchartIncidents'));

            chart.draw(data, options);
        }
</code>```

答:
use the 'annotation' column role...

1) add annotation column to the data table...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Period Incident');
  data.addColumn('number', '# of Incidents');

  // add annotation column role
  data.addColumn({type: 'string', role: 'annotation'});

  data.addRows([
    ['Mushrooms', 3, '3'],  // <-- add annotations to the data
    ['Onions', 4, '4'],
    ['Olives', 5, '5'],
    ['Zucchini', 11, '11'],
    ['Pepper', 7, '7'],
    ['Avocado', 4, '4'],
    ['Tomato', 5, '5'],
    ['Pepperoni', 2, '2']
  ]);

  var options = {
    title: 'How Much Pizza I Ate Last Night',
    legend: {
      position: 'top',
      alignment: 'start'
    },
    width: 570,
    height: 420
  };

  var chart = new google.visualization.ColumnChart(
    document.getElementById('columnchartIncidents')
  );
  chart.draw(data, options);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="columnchartIncidents"></div></code>```

2) or use a data view to add a calculated column for the annotation role...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Period Incident');
  data.addColumn('number', '# of Incidents');
  data.addRows([
    ['Mushrooms', 3],
    ['Onions', 4],
    ['Olives', 5],
    ['Zucchini', 11],
    ['Pepper', 7],
    ['Avocado', 4],
    ['Tomato', 5],
    ['Pepperoni', 2]
  ]);

  // create data view
  var view = new google.visualization.DataView(data);
  view.setColumns([0, 1, {
    calc: 'stringify',
    role: 'annotation',
    sourceColumn: 1,
    type: 'string'
  }]);

  var options = {
    title: 'How Much Pizza I Ate Last Night',
    legend: {
      position: 'top',
      alignment: 'start'
    },
    width: 570,
    height: 420
  };

  var chart = new google.visualization.ColumnChart(
    document.getElementById('columnchartIncidents')
  );
  chart.draw(view, options);  // <-- draw chart with view
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="columnchartIncidents"></div></code>```

Body:
How do i display the vertical number in a column bar??

This a simple Google Column Chart, how do i display the numbers in the column bars on top???

      var data = new google.visualization.DataTable();
      data.addColumn('string', 'Period Incident');
      data.addColumn('number', '# of Incidents');
      data.addRows([
        ['Mushrooms', 3],
        ['Onions', 4],
        ['Olives', 5],
        ['Zucchini', 11],
        ['Pepper', 7],
        ['Avocado', 4],
        ['Tomato', 5],
        ['Pepperoni', 2]
      ]);

      // Set chart options
      var options = {
          'title':'How Much Pizza I Ate Last Night',
          legend: { position: 'top', alignment: 'start' },
                    'width':570,
                    'height':420};

            var chart = new google.visualization.ColumnChart(
                    document.getElementById('columnchartIncidents'));

            chart.draw(data, options);
        }

Body:
use the 'annotation' column role...

1) add annotation column to the data table...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Period Incident');
  data.addColumn('number', '# of Incidents');

  // add annotation column role
  data.addColumn({type: 'string', role: 'annotation'});

  data.addRows([
    ['Mushrooms', 3, '3'],  // <-- add annotations to the data
    ['Onions', 4, '4'],
    ['Olives', 5, '5'],
    ['Zucchini', 11, '11'],
    ['Pepper', 7, '7'],
    ['Avocado', 4, '4'],
    ['Tomato', 5, '5'],
    ['Pepperoni', 2, '2']
  ]);

  var options = {
    title: 'How Much Pizza I Ate Last Night',
    legend: {
      position: 'top',
      alignment: 'start'
    },
    width: 570,
    height: 420
  };

  var chart = new google.visualization.ColumnChart(
    document.getElementById('columnchartIncidents')
  );
  chart.draw(data, options);
});

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="columnchartIncidents"></div>

2) or use a data view to add a calculated column for the annotation role...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Period Incident');
  data.addColumn('number', '# of Incidents');
  data.addRows([
    ['Mushrooms', 3],
    ['Onions', 4],
    ['Olives', 5],
    ['Zucchini', 11],
    ['Pepper', 7],
    ['Avocado', 4],
    ['Tomato', 5],
    ['Pepperoni', 2]
  ]);

  // create data view
  var view = new google.visualization.DataView(data);
  view.setColumns([0, 1, {
    calc: 'stringify',
    role: 'annotation',
    sourceColumn: 1,
    type: 'string'
  }]);

  var options = {
    title: 'How Much Pizza I Ate Last Night',
    legend: {
      position: 'top',
      alignment: 'start'
    },
    width: 570,
    height: 420
  };

  var chart = new google.visualization.ColumnChart(
    document.getElementById('columnchartIncidents')
  );
  chart.draw(view, options);  // <-- draw chart with view
});

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="columnchartIncidents"></div>


问:
Pre-populate user email from facebook API
I am trying to implement social login on my website. I am requesting user-email from facebook API and want to pre-populate email field in one of the form with that email. How do I do it?   </p>

答: I found it. I am new to programming so asked such a newbie question. I passed a hidden input parameter in form for email and assigned the value of email that I received from facebook to the input parameter.</p>


问:
Transpose rows and columns in a 2D array
I have created a table that displays a series of numbers in a table. I am trying to transpose the matrix (flip rows and columns) using a for each loop and a function named transpose_matrix but it doesnt seem to be working for me. Where am I going wrong with this? I am working with the following code:

```<code>    //Creating rows and columns for text file
    echo "<h1>Data Table</h1>";
    echo "<table border = 0 >";
    foreach($result as $key=>$value){
        echo "<tr>";
        foreach($value as $v){
            echo "<td>".$v."</td>";
        }
        echo "</tr>";

    }
    echo "</table>";
}

function transpose_matrix($result) {
    $transpose = array(); //
    foreach ($result as $key => $sub) {
        foreach ($sub as $subkey => $subvalue) {
            $transpose[$subkey][$key] = $subvalue;
        }
    }
    return $transpose;
}
</code>```

My first table displays as expected and looks somthing like this:

```<code>1 2 3 4 5
6 7 8 9 10
</code>```

I need it to appear as such (i.e rotating the position of the rows and columns):

```<code>1 6
2 7
3 8
4 9
5 10
</code>```

I have searched StackOverflow for similar questions or solutions but cannot seem to find one that works. I am fairly new to PHP also so apologies if it is a simple fix

答:
Check this: https://3v4l.org/OnuSu</p>

```<code>$table = [
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10],
];

$i         = 0;
$transpose = [];
while ($columns = array_column($table, $i++))
{
    $transpose[] = $columns;
}

$table = '<table border="1">';
$rows = count($transpose);
for ($i = 0; $i < $rows; $i++){
    $cols = count($transpose[$i]);
    $table .= '<tr>';
    for ($j = 0; $j < $cols; $j++)
    {
        $table .= '<td>' . $transpose[$i][$j] . '</td>';
    }
    $table .= '</tr>';
}
$table .= '</table>';
echo $table;
</code>```

Body:
I have created a table that displays a series of numbers in a table. I am trying to transpose the matrix (flip rows and columns) using a for each loop and a function named transpose_matrix but it doesnt seem to be working for me. Where am I going wrong with this? I am working with the following code:

    //Creating rows and columns for text file
    echo "
Data Table
";
    echo "
";
    foreach($result as $key=>$value){
        echo "
";
        foreach($value as $v){
            echo "".$v."	";
        }
        echo "
";

    }
    echo "
";
}

function transpose_matrix($result) {
    $transpose = array(); //
    foreach ($result as $key => $sub) {
        foreach ($sub as $subkey => $subvalue) {
            $transpose[$subkey][$key] = $subvalue;
        }
    }
    return $transpose;
}

My first table displays as expected and looks somthing like this:

1 2 3 4 5
6 7 8 9 10

I need it to appear as such (i.e rotating the position of the rows and columns):

1 6
2 7
3 8
4 9
5 10

I have searched StackOverflow for similar questions or solutions but cannot seem to find one that works. I am fairly new to PHP also so apologies if it is a simple fix

Body:
Check this: https://3v4l.org/OnuSu

$table = [
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10],
];

$i         = 0;
$transpose = [];
while ($columns = array_column($table, $i++))
{
    $transpose[] = $columns;
}

$table = '<table border="1">';
$rows = count($transpose);
for ($i = 0; $i < $rows; $i++){
    $cols = count($transpose[$i]);
    $table .= '<tr>';
    for ($j = 0; $j < $cols; $j++)
    {
        $table .= '<td>' . $transpose[$i][$j] . '</td>';
    }
    $table .= '</tr>';
}
$table .= '</table>';
echo $table;


问:
Synchronous Alamofire Request with DispatchGroup
I need to wait until Alamofire request finishes getting data. (Error or value). I'm calling Alamofire function inside a for loop in another function so that Alamofire requests should be finished before second for loop called. For example; first loop -> first request -> second loop -> second request...so on. Now It goes first loop -> second loop -> and after all loops finishes requests response is turning.

Request Function:

```<code> func like(sender_id: String, completion: @escaping (String?) -> ()){
    let group = DispatchGroup()
    if let key = api_key{
        let headers: HTTPHeaders = [
            "X-Auth-Token": key,
            "Accept": "application/json"
        ]
        group.enter()
        Alamofire.request(baseUrl + likeURL + sender_id, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers).validate()
            .responseJSON { (response) -> Void in
                guard response.result.isSuccess else {
                    print("Error while doing : \(response.result.error)")
                    completion(nil)
                    group.leave()
                    return
                }
                if let error = response.error{
                    completion(nil)
                    group.leave()
                    print("Error Occured with Request: \(error)")
                }
                if let jsonData = response.data{
                    let json = JSON(data: jsonData)
                    print(json)
                    group.leave()
                    if let matched = json["match"].bool{
                        completion(matched.description)
                        print("Liked!: \(matched)")
                        if(matched){
                        }
                    }else{
                        group.leave()
                        "There is an error with JSON"
                    }
                }}
    }
}
</code>```

Where I call:

```<code> func like_all(completion: @escaping() -> ()){
    for user in SharedUsers.sharedUser.users{
        if let id = user.id{
            Network.sharedInstance.like(sender_id: id) { result in
                print(result)
            }
        }
        else{
            continue
        }
    }
    completion()
}
</code>```

答:
You are using dispatch group, obviously with the intent on waiting for the group at the end of the function. But you're not waiting for it, so you're not getting the synchronous behavior you were looking for.

But that's good, because if you wait for that group (or semaphore, the other pattern to achieve this behavior) on the main thread, not only will you be blocking the main thread (which results in horrible UX and risk having your app killed by watchdog process), you're going to deadlock because responseJSON uses the main queue for it's completion handler. So before you add the wait() call on your dispatch group/semaphore, make sure you dispatch this whole for loop asynchronously to some background thread. That avoids blocking the main thread and eliminates the deadlock risk.

But this whole pattern is fundamentally flawed, as you really shouldn't use dispatch groups or semaphores to make it synchronous at all. That raises a few questions:

The first question is why you want to make this synchronous. Network requests have inherent latency, so you performing a sequence of them will be very slow. Only do this sequence of requests if you absolutely have to (e.g. each request cannot be formed because it needs something from the response of the prior request). But that doesn't appear to be the case here. So why make this process unnecessary so.

But let's assume for a second that you absolutely have to perform these sequentially (not true here, from what I can tell, but let's tease this out). Then there are two patterns for performing a series of requests consecutively rather than concurrently:

You can either lose this for loop entirely, and simply have a routine that sends the n-th request and sends request n+1 in its completion handler. That completely eliminates the need for dispatch groups/semaphores to block a thread.

Or you can wrap this in operation (e.g. https://stackoverflow.com/a/27022598/1271826) and use operation queue.

Body:
I need to wait until Alamofire request finishes getting data. (Error or value). I'm calling Alamofire function inside a for loop in another function so that Alamofire requests should be finished before second for loop called. For example; first loop -> first request -> second loop -> second request...so on. Now It goes first loop -> second loop -> and after all loops finishes requests response is turning.

Request Function:

 func like(sender_id: String, completion: @escaping (String?) -> ()){
    let group = DispatchGroup()
    if let key = api_key{
        let headers: HTTPHeaders = [
            "X-Auth-Token": key,
            "Accept": "application/json"
        ]
        group.enter()
        Alamofire.request(baseUrl + likeURL + sender_id, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers).validate()
            .responseJSON { (response) -> Void in
                guard response.result.isSuccess else {
                    print("Error while doing : \(response.result.error)")
                    completion(nil)
                    group.leave()
                    return
                }
                if let error = response.error{
                    completion(nil)
                    group.leave()
                    print("Error Occured with Request: \(error)")
                }
                if let jsonData = response.data{
                    let json = JSON(data: jsonData)
                    print(json)
                    group.leave()
                    if let matched = json["match"].bool{
                        completion(matched.description)
                        print("Liked!: \(matched)")
                        if(matched){
                        }
                    }else{
                        group.leave()
                        "There is an error with JSON"
                    }
                }}
    }
}

Where I call:

 func like_all(completion: @escaping() -> ()){
    for user in SharedUsers.sharedUser.users{
        if let id = user.id{
            Network.sharedInstance.like(sender_id: id) { result in
                print(result)
            }
        }
        else{
            continue
        }
    }
    completion()
}


问:
Method that takes in integers or strings. C++
So right now I'm trying to make a graphic C header file that could create shapes like triangle's, boxes, and circles in C++. Its supposed to help kids in my class, but I also want to be able for them to type stuff in the shapes. But I was wondering if there was a place holder for a integer in case you don't to cout<< a int.

For instance

the method (called up):

```<code> //goes to coordinates 5,6 (creates side of 5 with a char called 'X')
 triangle(5,6,5,'X',"",5);
</code>```

Will make a triangle with 2 sides of 5 units of X and have a regular base. But what if the user just wanted to print out the string w/o the integer. Then they would type

```<code>triangle(5,6,5,'X',"I love code", );
</code>```

But an error would pop up and say that it needs one more parameter.

I've done some searching on boolean methods, like in java when you can type

```<code>public static void randommethod bool(/*params*\){

  /*Enter code if its either true or false*/

}
</code>```

But I've come up empty with any trying to find a method like that in C++.

答:
As others have said, you can implement function overloading to achieve your desired behavior. Take a look at C++ Overloading to fully understand.  Here is a brief example.</p>

```<code>#include <iostream>
#include <string>

class Shapes
{
    public:

        void triangle(int x,
                      int y,
                      int z,
                      char unit,
                      std::string & text,
                      int optional)
        {
            std::cout << "triangle with optional parameters" << std::endl;
        }

        void triangle(int x,
                      int y,
                      int z,
                      char unit,
                      std::string & text)
        {
            std::cout << "triangle with minimal parameters" << std::endl;
        }
};
</code>```

Body:
So right now I'm trying to make a graphic C header file that could create shapes like triangle's, boxes, and circles in C++. Its supposed to help kids in my class, but I also want to be able for them to type stuff in the shapes. But I was wondering if there was a place holder for a integer in case you don't to cout<< a int.

For instance

the method (called up):

 //goes to coordinates 5,6 (creates side of 5 with a char called 'X')
 triangle(5,6,5,'X',"",5);

Will make a triangle with 2 sides of 5 units of X and have a regular base. But what if the user just wanted to print out the string w/o the integer. Then they would type

triangle(5,6,5,'X',"I love code", );

But an error would pop up and say that it needs one more parameter.

I've done some searching on boolean methods, like in java when you can type

public static void randommethod bool(/*params*\){

  /*Enter code if its either true or false*/

}

But I've come up empty with any trying to find a method like that in C++.

Body:
As others have said, you can implement function overloading to achieve your desired behavior. Take a look at C++ Overloading to fully understand.  Here is a brief example.

#include <iostream>
#include <string>

class Shapes
{
    public:

        void triangle(int x,
                      int y,
                      int z,
                      char unit,
                      std::string & text,
                      int optional)
        {
            std::cout << "triangle with optional parameters" << std::endl;
        }

        void triangle(int x,
                      int y,
                      int z,
                      char unit,
                      std::string & text)
        {
            std::cout << "triangle with minimal parameters" << std::endl;
        }
};


问:
jquery function unexpected token error
So I am trying to write a reusable function in jquery for a style guide I'm creating.  The goal of the function is to hide/show a number of divs based on the value of a range slider.

The html code looks like this

```<code><div class="primary-colors">
    <h3>Primary Colors</h3>
    <div class="primary-range-container">
        <input type="range" min="1" max="15" value ="5" class="primary-slider"><span class="value">0</span>
    </div>
    <hr>
    <div class="color-container">
        <div class="color primary-color-1"></div>
        <div class="color primary-color-2"></div>
        <div class="color primary-color-3"></div>
        <div class="color primary-color-4"></div>
        <div class="color primary-color-5"></div>
        <div class="color primary-color-6"></div>
        <div class="color primary-color-7"></div>
        <div class="color primary-color-8"></div>
        <div class="color primary-color-9"></div>
        <div class="color primary-color-10"></div>
        <div class="color primary-color-11"></div>
    </div>
</div>
</code>```

And the javascript code looks like this

```<code>var primarySlider = $(".primary-slider");
var primaryColorContainer = $(".primary-colors .color");
var primaryValue = $('.primary-range-container .value');

$.fn.colorBlocks(colorContainer, rangeSlider) {
    this.change(function() {
        var number = $(rangeSlider).val();
        $(colorContainer).hide();
        $(colorContainer).hide().slice( 0, number ).show();
    }
    this.change();
}

primarySlider.colorBlocks(primaryColorContainer, primaryValue);
</code>```

The expected result in my head would be that the function would work, but so far I'm just not seeing anything and instead the compiler is giving me Parsing error: Unexpected Token {.

Any advice or better methods would be incredibly helpful.

答:
Found couple other bugs inside: I think this is what you wanted to do:

JS Fiddle demo

HTML:

```<code><div class="primary-colors">
   <h3>Primary Colors</h3>
   <div class="primary-range-container">
    <input type="range" min="1" max="15" value ="5" class="primary-slider">
    <span id="sliderValue" class="value">0</span>
   </div>

   <div class="color-container">
    <div class="color primary-color-1">1</div>
    <div class="color primary-color-2">2</div>
    <div class="color primary-color-3">3</div>
    <div class="color primary-color-4">4</div>
    <div class="color primary-color-5">5</div>
    <div class="color primary-color-6">6</div>
    <div class="color primary-color-7">7</div>
    <div class="color primary-color-8">8</div>
    <div class="color primary-color-9">9</div>
    <div class="color primary-color-10">10</div>
    <div class="color primary-color-11">11</div>
  </div>
</div>
</code>```

JS

```<code>var primarySlider = $(".primary-slider");
var primaryColorContainer = $(".primary-colors .color");
var primaryValue = $('.primary-range-container .value');

$.fn.colorBlocks = function(colorContainer, rangeSlider) {
  this.change(function() {
    var number = $(rangeSlider).val();
    //$(colorContainer).hide();
    $(colorContainer).each(function(i1,obj) {
     if(i1 < number){
        $(this).hide();
     }
     else $(this).show();
 });
  });
  this.change();
}

primarySlider.colorBlocks(primaryColorContainer, primarySlider);
</code>```

I left an Id for you to update value of slider (number to the right), and optional hide commented, toggle it back on if you wish

Title: jquery function unexpected token error

Body:
So I am trying to write a reusable function in jquery for a style guide I'm creating.  The goal of the function is to hide/show a number of divs based on the value of a range slider.

The html code looks like this

Primary Colors

        <input type="range" min="1" max="15" value ="5" class="primary-slider">0

And the javascript code looks like this

var primarySlider = $(".primary-slider");
var primaryColorContainer = $(".primary-colors .color");
var primaryValue = $('.primary-range-container .value');

$.fn.colorBlocks(colorContainer, rangeSlider) {
    this.change(function() {
        var number = $(rangeSlider).val();
        $(colorContainer).hide();
        $(colorContainer).hide().slice( 0, number ).show();
    }
    this.change();
}

primarySlider.colorBlocks(primaryColorContainer, primaryValue);

The expected result in my head would be that the function would work, but so far I'm just not seeing anything and instead the compiler is giving me Parsing error: Unexpected Token {.

Any advice or better methods would be incredibly helpful.

Body:
Found couple other bugs inside: I think this is what you wanted to do:

JS Fiddle demo

HTML:

<div class="primary-colors">
   <h3>Primary Colors</h3>
   <div class="primary-range-container">
    <input type="range" min="1" max="15" value ="5" class="primary-slider">
    <span id="sliderValue" class="value">0</span>
   </div>

   <div class="color-container">
    <div class="color primary-color-1">1</div>
    <div class="color primary-color-2">2</div>
    <div class="color primary-color-3">3</div>
    <div class="color primary-color-4">4</div>
    <div class="color primary-color-5">5</div>
    <div class="color primary-color-6">6</div>
    <div class="color primary-color-7">7</div>
    <div class="color primary-color-8">8</div>
    <div class="color primary-color-9">9</div>
    <div class="color primary-color-10">10</div>
    <div class="color primary-color-11">11</div>
  </div>
</div>

JS

var primarySlider = $(".primary-slider");
var primaryColorContainer = $(".primary-colors .color");
var primaryValue = $('.primary-range-container .value');

$.fn.colorBlocks = function(colorContainer, rangeSlider) {
  this.change(function() {
    var number = $(rangeSlider).val();
    //$(colorContainer).hide();
    $(colorContainer).each(function(i1,obj) {
     if(i1 < number){
        $(this).hide();
     }
     else $(this).show();
 });
  });
  this.change();
}

primarySlider.colorBlocks(primaryColorContainer, primarySlider);

I left an Id for you to update value of slider (number to the right), and optional hide commented, toggle it back on if you wish