问:
How to seperate declaration and implementation of a templated class with a default template parameter?
I like to separate the declaration and implementation of my classes. I know that the implementation of class templates and function also has to go into the header file, that's not the problem.

I'm having trouble implementing this class:

```<code>template <size_t S, std::enable_if_t<(S > 0), int> = 0>
class Foo {
public:
    Foo();
}
</code>```

So far I have tried:

```<code>template<size_t S>
Foo<S>::Foo() {}
</code>```

which failed with

error C3860: template argument list following class template name must list parameters in the order used in template parameter list

error C2976: 'Foo<S,<__formal>>' : too few template arguments

and

```<code>template<size_t S, int i>
Foo<S, i>::Foo() {}
</code>```

which failed with

error C3860: template argument list following class template name must list parameters in the order used in template parameter list

error C3855: 'Foo<S,<unnamed-symbol>>' : template parameter '__formal' is incompatible with the declaration

I have also tried changing the template declaration to

template <size_t S, typename = std::enable_if_t<(S > 0)>>

which also failed with the first error message.

What is the correct way of doing this?

答:
You cannot partially specialize template functions (that's what you're doing in the first snippet). If you're asking about how to define it outside the class, try this:

```<code>template <size_t S, std::enable_if_t<(S > 0), int> j>
Foo<S, j>::Foo(){}
</code>```

You cannot just replace std::enable_if_t<(S > 0), int> by int, as the definitions are not equivalent (the enable_if one SFINAEs out the S == 0 case).

Live snippet

Body:
I like to separate the declaration and implementation of my classes. I know that the implementation of class templates and function also has to go into the header file, that's not the problem.

I'm having trouble implementing this class:

template <size_t S, std::enable_if_t<(S > 0), int> = 0>
class Foo {
public:
    Foo();
}

So far I have tried:

template<size_t S>
Foo<S>::Foo() {}

which failed with

error C3860: template argument list following class template name must list parameters in the order used in template parameter list

error C2976: 'Foo<S,<__formal>>' : too few template arguments

and

template<size_t S, int i>
Foo<S, i>::Foo() {}

which failed with

error C3860: template argument list following class template name must list parameters in the order used in template parameter list

error C3855: 'Foo<S,<unnamed-symbol>>' : template parameter '__formal' is incompatible with the declaration

I have also tried changing the template declaration to

template <size_t S, typename = std::enable_if_t<(S > 0)>>

which also failed with the first error message.

What is the correct way of doing this?

Body:
You cannot partially specialize template functions (that's what you're doing in the first snippet). If you're asking about how to define it outside the class, try this:

template <size_t S, std::enable_if_t<(S > 0), int> j>
Foo<S, j>::Foo(){}

You cannot just replace std::enable_if_t<(S > 0), int> by int, as the definitions are not equivalent (the enable_if one SFINAEs out the S == 0 case).

Live snippet


来源: stackexchange

问:
wildfly did not find jar inside war
After changing ear to war, wildfly 10 cant find the jar file from jboss-deployment-structure.xml from sub-deployment section. There is no gui.ejb.jar in war after project buildin and I copy it to war manually. I try to root folder and to WEB-INF lib. Help please how to fix it.

Caused by:
  org.jboss.as.server.deployment.DeploymentUnitProcessingException:
  WFLYSRV0166: Sub deployment gui.ejb.jar in
  jboss-deployment-structure.xml was not found. Available sub
  deployments:      at
  org.jboss.as.server.deployment.module.descriptor.DeploymentStructureDescriptorParser.subDeploymentNotFound(DeploymentStructureDescriptorParser.java:288)
    at
  org.jboss.as.server.deployment.module.descriptor.DeploymentStructureDescriptorParser.deploy(DeploymentStructureDescriptorParser.java:190)
    at
  org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:147)
    ... 5 more

```<code><jboss-deployment-structure>
    <deployment>
        <exclude-subsystems>
            <subsystem name="webservices"/>
            <subsystem name="jaxrs"/>
        </exclude-subsystems>
        <exclusions>
            <module name="org.apache.commons.logging"/>
            <module name="org.apache.log4j"/>
            <module name="org.jboss.logging"/>
            <module name="org.jboss.logging.jul-to-slf4j-stub"/>
            <module name="org.jboss.logmanager"/>
            <module name="org.jboss.logmanager.log4j"/>
            <module name="org.slf4j"/>
            <module name="org.slf4j.impl"/>
            <module name="org.apache.cxf.impl"/>
            <module name="org.apache.cxf"/>
            <module name="org.apache.cxf.services-sts"/>
            <module name="org.apache.cxf.ws-security"/>
            <module name="org.apache.cxf.ws-policy"/>
            <module name="org.apache.xerces"/>
            <module name="org.apache.xalan"/>
        </exclusions>
        <dependencies>
            <module name="com.sun.xml.bind" export="true"services="export"/>
            <module name="javax.xml.ws.api" export="true"/>
            <module name="javax.jws.api" export="true"/>
            <module name="org.slf4j" export="true"/>
        </dependencies>
    </deployment>
    <sub-deployment name="gui.ejb.jar">
        <exclusions>
            <module name="org.apache.xerces"/>
            <module name="org.apache.xalan"/>
            <module name="org.slf4j"/>
            <module name="org.slf4j.impl"/>
        </exclusions>
        <dependencies>
            <module name="com.sun.xml.bind" export="true"services="export"/>
            <module name="javax.xml.ws.api" export="true" />
            <module name="javax.jws.api" export="true" />
            <module name="org.slf4j" export="true"/>
        </dependencies>
    </sub-deployment>
</jboss-deployment-structure>
</code>```

答:
A WAR deployment does not have a sub-deployment. You can remove the  element and it will be inherited from the main deployment element.

As a side note it looks a bit weird to both include and exclude the org.slf4j module. If you're attempting to use you're own slf4j binding you'd need to keep it excluded and include an slf4j-api and binding library.

ContentLicense: CC BY-SA 3.0

Title: wildfly did not find jar inside war

Body:
After changing ear to war, wildfly 10 cant find the jar file from jboss-deployment-structure.xml from sub-deployment section. There is no gui.ejb.jar in war after project buildin and I copy it to war manually. I try to root folder and to WEB-INF lib. Help please how to fix it.

Caused by:
  org.jboss.as.server.deployment.DeploymentUnitProcessingException:
  WFLYSRV0166: Sub deployment gui.ejb.jar in
  jboss-deployment-structure.xml was not found. Available sub
  deployments:      at
  org.jboss.as.server.deployment.module.descriptor.DeploymentStructureDescriptorParser.subDeploymentNotFound(DeploymentStructureDescriptorParser.java:288)
    at
  org.jboss.as.server.deployment.module.descriptor.DeploymentStructureDescriptorParser.deploy(DeploymentStructureDescriptorParser.java:190)
    at
  org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:147)
    ... 5 more

<jboss-deployment-structure>
    <deployment>
        <exclude-subsystems>
            <subsystem name="webservices"/>
            <subsystem name="jaxrs"/>
        </exclude-subsystems>
        <exclusions>
            <module name="org.apache.commons.logging"/>
            <module name="org.apache.log4j"/>
            <module name="org.jboss.logging"/>
            <module name="org.jboss.logging.jul-to-slf4j-stub"/>
            <module name="org.jboss.logmanager"/>
            <module name="org.jboss.logmanager.log4j"/>
            <module name="org.slf4j"/>
            <module name="org.slf4j.impl"/>
            <module name="org.apache.cxf.impl"/>
            <module name="org.apache.cxf"/>
            <module name="org.apache.cxf.services-sts"/>
            <module name="org.apache.cxf.ws-security"/>
            <module name="org.apache.cxf.ws-policy"/>
            <module name="org.apache.xerces"/>
            <module name="org.apache.xalan"/>
        </exclusions>
        <dependencies>
            <module name="com.sun.xml.bind" export="true"services="export"/>
            <module name="javax.xml.ws.api" export="true"/>
            <module name="javax.jws.api" export="true"/>
            <module name="org.slf4j" export="true"/>
        </dependencies>
    </deployment>

        <exclusions>
            <module name="org.apache.xerces"/>
            <module name="org.apache.xalan"/>
            <module name="org.slf4j"/>
            <module name="org.slf4j.impl"/>
        </exclusions>
        <dependencies>
            <module name="com.sun.xml.bind" export="true"services="export"/>
            <module name="javax.xml.ws.api" export="true" />
            <module name="javax.jws.api" export="true" />
            <module name="org.slf4j" export="true"/>
        </dependencies>

</jboss-deployment-structure>

Body:
A WAR deployment does not have a sub-deployment. You can remove the <sub-deployment/> element and it will be inherited from the main deployment element.

As a side note it looks a bit weird to both include and exclude the org.slf4j module. If you're attempting to use you're own slf4j binding you'd need to keep it excluded and include an slf4j-api and binding library.


Title: How can I duplicate the result set like below

Body:
I have a table like below and I want to duplicate the records while the min date being less or equal the max date

686151209   E13232677   1333439 2017-10-23
686151209   E13232677   1333439 2017-10-26

I'd like to have the result set like below

686151209   E13232677   1333439 2017-10-23
686151209   E13232677   1333439 2017-10-24
686151209   E13232677   1333439 2017-10-25
86151209    E13232677   1333439 2017-10-26

Body:
You and use spt_values to get continous number :

   ;WITH testdata(col1,col2,col3,col4)AS(
      SELECT '686151209','E13232677','1333439','2017-10-23' UNION all
      SELECT '686151209','E13232677','1333439','2017-10-26'
   )
   SELECT col1,col2,col3,DATEADD(d,sv.number-1,a.mindate) AS col4,sv.number FROM (
      SELECT col1,col2,col3,CONVERT(DATE,MIN(col4)) AS mindate,CONVERT(DATE,MAX(col4)) AS maxdate
      FROM testdata AS t
     group  by col1,col2,col3
   ) AS a
   INNER JOIN master.dbo.spt_values AS sv ON sv.type='P' AND sv.number BETWEEN 1 AND DATEDIFF(d,mindate,maxdate)+1

+-----------+-----------+---------+------------+--------+
| col1      | col2      | col3    | col4       | number |
+-----------+-----------+---------+------------+--------+
| 686151209 | E13232677 | 1333439 | 2017-10-23 | 1      |
| 686151209 | E13232677 | 1333439 | 2017-10-24 | 2      |
| 686151209 | E13232677 | 1333439 | 2017-10-25 | 3      |
| 686151209 | E13232677 | 1333439 | 2017-10-26 | 4      |
+-----------+-----------+---------+------------+--------+


问:
How to extract data from json file with multiple arrays?
I'm writing a small flask app, that accesses a json-API.
All the urls from the json file should then be extracted and put into a list for further use. The code in question:

```<code>@app.route('/booro/<tags>') # <tags> acts as search
def process(tags):
    r=requests.get('https://example.com/post/index.json?'+tags+'&limit=1') #gives me a json file with only one array
    z = r.text[1:-1] # to remove "[" and "]" so that it can be loaded
    i = json.loads(z)
    m = i['file_url']
    return m
</code>```

The code above then presents me just a link on the generated page as expected.

But if I set &limit to 2 or higher, I get this error message.

```<code>Traceback (most recent call last):
  File "/home/user/.local/lib/python3.5/site-packages/flask/app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/user/.local/lib/python3.5/site-packages/flask/app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "/home/user/.local/lib/python3.5/site-packages/flask/app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/user/.local/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/home/user/.local/lib/python3.5/site-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/user/.local/lib/python3.5/site-packages/flask/app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/user/.local/lib/python3.5/site-packages/flask/app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/user/.local/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/home/user/.local/lib/python3.5/site-packages/flask/app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/user/.local/lib/python3.5/site-packages/flask/app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/user/Schreibtisch/FlaskProxy/maindrive.py", line 19, in process
    i = json.loads(z)
  File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.5/json/decoder.py", line 342, in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 1278 (char 1277)
</code>```

The problem is that the downloaded json-file then contains multiple arrays that can't be parsed. It looks something like this:

```<code>{"id":1383185,"tags":"new main default","file_url": "example1.com"} {"id":1383185, "tags":"vivid original alternative","file_url": "example2.com"}
</code>```

Is there a way to extract values with the same key across multiple arrays?

答:
You shouldn't be removing [ and ], since the returned object is a JSON array and setting the limit to 1 will return you an array with just one object in it. You need to parse the response content without modifications, i.e.

```<code>i = json.loads(r.text)
</code>```

In case of limit==1 you will have:

```<code>[{'file_url': 'example1.com', ...}]
</code>```

In case of limit==2 you will have:

```<code>[{'file_url': 'example1.com', ...}, {'file_url': 'example2.com', ...}]
</code>```

etc.
By removing [ and ], json.loads tries to treat the response as a single JSON object, instead of a JSON array of objects, i.e. trying to parse something like:

```<code>{"file_url": "example1.com", ...}, {"file_url": "example2.com", ...}
</code>```

which is not a valid JSON

That being said, you would have to do something like this:

```<code>r = requests.get(...)
response_content = json.loads(r.text)
for obj in response_content:
    file_url = obj['file_url']
    # Do something with your file_url here. Ex. append to list m.append(file_url)
</code>```

Body:
I'm writing a small flask app, that accesses a json-API.
All the urls from the json file should then be extracted and put into a list for further use. The code in question:

@app.route('/booro/<tags>') # <tags> acts as search
def process(tags):
    r=requests.get('https://example.com/post/index.json?'+tags+'&limit=1') #gives me a json file with only one array
    z = r.text[1:-1] # to remove "[" and "]" so that it can be loaded
    i = json.loads(z)
    m = i['file_url']
    return m

The code above then presents me just a link on the generated page as expected.

But if I set &limit to 2 or higher, I get this error message.

Traceback (most recent call last):
  File "/home/user/.local/lib/python3.5/site-packages/flask/app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/user/.local/lib/python3.5/site-packages/flask/app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "/home/user/.local/lib/python3.5/site-packages/flask/app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/user/.local/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/home/user/.local/lib/python3.5/site-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/user/.local/lib/python3.5/site-packages/flask/app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/user/.local/lib/python3.5/site-packages/flask/app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/user/.local/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/home/user/.local/lib/python3.5/site-packages/flask/app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/user/.local/lib/python3.5/site-packages/flask/app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/user/Schreibtisch/FlaskProxy/maindrive.py", line 19, in process
    i = json.loads(z)
  File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.5/json/decoder.py", line 342, in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 1278 (char 1277)

The problem is that the downloaded json-file then contains multiple arrays that can't be parsed. It looks something like this:

{"id":1383185,"tags":"new main default","file_url": "example1.com"} {"id":1383185, "tags":"vivid original alternative","file_url": "example2.com"}

Is there a way to extract values with the same key across multiple arrays?

Body:
You shouldn't be removing [ and ], since the returned object is a JSON array and setting the limit to 1 will return you an array with just one object in it. You need to parse the response content without modifications, i.e.

i = json.loads(r.text)

In case of limit==1 you will have:

[{'file_url': 'example1.com', ...}]

In case of limit==2 you will have:

[{'file_url': 'example1.com', ...}, {'file_url': 'example2.com', ...}]

etc.
By removing [ and ], json.loads tries to treat the response as a single JSON object, instead of a JSON array of objects, i.e. trying to parse something like:

{"file_url": "example1.com", ...}, {"file_url": "example2.com", ...}

which is not a valid JSON

That being said, you would have to do something like this:

r = requests.get(...)
response_content = json.loads(r.text)
for obj in response_content:
    file_url = obj['file_url']
    # Do something with your file_url here. Ex. append to list m.append(file_url)


问:
Freeing memory which has been allocated to an array of char pointers (strings). Do I have to free each string or just the "main" pointer?
I have a function that takes a pointer to a char ** and fills it with strings (an array of strings I guess). *list_of_strings* is allocated memory inside the function.

```<code>char * *list_of_strings = NULL;

/* list_of_strings malloc'd inside function */
fill_strings_with_stuff(&list_of strings);

use_list_for_something(list_of_strings);

/* Now how do I free it all? */
</code>```

How would I go about freeing the memory after I've used the strings? If I call

```<code>free(list_of_strings);
</code>```

won't that just free the actual pointers and not the memory each string itself was using? How do I completely free the memory

Just for clarity the function looks something like this:

```<code>fill_strings_with_stuff(char *** list)
{
    *list = malloc(AMOUNT);

    for (i = 0; i < SOMETHING; i++) {
        *(list + i) = malloc(LINE_LEN);
        *(list + i) = some_string_from_somewhere
    }

    /* ... */

}
</code>```

答:
Yes, you have to free() every block you obtained from malloc(). You do it by traversing the array of pointers and caling free() on each element and only then freeing the array itself.

Only you know that there's a tree-like structure that could be freed recursively, that knowledge is not anywhere in the C runtime heap, so the heap manager has no idea about that and your program has to free everything itself.

ContentLicense: CC BY-SA 2.5

Body:
I have a function that takes a pointer to a char ** and fills it with strings (an array of strings I guess). *list_of_strings* is allocated memory inside the function.

char * *list_of_strings = NULL;

/* list_of_strings malloc'd inside function */
fill_strings_with_stuff(&list_of strings);

use_list_for_something(list_of_strings);

/* Now how do I free it all? */

How would I go about freeing the memory after I've used the strings? If I call

free(list_of_strings);

won't that just free the actual pointers and not the memory each string itself was using? How do I completely free the memory

Just for clarity the function looks something like this:

fill_strings_with_stuff(char *** list)
{
    *list = malloc(AMOUNT);

    for (i = 0; i < SOMETHING; i++) {
        *(list + i) = malloc(LINE_LEN);
        *(list + i) = some_string_from_somewhere
    }

    /* ... */

}


问:
Cell by cell diff in excel
I've seen a couple similar questions, but nothing I've found quite hits the mark with me.

I have two tables on two different sheets. The tables themselves are structured identically, but hold different content. Each data cell within the table can have MULTIPLE lines of information (e.g. E5 is 5 lines (actual lines, not wrapped) of data).

I'd like to create a third table that is also structurally identical (row 1 and column A are the same) to the first two, but have each data cell contain in some meaningful syntax the difference between the same two cells in the first two tables. It could be as straightforward as the output of a diff between the contents of the first two cells.

Is there a way to essentially take the diff of sheet1!E5 and sheet2!E5 and store it in sheet3!E5 ?

EDIT:
Some clarification. All the data cells contain information on MULTIPLE lines. Some lines are present in one sheet but not in another. For instance, sheet1!E5 may contain "string1", "string2", and "string3" on THREE lines whereas sheet2!E5 contains "string2", "string3", "string7", and "string8" on FOUR lines. The output on sheet3!E5 could be anything that clearly marks the difference between the two, for instance (as was mentioned before), exactly what the output would be if the two cells were text files and you ran a diff (or diff -c) on them like this:

```<code>*** 1,3 ****
- string1
  string2
! string3
\ No newline at end of file
--- 1,4 ----
  string2
! string3
! string7
! string8
\ No newline at end of file
</code>```

or even just something much simpler that lists the strings that are/are not in each cell like:

```<code><  string1
<> string2
<> string3
>  string7
>  string8
</code>```

答:
Yes. duplicate your structure in Sheet 3, and simply make sure all your references are accurate. For example, in cell A1 on sheet 3, you would just type:

```<code>= [navigate to sheet1!A1 and click it] - [navigate to sheet2!A1 and click it]
</code>```

pretty easy, actually.

Title: Cell by cell diff in excel

Body:
I've seen a couple similar questions, but nothing I've found quite hits the mark with me.

I have two tables on two different sheets. The tables themselves are structured identically, but hold different content. Each data cell within the table can have MULTIPLE lines of information (e.g. E5 is 5 lines (actual lines, not wrapped) of data).

I'd like to create a third table that is also structurally identical (row 1 and column A are the same) to the first two, but have each data cell contain in some meaningful syntax the difference between the same two cells in the first two tables. It could be as straightforward as the output of a diff between the contents of the first two cells.

Is there a way to essentially take the diff of sheet1!E5 and sheet2!E5 and store it in sheet3!E5 ?

EDIT:
Some clarification. All the data cells contain information on MULTIPLE lines. Some lines are present in one sheet but not in another. For instance, sheet1!E5 may contain "string1", "string2", and "string3" on THREE lines whereas sheet2!E5 contains "string2", "string3", "string7", and "string8" on FOUR lines. The output on sheet3!E5 could be anything that clearly marks the difference between the two, for instance (as was mentioned before), exactly what the output would be if the two cells were text files and you ran a diff (or diff -c) on them like this:

*** 1,3 ****
- string1
  string2
! string3
\ No newline at end of file
--- 1,4 ----
  string2
! string3
! string7
! string8
\ No newline at end of file

or even just something much simpler that lists the strings that are/are not in each cell like:

<  string1
<> string2
<> string3
>  string7
>  string8

Body:
Yes. duplicate your structure in Sheet 3, and simply make sure all your references are accurate. For example, in cell A1 on sheet 3, you would just type:

= [navigate to sheet1!A1 and click it] - [navigate to sheet2!A1 and click it]

pretty easy, actually.


问:
I want to pass a list of SqlParameter to a function which executes stored procedure in C#
I want to save two values say @name and @pwd to a table, for this I can use following code in aspx page.

```<code>public void save1()
{
    try
    {
        using (SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["myCon"].ConnectionString))
        {
            using(SqlCommand cmd = new SqlCommand("SP_TEST",con))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@name", txtUname.Text);
                cmd.Parameters.Add("@pwd", txtPwd.Text);

                cmd.ExecuteNonQuery();
            }
        }
    }
    catch (Exception ex)
    { }
}
</code>```

But I want to pass these two variable as a single List<SqlParameter> variable as

```<code>List<SqlParameter> param = new List<SqlParameter>();
param.Add(new SqlParameter("@name", uname));
param.Add(new SqlParameter("@pwd", pwd));
</code>```

Thus the declaration of above function changes from

```<code>public void save1()
</code>```

to

```<code>public void save1(List<SqlParameter> param)
</code>```

But my problem is I don't know how to extract those two variables from this param and then add them to the cmd variable. I need your help.

答:
If you know there's only going to be two parameters you could use this</p>

```<code>cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(param[0]);
cmd.Parameters.Add(param[1]);
cmd.ExecuteNonQuery();
</code>```

Body:
I want to save two values say @name and @pwd to a table, for this I can use following code in aspx page.

public void save1()
{
    try
    {
        using (SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["myCon"].ConnectionString))
        {
            using(SqlCommand cmd = new SqlCommand("SP_TEST",con))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@name", txtUname.Text);
                cmd.Parameters.Add("@pwd", txtPwd.Text);

                cmd.ExecuteNonQuery();
            }
        }
    }
    catch (Exception ex)
    { }
}

But I want to pass these two variable as a single List<SqlParameter> variable as

List<SqlParameter> param = new List<SqlParameter>();
param.Add(new SqlParameter("@name", uname));
param.Add(new SqlParameter("@pwd", pwd));

Thus the declaration of above function changes from

public void save1()

to

public void save1(List<SqlParameter> param)

But my problem is I don't know how to extract those two variables from this param and then add them to the cmd variable. I need your help.

Body:
If you know there's only going to be two parameters you could use this

cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(param[0]);
cmd.Parameters.Add(param[1]);
cmd.ExecuteNonQuery();


问:
Algorithm Analysis of Simple 2 Cases
Well I am studying algorithms for an upcoming exam and I am having hard time verifying if the practices below are answered right.

```<code> i=1
 while(i<=n)
      j=1
      while(j<i)
            j=j+1
      i=i*2
</code>```

The answer of mine for this one is O(n.log n)

```<code>i=1
 while(i<=n)
      j=1
      while(j<i)
            j=j*2
      i=i+1
</code>```

Again I have answered it as O(n.log n)

Can someone verify that I am answering correct or not ? Also any tips regarding analysis for future practices are welcome.

答: Yes, each of these is O(n log n).  You have one loop that is a linear iteration, i.e. O(n).  You have another loop that is exponential; the inverse is log, so that loop is O(log n).  As they are nested, you multiple the complexities, and get O(n log n).

Title: Algorithm Analysis of Simple 2 Cases

Body:
Well I am studying algorithms for an upcoming exam and I am having hard time verifying if the practices below are answered right.

 i=1
 while(i<=n)
      j=1
      while(j<i)
            j=j+1
      i=i*2

The answer of mine for this one is O(n.log n)

i=1
 while(i<=n)
      j=1
      while(j<i)
            j=j*2
      i=i+1

Again I have answered it as O(n.log n)

Can someone verify that I am answering correct or not ? Also any tips regarding analysis for future practices are welcome.


问:
Shift all elements of a increasing list to another list
I have a synchronized ArrayList which is getting it's size increased by multiple threads by adding objects to the list. I need to read this list in chunks and keep appending to a file. I need a code using which I can move first few elements of the ArrayList to another ArrayList and use the second arraylist to append to the file. All the elements of second arraylist should be removed from the synchronized ArrayList. I need to repeat this function till the synchronized ArrayList becomes empty. Please suggest a code for same.</p>

答:
I used the suggestions given by @Novaterata and @Tharun and finally achieved this by using LinkedBlockingQueue.

```<code>LinkedBlockingQueue<CustomObject> sharedList = new LinkedBlockingQueue<>();

// Sharing the queue with multiple threads to write to it.
new ForkJoinPool().submit(() -> logicForAddingDataToQueue(sharedList)).join();
</code>```

And drained the elements form BlockingQueue to a list and appended the list to the file, every 10 seconds like below :

```<code>ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(new Thread(() -> writeToFile(sharedList)){}, 1, 10, TimeUnit.SECONDS);
</code>```

where writeToFile method is defined as below:

```<code>public void writeToFile(LinkedBlockingQueue<CustomObject> sharedList) {
      List<CustomObject> subList = new ArrayList<>();
      sharedList.drainTo(subList);
      FileWriterUtil.appendToFile(fileName, subList);
      subList.clear();
}
</code>```

Body:
I used the suggestions given by @Novaterata and @Tharun and finally achieved this by using LinkedBlockingQueue.

LinkedBlockingQueue<CustomObject> sharedList = new LinkedBlockingQueue<>();

// Sharing the queue with multiple threads to write to it.
new ForkJoinPool().submit(() -> logicForAddingDataToQueue(sharedList)).join();

And drained the elements form BlockingQueue to a list and appended the list to the file, every 10 seconds like below :

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(new Thread(() -> writeToFile(sharedList)){}, 1, 10, TimeUnit.SECONDS);

where writeToFile method is defined as below:

public void writeToFile(LinkedBlockingQueue<CustomObject> sharedList) {
      List<CustomObject> subList = new ArrayList<>();
      sharedList.drainTo(subList);
      FileWriterUtil.appendToFile(fileName, subList);
      subList.clear();
}


答:
won't that just free the actual pointers and not the memory each string itself was using?

Yes, indeed.

How do I completely free the memory

By looping through the array and freeing each string one by one before freeing up the array itself. E.g.

```<code>for (i = 0; i < SOMETHING; i++) {
    free(list[i]);
}
free(list);
</code>```

Title: Freeing memory which has been allocated to an array of char pointers (strings). Do I have to free each string or just the "main" pointer?

Body:
won't that just free the actual pointers and not the memory each string itself was using?

Yes, indeed.

How do I completely free the memory

By looping through the array and freeing each string one by one before freeing up the array itself. E.g.

for (i = 0; i < SOMETHING; i++) {
    free(list[i]);
}
free(list);


问:
C++ Qt Timer For Each Object
How can implement Timer for each object

for example i have class like this

---------------------------------------> person.h

```<code>#ifndef PERSON_H
#define PERSON_H

#include <QMainWindow>

namespace Ui {
class person;
}

class person : public QMainWindow
{
    Q_OBJECT

public:
    explicit person(QWidget *parent = 0);
    ~person();
    QString Name;
    QTimer *timer;

private:
    Ui::person *ui;
signals:

public slots:

    void onTimer();
private slots:

};

#endif // PERSON_H
</code>```

person.cpp ---------------------->

```<code>#include "person.h"
#include "ui_person.h"
#include <QString>
#include <QDebug>
#include <QTimer>

person::person(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::person)
{
    ui->setupUi(this);
    timer=new QTimer(this);
    connect(timer, SIGNAL(timeout()), this,SLOT(this->onTimer()));
    timer->start(1000);

}

person::~person()
{
    delete ui;
}

void person::onTimer()
{
    qDebug() << "timer call for "<< Name  ;
</code>```

------------------> main.cpp

```<code>#include "person.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    person first;
    person second;
    first.Name="jack";
    second.Name="frank";

    return a.exec();
}
</code>```

this code work but the timer should interval in constructor and both of object have same interval!

OUtPut picture

you can see the out put in attached image

Problem is I want start , setInterval the Timer with object like:

```<code>person first;
first Name= "jack";
first.timer->start(200);
person second;
second Name "frank";
second.timer->start(500);
</code>```

and after my command timer start work not in constractor

in my code when i try to inpet first.timer the ponter sign -> didnt apear!!! and not working

答:
When you construct your person object, you get a new copy of each data member variable for each instance of the object.

Therefore, you will have a new QObject* timer for person john and for person frank.

However, timer is only a pointer, so you need to construct the timer in the constructor of your person class.

```<code>timer = new QTimer();
</code>```

A timer is kind of useless if you don't specify a mechanism to receive notification when the timer has expired.

As such you need to specify a callback.

Prior to C++11 and Qt5, the callback for the timer expiry has to be a class which inherits from QObject.

However, with the advent of C++11 and Qt5, you can use lambdas for callback functions, so you can specify your callback as follows:

```<code>person::person()
{
    timer = new QTimer();
    QObject::connect(timer, QTimer::timeout, [this]()
        {
            this->onTimer();
        });
}
</code>```

Now when you call, eg, john.timer->start(2000), the callback person::onTimer will be called after 2 seconds.

So you need to create a callback function, for example:

```<code>void person::onTimer()
{
    std::cout << timer called for " << Name.toStdString() << '\n';
}
</code>```

Whether you use a QObject derived design, or lambdas, depends on the needs of your design.

I would recommend reading Qt for Beginners on the qt wiki.

Title: C++ Qt Timer For Each Object

Body:
How can implement Timer for each object

for example i have class like this

---------------------------------------> person.h

#ifndef PERSON_H
#define PERSON_H

#include <QMainWindow>

namespace Ui {
class person;
}

class person : public QMainWindow
{
    Q_OBJECT

public:
    explicit person(QWidget *parent = 0);
    ~person();
    QString Name;
    QTimer *timer;

private:
    Ui::person *ui;
signals:

public slots:

    void onTimer();
private slots:

};

#endif // PERSON_H

person.cpp ---------------------->

#include "person.h"
#include "ui_person.h"
#include <QString>
#include <QDebug>
#include <QTimer>

person::person(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::person)
{
    ui->setupUi(this);
    timer=new QTimer(this);
    connect(timer, SIGNAL(timeout()), this,SLOT(this->onTimer()));
    timer->start(1000);

}

person::~person()
{
    delete ui;
}

void person::onTimer()
{
    qDebug() << "timer call for "<< Name  ;

------------------> main.cpp

#include "person.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    person first;
    person second;
    first.Name="jack";
    second.Name="frank";

    return a.exec();
}

this code work but the timer should interval in constructor and both of object have same interval!

OUtPut picture

you can see the out put in attached image

Problem is I want start , setInterval the Timer with object like:

person first;
first Name= "jack";
first.timer->start(200);
person second;
second Name "frank";
second.timer->start(500);

and after my command timer start work not in constractor

in my code when i try to inpet first.timer the ponter sign -> didnt apear!!! and not working

Body:
When you construct your person object, you get a new copy of each data member variable for each instance of the object.

Therefore, you will have a new QObject* timer for person john and for person frank.

However, timer is only a pointer, so you need to construct the timer in the constructor of your person class.

timer = new QTimer();

A timer is kind of useless if you don't specify a mechanism to receive notification when the timer has expired.

As such you need to specify a callback.

Prior to C++11 and Qt5, the callback for the timer expiry has to be a class which inherits from QObject.

However, with the advent of C++11 and Qt5, you can use lambdas for callback functions, so you can specify your callback as follows:

person::person()
{
    timer = new QTimer();
    QObject::connect(timer, QTimer::timeout, [this]()
        {
            this->onTimer();
        });
}

Now when you call, eg, john.timer->start(2000), the callback person::onTimer will be called after 2 seconds.

So you need to create a callback function, for example:

void person::onTimer()
{
    std::cout << timer called for " << Name.toStdString() << '\n';
}

Whether you use a QObject derived design, or lambdas, depends on the needs of your design.

I would recommend reading Qt for Beginners on the qt wiki.


问:
Segmentation Fault with mkfifo
I've got a problem with the following code:

```<code>#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>

int main(int argc, char*argv[]){

    FILE * tube;
    char chaine[10];
    mkfifo("glue", 0666);
    tube = fopen("glue", "r");

    while(1){
        fgets(chaine, 10, tube);
        printf("%s\n", chaine);

    }

}
</code>```

It's a program that mimics a server behavior, however when I run it on my Ubuntu Machine, either Windows 10 Ubuntu subsystem or the normal OS, the mkfifo line returns this error:

```<code>Segmentation Fault(core dumped)
</code>```

Pls Help!

EDIT:

Forgot to send the version with the mkfifo test:

```<code>#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>

int main(int argc, char*argv[]){

    FILE * tube;
    char chaine[10];
    int errValue = mkfifo("glue", 0666);
    perror("mkfifo");
    if( errValue < 0){
        printf("Error: %d\n", errValue);
        exit(EXIT_FAILURE);
    }
    tube = fopen("glue", "r");

    while(1){
        fgets(chaine, 10, tube);
        printf("%s\n", chaine);

    }

}
</code>```

The output of the program is:

```<code>mkfifo: Operation not permitted
Error: -1
</code>```

And the one of umask is:

```<code>0000
</code>```

And thank you immensely everyone for participating in this post!!:)

EDIT, PROBLEM SOLVED THANKS TO achal and everyone, thank you sooo much:

-One problem, the core one, was in using a 0022 umask instead of an 0002, thanks achal for this solution.

-The second problem was me using the Ubuntu subsystem for windows and try to run the program from CLI while it was located on the Windows desktop, windows doesn't give pipe permissions for the desktop apparently.

-The solution was to switch to my Ubuntu boot and change the umask and then it worked perfectly:)

Thanks to achal and everyone who participated in this post.

PROBLEM SOLVED.

答:
mkfifo() is a IPC mechanism useful for create a FIFO for communicating same or different process.

man pages of mkfifo() says "The mkfifo() system call creates a new fifo file with name path.  The access permissions are specified by mode and restricted by the umask(2) of the calling process"

As you mentioned in comments in your terminal umask value was 0000 means no permission that's why mkfifo() fails, so modify umask value using CLI  according your requirement.

```<code>xyz@xyz-PC:~$ umask 0002
xyz@xyz-PC:~/s_flow$ umask
0002
</code>```

and modify your code as

```<code>int main(int argc, char*argv[]){

    FILE * tube;
    char chaine[10];
    int errValue = mkfifo("glue", 0666);
    perror("mkfifo");
    if( errValue < 0){
        printf("Error: %d\n", errValue);
        exit(EXIT_FAILURE);
    }
    tube = fopen("glue", "r");
    if(tube == NULL)
    {
     printf("error in opening file :\n");
     return 0;
    }
    while(1){
        fgets(chaine, 10, tube);
        printf("%s\n", chaine);

    }

}
</code>```

Once umask value is set, execute your program.

I hope it helped lot

Title: Segmentation Fault with mkfifo

Body:
I've got a problem with the following code:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>

int main(int argc, char*argv[]){

    FILE * tube;
    char chaine[10];
    mkfifo("glue", 0666);
    tube = fopen("glue", "r");

    while(1){
        fgets(chaine, 10, tube);
        printf("%s\n", chaine);

    }

}

It's a program that mimics a server behavior, however when I run it on my Ubuntu Machine, either Windows 10 Ubuntu subsystem or the normal OS, the mkfifo line returns this error:

Segmentation Fault(core dumped)

Pls Help!

EDIT:

Forgot to send the version with the mkfifo test:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>

int main(int argc, char*argv[]){

    FILE * tube;
    char chaine[10];
    int errValue = mkfifo("glue", 0666);
    perror("mkfifo");
    if( errValue < 0){
        printf("Error: %d\n", errValue);
        exit(EXIT_FAILURE);
    }
    tube = fopen("glue", "r");

    while(1){
        fgets(chaine, 10, tube);
        printf("%s\n", chaine);

    }

}

The output of the program is:

mkfifo: Operation not permitted
Error: -1

And the one of umask is:

0000

And thank you immensely everyone for participating in this post!!:)

EDIT, PROBLEM SOLVED THANKS TO achal and everyone, thank you sooo much:

-One problem, the core one, was in using a 0022 umask instead of an 0002, thanks achal for this solution.

-The second problem was me using the Ubuntu subsystem for windows and try to run the program from CLI while it was located on the Windows desktop, windows doesn't give pipe permissions for the desktop apparently.

-The solution was to switch to my Ubuntu boot and change the umask and then it worked perfectly:)

Thanks to achal and everyone who participated in this post.

PROBLEM SOLVED.

Body:
mkfifo() is a IPC mechanism useful for create a FIFO for communicating same or different process.

man pages of mkfifo() says "The mkfifo() system call creates a new fifo file with name path.  The access permissions are specified by mode and restricted by the umask(2) of the calling process"

As you mentioned in comments in your terminal umask value was 0000 means no permission that's why mkfifo() fails, so modify umask value using CLI  according your requirement.

xyz@xyz-PC:~$ umask 0002
xyz@xyz-PC:~/s_flow$ umask
0002

and modify your code as

int main(int argc, char*argv[]){

    FILE * tube;
    char chaine[10];
    int errValue = mkfifo("glue", 0666);
    perror("mkfifo");
    if( errValue < 0){
        printf("Error: %d\n", errValue);
        exit(EXIT_FAILURE);
    }
    tube = fopen("glue", "r");
    if(tube == NULL)
    {
     printf("error in opening file :\n");
     return 0;
    }
    while(1){
        fgets(chaine, 10, tube);
        printf("%s\n", chaine);

    }

}

Once umask value is set, execute your program.

I hope it helped lot


问:
Changing the name of the method called dynamically in java
I have an object "JudgesSubmission" with the following methods:

```<code>public String getInnovationGrade1() {
    return innovationGrade1;
}
public String getInnovationGrade2() {
    return innovationGrade2;
}
public String getInnovationGrade3() {
    return innovationGrade3;
}
public String getInnovationGrade4() {
    return innovationGrade4;
}
</code>```

Now, when calling these methods, I want to put them in a loop where the called method name gets the index of the loop attached to its end changing the method called. Is this possible?
For example, the following code would never work, but I am writing it to explain what I need:

```<code>judgesSubmission metricScores= new judgesSubmission;
int metricSum=0;
for (int i=0;i<4;i++){
metricSum=metricSum
      Integer.parseInt(metricScores.getInnovationGrade+"i"());
}
</code>```

Is there a way to do that or do I always have the full method name written?

答:
It is not possible without reflection (and is highly not recommended)

Instead you may want to use other methods:

An array of the data (either replacing the 4 methods, or in addition)

```<code>String[] getInnovationGrades()
{
    return new String[]{innovationGrade1, innovationGrade2, innovationGrade3, innovationGrade4};
}
</code>```

Then later you can use

```<code>for(String innovationGrade : getInnovationGrades())
    //do stuff
</code>```

An argument to get the data you want

```<code>String getInnovationGrade(int i)
{
    switch(i)
    {
        case 1:
            return getInnovationGrade1();
        case 2:
            return getInnovationGrade2();
        case 3:
            return getInnovationGrade3();
        case 4:
            return getInnovationGrade4();
        default:
            return ""; //or throw exception, depends on how you wish to handle errors
    }
}
</code>```

Then later you can use

```<code>for(int i = 1; i <= 4; i++)
    getInnovationGrade(i); //and do stuff with it
</code>```

Body:
I have an object "JudgesSubmission" with the following methods:

public String getInnovationGrade1() {
    return innovationGrade1;
}
public String getInnovationGrade2() {
    return innovationGrade2;
}
public String getInnovationGrade3() {
    return innovationGrade3;
}
public String getInnovationGrade4() {
    return innovationGrade4;
}

Now, when calling these methods, I want to put them in a loop where the called method name gets the index of the loop attached to its end changing the method called. Is this possible?
For example, the following code would never work, but I am writing it to explain what I need:

judgesSubmission metricScores= new judgesSubmission;
int metricSum=0;
for (int i=0;i<4;i++){
metricSum=metricSum
      Integer.parseInt(metricScores.getInnovationGrade+"i"());
}

Is there a way to do that or do I always have the full method name written?

Body:
It is not possible without reflection (and is highly not recommended)

Instead you may want to use other methods:

An array of the data (either replacing the 4 methods, or in addition)

String[] getInnovationGrades()
{
    return new String[]{innovationGrade1, innovationGrade2, innovationGrade3, innovationGrade4};
}

Then later you can use

for(String innovationGrade : getInnovationGrades())
    //do stuff

An argument to get the data you want

String getInnovationGrade(int i)
{
    switch(i)
    {
        case 1:
            return getInnovationGrade1();
        case 2:
            return getInnovationGrade2();
        case 3:
            return getInnovationGrade3();
        case 4:
            return getInnovationGrade4();
        default:
            return ""; //or throw exception, depends on how you wish to handle errors
    }
}

Then later you can use

for(int i = 1; i <= 4; i++)
    getInnovationGrade(i); //and do stuff with it


问:
Excel formula quotation symbol meaning
what do the quotation symbols mean in this equation? I cant find a simple straight answer. </p>

```<code>=IF(K25="","",L24+K25)
</code>```

答:
"" means empty, or technically an empty value/string.

If K25 is empty ("") then return an empty string (""). Otherwise, add.

An alternative is using ISBLANK(), =IF(ISBLANK(K25),"",L24+K25).

Note that =A1="" will return TRUE if a formula returns "" but using ISBLANK on that same cell will return FALSE, since technically the cell is not blank.

In the above, B2 is empty.  B3 is a formula, ="".

Title: Excel formula quotation symbol meaning

Body:
what do the quotation symbols mean in this equation? I cant find a simple straight answer.

=IF(K25="","",L24+K25)


答:
What is the correct way of doing this?

I suppose the second one you've tried, with the typename.

Given

```<code>template <size_t S, typename = std::enable_if_t<(S > 0)>>
class Foo {
public:
    Foo();
};
</code>```

the constructor can be defined as

```<code>template <std::size_t S, typename T>
Foo<S, T>::Foo() {}
</code>```

A full compiling example

```<code>#include <iostream>
#include <type_traits>

template <size_t S, typename = std::enable_if_t<(S > 0)>>
class Foo {
public:
    Foo();
};

template <std::size_t S, typename T>
Foo<S, T>::Foo() {}

int main ()
 {
   Foo<12U>  f12;   // compile
   // Foo<0U>   f0; // compilation error
 }
</code>```

Title: How to seperate declaration and implementation of a templated class with a default template parameter?

Body:
I like to separate the declaration and implementation of my classes. I know that the implementation of class templates and function also has to go into the header file, that's not the problem.

I'm having trouble implementing this class:

template <size_t S, std::enable_if_t<(S > 0), int> = 0>
class Foo {
public:
    Foo();
}

So far I have tried:

template<size_t S>
Foo<S>::Foo() {}

which failed with

error C3860: template argument list following class template name must list parameters in the order used in template parameter list

error C2976: 'Foo<S,<__formal>>' : too few template arguments

and

template<size_t S, int i>
Foo<S, i>::Foo() {}

which failed with

error C3860: template argument list following class template name must list parameters in the order used in template parameter list

error C3855: 'Foo<S,<unnamed-symbol>>' : template parameter '__formal' is incompatible with the declaration

I have also tried changing the template declaration to

template <size_t S, typename = std::enable_if_t<(S > 0)>>

which also failed with the first error message.

What is the correct way of doing this?

Body:
What is the correct way of doing this?

I suppose the second one you've tried, with the typename.

Given

template <size_t S, typename = std::enable_if_t<(S > 0)>>
class Foo {
public:
    Foo();
};

the constructor can be defined as

template <std::size_t S, typename T>
Foo<S, T>::Foo() {}

A full compiling example

#include <iostream>
#include <type_traits>

template <size_t S, typename = std::enable_if_t<(S > 0)>>
class Foo {
public:
    Foo();
};

template <std::size_t S, typename T>
Foo<S, T>::Foo() {}

int main ()
 {
   Foo<12U>  f12;   // compile
   // Foo<0U>   f0; // compilation error
 }


问:
Cannot add the assembly System.Collections.Concurrent as using in Xamarin PCL project
I can see my Xamarin PCL project has the NET library added to it.

.Net library in pcl references

So I view in the Object explorer and I can see 2 versions of my mscorlib. [2.0.5.0] and [4.0.0.0].

duplicate libraries of CSharp and mscorlib

And if you check I have a duplicate of similar version for my CSharp library also.
I am assuming that its automatically pointing towards the [2.0.5.0] version.

But interestingly my android project in the same solution has mscorlib directly refrenced in the references section and yes I can access my System.Collections.Concurrent library in my android project.

But I need to access it in my Xamarin project.
I need a way to add that assembly in my PCL project too. Any one any idea?

答:
LexLi's comment actually got me thinking. So here's what I did. Hopefully this is going to be helpful.

I checked my VS2017 (Professional) version, and it was pending three updates.
Latest(as of now) is 15.4.4.4, got that updated.

I created a fresh Xamarin cross platform application with the same name (obviously a different location).

Got all the nuget packages that I needed. (Its better you do it manually for each project, because this has a lot of version compatibility dependencies).

And then fetched all the class files into this from my previous application. (Make sure you create the required folder structures). I double checked the app configs and package files to make sure everything is identical.

Fixed my Android manifest file by making changes in android Project(Right Click) >> Properties >> Android Manifest.

Do check your AppDelegate file in iOS and your App.xaml.cs file in UWP. Because sometimes some plugins require some changes in these. So make sure you have them exactly the way they were before.

And that was it. All for fixing the Object Model and Concurrent Collections issue. But in the process I got a nice migration done for my app.

If you want you can directly add projects to your solution but I'm not sure if that'll work because I haven't tried that.


问:
JSON-Server not returning single child element by ID
I'm trying to get Json-Server (v 0.12.1) working without the need for middleware or using it as a component - I already have something that works fine if I'm going to take the time to manually code all the endpoints. I'm attracted to the simplistic route config, and I believe I should be able to use it without requiring anything but a routes.json and db.json (letting me remove a lot of boilerplate express stuff).

My db.json:

```<code>  "users": [
    {
      "userId": 1,
      "favoriteColor": "red"
    },
    {
      "userId": 2,
      "favoriteColor": "blue"
    },
    {
      "userId": 3,
      "favoriteColor": "green"
    }
  ]
</code>```

My routes.json:

```<code>{
    "/api/users": "/users",
    "/api/users/:userId": "/users/:userId"
}
</code>```

I want to be able to make a GET call to: http://localhost:3000/api/users/2 and get

```<code>{
  "userId": 2,
  "favoriteColor": "blue"
}
</code>```

in return. However, I always just get {}.

Trying to use some suggestions from SO which either change the data structure (which I don't have control over) or using filters (which returns an array, not an object) are no-go for me.

Does anyone know why this seemingly-simply route is not working? I believe I'm following the custom route guidelines. I'm starting the server with json-server --watch ./api/db.json --routes ./api/routes.json, and hitting http://localhost:3000/api/users returns exactly what I expect, so I know the routes.json file and db.json file are both being picked up successfully.

Thank you!

答:
I gotta working starting the server with:
json-server --watch db.json --routes routes.json

db.json

```<code>{
  "users": [
    {
      "id": 1,
      "first_name": "Sebastian",
      "last_name": "Eschweiler",
      "email": "sebastian@codingthesmartway.com"
    },
    {
      "id": 2,
      "first_name": "Steve",
      "last_name": "Palmer",
      "email": "steve@codingthesmartway.com"
    },
    {
      "id": 3,
      "first_name": "Ann",
      "last_name": "Smith",
      "email": "ann@codingthesmartway.com"
    }
  ]
}
</code>```

routes.json

```<code>{
    "/api/users": "/users",
    "/api/users/:id": "/users/:id"
}
</code>```

Body:
I'm trying to get Json-Server (v 0.12.1) working without the need for middleware or using it as a component - I already have something that works fine if I'm going to take the time to manually code all the endpoints. I'm attracted to the simplistic route config, and I believe I should be able to use it without requiring anything but a routes.json and db.json (letting me remove a lot of boilerplate express stuff).

My db.json:

  "users": [
    {
      "userId": 1,
      "favoriteColor": "red"
    },
    {
      "userId": 2,
      "favoriteColor": "blue"
    },
    {
      "userId": 3,
      "favoriteColor": "green"
    }
  ]

My routes.json:

{
    "/api/users": "/users",
    "/api/users/:userId": "/users/:userId"
}

I want to be able to make a GET call to: http://localhost:3000/api/users/2 and get

{
  "userId": 2,
  "favoriteColor": "blue"
}

in return. However, I always just get {}.

Trying to use some suggestions from SO which either change the data structure (which I don't have control over) or using filters (which returns an array, not an object) are no-go for me.

Does anyone know why this seemingly-simply route is not working? I believe I'm following the custom route guidelines. I'm starting the server with json-server --watch ./api/db.json --routes ./api/routes.json, and hitting http://localhost:3000/api/users returns exactly what I expect, so I know the routes.json file and db.json file are both being picked up successfully.

Thank you!

Body:
I gotta working starting the server with:
json-server --watch db.json --routes routes.json

db.json

{
  "users": [
    {
      "id": 1,
      "first_name": "Sebastian",
      "last_name": "Eschweiler",
      "email": "sebastian@codingthesmartway.com"
    },
    {
      "id": 2,
      "first_name": "Steve",
      "last_name": "Palmer",
      "email": "steve@codingthesmartway.com"
    },
    {
      "id": 3,
      "first_name": "Ann",
      "last_name": "Smith",
      "email": "ann@codingthesmartway.com"
    }
  ]
}

routes.json

{
    "/api/users": "/users",
    "/api/users/:id": "/users/:id"
}


问:
Get absolute path of the script directory that is being processed by Job DSL
I have a DSL groovy script defining a pipeline job. I need to load Jenkinsfile from the workspace. The Jenkinsfile resides in the same folder as that of the groovy script. I am trying to get the path of the groovy script programmatically so that I can use that to figure out the path of the Jenkinsfile and load it using readFileFromWorkspace. I tried using __FILE__ directive after going through the job-dsl-wiki. But I am getting the following error:

```<code>Processing provided DSL script
ERROR: (test_job.groovy, line 3) No such property: absolutePath for class: java.lang.String
Finished: FAILURE
</code>```

Here is my DSL script

```<code>job_name = "my-pipeline-job"
job_path = "${new File(__FILE__).parent.absolutePath}"
jenkinsfile = job_path + "/Jenkinsfile"
pipelineJob(job_name){
 description("Jenkins pipeline job")
 parameters{
  stringParam("MyTestParam", "", "a sample parameter")
 }
 definition {
   cps {
      sandbox()
      script(readFileFromWorkspace(jenkinsfile))
   }
 }
}
</code>```

Is there anything that I am doing wrong here? Really appreciate any help on this.

答:
The documentation in the wiki is a little misleading. Here is the working solution. </p>

```<code>job_name = "my-pipeline-job"
println "Script: ${ __FILE__}"
println("script directory: ${new File(__FILE__).parent}")
job_path = "${new File(__FILE__).parent}"
jenkinsfile = job_path + "/Jenkinsfile"
pipelineJob(job_name){
 description("Jenkins pipeline job")
 parameters{
   stringParam("MyTestParam", "", "a sample parameter")
 }
 definition {
   cps {
      sandbox()
      script(readFileFromWorkspace(jenkinsfile))
   }
 }
}
</code>```

Body:
I have a DSL groovy script defining a pipeline job. I need to load Jenkinsfile from the workspace. The Jenkinsfile resides in the same folder as that of the groovy script. I am trying to get the path of the groovy script programmatically so that I can use that to figure out the path of the Jenkinsfile and load it using readFileFromWorkspace. I tried using __FILE__ directive after going through the job-dsl-wiki. But I am getting the following error:

Processing provided DSL script
ERROR: (test_job.groovy, line 3) No such property: absolutePath for class: java.lang.String
Finished: FAILURE

Here is my DSL script

job_name = "my-pipeline-job"
job_path = "${new File(__FILE__).parent.absolutePath}"
jenkinsfile = job_path + "/Jenkinsfile"
pipelineJob(job_name){
 description("Jenkins pipeline job")
 parameters{
  stringParam("MyTestParam", "", "a sample parameter")
 }
 definition {
   cps {
      sandbox()
      script(readFileFromWorkspace(jenkinsfile))
   }
 }
}

Is there anything that I am doing wrong here? Really appreciate any help on this.

Body:
The documentation in the wiki is a little misleading. Here is the working solution.

job_name = "my-pipeline-job"
println "Script: ${ __FILE__}"
println("script directory: ${new File(__FILE__).parent}")
job_path = "${new File(__FILE__).parent}"
jenkinsfile = job_path + "/Jenkinsfile"
pipelineJob(job_name){
 description("Jenkins pipeline job")
 parameters{
   stringParam("MyTestParam", "", "a sample parameter")
 }
 definition {
   cps {
      sandbox()
      script(readFileFromWorkspace(jenkinsfile))
   }
 }
}


问:
Convert void (*)() to void (*)(unsigned char)
I'm trying to convert a void (*)() to void (*)(unsigned char) but my knowledge in C++ isn't good enough. I searched, but I could not find any examples. So I thought to create a function of function but I get some error:

```<code>typedef void (* voidFuncPtr)();
void castHandler(voidFuncPtr handler)(uint8_t gpio_num)
{
    handler();
}

void attachInterrupt(uint8_t pin, voidFuncPtr handler, int mode)
{
    // typedef void (* voidFuncPtr)();
    // typedef void (* gpio_interrupt_handler_t)(uint8_t gpio_num);
    // typedef void (* gpio_interrupt_handler_t)(unsigned char)
    gpio_set_interrupt(pin, GPIO_INTTYPE_EDGE_ANY, castHandler(handler));
}
</code>```

error: 'castHandler' declared as function returning a function  void
  castHandler(voidFuncPtr handler)(uint8_t gpio_num)

error: 'castHandler' was not declared in this scope
       gpio_set_interrupt(pin, GPIO_INTTYPE_EDGE_ANY, castHandler(handler));

Can someone help me?

答:
Why not just write a function to do a redirection i.e.

```<code>void redirectFunction(unsigned char)
{
   handler();
}
</code>```

then

```<code>gpio_set_interrupt(pin, GPIO_INTTYPE_EDGE_ANY,redirectFunction);
</code>```

EDIT

Perhaps this in C++:

```<code>void redirectFunction(std::function<void()> handler, unsigned char)
{
   handler();
}

void wibble() { }

gpio_set_interrupt(pin, GPIO_INTTYPE_EDGE_ANY,
   std::bind(redirectFunction, _1, wibble)

);
</code>```

Body:
I'm trying to convert a void (*)() to void (*)(unsigned char) but my knowledge in C++ isn't good enough. I searched, but I could not find any examples. So I thought to create a function of function but I get some error:

typedef void (* voidFuncPtr)();
void castHandler(voidFuncPtr handler)(uint8_t gpio_num)
{
    handler();
}

void attachInterrupt(uint8_t pin, voidFuncPtr handler, int mode)
{
    // typedef void (* voidFuncPtr)();
    // typedef void (* gpio_interrupt_handler_t)(uint8_t gpio_num);
    // typedef void (* gpio_interrupt_handler_t)(unsigned char)
    gpio_set_interrupt(pin, GPIO_INTTYPE_EDGE_ANY, castHandler(handler));
}

error: 'castHandler' declared as function returning a function  void
  castHandler(voidFuncPtr handler)(uint8_t gpio_num)

error: 'castHandler' was not declared in this scope
       gpio_set_interrupt(pin, GPIO_INTTYPE_EDGE_ANY, castHandler(handler));

Can someone help me?

Body:
Why not just write a function to do a redirection i.e.

void redirectFunction(unsigned char)
{
   handler();
}

then

gpio_set_interrupt(pin, GPIO_INTTYPE_EDGE_ANY,redirectFunction);

EDIT

Perhaps this in C++:

void redirectFunction(std::function<void()> handler, unsigned char)
{
   handler();
}

void wibble() { }

gpio_set_interrupt(pin, GPIO_INTTYPE_EDGE_ANY,
   std::bind(redirectFunction, _1, wibble)

);


问:
How do I properly setup a conditional validator in symfony 1.4?
For some reason, the fields in my form are not being validated. Perhaps someone can point out any errors or missing items in my code. I was trying to follow the example here: http://www.symfony-project.org/cookbook/1_2/en/conditional-validator

Any help is appreciated!

I have the following form class:

```<code>    <?php

/**
 * dnc_btns form.
 *
 * @package    NMPlus
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class dnc_btnsForm extends Basednc_btnsForm
{
    public function configure()
  {
    $this->useFields(array('btn', 'btn_low', 'btn_high', 'company', 'source'));

    $this->setValidator('company', new sfValidatorPass());
    $this->setValidator('source', new sfValidatorPass());
    $this->validatorSchema->setPostValidator(
          new sfValidatorCallback(array('callback' => array($this, 'checkBtnType')))
        );

  }

    public function checkBtnType($validator, $values)
        {
                if (!empty($values['btn']))
                    {
                        $this->setValidator('btn', new sfValidatorBtn());
                        $this->setValidator('btn_low', new sfValidatorPass());
                        $this->setValidator('btn_high', new sfValidatorPass());
                    }

                if(empty($values['btn']))
                    {
                        $this->setValidator('btn_low', new sfValidatorBtn());
                        $this->setValidator('btn_high', new sfValidatorBtn());
                        $this->mergePostValidator(
                                    new sfValidatorSchemaCompare('btn_low', sfValidatorSchemaCompare::LESS_THAN, 'btn_high', array(),
                                    array('invalid' => 'The first BTN must be lower than the second.')));

                    }

                    return $values;
        }

}
</code>```

And here is my custom validator:

```<code><?php

class sfValidatorBtn extends sfValidatorAnd
{

    public function __construct()
    {
        parent::__construct();
        $this->setValidators();
    }

    public function setValidators()
    {

        //Btn should be required, not trimmed, and min and max length set.
        $this->addValidator(
                new sfValidatorString(
                        array(
                            'required' => true,
                            'trim' => false,
                            'min_length' => 10,
                            'max_length' => 10,
                            ),
                        array(
                            'invalid' => 'BTN must be 10 digits.'
                            )
                        )
                );

        // Adapted from http://stackoverflow.com/questions/1964399/validation-for-a-10-digit-phone-number
        $this->addValidator(
                new sfValidatorRegex(
                        array( 'pattern' => '/^([1-9]\d*)/' ),
                        array( 'invalid' => 'BTN may not start with a 0.')
                        )
                );

        //Checking for existance of given btn in database
        $this->addValidator(
                new sfValidatorDoctrineUnique(
                        array( 'model' => 'dnc_btns', 'column' => 'btn' ),
                        array('invalid' => 'This BTN is already in the database.')
                        )
                );
    }
}
</code>```

答:
The checkBtnType() method should perform a validation rather then add new validators.

Your method should return the values if everything is ok and throw an sfValidatorError exception otherwise.

You don't seem to follow the tutorial from the link you pasted.

Body:
For some reason, the fields in my form are not being validated. Perhaps someone can point out any errors or missing items in my code. I was trying to follow the example here: http://www.symfony-project.org/cookbook/1_2/en/conditional-validator

Any help is appreciated!

I have the following form class:

    <?php

/**
 * dnc_btns form.
 *
 * @package    NMPlus
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class dnc_btnsForm extends Basednc_btnsForm
{
    public function configure()
  {
    $this->useFields(array('btn', 'btn_low', 'btn_high', 'company', 'source'));

    $this->setValidator('company', new sfValidatorPass());
    $this->setValidator('source', new sfValidatorPass());
    $this->validatorSchema->setPostValidator(
          new sfValidatorCallback(array('callback' => array($this, 'checkBtnType')))
        );

  }

    public function checkBtnType($validator, $values)
        {
                if (!empty($values['btn']))
                    {
                        $this->setValidator('btn', new sfValidatorBtn());
                        $this->setValidator('btn_low', new sfValidatorPass());
                        $this->setValidator('btn_high', new sfValidatorPass());
                    }

                if(empty($values['btn']))
                    {
                        $this->setValidator('btn_low', new sfValidatorBtn());
                        $this->setValidator('btn_high', new sfValidatorBtn());
                        $this->mergePostValidator(
                                    new sfValidatorSchemaCompare('btn_low', sfValidatorSchemaCompare::LESS_THAN, 'btn_high', array(),
                                    array('invalid' => 'The first BTN must be lower than the second.')));

                    }

                    return $values;
        }

}

And here is my custom validator:

<?php

class sfValidatorBtn extends sfValidatorAnd
{

    public function __construct()
    {
        parent::__construct();
        $this->setValidators();
    }

    public function setValidators()
    {

        //Btn should be required, not trimmed, and min and max length set.
        $this->addValidator(
                new sfValidatorString(
                        array(
                            'required' => true,
                            'trim' => false,
                            'min_length' => 10,
                            'max_length' => 10,
                            ),
                        array(
                            'invalid' => 'BTN must be 10 digits.'
                            )
                        )
                );

        // Adapted from http://stackoverflow.com/questions/1964399/validation-for-a-10-digit-phone-number
        $this->addValidator(
                new sfValidatorRegex(
                        array( 'pattern' => '/^([1-9]\d*)/' ),
                        array( 'invalid' => 'BTN may not start with a 0.')
                        )
                );

        //Checking for existance of given btn in database
        $this->addValidator(
                new sfValidatorDoctrineUnique(
                        array( 'model' => 'dnc_btns', 'column' => 'btn' ),
                        array('invalid' => 'This BTN is already in the database.')
                        )
                );
    }
}


问:
Fsharp: Passing N Parameters for a function
I'm trying to create a function that takes in a variable amount of parameters but I can't seem to find any viable solution for F#.

```<code>let expression = (fun a b -> a || b)
let expressionTriple = (fun a b c -> (a || b) && c)

// This doesn't work because expression can either be a function that takes fixed arguments
let truthTable numPredicates expression =
    if numPredicates = 2 then
        expression true true
    else
        expression true true false

truthTable 2 expression
truthTable 3 expressionTriple
</code>```

How can I pass in a variable amount of arguments into the expression function?

答:
In F#, functions with different signatures (including a different number of parameters) are considered distinct types. And any time you want to have a function take a parameter that could be two distinct types (or even a dozen distinct types), you need to use discriminated unions. Here's how you could write your code in a way that will compile and do what you're trying to do:

```<code>type Expression<'a> =
    | Double of ('a -> 'a -> 'a)
    | Triple of ('a -> 'a -> 'a -> 'a)

let expression = fun a b -> a || b
let expressionTriple = fun a b c -> (a || b) && c

// This works because expression is a discriminated union
let truthTable expression =
    match expression with
    | Double f -> f true true
    | Triple f -> f true true false

truthTable (Double expression)
truthTable (Triple expressionTriple)
</code>```

If you wanted to add a four-parameter version, just add a Quad of ('a -> 'a -> 'a -> 'a -> 'a) case to that discriminated union, and so on.

If you have any questions about this, like why I wrote this with generic type 'a instead of bool, please feel free to ask follow-up questions.

Body:
I'm trying to create a function that takes in a variable amount of parameters but I can't seem to find any viable solution for F#.

let expression = (fun a b -> a || b)
let expressionTriple = (fun a b c -> (a || b) && c)

// This doesn't work because expression can either be a function that takes fixed arguments
let truthTable numPredicates expression =
    if numPredicates = 2 then
        expression true true
    else
        expression true true false

truthTable 2 expression
truthTable 3 expressionTriple

How can I pass in a variable amount of arguments into the expression function?

Body:
In F#, functions with different signatures (including a different number of parameters) are considered distinct types. And any time you want to have a function take a parameter that could be two distinct types (or even a dozen distinct types), you need to use discriminated unions. Here's how you could write your code in a way that will compile and do what you're trying to do:

type Expression<'a> =
    | Double of ('a -> 'a -> 'a)
    | Triple of ('a -> 'a -> 'a -> 'a)

let expression = fun a b -> a || b
let expressionTriple = fun a b c -> (a || b) && c

// This works because expression is a discriminated union
let truthTable expression =
    match expression with
    | Double f -> f true true
    | Triple f -> f true true false

truthTable (Double expression)
truthTable (Triple expressionTriple)

If you wanted to add a four-parameter version, just add a Quad of ('a -> 'a -> 'a -> 'a -> 'a) case to that discriminated union, and so on.

If you have any questions about this, like why I wrote this with generic type 'a instead of bool, please feel free to ask follow-up questions.


问:
I don't know how I do that
I have been trying to redirect my webpage from http://35.176.138.35/CSGO/ to http://www.csgoskins.es using .htaccess and don't know what I've done that I destroyed my page, you can see that by entering at my page, that is the URL, I don't know how I generated:

```<code>http://csgoskins.es/www/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.es
</code>```

Solution: make a forced refresh of the page.

答:
Try this:

RewriteCond %{HTTP_HOST} ^35\.176\.138\.35$
RewriteCond %{REQUEST_URI} ^/CSGO
RewriteRule ^(.*)$ http://csgoskins.es [R=301]```

ContentLicense: CC BY-SA 4.0

Title: I don't know how I do that

Body:
I have been trying to redirect my webpage from http://35.176.138.35/CSGO/ to http://www.csgoskins.es using .htaccess and don't know what I've done that I destroyed my page, you can see that by entering at my page, that is the URL, I don't know how I generated:

http://csgoskins.es/www/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.eswww/NOMHOME/es/c/s/g/csgoskins/www/htdocs/public/www.csgoskins.es

Solution: make a forced refresh of the page.


答: You need to iterate over list and call free() on every array member. Then free the array.

Body:
I have a function that takes a pointer to a char ** and fills it with strings (an array of strings I guess). *list_of_strings* is allocated memory inside the function.

char * *list_of_strings = NULL;

/* list_of_strings malloc'd inside function */
fill_strings_with_stuff(&list_of strings);

use_list_for_something(list_of_strings);

/* Now how do I free it all? */

How would I go about freeing the memory after I've used the strings? If I call

free(list_of_strings);

won't that just free the actual pointers and not the memory each string itself was using? How do I completely free the memory

Just for clarity the function looks something like this:

fill_strings_with_stuff(char *** list)
{
    *list = malloc(AMOUNT);

    for (i = 0; i < SOMETHING; i++) {
        *(list + i) = malloc(LINE_LEN);
        *(list + i) = some_string_from_somewhere
    }

    /* ... */

}


问:
Magento Enterprise Licence - Does it include SQL Cluster?
Trying to Evaluate Magento for an E-commerce solution. I have a naive question regarding the licence (Interestingly Magento Sales North America is not able to get me an answer, since i haven't bought licence yet, i cant raise this question under technical support either). So the Question is

Does Enterprise Edition comes with a MYSQL Cluster licence also or should i procure that MySQL cluster licence separately. I know it supports MySQL cluster in Enterprise Version but does the Licence include cluster license too is the question.

Any help is appreciated.

答: Magento just confirmed that we need to procure separate licence for SQL Cluster if we need support.</p>


问:
Netty NIO: Read received messages
I am developing a client and server communication system using Netty NIO in Java. My code can be found in the following repository. Currently I am having one server and two clients and I am sending information from server to the clients and the opposite.

What I am trying to figure out, when I am receiving a message form the first client to the server, how can i send that message to the second client (and the opposite from client 2 to client 1). How can I send a message to a specific client?

I have noticed that my issues arised because of the way that I am trying to send the messages from the server. My code in serverHandler is the following:

```<code>for (Channel ch : channels1) {
    responseData.setIntValue(channels1.size());
    remoteAddr.add(ch.remoteAddress().toString());
    future = ch.writeAndFlush(responseData);
    //future.addListener(ChannelFutureListener.CLOSE);
    System.out.println("the requested data from the clients are: "+requestData);
    responseData1.setStringValue(requestData.toString());
    future = ch.writeAndFlush(responseData1);
    System.out.println(future);
}
</code>```

By default am sending a message about the number of the connections, but also when I am receiving message from the client 1 or 2 I want to send it back to 2 and 1. So I want to perform the communication between the two components. How can I send from the server to a specific client? I am not sure how can I send the messages back to the clients.

答:
General approach

Let's describe an approach to the problem.

When receiving data on the server side, use the remote address of the channel (the java.net.SocketAddress Channel.remoteAddress() method) to identify the client.

Such identification may be done using a map like: Map<SocketAddress, Client>, where the Client class or interface should contain the appropriate client connection (channel) associated context, including its Channel. Be sure to keep the map up-to-date: handle the «client connected» and «client disconnected» events appropriately.

After a client is identified, you may just send the appropriate messages to the clients, except the current sending client, using the client connection (channel) map.

Additionally, I would like to recommend you to find a good implementation of a chat application using Netty and to take a look at it.

Netty-specific solution

Let's consider the server side implementation, in particular, the implementation of the ProcessingHandler class.

It already manages the active channels by representing them as the channel group:

```<code>static final ChannelGroup channels1 =
    new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
</code>```

Keeping the channel group up-to-date

The current implementation handles the «channel becomes active» event to keep the channel group up-to-date:

```<code>@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    channels1.add(ctx.channel());
    // ...
}
</code>```

But this is only a half: it is necessary to handle the «channel becomes inactive» event symmetrically as well. The implementation should look like:

```<code>@Override
public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
    channels1.remove(ctx.channel());
}
</code>```

Broadcasting: Sending the received message to all channels, except the current one

To implement the desired behaviour, just update the implementation by introducing the appropriate check as follows:

```<code>@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // ...

    for (Channel ch : channels1) {
        // Does `ch` represent the channel of the current sending client?
        if (ch.equals(ctx.channel())) {
            // Skip.
            continue;
        }

        // Send the message to the `ch` channel.
        // ...
    }

    // ...
}
</code>```

Sending and receiving string problem

Currently, the functionality around the ResponseData class is not present (not implemented).

The following draft changes are required to make both the client and the server work.

The ResponseData class: the getStringValue and toString methods should be corrected:

```<code>String getStringValue() {
    return this.strValue;
}

@Override
public String toString() {
    return intValue + ";" + strValue;
}
</code>```

The ResponseDataEncoder class: it should use the string value:

```<code>private final Charset charset = Charset.forName("UTF-8");

@Override
protected void encode(final ChannelHandlerContext ctx, final ResponseData msg, final ByteBuf out) throws Exception {
    out.writeInt(msg.getIntValue());
    out.writeInt(msg.getStringValue().length());
    out.writeCharSequence(msg.getStringValue(), charset);
}
</code>```

The ResponseDataDecoder class: it should use the string value:

```<code>private final Charset charset = Charset.forName("UTF-8");

@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws Exception {
    ResponseData data = new ResponseData();
    data.setIntValue(in.readInt());
    int strLen = in.readInt();
    data.setStringValue(in.readCharSequence(strLen, charset).toString());
    out.add(data);
}
</code>```

The ClientHandler class: it should correctly receive and handle the message:

```<code>@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    final ResponseData responseData = (ResponseData) msg;
    System.out.println("The message sent from the server " + responseData);
    update.accept(responseData.getIntValue());
}
</code>```

Additional references

«SecureChat ‐ an TLS-based chat server, derived from the Telnet example», Netty Documentation. In particular, the implementation of the SecureChatServerHandler class.

«Netty in Action», Norman Maurer, Marvin Allen Wolfthal (ISBN-13: 978-1617291470), «Part 3 — Network protocols», the «12.2 Our example WebSocket application» subchapter. Covers implementation of «a browser-based chat application».

Title: Netty NIO: Read received messages

Body:
I am developing a client and server communication system using Netty NIO in Java. My code can be found in the following repository. Currently I am having one server and two clients and I am sending information from server to the clients and the opposite.

What I am trying to figure out, when I am receiving a message form the first client to the server, how can i send that message to the second client (and the opposite from client 2 to client 1). How can I send a message to a specific client?

I have noticed that my issues arised because of the way that I am trying to send the messages from the server. My code in serverHandler is the following:

for (Channel ch : channels1) {
    responseData.setIntValue(channels1.size());
    remoteAddr.add(ch.remoteAddress().toString());
    future = ch.writeAndFlush(responseData);
    //future.addListener(ChannelFutureListener.CLOSE);
    System.out.println("the requested data from the clients are: "+requestData);
    responseData1.setStringValue(requestData.toString());
    future = ch.writeAndFlush(responseData1);
    System.out.println(future);
}

By default am sending a message about the number of the connections, but also when I am receiving message from the client 1 or 2 I want to send it back to 2 and 1. So I want to perform the communication between the two components. How can I send from the server to a specific client? I am not sure how can I send the messages back to the clients.

Body:
General approach

Let's describe an approach to the problem.

When receiving data on the server side, use the remote address of the channel (the java.net.SocketAddress Channel.remoteAddress() method) to identify the client.

Such identification may be done using a map like: Map<SocketAddress, Client>, where the Client class or interface should contain the appropriate client connection (channel) associated context, including its Channel. Be sure to keep the map up-to-date: handle the «client connected» and «client disconnected» events appropriately.

After a client is identified, you may just send the appropriate messages to the clients, except the current sending client, using the client connection (channel) map.

Additionally, I would like to recommend you to find a good implementation of a chat application using Netty and to take a look at it.

Netty-specific solution

Let's consider the server side implementation, in particular, the implementation of the ProcessingHandler class.

It already manages the active channels by representing them as the channel group:

static final ChannelGroup channels1 =
    new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

Keeping the channel group up-to-date

The current implementation handles the «channel becomes active» event to keep the channel group up-to-date:

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    channels1.add(ctx.channel());
    // ...
}

But this is only a half: it is necessary to handle the «channel becomes inactive» event symmetrically as well. The implementation should look like:

@Override
public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
    channels1.remove(ctx.channel());
}

Broadcasting: Sending the received message to all channels, except the current one

To implement the desired behaviour, just update the implementation by introducing the appropriate check as follows:

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // ...

    for (Channel ch : channels1) {
        // Does `ch` represent the channel of the current sending client?
        if (ch.equals(ctx.channel())) {
            // Skip.
            continue;
        }

        // Send the message to the `ch` channel.
        // ...
    }

    // ...
}

Sending and receiving string problem

Currently, the functionality around the ResponseData class is not present (not implemented).

The following draft changes are required to make both the client and the server work.

The ResponseData class: the getStringValue and toString methods should be corrected:

String getStringValue() {
    return this.strValue;
}

@Override
public String toString() {
    return intValue + ";" + strValue;
}

The ResponseDataEncoder class: it should use the string value:

private final Charset charset = Charset.forName("UTF-8");

@Override
protected void encode(final ChannelHandlerContext ctx, final ResponseData msg, final ByteBuf out) throws Exception {
    out.writeInt(msg.getIntValue());
    out.writeInt(msg.getStringValue().length());
    out.writeCharSequence(msg.getStringValue(), charset);
}

The ResponseDataDecoder class: it should use the string value:

private final Charset charset = Charset.forName("UTF-8");

@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws Exception {
    ResponseData data = new ResponseData();
    data.setIntValue(in.readInt());
    int strLen = in.readInt();
    data.setStringValue(in.readCharSequence(strLen, charset).toString());
    out.add(data);
}

The ClientHandler class: it should correctly receive and handle the message:

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    final ResponseData responseData = (ResponseData) msg;
    System.out.println("The message sent from the server " + responseData);
    update.accept(responseData.getIntValue());
}

Additional references

«SecureChat ‐ an TLS-based chat server, derived from the Telnet example», Netty Documentation. In particular, the implementation of the SecureChatServerHandler class.

«Netty in Action», Norman Maurer, Marvin Allen Wolfthal (ISBN-13: 978-1617291470), «Part 3 — Network protocols», the «12.2 Our example WebSocket application» subchapter. Covers implementation of «a browser-based chat application».


问:
Long Numeric to Character in SAS
When I try to convert a 10 digit number which is stored as 8. into a character using put(,8.) it gives me the character value as something like 1.2345e10. I want the character string to be as 1234567890. Can someone please help ?</p>

答:
Unless very sure of your inputs, I find it best to use best.:

```<code>data have;
  x=1234567890;output;
  x=12345.67890;output;
  x=.1234567890;output;
  x=12345678901234;output;
run;

data want;
  set have;
  length ten best $32;
  ten=put(x,10.);
  best=put(x,best32.);
run;
</code>```

Note that using 10. here would wipe out any decimals, as well as larger numbers:

Title: Long Numeric to Character in SAS

Body:
Unless very sure of your inputs, I find it best to use best.:

data have;
  x=1234567890;output;
  x=12345.67890;output;
  x=.1234567890;output;
  x=12345678901234;output;
run;

data want;
  set have;
  length ten best $32;
  ten=put(x,10.);
  best=put(x,best32.);
run;

Note that using 10. here would wipe out any decimals, as well as larger numbers:


问:
jQuery unbind/disable navigation link
Hy,

a really stupid problem, but i cant get it to work:

I have some function that binds the click of my navigation. When a link is clicker it gets the class "active". So my idea was that i just say:

```<code><a id="link1" class="main">link1</a>
<a id="link2" class="main">link2</a>
<a id="link3" class="main">link3</a>

$('a.main').bind('click', function(){
$(this).removeClass('active');
//some code
$(this).addClass('active');
}
</code>```

So far thats working. My element gets the active class when it´s hit and removes when another has been clicked. My idea now was just simple unbind all active links (otherwise some double reloading happends by paranoid 10000 clicks on my navigation =)

```<code>§('a.active').unbind('click');
</code>```

I also specify for each element in my navigation a special event:

```<code>$('a#link1').bind('click', function() {
$img.fadeOut('slow', function() {
      $('#bg div table tr td').addClass('loading');
        $img.attr('src', 'images/image.jpg');
     });
});
</code>```

Now what happends is, that if i click an element in my navigation (accordion), the thing slides down, gets the active class (still keeps the main class):

```<code><a id="link1" class="main active">link1</a>
</code>```

When i click another element in the navigation, this one closes and the active class is removed.

BUT when i go back to that link before, it´s nnot clickable anymore? So, i guess jQuery unbinds the click event for ever from an element that has been active. Sounds a bit stupid and unlogic to me...

Maybe is there a way to enable/disabel these. So a function that checks if the element has an active class it should be disabled. Or is the problem the "main" class beside the "active" class...

Any idea?

答:
You can namespace event handlers, so you can easily unbind them without affecting other handlers of the same type attached to the same elements:

```<code>$('a.main').bind('click.activeState', function() {
    ...
});

$('a.active').unbind('click.activeState');

// and instead of binding several times, you can use attributeStartswith
$('a[id^=link]').bind('click.animation', function() {
    ...
});
</code>```

Take a look at the 'Using Namespaces' subsections of .bind and .unbind.

Title: jQuery unbind/disable navigation link

Body:
Hy,

a really stupid problem, but i cant get it to work:

I have some function that binds the click of my navigation. When a link is clicker it gets the class "active". So my idea was that i just say:

link1
link2
link3

$('a.main').bind('click', function(){
$(this).removeClass('active');
//some code
$(this).addClass('active');
}

So far thats working. My element gets the active class when it´s hit and removes when another has been clicked. My idea now was just simple unbind all active links (otherwise some double reloading happends by paranoid 10000 clicks on my navigation =)

§('a.active').unbind('click');

I also specify for each element in my navigation a special event:

$('a#link1').bind('click', function() {
$img.fadeOut('slow', function() {
      $('#bg div table tr td').addClass('loading');
        $img.attr('src', 'images/image.jpg');
     });
});

Now what happends is, that if i click an element in my navigation (accordion), the thing slides down, gets the active class (still keeps the main class):

link1

When i click another element in the navigation, this one closes and the active class is removed.

BUT when i go back to that link before, it´s nnot clickable anymore? So, i guess jQuery unbinds the click event for ever from an element that has been active. Sounds a bit stupid and unlogic to me...

Maybe is there a way to enable/disabel these. So a function that checks if the element has an active class it should be disabled. Or is the problem the "main" class beside the "active" class...

Any idea?

Body:
You can namespace event handlers, so you can easily unbind them without affecting other handlers of the same type attached to the same elements:

$('a.main').bind('click.activeState', function() {
    ...
});

$('a.active').unbind('click.activeState');

// and instead of binding several times, you can use attributeStartswith
$('a[id^=link]').bind('click.animation', function() {
    ...
});

Take a look at the 'Using Namespaces' subsections of .bind and .unbind.