问:
ER Diagram Design Method
I have an entity: Employee. This is at the top of my ER diagram (rectangle box)

I have another entity: Crew. This is the second object on my ER diagram (rectangle box). It is under the above rectangle.

I have a composite entity, containing foreign keys made up of primary key Employee_ID and Crew_ID

Because the composite entity contains foreign keys from the employee and crew table, does that mean I have to draw a line in my ER diagram from the composite entity to the TWO rectangles, or just the one above it?

答: What you're describing sounds like a relationship between two entity sets. I would diagram it like so:

Title: ER Diagram Design Method


来源: stackexchange

问:
simple dynamic allocation question
What is the difference between this:-

```<code>width = new int;
</code>```

And this:-

```<code>int width;
</code>```

i.e. of what use is the dynamic allocation in the first code?

答:
The former allocates dynamically one int and returns its address in memory (which is written to the variable width and you have to free it later with delete. It exists until then.

The latter declares a local variable of type int which becomes invalid when it leaves the current scope.

ContentLicense: CC BY-SA 3.0

Title: simple dynamic allocation question

Body:
What is the difference between this:-

width = new int;

And this:-

int width;

i.e. of what use is the dynamic allocation in the first code?

ContentLicense: CC BY-SA 2.5


问:
JDBC pass parameters to sql query
I have

```<code>employee(id, name, company, salary);
</code>```

Need to display data for given id

```<code>public static void Connect(String conString, String username, String password, int id) throws SQLException{
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = null;
            conn = DriverManager.getConnection(conString, username, password);
            String query = "select * from employee where id = " + id + "" ;
            ResultSet rs = null;
            Statement stmt = null;
            stmt = conn.createStatement();
            rs = stmt.executeQuery(query);
            while(rs.next()){
                String name = rs.getString("name");
                String company = rs.getString("company");
                int salary = rs.getInt("salary");
                System.out.println("Name: " + name + "\tCompany: " + company + "\tSalary: " + salary);
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
</code>```

But here we are passing the id directly. How can we pass it like parametrized queries (like how we pass ? during  PreparedStatement)

答:
It's old post but I would still like to add my answer.

I don't have enough reputation to  comment on @prasad's answer, so I am adding small correction as separate answer. Actually, passing query inside praparedStatement.executeQuery() throws MySQLSyntaxErrorException because still it calls Statement.executeQuery instead of PreparedStatement.executeQuery(). And how do I know? I had to spent ample amount of time in figuring out this issue.

So use PreparedStatement.executeQuery() instead of PreparedStament.executeQuery(query).

Title: JDBC pass parameters to sql query

Body:
I have

employee(id, name, company, salary);

Need to display data for given id

public static void Connect(String conString, String username, String password, int id) throws SQLException{
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = null;
            conn = DriverManager.getConnection(conString, username, password);
            String query = "select * from employee where id = " + id + "" ;
            ResultSet rs = null;
            Statement stmt = null;
            stmt = conn.createStatement();
            rs = stmt.executeQuery(query);
            while(rs.next()){
                String name = rs.getString("name");
                String company = rs.getString("company");
                int salary = rs.getInt("salary");
                System.out.println("Name: " + name + "\tCompany: " + company + "\tSalary: " + salary);
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

But here we are passing the id directly. How can we pass it like parametrized queries (like how we pass ? during  PreparedStatement)

ContentLicense: CC BY-SA 4.0


问:
Add new member in Google Group Using Angular 2
I made a Web App using angular 2 and created a Sign In and Sign Out with Google API. I'm reading this documentation:

https://developers.google.com/admin-sdk/directory/v1/guides/manage-group-members.

But I'm don't understand how to use it.

How can I use the Google Groups API to add new members to group?

答:
You use the http Service to make http requests

There's more info here: https://angular.io/docs/ts/latest/guide/server-communication.html

I didn't read Google's full documentation but the function below should get you started.

```<code>addNewUserToGroup(email: string, role:string, groupKey: string): Observable<Hero> {
 let headers = new Headers({ 'Content-Type': 'application/json' });
 let options = new RequestOptions({ headers: headers });
 let data = {
   email: email,
   role: role
 }
 return this.http.post("https://www.googleapis.com/admin/directory/v1/groups/"+ groupKey +"/members", { data }, options)
                .map(response => response.json());
}
</code>```

Good luck

Body:
You use the http Service to make http requests

There's more info here: https://angular.io/docs/ts/latest/guide/server-communication.html

I didn't read Google's full documentation but the function below should get you started.

addNewUserToGroup(email: string, role:string, groupKey: string): Observable<Hero> {
 let headers = new Headers({ 'Content-Type': 'application/json' });
 let options = new RequestOptions({ headers: headers });
 let data = {
   email: email,
   role: role
 }
 return this.http.post("https://www.googleapis.com/admin/directory/v1/groups/"+ groupKey +"/members", { data }, options)
                .map(response => response.json());
}

Good luck


问:
Updating maximum sum subinterval for an array when two elements are swapped
For a given array of real numbers, Kadane's dynamic programming algorithm can find the maximum sum subinterval in the array in linear time. However, suppose that we have done some preprocessing to obtain the optimal solution as well as any required auxilary information, and then we are given a transposition that swaps two elements in the array. Is there a scheme that will allow updating the optimal solution subinterval in sub-linear time, and allow future updates for subsequent transpositions as well? I'm looking for the preprocessing time and extra memory to be o(N^2) for an array of size N.

答:
You can use square root decomposition.

Just divide whole array into blocks of sqrt(n) size and compute answer for each block separately. When you update, you update only at most 2 blocks. Once you do it, you can apply Kadane's algorithm on block array (note, that there are at most sqrt(n) blocks). So you can get O(sqrt(n)) time per update with linear preprocessing.


问:
JSON Array in Newtonsoft using C#
I am pretty new to using JSON and Newtonsoft together and I am trying to replicate this format without success using JArray(). Does anyone have any ideas on how this can be accomplished?</p>

```<code>   "attrList":[
      {
         "name":"Attendee Status",
         "val":"Accepted"
      },
      {
         "name":"Attendee Type",
         "val":"Attendee"
      }
   ]
</code>```

答:
Using manual JArray creation, you can do it as follows:

```<code>var root = new JObject
(
    new JProperty("attrList",
        new JArray
        (
            new JObject
            (
                new JProperty("name", "Attendee Status"),
                new JProperty("val", "Accepted")
            ),
            new JObject
            (
                new JProperty("name", "Attendee Type"),
                new JProperty("val", "Attendee")
            )
        )
    )
);
</code>```

You wrote The error I keep running into is the keys being the same, so you are probably doing something like this instead:

```<code>var root = new JObject
(
    new JProperty("attrList",
        new JArray
        (
            new JObject
            (
                new JProperty("name", "Attendee Status"),
                new JProperty("val", "Accepted"),
                new JProperty("name", "Attendee Type"),
                new JProperty("val", "Attendee")
            )
        )
    )
);
</code>```

Notice that only one inner object is being created rather than two?  If you forget to allocate both objects you will end up trying to add the properties "name" and "val" twice, thereby reproducing the problem.

Sample fiddle.

See also Creating JSON: Manually Creating JSON.

Title: JSON Array in Newtonsoft using C#

Body:
I am pretty new to using JSON and Newtonsoft together and I am trying to replicate this format without success using JArray(). Does anyone have any ideas on how this can be accomplished?

   "attrList":[
      {
         "name":"Attendee Status",
         "val":"Accepted"
      },
      {
         "name":"Attendee Type",
         "val":"Attendee"
      }
   ]

Body:
Using manual JArray creation, you can do it as follows:

var root = new JObject
(
    new JProperty("attrList",
        new JArray
        (
            new JObject
            (
                new JProperty("name", "Attendee Status"),
                new JProperty("val", "Accepted")
            ),
            new JObject
            (
                new JProperty("name", "Attendee Type"),
                new JProperty("val", "Attendee")
            )
        )
    )
);

You wrote The error I keep running into is the keys being the same, so you are probably doing something like this instead:

var root = new JObject
(
    new JProperty("attrList",
        new JArray
        (
            new JObject
            (
                new JProperty("name", "Attendee Status"),
                new JProperty("val", "Accepted"),
                new JProperty("name", "Attendee Type"),
                new JProperty("val", "Attendee")
            )
        )
    )
);

Notice that only one inner object is being created rather than two?  If you forget to allocate both objects you will end up trying to add the properties "name" and "val" twice, thereby reproducing the problem.

Sample fiddle.

See also Creating JSON: Manually Creating JSON.


问:
Reusing a angular 1.4 directive inside an angular 1.5 application
I would like to reuse an angularjs 1.4 directive within an angularjs 1.5 application.
Is this possible?
Are there any issues ?
Thank you</p>

答:
Is this possible?

Yes

Are there any issues?

Not regarding custom directives. Take a look at the migration guide for migration from version 1.4 to 1.5.


问:
RegularExpressionValidator for more than just AlphaNumerics
I have a RegularExpressionValidator with:

```<code>ValidationExpression="^(a-zA-Z0-9 '-]+$"
</code>```

so this was working for alphanumerics, spaces, apostrophes and hyphen.

I was told that I now need it to additionally work for underscore, ampersand '&', comma, parentheses and fullstop.

I tried:

```<code>ValidationExpression="^(a-zA-Z0-9 '-_&,().]+$"
</code>```

but this made it accept virtually anything.

Could someone please tell me where I'm going wrong? I'm relatively new to Regex.

答:
The dot means "anything" (except, depending on your settings, line returns). You must escape it with a backslash if you want to match the dot character:

```<code>ValidationExpression="^(a-zA-Z0-9 '-_&,()\.]+$"
</code>```

You would probably also need to escape parentheses and brackets, since they also are metacharacters.

Body:
I have a RegularExpressionValidator with:

ValidationExpression="^(a-zA-Z0-9 '-]+$"

so this was working for alphanumerics, spaces, apostrophes and hyphen.

I was told that I now need it to additionally work for underscore, ampersand '&', comma, parentheses and fullstop.

I tried:

ValidationExpression="^(a-zA-Z0-9 '-_&,().]+$"

but this made it accept virtually anything.

Could someone please tell me where I'm going wrong? I'm relatively new to Regex.

Body:
The dot means "anything" (except, depending on your settings, line returns). You must escape it with a backslash if you want to match the dot character:

ValidationExpression="^(a-zA-Z0-9 '-_&,()\.]+$"

You would probably also need to escape parentheses and brackets, since they also are metacharacters.


问:
Cumulative total by group in Power BI (DAX)
After googling for two pages, I'm struggling to find a simple way to create a cumulative sum measure by date and item in Power BI (using DAX). I have a table which contains:

Username

Date (DD-MM-YYYY)

Number of requests in that day

I have managed to obtain the cumulative sum by using the following expression (extracted from DAXPatterns):

```<code>CALCULATE (
SUM ( Table[Requests] ),
FILTER (
    ALL ( 'Date'[Date] ),
    'Date'[Date] <= MAX ( 'Date'[Date] )
)
)
</code>```

But I would like to obtain a measure indicating how many requests have been made by a user up to a certain date.

Is there a simple way to do this?

答:
Create calculated table using SUMMARIZECOLUMNS function and apply filter that you need on the top of that calculated table.

```<code>YourCalcTableName =
SUMMARIZECOLUMNS (
    'UsernameTable'[Username],
    'Date'[Date],
    "Number Of Requests", SUMX ( 'UsernameTable', 'UsernameTable'[NumberOfRequests] )
)
</code>```

This calculated table essencialy produces 3 column table with user name, date and number of requests sent by this user on this date.

SUMMARIZECOLUMNS

Body:
After googling for two pages, I'm struggling to find a simple way to create a cumulative sum measure by date and item in Power BI (using DAX). I have a table which contains:

Username

Date (DD-MM-YYYY)

Number of requests in that day

I have managed to obtain the cumulative sum by using the following expression (extracted from DAXPatterns):

CALCULATE (
SUM ( Table[Requests] ),
FILTER (
    ALL ( 'Date'[Date] ),
    'Date'[Date] <= MAX ( 'Date'[Date] )
)
)

But I would like to obtain a measure indicating how many requests have been made by a user up to a certain date.

Is there a simple way to do this?

Body:
Create calculated table using SUMMARIZECOLUMNS function and apply filter that you need on the top of that calculated table.

YourCalcTableName =
SUMMARIZECOLUMNS (
    'UsernameTable'[Username],
    'Date'[Date],
    "Number Of Requests", SUMX ( 'UsernameTable', 'UsernameTable'[NumberOfRequests] )
)

This calculated table essencialy produces 3 column table with user name, date and number of requests sent by this user on this date.

SUMMARIZECOLUMNS


问:
ES6 pattern match in Switch
Consider the following code snippet:

```<code>if (msg.operation == 'create') {
  model.blocks.push(msg.block)
  drawBlock(msg.block);
} else if (msg.operation == 'select' && msg.properties.snap == 'arbitrary') {
  doStuff(msg.properties.x, msg.properties.y);
} else if (msg.operation == 'unselect') {
  doOtherStuff(msg.properties.geometry);
}
</code>```

Is there a way to refactor this so I can pattern match on msg, akin to the following invalid code:

```<code>msg match {
  case { operation: 'create', block: b } =>
    model.blocks.push(b);
    drawBlock(b);
  case { operation: 'select', properties: { snap: 'arbitrary', x: sx, y: sy } } =>
    doStuff(sx, sy);
  case { operation: 'unselect', properties: { snap: 'specific' }, geometry: geom } =>
    doOtherStuff(geom);
}
</code>```

Alternatively, what would be the most idiomatic way of achieving this in ES6, without the ugly if-then-else chain?

Update. Granted that this is a simplistic example where a full-blown pattern matching is probably unneeded. But one can imagine a scenario of matching arbitrary hierarchical pieces of a long AST.

TL;DR; the power of destructuring, accompanied with an automatic check if it is possible to do it or not.

答:
I think @gunn's answer is onto something good here, but the primary issue I have with his code is that it relies upon a side-effecting function in order to produce a result – his match function does not have a useful return value.

For the sake of keeping things pure, I will implement match in a way that returns a value. In addition, I will also force you to include an else branch, just the way the ternary operator (?:) does - matching without an else is reckless and should be avoided.

Caveat: this does not work for matching on nested data structures but support could be added

// match.js
// only export the match function
const matchKeys = x => y =>
  Object.keys(x).every(k => x[k] === y[k])

const matchResult = x => ({
  case: () => matchResult(x),
  else: () => x
})

const match = x => ({
  case: (pattern, f) =>
    matchKeys (pattern) (x) ? matchResult(f(x)) : match(x),
  else: f => f(x)
})

// demonstration
const myfunc = msg => match(msg)
  .case({operation: 'create'},       ({block}) => ['create', block])
  .case({operation: 'select-block'},    ({id}) => ['select-block', id])
  .case({operation: 'unselect-block'},  ({id}) => ['unselect-block', id])
  .else(                                 (msg) => ['unmatched-operation', msg])

const messages = [
  {operation: 'create', block: 1, id: 2},
  {operation: 'select-block', block: 1, id: 2},
  {operation: 'unselect-block', block: 1, id: 2},
  {operation: 'other', block: 1, id: 2}
]

for (let m of messages)
  // myfunc returns an actual value now
  console.log(myfunc(m))

// [ 'create', 1 ]
// [ 'select-block', 2 ]
// [ 'unselect-block', 2 ]
// [ 'unmatched-operation', { operation: 'other', block: 1, id: 2 } ]```

not quite pattern matching

Now actual pattern matching would allow us to destructure and match in the same expression – due to limitations of JavaScript, we have to match in one expression and destructure in another. Of course this only works on natives that can be destructured like {} and [] – if a custom data type was used, we'd have to dramatically rework this function and a lot of conveniences would be lost.

Title: ES6 pattern match in Switch

Body:
Consider the following code snippet:

if (msg.operation == 'create') {
  model.blocks.push(msg.block)
  drawBlock(msg.block);
} else if (msg.operation == 'select' && msg.properties.snap == 'arbitrary') {
  doStuff(msg.properties.x, msg.properties.y);
} else if (msg.operation == 'unselect') {
  doOtherStuff(msg.properties.geometry);
}

Is there a way to refactor this so I can pattern match on msg, akin to the following invalid code:

msg match {
  case { operation: 'create', block: b } =>
    model.blocks.push(b);
    drawBlock(b);
  case { operation: 'select', properties: { snap: 'arbitrary', x: sx, y: sy } } =>
    doStuff(sx, sy);
  case { operation: 'unselect', properties: { snap: 'specific' }, geometry: geom } =>
    doOtherStuff(geom);
}

Alternatively, what would be the most idiomatic way of achieving this in ES6, without the ugly if-then-else chain?

Update. Granted that this is a simplistic example where a full-blown pattern matching is probably unneeded. But one can imagine a scenario of matching arbitrary hierarchical pieces of a long AST.

TL;DR; the power of destructuring, accompanied with an automatic check if it is possible to do it or not.

Body:
I think @gunn's answer is onto something good here, but the primary issue I have with his code is that it relies upon a side-effecting function in order to produce a result – his match function does not have a useful return value.

For the sake of keeping things pure, I will implement match in a way that returns a value. In addition, I will also force you to include an else branch, just the way the ternary operator (?:) does - matching without an else is reckless and should be avoided.

Caveat: this does not work for matching on nested data structures but support could be added

// match.js
// only export the match function
const matchKeys = x => y =>
  Object.keys(x).every(k => x[k] === y[k])

const matchResult = x => ({
  case: () => matchResult(x),
  else: () => x
})

const match = x => ({
  case: (pattern, f) =>
    matchKeys (pattern) (x) ? matchResult(f(x)) : match(x),
  else: f => f(x)
})

// demonstration
const myfunc = msg => match(msg)
  .case({operation: 'create'},       ({block}) => ['create', block])
  .case({operation: 'select-block'},    ({id}) => ['select-block', id])
  .case({operation: 'unselect-block'},  ({id}) => ['unselect-block', id])
  .else(                                 (msg) => ['unmatched-operation', msg])

const messages = [
  {operation: 'create', block: 1, id: 2},
  {operation: 'select-block', block: 1, id: 2},
  {operation: 'unselect-block', block: 1, id: 2},
  {operation: 'other', block: 1, id: 2}
]

for (let m of messages)
  // myfunc returns an actual value now
  console.log(myfunc(m))

// [ 'create', 1 ]
// [ 'select-block', 2 ]
// [ 'unselect-block', 2 ]
// [ 'unmatched-operation', { operation: 'other', block: 1, id: 2 } ]

not quite pattern matching

Now actual pattern matching would allow us to destructure and match in the same expression – due to limitations of JavaScript, we have to match in one expression and destructure in another. Of course this only works on natives that can be destructured like {} and [] – if a custom data type was used, we'd have to dramatically rework this function and a lot of conveniences would be lost.


问:
serialize and deserialise using boost binary_iarchive from sstream
Finally , After lot of struggle i found a way to serialise and deserialize  the std::map<int,map<int,structute values> and iam able to print the values.

Would you please clarify the doubts i have pertaining to the code below

Is void serialize(archive & ar,  const unsigned int version) function used for both serialising and deserialising

Can we have separate functions for both serialise and deserialise in each class and structs

Can the same function be utilised for creating xml also , or is it a neat way to have separate serialise and deserialise functionality for xml

```<code> #include <boost/archive/binary_oarchive.hpp>
 #include <boost/archive/binary_iarchive.hpp>
 #include <boost/serialization/binary_object.hpp>
 #include <boost/serialization/serialization.hpp>
 #include <iostream>
 #include <string>
 #include <iomanip>
 #include <sstream>
 #include <map>
 #include <boost/serialization/map.hpp>

struct values
{
    std::string name;
    std::string sex;
    values():name("dummy"),sex("dummy"){} ;
    template<class archive>
    void serialize(archive & ar,  const unsigned int version)
    {
      ar & name ;
      ar & sex ;
    }
};
class Myclass
{
public:

  Myclass()
  {
    values val1;
    e_group.insert( std::make_pair(1,val1) ) ;
    e_group.insert( std::make_pair(2,val1) ) ;
    p_group.insert( std::make_pair(1,e_group) ) ;
    p_group.insert( std::make_pair(2,e_group) ) ;
  }
  template<class archive>
  void serialize(archive & ar,  const unsigned int version)
  {
    ar & e_group ;
    ar & p_group;
  }
  typedef   std::map<int,values> groups;
  typedef   std::map<int,groups> Pgroups;
  groups  e_group;
  Pgroups p_group;
};

int main() {
    char buf[256];

    Myclass obj;

    std::stringstream os(std::ios_base::binary| std::ios_base::out| std::ios_base::in);
    {
        boost::archive::binary_oarchive oa(os, boost::archive::no_header);
        oa << obj ;
      // oa << make_binary_object(&e_group, sizeof(e_group));
    }

   //print binary data
    std::string data = os.str();
    for (uint8_t ch : data) {
        std::cout << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(ch) << " ";
    }

    Myclass t2;
    {
        memcpy(buf, os.str().data(), os.str().length());
        if(memcmp(buf, os.str().data(), os.str().length()) != 0)
          printf("memcpy error\n");
        std::stringstream is(std::string(buf, buf+os.str().length() ), std::ios_base::binary| std::ios_base::out| std::ios_base::in);
        boost::archive::binary_iarchive ia(is, boost::archive::no_header);
        ia >> t2;
    }

   for(auto &i:t2.p_group){
       std::cout<<"\n"<<i.first<<"\n";
        for(auto &j:i.second){
          std::cout<<"\t"<<j.first<<"\t"<<j.second.name<<"\t"<<j.second.sex<<"\n";
        }
   }
   return 0;
}
</code>```

Update : i have updated richard's code and added a function to deserilaize the binary

```<code>#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/binary_object.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/nvp.hpp>
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
#include <fstream>

#include <map>
#include <boost/serialization/map.hpp>
#include <boost/serialization/split_member.hpp>

struct values
{
    std::string name;
    std::string sex;
    values():name("dummy"),sex("dummy"){} ;

    BOOST_SERIALIZATION_SPLIT_MEMBER();

    template<class Archive>
    void save(Archive & ar, const unsigned int version) const
    {
        // note, version is always the latest when saving
        ar & BOOST_SERIALIZATION_NVP(name);
        ar & BOOST_SERIALIZATION_NVP(sex);
    }
    template<class Archive>
    void load(Archive & ar, const unsigned int version)
    {
        ar & BOOST_SERIALIZATION_NVP(name);
        ar & BOOST_SERIALIZATION_NVP(sex);
    }
};
class Myclass
{
public:

    Myclass()
    {
        values val1;
        e_group.insert( std::make_pair(1,val1) ) ;
        e_group.insert( std::make_pair(2,val1) ) ;
        p_group.insert( std::make_pair(1,e_group) ) ;
        p_group.insert( std::make_pair(2,e_group) ) ;
    }

    BOOST_SERIALIZATION_SPLIT_MEMBER();

    template<class Archive>
    void save(Archive & ar, const unsigned int version) const
    {
        // note, version is always the latest when saving
        ar & BOOST_SERIALIZATION_NVP(e_group);
        ar & BOOST_SERIALIZATION_NVP(p_group);
    }
    template<class Archive>
    void load(Archive & ar, const unsigned int version)
    {
        ar & BOOST_SERIALIZATION_NVP(e_group);
        ar & BOOST_SERIALIZATION_NVP(p_group);
    }

    typedef   std::map<int,values> groups;
    typedef   std::map<int,groups> Pgroups;
    groups  e_group;
    Pgroups p_group;
};

template<class Archive, class Object>
std::string serialise_to_string(Object const& assetlist)
{
    auto os = std::ostringstream(std::ios::binary);
    Archive arch { os, boost::archive::no_header };
    arch << BOOST_SERIALIZATION_NVP(assetlist);
    return os.str();
};

std::ostream& dump(std::ostream& os, std::string const& s)
{
    const char *sep = "";
    for (uint8_t ch : s) {
        std::cout << sep << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(ch);
        sep = " ";
    }
    return os;
}

template<class Archive , class Object>
void deserialise_to_obj(std::string const &s1,Object &outObj)
{
    std::stringstream is( s1, std::ios_base::binary| std::ios_base::out| std::ios_base::in);
    Archive arch { is, boost::archive::no_header };
    arch >> BOOST_SERIALIZATION_NVP(outObj);
};

int main() {

    Myclass obj ;
    std::string  s1 = serialise_to_string<boost::archive::binary_oarchive>(obj);
    dump(std::cout, s1) << std::endl << std::endl;

    auto s2 = serialise_to_string<boost::archive::xml_oarchive>(obj);

   //Save xml to a file
    std::ofstream ofs("output.xml");
    ofs << s2 << std::endl << std::endl;

    //Deserialize the binary data to object
    Myclass outObj;
    deserialise_to_obj<boost::archive::binary_iarchive>(s1,outObj);

    //Print the object
    for(auto &i:outObj.p_group){
       std::cout<<"\n"<<i.first<<"\n";
        for(auto &j:i.second){
          std::cout<<"\t"<<j.first<<"\t"<<j.second.name<<"\t"<<j.second.sex<<"\n";
        }
    }
}
</code>```

code compiled using coliru

Please suggest . advice me if my approach is wrong

I would want to thank @sehe and @richard helping me with boost.

Thanks
Tejas

答:
First, don't do this:

```<code>    memcpy(buf, os.str().data(), os.str().length());
    if(memcmp(buf, os.str().data(), os.str().length()) != 0)
</code>```

That's just created 4 separate copies of a string.

Now the questions:

Is void serialize(archive & ar,  const unsigned int version) function used for both serialising and deserialising

Yes

Can we have separate functions for both serialise and deserialise in each class and structs

Yes

Can the same function be utilised for creating xml also , or is it a neat way to have separate serialise and deserialise functionality for xml

Yes

You want the xml_oarchive and the macros BOOST_SERIALIZATION_SPLIT_MEMBER and BOOST_SERIALIZATION_NVP

```<code>#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/binary_object.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/nvp.hpp>
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
#include <map>
#include <boost/serialization/map.hpp>
#include <boost/serialization/split_member.hpp>

struct values
{
    std::string name;
    std::string sex;
    values():name("dummy"),sex("dummy"){} ;

    BOOST_SERIALIZATION_SPLIT_MEMBER();

    template<class Archive>
    void save(Archive & ar, const unsigned int version) const
    {
        // note, version is always the latest when saving
        ar & BOOST_SERIALIZATION_NVP(name);
        ar & BOOST_SERIALIZATION_NVP(sex);
    }
    template<class Archive>
    void load(Archive & ar, const unsigned int version)
    {
        ar & BOOST_SERIALIZATION_NVP(name);
        ar & BOOST_SERIALIZATION_NVP(sex);
    }
};
class Myclass
{
public:

    Myclass()
    {
        values val1;
        e_group.insert( std::make_pair(1,val1) ) ;
        e_group.insert( std::make_pair(2,val1) ) ;
        p_group.insert( std::make_pair(1,e_group) ) ;
        p_group.insert( std::make_pair(2,e_group) ) ;
    }

    BOOST_SERIALIZATION_SPLIT_MEMBER();

    template<class Archive>
    void save(Archive & ar, const unsigned int version) const
    {
        // note, version is always the latest when saving
        ar & BOOST_SERIALIZATION_NVP(e_group);
        ar & BOOST_SERIALIZATION_NVP(p_group);
    }
    template<class Archive>
    void load(Archive & ar, const unsigned int version)
    {
        ar & BOOST_SERIALIZATION_NVP(e_group);
        ar & BOOST_SERIALIZATION_NVP(p_group);
    }

    typedef   std::map<int,values> groups;
    typedef   std::map<int,groups> Pgroups;
    groups  e_group;
    Pgroups p_group;
};

template<class Archive, class Object>
std::string serialise_to_string(Object const& o)
{
    auto os = std::ostringstream(std::ios::binary);
    Archive arch { os, boost::archive::no_header };
    arch << BOOST_SERIALIZATION_NVP(o);
    return os.str();
};

std::ostream& dump(std::ostream& os, std::string const& s)
{
    const char *sep = "";
    for (uint8_t ch : s) {
        std::cout << sep << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(ch);
        sep = " ";
    }
    return os;
}

int main() {
    char buf[256];

    Myclass obj;

    auto s1 = serialise_to_string<boost::archive::binary_oarchive>(obj);
    dump(std::cout, s1) << std::endl << std::endl;

    auto s2 = serialise_to_string<boost::archive::xml_oarchive>(obj);
    std::cout<< s2 << std::endl << std::endl;

    return 0;
}
</code>```

example output:

```<code>00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 05 00 00 00 00 00 00 00 64 75 6d 6d 79 05 00 00 00 00 00 00 00 64 75 6d 6d 79 02 00 00 00 05 00 00 00 00 00 00 00 64 75 6d 6d 79 05 00 00 00 00 00 00 00 64 75 6d 6d 79 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 05 00 00 00 00 00 00 00 64 75 6d 6d 79 05 00 00 00 00 00 00 00 64 75 6d 6d 79 02 00 00 00 05 00 00 00 00 00 00 00 64 75 6d 6d 79 05 00 00 00 00 00 00 00 64 75 6d 6d 79 02 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 05 00 00 00 00 00 00 00 64 75 6d 6d 79 05 00 00 00 00 00 00 00 64 75 6d 6d 79 02 00 00 00 05 00 00 00 00 00 00 00 64 75 6d 6d 79 05 00 00 00 00 00 00 00 64 75 6d 6d 79

<o class_id="0" tracking_level="0" version="0">
    <e_group class_id="1" tracking_level="0" version="0">
        <count>2</count>
        <item_version>0</item_version>
        <item class_id="2" tracking_level="0" version="0">
            <first>1</first>
            <second class_id="3" tracking_level="0" version="0">
                <name>dummy</name>
                <sex>dummy</sex>
            </second>
        </item>
        <item>
            <first>2</first>
            <second>
                <name>dummy</name>
                <sex>dummy</sex>
            </second>
        </item>
    </e_group>
    <p_group class_id="4" tracking_level="0" version="0">
        <count>2</count>
        <item_version>0</item_version>
        <item class_id="5" tracking_level="0" version="0">
            <first>1</first>
            <second>
                <count>2</count>
                <item_version>0</item_version>
                <item>
                    <first>1</first>
                    <second>
                        <name>dummy</name>
                        <sex>dummy</sex>
                    </second>
                </item>
                <item>
                    <first>2</first>
                    <second>
                        <name>dummy</name>
                        <sex>dummy</sex>
                    </second>
                </item>
            </second>
        </item>
        <item>
            <first>2</first>
            <second>
                <count>2</count>
                <item_version>0</item_version>
                <item>
                    <first>1</first>
                    <second>
                        <name>dummy</name>
                        <sex>dummy</sex>
                    </second>
                </item>
                <item>
                    <first>2</first>
                    <second>
                        <name>dummy</name>
                        <sex>dummy</sex>
                    </second>
                </item>
            </second>
        </item>
    </p_group>
</o>
</code>```

Body:
Finally , After lot of struggle i found a way to serialise and deserialize  the std::map<int,map<int,structute values> and iam able to print the values.

Would you please clarify the doubts i have pertaining to the code below

Is void serialize(archive & ar,  const unsigned int version) function used for both serialising and deserialising

Can we have separate functions for both serialise and deserialise in each class and structs

Can the same function be utilised for creating xml also , or is it a neat way to have separate serialise and deserialise functionality for xml

 #include <boost/archive/binary_oarchive.hpp>
 #include <boost/archive/binary_iarchive.hpp>
 #include <boost/serialization/binary_object.hpp>
 #include <boost/serialization/serialization.hpp>
 #include <iostream>
 #include <string>
 #include <iomanip>
 #include <sstream>
 #include <map>
 #include <boost/serialization/map.hpp>

struct values
{
    std::string name;
    std::string sex;
    values():name("dummy"),sex("dummy"){} ;
    template<class archive>
    void serialize(archive & ar,  const unsigned int version)
    {
      ar & name ;
      ar & sex ;
    }
};
class Myclass
{
public:

  Myclass()
  {
    values val1;
    e_group.insert( std::make_pair(1,val1) ) ;
    e_group.insert( std::make_pair(2,val1) ) ;
    p_group.insert( std::make_pair(1,e_group) ) ;
    p_group.insert( std::make_pair(2,e_group) ) ;
  }
  template<class archive>
  void serialize(archive & ar,  const unsigned int version)
  {
    ar & e_group ;
    ar & p_group;
  }
  typedef   std::map<int,values> groups;
  typedef   std::map<int,groups> Pgroups;
  groups  e_group;
  Pgroups p_group;
};

int main() {
    char buf[256];

    Myclass obj;

    std::stringstream os(std::ios_base::binary| std::ios_base::out| std::ios_base::in);
    {
        boost::archive::binary_oarchive oa(os, boost::archive::no_header);
        oa << obj ;
      // oa << make_binary_object(&e_group, sizeof(e_group));
    }

   //print binary data
    std::string data = os.str();
    for (uint8_t ch : data) {
        std::cout << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(ch) << " ";
    }

    Myclass t2;
    {
        memcpy(buf, os.str().data(), os.str().length());
        if(memcmp(buf, os.str().data(), os.str().length()) != 0)
          printf("memcpy error\n");
        std::stringstream is(std::string(buf, buf+os.str().length() ), std::ios_base::binary| std::ios_base::out| std::ios_base::in);
        boost::archive::binary_iarchive ia(is, boost::archive::no_header);
        ia >> t2;
    }

   for(auto &i:t2.p_group){
       std::cout<<"\n"<<i.first<<"\n";
        for(auto &j:i.second){
          std::cout<<"\t"<<j.first<<"\t"<<j.second.name<<"\t"<<j.second.sex<<"\n";
        }
   }
   return 0;
}

Update : i have updated richard's code and added a function to deserilaize the binary

#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/binary_object.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/nvp.hpp>
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
#include <fstream>

#include <map>
#include <boost/serialization/map.hpp>
#include <boost/serialization/split_member.hpp>

struct values
{
    std::string name;
    std::string sex;
    values():name("dummy"),sex("dummy"){} ;

    BOOST_SERIALIZATION_SPLIT_MEMBER();

    template<class Archive>
    void save(Archive & ar, const unsigned int version) const
    {
        // note, version is always the latest when saving
        ar & BOOST_SERIALIZATION_NVP(name);
        ar & BOOST_SERIALIZATION_NVP(sex);
    }
    template<class Archive>
    void load(Archive & ar, const unsigned int version)
    {
        ar & BOOST_SERIALIZATION_NVP(name);
        ar & BOOST_SERIALIZATION_NVP(sex);
    }
};
class Myclass
{
public:

    Myclass()
    {
        values val1;
        e_group.insert( std::make_pair(1,val1) ) ;
        e_group.insert( std::make_pair(2,val1) ) ;
        p_group.insert( std::make_pair(1,e_group) ) ;
        p_group.insert( std::make_pair(2,e_group) ) ;
    }

    BOOST_SERIALIZATION_SPLIT_MEMBER();

    template<class Archive>
    void save(Archive & ar, const unsigned int version) const
    {
        // note, version is always the latest when saving
        ar & BOOST_SERIALIZATION_NVP(e_group);
        ar & BOOST_SERIALIZATION_NVP(p_group);
    }
    template<class Archive>
    void load(Archive & ar, const unsigned int version)
    {
        ar & BOOST_SERIALIZATION_NVP(e_group);
        ar & BOOST_SERIALIZATION_NVP(p_group);
    }

    typedef   std::map<int,values> groups;
    typedef   std::map<int,groups> Pgroups;
    groups  e_group;
    Pgroups p_group;
};

template<class Archive, class Object>
std::string serialise_to_string(Object const& assetlist)
{
    auto os = std::ostringstream(std::ios::binary);
    Archive arch { os, boost::archive::no_header };
    arch << BOOST_SERIALIZATION_NVP(assetlist);
    return os.str();
};

std::ostream& dump(std::ostream& os, std::string const& s)
{
    const char *sep = "";
    for (uint8_t ch : s) {
        std::cout << sep << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(ch);
        sep = " ";
    }
    return os;
}

template<class Archive , class Object>
void deserialise_to_obj(std::string const &s1,Object &outObj)
{
    std::stringstream is( s1, std::ios_base::binary| std::ios_base::out| std::ios_base::in);
    Archive arch { is, boost::archive::no_header };
    arch >> BOOST_SERIALIZATION_NVP(outObj);
};

int main() {

    Myclass obj ;
    std::string  s1 = serialise_to_string<boost::archive::binary_oarchive>(obj);
    dump(std::cout, s1) << std::endl << std::endl;

    auto s2 = serialise_to_string<boost::archive::xml_oarchive>(obj);

   //Save xml to a file
    std::ofstream ofs("output.xml");
    ofs << s2 << std::endl << std::endl;

    //Deserialize the binary data to object
    Myclass outObj;
    deserialise_to_obj<boost::archive::binary_iarchive>(s1,outObj);

    //Print the object
    for(auto &i:outObj.p_group){
       std::cout<<"\n"<<i.first<<"\n";
        for(auto &j:i.second){
          std::cout<<"\t"<<j.first<<"\t"<<j.second.name<<"\t"<<j.second.sex<<"\n";
        }
    }
}

code compiled using coliru

Please suggest . advice me if my approach is wrong

I would want to thank @sehe and @richard helping me with boost.

Thanks
Tejas

Body:
First, don't do this:

    memcpy(buf, os.str().data(), os.str().length());
    if(memcmp(buf, os.str().data(), os.str().length()) != 0)

That's just created 4 separate copies of a string.

Now the questions:

Is void serialize(archive & ar,  const unsigned int version) function used for both serialising and deserialising

Yes

Can we have separate functions for both serialise and deserialise in each class and structs

Yes

Can the same function be utilised for creating xml also , or is it a neat way to have separate serialise and deserialise functionality for xml

Yes

You want the xml_oarchive and the macros BOOST_SERIALIZATION_SPLIT_MEMBER and BOOST_SERIALIZATION_NVP

#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/binary_object.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/nvp.hpp>
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
#include <map>
#include <boost/serialization/map.hpp>
#include <boost/serialization/split_member.hpp>

struct values
{
    std::string name;
    std::string sex;
    values():name("dummy"),sex("dummy"){} ;

    BOOST_SERIALIZATION_SPLIT_MEMBER();

    template<class Archive>
    void save(Archive & ar, const unsigned int version) const
    {
        // note, version is always the latest when saving
        ar & BOOST_SERIALIZATION_NVP(name);
        ar & BOOST_SERIALIZATION_NVP(sex);
    }
    template<class Archive>
    void load(Archive & ar, const unsigned int version)
    {
        ar & BOOST_SERIALIZATION_NVP(name);
        ar & BOOST_SERIALIZATION_NVP(sex);
    }
};
class Myclass
{
public:

    Myclass()
    {
        values val1;
        e_group.insert( std::make_pair(1,val1) ) ;
        e_group.insert( std::make_pair(2,val1) ) ;
        p_group.insert( std::make_pair(1,e_group) ) ;
        p_group.insert( std::make_pair(2,e_group) ) ;
    }

    BOOST_SERIALIZATION_SPLIT_MEMBER();

    template<class Archive>
    void save(Archive & ar, const unsigned int version) const
    {
        // note, version is always the latest when saving
        ar & BOOST_SERIALIZATION_NVP(e_group);
        ar & BOOST_SERIALIZATION_NVP(p_group);
    }
    template<class Archive>
    void load(Archive & ar, const unsigned int version)
    {
        ar & BOOST_SERIALIZATION_NVP(e_group);
        ar & BOOST_SERIALIZATION_NVP(p_group);
    }

    typedef   std::map<int,values> groups;
    typedef   std::map<int,groups> Pgroups;
    groups  e_group;
    Pgroups p_group;
};

template<class Archive, class Object>
std::string serialise_to_string(Object const& o)
{
    auto os = std::ostringstream(std::ios::binary);
    Archive arch { os, boost::archive::no_header };
    arch << BOOST_SERIALIZATION_NVP(o);
    return os.str();
};

std::ostream& dump(std::ostream& os, std::string const& s)
{
    const char *sep = "";
    for (uint8_t ch : s) {
        std::cout << sep << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(ch);
        sep = " ";
    }
    return os;
}

int main() {
    char buf[256];

    Myclass obj;

    auto s1 = serialise_to_string<boost::archive::binary_oarchive>(obj);
    dump(std::cout, s1) << std::endl << std::endl;

    auto s2 = serialise_to_string<boost::archive::xml_oarchive>(obj);
    std::cout<< s2 << std::endl << std::endl;

    return 0;
}

example output:

00 00 00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 00 05 00 00 00 00 00 00 00 64 75 6d 6d 79 05 00 00 00 00 00 00 00 64 75 6d 6d 79 02 00 00 00 05 00 00 00 00 00 00 00 64 75 6d 6d 79 05 00 00 00 00 00 00 00 64 75 6d 6d 79 00 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 05 00 00 00 00 00 00 00 64 75 6d 6d 79 05 00 00 00 00 00 00 00 64 75 6d 6d 79 02 00 00 00 05 00 00 00 00 00 00 00 64 75 6d 6d 79 05 00 00 00 00 00 00 00 64 75 6d 6d 79 02 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 05 00 00 00 00 00 00 00 64 75 6d 6d 79 05 00 00 00 00 00 00 00 64 75 6d 6d 79 02 00 00 00 05 00 00 00 00 00 00 00 64 75 6d 6d 79 05 00 00 00 00 00 00 00 64 75 6d 6d 79

<o class_id="0" tracking_level="0" version="0">
    <e_group class_id="1" tracking_level="0" version="0">
        <count>2</count>
        <item_version>0</item_version>
        <item class_id="2" tracking_level="0" version="0">
            <first>1</first>
            <second class_id="3" tracking_level="0" version="0">
                <name>dummy</name>
                <sex>dummy</sex>
            </second>
        </item>
        <item>
            <first>2</first>
            <second>
                <name>dummy</name>
                <sex>dummy</sex>
            </second>
        </item>
    </e_group>
    <p_group class_id="4" tracking_level="0" version="0">
        <count>2</count>
        <item_version>0</item_version>
        <item class_id="5" tracking_level="0" version="0">
            <first>1</first>
            <second>
                <count>2</count>
                <item_version>0</item_version>
                <item>
                    <first>1</first>
                    <second>
                        <name>dummy</name>
                        <sex>dummy</sex>
                    </second>
                </item>
                <item>
                    <first>2</first>
                    <second>
                        <name>dummy</name>
                        <sex>dummy</sex>
                    </second>
                </item>
            </second>
        </item>
        <item>
            <first>2</first>
            <second>
                <count>2</count>
                <item_version>0</item_version>
                <item>
                    <first>1</first>
                    <second>
                        <name>dummy</name>
                        <sex>dummy</sex>
                    </second>
                </item>
                <item>
                    <first>2</first>
                    <second>
                        <name>dummy</name>
                        <sex>dummy</sex>
                    </second>
                </item>
            </second>
        </item>
    </p_group>
</o>


问:
probability modifiers for Math.random()
I'd like to know what the best or most accepted method of creating probabilities is. I've done some research and found some interesting questions and answers on the Math.random() topic such as:

How random is JavaScript's Math.random?

and

Generating random whole numbers in JavaScript in a specific range?

I'm looking for a simple way to modify the probability that a value will be true or not using Math.random()

For example, I know that Math.floor(Math.random() * 2) is a useful method for generating a 1 nearly 50% of the time:

-Math.random() generates a random number between 0 (inclusive) and 1 (exclusive)

-If the number generated is < 0.5, this number multiplied by 2 will still be less than 1, so this number .floor() returns a 0

-If the number generated is > 0.5, this number multiplied by 2 will be greater than 1, so this number .floor() returns a 1

I wanted to skew the probability of getting a 1 using a "modifier" and this is as close as I have to come to getting the desired probability...

Every time you run the code snippet the console prints the percentage of hits. As you can see they are almost accurate, but not quite. I came up with the exponent modifying function by trial and error. Is there any way I can make this more accurate?

var youHit = Math.floor(Math.random() * 2);
var totalTries = 0;
var hits = 0;

var pointNine = 0.9; // you want 90% of tries to hit
var pointEight = 0.8;// you want 80% of tries to hit
var pointSeven = 0.7;// you want 70% of tries to hit

function probCheck(modifier) {
  var exponent = 1 + (1 - modifier) + (1 - modifier)*10;
  for (var x = 0; x < 100; x++) {
     youHit = Math.floor((Math.pow(modifier, exponent)) + (Math.random() * 2));
     totalTries += 1;
     if (youHit) {
        hits += 1;
     }
  }
  console.log("final probability check: " + hits / totalTries);
};

 probCheck(pointNine);
 probCheck(pointEight);
 probCheck(pointSeven);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

答:
Exponents don’t really make sense here. Stepping back: a uniformly-distributed number on [0, 1) is less than an x in the same range with probability x, so:

```<code>function randomHit(modifier) {
    return Math.random() < modifier;
}
</code>```

Testing:

function randomHit(modifier) {
  return Math.random() < modifier;
}

function probCheck(modifier) {
  var totalTries = 100;
  var hits = 0;

  for (var x = 0; x < totalTries; x++) {
    if (randomHit(modifier)) {
      hits++;
    }
  }

  console.log("final probability check: " + hits / totalTries);
}

probCheck(0.9);
probCheck(0.8);
probCheck(0.7);```

Title: probability modifiers for Math.random()

Body:
Exponents don’t really make sense here. Stepping back: a uniformly-distributed number on [0, 1) is less than an x in the same range with probability x, so:

function randomHit(modifier) {
    return Math.random() < modifier;
}

Testing:

function randomHit(modifier) {
  return Math.random() < modifier;
}

function probCheck(modifier) {
  var totalTries = 100;
  var hits = 0;

  for (var x = 0; x < totalTries; x++) {
    if (randomHit(modifier)) {
      hits++;
    }
  }

  console.log("final probability check: " + hits / totalTries);
}

probCheck(0.9);
probCheck(0.8);
probCheck(0.7);


问:
What's a Good First Open Source Project?
I'm currently studying computer science and looking for a good way to practice and hone my programming skills.  Contributing to an open source project seems like a natural way to do this to me.  I currently know Java, Python, and some C, but wanted to open this up to any established language.

In particular, I'm looking for a project that's fairly active and has a lot of work for less experienced coders.

A better known project such as Firefox might have the advantage of being more recognizable on a resume, but perhaps one could have a larger impact on a smaller project.  Any thoughts on this?

Thanks in advance =) -Matt

答:
I prefer contributing to an open-source project already actove. Depending on what you want you will find games, databases..anything you's think about surely needs your contribution.

My really first contribution was to a game that used opengl ...space stariods i think, it was more like an optimization, or bug fix, i dont really remember.

I've done a plugin for GAIM (now known as Pidgin).. but never get to publish it as it changed name and api structure. It should have display the currently played song in the status-bar..with lots of configure options. Never finished it though.

Another thing was a 'echo' plugin for XMMS, but i found some bugs, it crashed easily and random (during development phase) ..and it was no longer maintained in the moment i've started developing, so left it in the dark also:) This one i liked a lot.. lots of cool and weird sound effects.

They were all cool as they all used different structures, and already established rules for coding, and commenting. Lots of thing to learn like this instead of starting my own project which wouldn't change my programming skills in any way:)

OwnerDisplayName: Misquamaqus


问:
How to select data top x data after y rows from SQL Server
For example I have a table which contains 10'000 rows. I want to select top 100 rows after top 500th row. How can I do this most efficiently.

Query needed for SQL Server 2008

For example i have this query already but i wonder are there any more effective solution

```<code>SELECT TOP 100 xx
FROM nn
WHERE cc NOT IN
   (SELECT TOP 500 cc
      FROM nn ORDER BY cc ASC)
</code>```

答:
```<code>Select T0P 600 *
from my table
where --whatever condition you want
except
select top 500 *
from mytable
where --whatever condition you want
</code>```

Body:
For example I have a table which contains 10'000 rows. I want to select top 100 rows after top 500th row. How can I do this most efficiently.

Query needed for SQL Server 2008

For example i have this query already but i wonder are there any more effective solution

SELECT TOP 100 xx
FROM nn
WHERE cc NOT IN
   (SELECT TOP 500 cc
      FROM nn ORDER BY cc ASC)


问:
How to find Support/Resistance Levels using R
I have not found any good answers on how to go about finding Support/Resistance levels in R. Essentially I would like clusters/areas or pivots where the stock is consolidating, but have found it difficult to do so.

```<code># loads quatmod & xts
library("quantmod")
# Retrive 'ESSI' TICKER OHLCV data
STOCK = getSymbols("ESSI",auto.assign = FALSE)
# last observation carried formward / facilitates NAs
STOCK <- reclass(apply(STOCK,2,na.locf),match.to=STOCK)

# To be used as a rolling window
K=20
# Find MAX for Each Open, High, Low, Close Column & merge them
MAX <- merge.xts(rollmax(Op(STOCK), k=K, na.pad=TRUE),rollmax(Hi(STOCK), k=K, na.pad=TRUE),rollmax(Lo(STOCK), k=K, na.pad=TRUE),rollmax(Cl(STOCK), k=K, na.pad=TRUE))
# Find the mean of each MAX row
MAX <- na.locf(reclass(apply(MAX,1,mean),match.to=MAX))
</code>```

I would do the same for the Low's but I think I would be better off going about using DonchianChannel() but it is not what I want... The output should return something similar to FinViz's :

答: You could apply a swing filter such as TTR's ZigZag function.  Identifying reversals this way seems like a better way to go than Donchian channels and you can define support / resistance as levels where the reversals tend to cluster.

Body:
I have not found any good answers on how to go about finding Support/Resistance levels in R. Essentially I would like clusters/areas or pivots where the stock is consolidating, but have found it difficult to do so.

# loads quatmod & xts
library("quantmod")
# Retrive 'ESSI' TICKER OHLCV data
STOCK = getSymbols("ESSI",auto.assign = FALSE)
# last observation carried formward / facilitates NAs
STOCK <- reclass(apply(STOCK,2,na.locf),match.to=STOCK)

# To be used as a rolling window
K=20
# Find MAX for Each Open, High, Low, Close Column & merge them
MAX <- merge.xts(rollmax(Op(STOCK), k=K, na.pad=TRUE),rollmax(Hi(STOCK), k=K, na.pad=TRUE),rollmax(Lo(STOCK), k=K, na.pad=TRUE),rollmax(Cl(STOCK), k=K, na.pad=TRUE))
# Find the mean of each MAX row
MAX <- na.locf(reclass(apply(MAX,1,mean),match.to=MAX))

I would do the same for the Low's but I think I would be better off going about using DonchianChannel() but it is not what I want... The output should return something similar to FinViz's :


问:
Using Google OAuth 2 on embedded Android-based device
We have an application for embedded Android-based device, it uses WebView and inside it we use Google OAuth 2 to login to the app. Unfortunately Google will soon block OAuth 2 inside WebView, and we have lots of restrictions:

The device doesn't have Google Services installed, so probably no 'official' way of logging in would work (or maybe any of them would work without Google Services?)

We can't just invoke Android browser to do login, because it shows address bar, which would allow the user to surf the internet, which we can't allow

We don't fully control the software installed on the device: can't install Google Services, update Android version, install Google Chrome, etc..., we can just update our app.

What else could we do having those restrictions?

答:
There is a library that supports Android 1.5 and higher for Google OAuth 2:

Sample code found here:

https://github.com/google/google-api-java-client-samples/blob/master/oauth2-cmdline-sample/src/main/java/com/google/api/services/samples/oauth2/cmdline/OAuth2Sample.java


问:
Error connecting to a remote SQL server database Visual Studio 2017
I have an SQL server 2016 instance running on Windows server 2016,
I'm trying to connect to the DB from a remote PC in Visual Studio 2017 Community using the Server Explorer. The connection is successful and I can see the Databases available on the server and login just fine but when I try to expand the tables folder I get this error:

Failed to retrieve data for this request

  Failed to connect to server (local)

  Login Failed for user 'xxxxx'

The thing is I can connect just fine the same way using Visual Studio 2015 Enterprise means I can see the tables and alter them.

I made sure that the user had all the permissions granted on the server,
And to me it doesn't seem to be a permission issue since the connection work just fine in VS 2015.

答: Have you tried saving the Solution/Project and trying again? I've been wrestling with this on a new install of VS 2017 Community and that's what just worked for me. The .rds file wasn't updating until I saved all. After that it let me use the "add table" button again.</p>


问:
sort graph edges in increasing order
I am representing graphs using the standard adjacency list representation where each node is going out as an linked list. You can read more about adjacency list here.

Lets say below is my graph:

```<code>         10
    0--------1
    |  \     |
   6|   5\   |15
    |      \ |
    2--------3
        4
</code>```

Adjacency list would look like as :

```<code>[0,  1,  2,  3]
 |   |   |   |
 10  10  6   6
 |   |   |   |
[1] [0] [0] [2]
 |   |   |   |
 6   15  4   5
 |   |   |   |
[2] [3] [3] [0]
 |   |   |   |
 |   |   |   15
    NULL     |
            [1]
             |
             |
            NULL
</code>```

Since the graph is undirected, edges should be added from source to destination and from destination to source as well along with the weight of the edges. This is how code representation would looks like in that case.

```<code>// Linked list representation
class Adj_Node {
  public:
    int data;
    int weight;
    Adj_Node* next;
};

// Adjacency list representation
class Adj_List {
  public:
    Adj_Node* head;
};

// Graph representation
class Graph {
  public:
    int vertices;
    Adj_List* source;
    Graph(int v) {
      vertices = v;
      source = new Adj_List[vertices];

      for (int i = 0; i < vertices; ++i) {
        source[i].head = NULL;
      }
    }
    void addEdge(int, int, int);
    void printGraph();
};

// Creates an linked list node
Adj_Node* createNode(int d) {
  Adj_Node* tmp = new Adj_Node;
  tmp->data   = d;
  tmp->weight = 0;
  tmp->next   = NULL;

  return tmp;
}

// Adds edge to both src and destination
void Graph::addEdge(int src, int dest, int weight) {
  Adj_Node* node = createNode(dest);
  node->next = source[src].head;
  source[src].head = node;
  node->weight = weight;

  node = createNode(src);
  node->next = source[dest].head;
  source[dest].head = node;
  node->weight = weight;
}

void Graph::printGraph() {
  for(int i = 0; i < vertices; ++i) {
  Adj_Node* n = source[i].head;
  std::cout << i << " = ";
  while(n != NULL) {
    std::cout << n->data << " " << n->weight << ", ";
    n = n->next;
  }
  std::cout << std::endl;
}
</code>```

So, having said all of the above, I have above depiction linked list representation with me where each weighted edge of the graph is depicted as an node in an linked list.
Question is : What are the ways you will suggest to get the edges in increasing order?

答:
If additional space is not a problem, I'd recommend to just create an Edge class with an appropriate operator<, but the edges into a standard container (I'd use std::vector) and sort it using std::sort. It's definitely a better idea than implementing your own sorting algorithm.

By the way, I don't see any reason to use the structure you're using now. If you want to store edges in a list, not in a vector, you can just use std::list (which has a sort member-function) instead of reimplementing it.

Title: sort graph edges in increasing order

Body:
I am representing graphs using the standard adjacency list representation where each node is going out as an linked list. You can read more about adjacency list here.

Lets say below is my graph:

         10
    0--------1
    |  \     |
   6|   5\   |15
    |      \ |
    2--------3
        4

Adjacency list would look like as :

[0,  1,  2,  3]
 |   |   |   |
 10  10  6   6
 |   |   |   |
[1] [0] [0] [2]
 |   |   |   |
 6   15  4   5
 |   |   |   |
[2] [3] [3] [0]
 |   |   |   |
 |   |   |   15
    NULL     |
            [1]
             |
             |
            NULL

Since the graph is undirected, edges should be added from source to destination and from destination to source as well along with the weight of the edges. This is how code representation would looks like in that case.

// Linked list representation
class Adj_Node {
  public:
    int data;
    int weight;
    Adj_Node* next;
};

// Adjacency list representation
class Adj_List {
  public:
    Adj_Node* head;
};

// Graph representation
class Graph {
  public:
    int vertices;
    Adj_List* source;
    Graph(int v) {
      vertices = v;
      source = new Adj_List[vertices];

      for (int i = 0; i < vertices; ++i) {
        source[i].head = NULL;
      }
    }
    void addEdge(int, int, int);
    void printGraph();
};

// Creates an linked list node
Adj_Node* createNode(int d) {
  Adj_Node* tmp = new Adj_Node;
  tmp->data   = d;
  tmp->weight = 0;
  tmp->next   = NULL;

  return tmp;
}

// Adds edge to both src and destination
void Graph::addEdge(int src, int dest, int weight) {
  Adj_Node* node = createNode(dest);
  node->next = source[src].head;
  source[src].head = node;
  node->weight = weight;

  node = createNode(src);
  node->next = source[dest].head;
  source[dest].head = node;
  node->weight = weight;
}

void Graph::printGraph() {
  for(int i = 0; i < vertices; ++i) {
  Adj_Node* n = source[i].head;
  std::cout << i << " = ";
  while(n != NULL) {
    std::cout << n->data << " " << n->weight << ", ";
    n = n->next;
  }
  std::cout << std::endl;
}

So, having said all of the above, I have above depiction linked list representation with me where each weighted edge of the graph is depicted as an node in an linked list.
Question is : What are the ways you will suggest to get the edges in increasing order?


问:
How do I use the value of a column in a csv to determine value of another column in the same csv using bash?
I have a large csv containing database information that I would like to update.

I would like to use the values in the email column (column 1) to determine the value of the segment column (column 4).

For example, if the email contains 'nhs.net' then the segment column should read 'Health - NHS'.

Currently the segment column reads 'Unknown Specialism' and I'm not sure how to overwrite this value using bash based on if the value in another column is true.

Example

zoe.russell@nhs.net, zoe, russell, Unknown Specialism

will become:

zoe.russell@nhs.net, zoe, russell, Health - NHS

I have this so far...(my first bash script, and first q on here)

```<code>#!/bin/bash

echo 'enter the email domain you are searching for in the email field'
read email
echo 'please enter the file you wish to search'
read file
echo 'ok looking for' $email 'in' $file
echo ...
# cat $file | grep -E -i $email

x=$(cat $file | grep -E -i $email | wc -l)
echo 'ok' $x 'email address were found in' $file
echo 'here is a sample of the first 10 lines in the segment column'
cat us.tmp | cut -d ',' -f10 | head -10

echo 'please enter the segment name you want to replace these with'
read new
echo value will be replaced with $new
</code>```

答:
Based on your requirement, you can use below awk -  </p>

```<code>$cat file
zoe.russell@nhs.net, zoe, russell, Unknown Specialism
</code>```

<hr>

```<code>$awk -F, '{if($1 ~ /nhs.net/) {$4=" Health - NHS"}; print $0}' OFS=, f
zoe.russell@nhs.net, zoe, russell, Health - NHS
</code>```

Body:
I have a large csv containing database information that I would like to update.

I would like to use the values in the email column (column 1) to determine the value of the segment column (column 4).

For example, if the email contains 'nhs.net' then the segment column should read 'Health - NHS'.

Currently the segment column reads 'Unknown Specialism' and I'm not sure how to overwrite this value using bash based on if the value in another column is true.

Example

zoe.russell@nhs.net, zoe, russell, Unknown Specialism

will become:

zoe.russell@nhs.net, zoe, russell, Health - NHS

I have this so far...(my first bash script, and first q on here)

#!/bin/bash

echo 'enter the email domain you are searching for in the email field'
read email
echo 'please enter the file you wish to search'
read file
echo 'ok looking for' $email 'in' $file
echo ...
# cat $file | grep -E -i $email

x=$(cat $file | grep -E -i $email | wc -l)
echo 'ok' $x 'email address were found in' $file
echo 'here is a sample of the first 10 lines in the segment column'
cat us.tmp | cut -d ',' -f10 | head -10

echo 'please enter the segment name you want to replace these with'
read new
echo value will be replaced with $new

Body:
Based on your requirement, you can use below awk -

$cat file
zoe.russell@nhs.net, zoe, russell, Unknown Specialism

$awk -F, '{if($1 ~ /nhs.net/) {$4=" Health - NHS"}; print $0}' OFS=, f
zoe.russell@nhs.net, zoe, russell, Health - NHS


问:
Parsing HTML Response in jQuery
My page needs to grab a specific div from another page to display within a div on the current page. It's a perfect job for $.load, except that the HTML source I'm pulling from is not necessarily well-formed, and seems to have occasional tag errors, and IE just plain won't use it in that case. So I've changed it to a $.get to grab the HTML source of the page as a string. Passing it to $ to parse it as a DOM has the same problem in IE as $.load, so I can't do that. I need a way to parse the HTML string to find the contents of my div#information, but not the rest of the page after its
. (PS My div#information contains various other div's and elements.)

EDIT: Also if anyone has a fix for jQuery's $.load not being able to parse response HTML in IE, I'd love to hear that too.

答:
Strictly with strings you could use a regular expression to find the id="information" tag contents. Never parse it as html.

I'd try the $.load parameter that accepts a html selector as well

```<code>$('#results').load('/MySite/Url #Information');
</code>```

Title: Parsing HTML Response in jQuery

Body:
Strictly with strings you could use a regular expression to find the id="information" tag contents. Never parse it as html.

I'd try the $.load parameter that accepts a html selector as well

$('#results').load('/MySite/Url #Information');


问:
Calculate Elapsed time in python in specific format
I am trying to write a program to determine the time and date corresponding to a elapsed number of seconds since 00: 00: 00 on 1 January 2016.

But i wanted my result in specific format.
i.e should be the corresponding hour (in military time), minute, second, day of the month, month name, year, and day of the week name (Sunday – Saturday).
for example,output should look like the following

```<code>23:59:32 2 January 2018 Tuesday
</code>```

i tried to code this

```<code>import time
start = time.time()
#do something
end = time.time()
temp = end-start
print(temp)
hours = temp//3600
temp = temp - 3600*hours
minutes = temp//60
seconds = temp - 60*minutes
print('%d:%d:%d' %(hours,minutes,seconds))
</code>```

But i could only get the hours, minutes and seconds part,
Is there any way i can get the month,year,and week name too ?

Also i'm trying to handle leap years too.since a leap year has 366 days with 29 days in February. Leap years are years that are evenly divisible by 4, with the exception of those evenly divisible by 100 but not 400.

答:
You want to use the Datetime Module. Handling dates and times is trickier than it appears! That's why it's good that Python has datetime handling built-in. Datetime and timedelta objects account for leap years and leap seconds, and they handle operations like addition and subtraction 'intuitively'.

```<code>import datetime
def convert_seconds_since_jan_1(seconds):
    JAN_1_2001 = datetime.datetime(year = 2001, month = 1, day = 1)
    added_time = datetime.timedelta(seconds = seconds)
    return (JAN_1_2001+added_time)
</code>```

Getting the weekday is simply a matter of string formatting. Remember that weekdays are modulo 7!

Body:
I am trying to write a program to determine the time and date corresponding to a elapsed number of seconds since 00: 00: 00 on 1 January 2016.

But i wanted my result in specific format.
i.e should be the corresponding hour (in military time), minute, second, day of the month, month name, year, and day of the week name (Sunday – Saturday).
for example,output should look like the following

23:59:32 2 January 2018 Tuesday

i tried to code this

import time
start = time.time()
#do something
end = time.time()
temp = end-start
print(temp)
hours = temp//3600
temp = temp - 3600*hours
minutes = temp//60
seconds = temp - 60*minutes
print('%d:%d:%d' %(hours,minutes,seconds))

But i could only get the hours, minutes and seconds part,
Is there any way i can get the month,year,and week name too ?

Also i'm trying to handle leap years too.since a leap year has 366 days with 29 days in February. Leap years are years that are evenly divisible by 4, with the exception of those evenly divisible by 100 but not 400.

Body:
You want to use the Datetime Module. Handling dates and times is trickier than it appears! That's why it's good that Python has datetime handling built-in. Datetime and timedelta objects account for leap years and leap seconds, and they handle operations like addition and subtraction 'intuitively'.

import datetime
def convert_seconds_since_jan_1(seconds):
    JAN_1_2001 = datetime.datetime(year = 2001, month = 1, day = 1)
    added_time = datetime.timedelta(seconds = seconds)
    return (JAN_1_2001+added_time)

Getting the weekday is simply a matter of string formatting. Remember that weekdays are modulo 7!


问:
How to configure python nosetests to run print() statements?
While I know that this can be done from the command line nosetests --nocapture test.py

I would like to know if is it possible to add code into test.py so that I can just type nosetests test.py without adding --nosecapture.

答:
You can see the print statements by adding the -s flag to your terminal command. e.g.

```<code>$ nosetests -s test.py
</code>```

-s, --nocapture

Don’t capture stdout (any stdout output will be printed immediately) [NOSE_NOCAPTURE].

Check the official document here

Body:
You can see the print statements by adding the -s flag to your terminal command. e.g.

$ nosetests -s test.py

-s, --nocapture

Don’t capture stdout (any stdout output will be printed immediately) [NOSE_NOCAPTURE].

Check the official document here


问:
Updating a table with different values for different conditions
I have a situation like this:

```<code>update lskinproperty
set frn_lskin_stateid = 2
where frn_lskinid IN (61209, 61208)

update lskinproperty
set frn_lskin_stateid = 3
where frn_lskinid IN (72670, 56916)

update lskinproperty
set frn_lskin_stateid = 4
where frn_lskinid IN (55451)
</code>```

If I run this three queries, it will do what exactly what I want however I feel there it should be a better way to do this. Does SQL Server has anything like case or switch or something similar where you can say for case equal to x do this and for case equal to y do something else and so on?

答:
There probably isn't a real shortcut to doing this type of update. Using case forces you to supply the ids twice: once in the case clause and then again in the where clause. However, in case you have the values to change to in a tabular way, then you could do something like the following:

```<code>update tbl set frn_lskin_stateid=st
from (       select 61209 i,2 st
   union all select 61208,2
   union all select 72670,3
   union all select 56916,3
   union all select 55451,4 ) tvalues
inner join lskinproperty tbl on frn_lskinid=i;
</code>```

In a real application tvalues would most likely be a table with your target values, but, of course, you can also supply the values in a sub-query with several union all lines like shown above.

For a demo see here: http://rextester.com/NDQGL19748

Body:
I have a situation like this:

update lskinproperty
set frn_lskin_stateid = 2
where frn_lskinid IN (61209, 61208)

update lskinproperty
set frn_lskin_stateid = 3
where frn_lskinid IN (72670, 56916)

update lskinproperty
set frn_lskin_stateid = 4
where frn_lskinid IN (55451)

If I run this three queries, it will do what exactly what I want however I feel there it should be a better way to do this. Does SQL Server has anything like case or switch or something similar where you can say for case equal to x do this and for case equal to y do something else and so on?

Body:
There probably isn't a real shortcut to doing this type of update. Using case forces you to supply the ids twice: once in the case clause and then again in the where clause. However, in case you have the values to change to in a tabular way, then you could do something like the following:

update tbl set frn_lskin_stateid=st
from (       select 61209 i,2 st
   union all select 61208,2
   union all select 72670,3
   union all select 56916,3
   union all select 55451,4 ) tvalues
inner join lskinproperty tbl on frn_lskinid=i;

In a real application tvalues would most likely be a table with your target values, but, of course, you can also supply the values in a sub-query with several union all lines like shown above.

For a demo see here: http://rextester.com/NDQGL19748


问:
Bootstrap 3 several toggle buttons
I have three toggle buttons on mobile view. I would like the content of each to appear separately, i.e. when I click on one button, the content of the other closes and is replaced by the clicked button's one. Right now when I click on each button the content of other buttons doesn't go away anywhere, it just appears under each other. Is it possible to switch this somehow?</p>

```<code>  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-navbar-collapse-1">
    <span class="sr-only">Toggle navigation</span>
        Button 1 content
  </button>
  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-navbar-collapse-2">
    <span class="sr-only">Toggle navigation</span>
        Button 2 content
  </button>
  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-navbar-collapse-3">
    <span class="sr-only">Toggle navigation</span>
        Button 3 content
  </button>
  <div class="collapse navbar-collapse" id="bs-navbar-collapse-1">
  Content 1
  </div>
  <div class="collapse navbar-collapse" id="bs-navbar-collapse-2">
  Content 2
  </div>
  <div class="collapse navbar-collapse" id="bs-navbar-collapse-3">
  Content 3
  </div>
</code>```

答:
The data-target for your buttons are currently the same for all three, "#bs-navbar-collapse-1".  You need to make them match the id of the div that you want them to open and close.</p>

```<code>  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-navbar-collapse-1">
      <span class="sr-only">Toggle navigation</span>
    Button 1 content
  </button>
  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-navbar-collapse-2">
      <span class="sr-only">Toggle navigation</span>
    Button 2 content
  </button>
  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-navbar-collapse-3">
      <span class="sr-only">Toggle navigation</span>
    Button 3 content
  </button>
  <div class="collapse navbar-collapse" id="bs-navbar-collapse-1">
      Content 1
  </div>
  <div class="collapse navbar-collapse" id="bs-navbar-collapse-2">
      Content 2
  </div>
  <div class="collapse navbar-collapse" id="bs-navbar-collapse-3">
      Content 3
  </div>
</code>```

Title: Bootstrap 3 several toggle buttons

Body:
I have three toggle buttons on mobile view. I would like the content of each to appear separately, i.e. when I click on one button, the content of the other closes and is replaced by the clicked button's one. Right now when I click on each button the content of other buttons doesn't go away anywhere, it just appears under each other. Is it possible to switch this somehow?

  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-navbar-collapse-1">
    Toggle navigation
        Button 1 content
  </button>
  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-navbar-collapse-2">
    Toggle navigation
        Button 2 content
  </button>
  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-navbar-collapse-3">
    Toggle navigation
        Button 3 content
  </button>

  Content 1

  Content 2

  Content 3

Body:
The data-target for your buttons are currently the same for all three, "#bs-navbar-collapse-1".  You need to make them match the id of the div that you want them to open and close.

  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-navbar-collapse-1">
      <span class="sr-only">Toggle navigation</span>
    Button 1 content
  </button>
  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-navbar-collapse-2">
      <span class="sr-only">Toggle navigation</span>
    Button 2 content
  </button>
  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-navbar-collapse-3">
      <span class="sr-only">Toggle navigation</span>
    Button 3 content
  </button>
  <div class="collapse navbar-collapse" id="bs-navbar-collapse-1">
      Content 1
  </div>
  <div class="collapse navbar-collapse" id="bs-navbar-collapse-2">
      Content 2
  </div>
  <div class="collapse navbar-collapse" id="bs-navbar-collapse-3">
      Content 3
  </div>


问:
simple dynamic allocation question
What is the difference between this:-

```<code>width = new int;
</code>```

And this:-

```<code>int width;
</code>```

i.e. of what use is the dynamic allocation in the first code?

答:
one is allocated on the heap and the other on the stack, one you have to manage and the other is "automatic", one you access via a de-reference the other you don't...

EDIT: with respect to your second question, not much... there are a few cases, but then you'd almost always use a smart pointer, if not, you're playing with fire... :)

Title: simple dynamic allocation question

Body:
What is the difference between this:-

width = new int;

And this:-

int width;

i.e. of what use is the dynamic allocation in the first code?


问:
Using nested time series columns as input into function, return value to nested df
I would like to use ts.union() to create a column in my nested data frame, with the inputs to ts.union() being two nested time series in my nested data frame. See set up below.

```<code>library(tidyverse)
library(forecast)
ts_special <- function(df){ts(df,start = c(2010,01), frequency = 4)}
ets_spec <- function(df){ets(df, mod="MMM", opt.crit="lik", damped=NULL)}
x <- cumsum(rnorm(48))
grp <- rep(c("A","B"), 24)
dtf <- cbind(x, grp) %>% data.frame
dtf <- dtf %>% group_by(grp) %>% nest
dtf <- dtf %>%  mutate(ts = map(data, ts_special))
dtf <- dtf %>%  mutate(ets = map(ts, ets_spec))
dtf <- dtf %>%  mutate(ets_fcast = map(ets, forecast))
dtf <- dtf %>%  mutate(pred= map(dtf$ets_fcast, ~ .x[["mean"]]))

# below works but I want to do this the dplyr way and nest this result in a column in dtf
ts.union(dtf$ts[[1]], dtf$pred[[1]])
</code>```

I'd like to have the result of ts.union for each group's time series and prediction combination stored in a nested column in my data frame, dtf.

答:
You can use purrr::map2 to map over the inputs for ts.union in parallel:

```<code>dtf %>% mutate(union = map2(ts, pred, ts.union))
</code>```

Body:
I would like to use ts.union() to create a column in my nested data frame, with the inputs to ts.union() being two nested time series in my nested data frame. See set up below.

library(tidyverse)
library(forecast)
ts_special <- function(df){ts(df,start = c(2010,01), frequency = 4)}
ets_spec <- function(df){ets(df, mod="MMM", opt.crit="lik", damped=NULL)}
x <- cumsum(rnorm(48))
grp <- rep(c("A","B"), 24)
dtf <- cbind(x, grp) %>% data.frame
dtf <- dtf %>% group_by(grp) %>% nest
dtf <- dtf %>%  mutate(ts = map(data, ts_special))
dtf <- dtf %>%  mutate(ets = map(ts, ets_spec))
dtf <- dtf %>%  mutate(ets_fcast = map(ets, forecast))
dtf <- dtf %>%  mutate(pred= map(dtf$ets_fcast, ~ .x[["mean"]]))

# below works but I want to do this the dplyr way and nest this result in a column in dtf
ts.union(dtf$ts[[1]], dtf$pred[[1]])

I'd like to have the result of ts.union for each group's time series and prediction combination stored in a nested column in my data frame, dtf.

Body:
You can use purrr::map2 to map over the inputs for ts.union in parallel:

dtf %>% mutate(union = map2(ts, pred, ts.union))


问:
Populate Dropdown Select with Props React
So I am trying to populate the dropdown with some info from another table using props. Currently have this. I had to do the loop backwards because earlier it was breaking, </p>

```<code>import React, { Component, PropTypes } from 'react';
import {
  Button,
  ControlLabel,
  FormGroup,
  Form,
  FormControl
} from 'react-bootstrap';

class UserForm extends Component {

  constructor(props) {
    super(props);
  }

  createPosItems() {
    const posItems = [];
    console.log('heyyyy', this.props);
    for (let i = this.props.position.length; i > this.props.position.length; i--) {
      posItems.push(<option key={i} value={this.props.position.i}>{this.props.position.position_name}</option>);
    }
    return posItems;
  }

  createTeamItems() {
    const teamItems = [];
    console.log('whyyyyy', this.props);
    for (let i = this.props.team.length; i > this.props.team.length; i--) {
      teamItems.push(<option key={i} value={this.props.team.i}>{this.props.team.team_name}</option>);
    }
    return teamItems;
  }

  render() {
    return (
      <div className="row">
        <div className="col-lg-12">
          <Form>
            <FormGroup controlId="employeeFirstName">
              <ControlLabel>First Name</ControlLabel>
              <FormControl
                type="text"
                name="firstName"
                required=""
                value={this.props.user.firstName}
                onChange={this.props.onChange}
              />
            </FormGroup>
            <FormGroup controlId="empEmail">
              <ControlLabel>Email</ControlLabel>
              <FormControl
                type="email"
                name="email"
                required=""
                value={this.props.user.email}
                onChange={this.props.onChange}
              />
            </FormGroup>
            <FormGroup controlId="position">
              <ControlLabel>Job Position</ControlLabel>
              <FormControl
                componentClass="select"
              >
                <option value="">Select a Position</option>
                {this.createPosItems()}
              </FormControl>
            </FormGroup>
            <FormGroup controlId="Team">
              <ControlLabel>Team</ControlLabel>
              <FormControl
                componentClass="select"
              >
                <option value="">Select a Team</option>
                {this.createTeamItems()}
              </FormControl>
            </FormGroup>
            <FormGroup>
              <Button
                pullRight
                type="submit"
                className="btn btn-success"
                disabled={this.props.saving}
                onClick={this.props.onSave}
              >Save</Button>

              <Button
                pullRight
                type="submit"
                className="btn btn-danger pull-right"
                // onClick={this.props.onDelete}
              >Delete</Button>
            </FormGroup>
          </Form>
        </div>
      </div>
    );
  }
}

UserForm.propTypes = {
  user: React.PropTypes.object.isRequired,
  team: React.PropTypes.array.isRequired,
  position: React.PropTypes.array.isRequired,
  onSave: React.PropTypes.func.isRequired,
  onChange: React.PropTypes.func.isRequired,
  saving: React.PropTypes.bool
};

export default UserForm;
</code>```

<p>The forms is a child of another page. Every other field works, expect for the drop downs, the element shows up, but doesn't populate the drop down. Have tried using multiple people's examples, and still cannot get it to run.
Thanks in advance! </p>

答:
You just create a variable from props like this:

```<code>const {organizations} = this.props;
</code>```

And the use it to fill the dropdown in a render() method like this:

```<code><DropdownButton title="Organization" className="m-b m-t" id="dropdown-organization">
                    {organizations.map((organization, i) =>
    <MenuItem key={i}>{organization.name}</MenuItem>)}
</DropdownButton>
</code>```

The onClick handlers can be passed down via props the same way.

Body:
So I am trying to populate the dropdown with some info from another table using props. Currently have this. I had to do the loop backwards because earlier it was breaking,

import React, { Component, PropTypes } from 'react';
import {
  Button,
  ControlLabel,
  FormGroup,
  Form,
  FormControl
} from 'react-bootstrap';

class UserForm extends Component {

  constructor(props) {
    super(props);
  }

  createPosItems() {
    const posItems = [];
    console.log('heyyyy', this.props);
    for (let i = this.props.position.length; i > this.props.position.length; i--) {
      posItems.push(<option key={i} value={this.props.position.i}>{this.props.position.position_name}</option>);
    }
    return posItems;
  }

  createTeamItems() {
    const teamItems = [];
    console.log('whyyyyy', this.props);
    for (let i = this.props.team.length; i > this.props.team.length; i--) {
      teamItems.push(<option key={i} value={this.props.team.i}>{this.props.team.team_name}</option>);
    }
    return teamItems;
  }

  render() {
    return (

          <Form>
            <FormGroup controlId="employeeFirstName">
              <ControlLabel>First Name</ControlLabel>
              <FormControl
                type="text"
                name="firstName"
                required=""
                value={this.props.user.firstName}
                onChange={this.props.onChange}
              />
            </FormGroup>
            <FormGroup controlId="empEmail">
              <ControlLabel>Email</ControlLabel>
              <FormControl
                type="email"
                name="email"
                required=""
                value={this.props.user.email}
                onChange={this.props.onChange}
              />
            </FormGroup>
            <FormGroup controlId="position">
              <ControlLabel>Job Position</ControlLabel>
              <FormControl
                componentClass="select"
              >
                <option value="">Select a Position</option>
                {this.createPosItems()}
              </FormControl>
            </FormGroup>
            <FormGroup controlId="Team">
              <ControlLabel>Team</ControlLabel>
              <FormControl
                componentClass="select"
              >
                <option value="">Select a Team</option>
                {this.createTeamItems()}
              </FormControl>
            </FormGroup>
            <FormGroup>
              <Button
                pullRight
                type="submit"
                className="btn btn-success"
                disabled={this.props.saving}
                onClick={this.props.onSave}
              >Save</Button>

              <Button
                pullRight
                type="submit"
                className="btn btn-danger pull-right"
                // onClick={this.props.onDelete}
              >Delete</Button>
            </FormGroup>
          </Form>

    );
  }
}

UserForm.propTypes = {
  user: React.PropTypes.object.isRequired,
  team: React.PropTypes.array.isRequired,
  position: React.PropTypes.array.isRequired,
  onSave: React.PropTypes.func.isRequired,
  onChange: React.PropTypes.func.isRequired,
  saving: React.PropTypes.bool
};

export default UserForm;

The forms is a child of another page. Every other field works, expect for the drop downs, the element shows up, but doesn't populate the drop down. Have tried using multiple people's examples, and still cannot get it to run.
Thanks in advance!

Body:
You just create a variable from props like this:

const {organizations} = this.props;

And the use it to fill the dropdown in a render() method like this:

<DropdownButton title="Organization" className="m-b m-t" id="dropdown-organization">
                    {organizations.map((organization, i) =>
    <MenuItem key={i}>{organization.name}</MenuItem>)}
</DropdownButton>

The onClick handlers can be passed down via props the same way.


问:
Javascript filter deep array in array while maintaining original array
I'm wanting to filter an array without changing the original array that I've sliced from. You can see that the first thing I do within the filterChange function is to splice from the original array. The original array still ends up changed as well and I don't understand why.</p>

```<code>var MenuDisplayModule = (function ($, window, document, Handlebars) {

    var module = {};
    module.menuItems = [];
    module.init = function () {
        console.info('BreadcrumbDisplayModule Init');

    };
    module.template = function (array) {
        module.menuItems = array;
        var filteredMenuItems = array.slice(0);
        _template(filteredMenuItems);
    }
    module.filterChange = function (filterText) {

        var filteredMenuItems = module.menuItems.slice(0);

        filteredMenuItems.forEach(function (item, index) {
            var filteredItems = item.MenuItems.filter(function (el) {
                return (el.MenuText.includes(filterText));
            });
            filteredMenuItems[index].MenuItems = filteredItems;
        })
        _template(filteredMenuItems);
    }
    function _template(filteredMenuItems) {
        var menu_items_source = $("#menu-items-template").html();
        var menu_items_template = Handlebars.compile(menu_items_source);
        $("#menu-items-placeholder").empty().html(menu_items_template({ menuItems: filteredMenuItems }));
    }
    return module;
}(window.jQuery, window, document, window.Handlebars));
</code>```

答:
So it appears I didn't understand splice. Specifically the shallow aspect of it. Since I was wanting to filter on a sub array of the array I was trying to copy I ended up not getting an actual copy.

Instead of copying the array I'm creating a new array and pushing the results of the filter to it. Taking with it the un-filtered properties from the original array.

```<code>module.filterChange = function (filterText) {
    var filteredMenuItems = [];
    module.menuItems.forEach(function (item, index) {
        var filteredItems = item.MenuItems.filter(function (el) {
            return (el.MenuText.includes(filterText));
        });
        filteredMenuItems.push({
            HeaderText: item.HeaderText,
            ID: item.ID,
            MenuItems: filteredItems
        })
    })
    _templateOnChange(filteredMenuItems);
}
</code>```

Body:
I'm wanting to filter an array without changing the original array that I've sliced from. You can see that the first thing I do within the filterChange function is to splice from the original array. The original array still ends up changed as well and I don't understand why.

var MenuDisplayModule = (function ($, window, document, Handlebars) {

    var module = {};
    module.menuItems = [];
    module.init = function () {
        console.info('BreadcrumbDisplayModule Init');

    };
    module.template = function (array) {
        module.menuItems = array;
        var filteredMenuItems = array.slice(0);
        _template(filteredMenuItems);
    }
    module.filterChange = function (filterText) {

        var filteredMenuItems = module.menuItems.slice(0);

        filteredMenuItems.forEach(function (item, index) {
            var filteredItems = item.MenuItems.filter(function (el) {
                return (el.MenuText.includes(filterText));
            });
            filteredMenuItems[index].MenuItems = filteredItems;
        })
        _template(filteredMenuItems);
    }
    function _template(filteredMenuItems) {
        var menu_items_source = $("#menu-items-template").html();
        var menu_items_template = Handlebars.compile(menu_items_source);
        $("#menu-items-placeholder").empty().html(menu_items_template({ menuItems: filteredMenuItems }));
    }
    return module;
}(window.jQuery, window, document, window.Handlebars));

Body:
So it appears I didn't understand splice. Specifically the shallow aspect of it. Since I was wanting to filter on a sub array of the array I was trying to copy I ended up not getting an actual copy.

Instead of copying the array I'm creating a new array and pushing the results of the filter to it. Taking with it the un-filtered properties from the original array.

module.filterChange = function (filterText) {
    var filteredMenuItems = [];
    module.menuItems.forEach(function (item, index) {
        var filteredItems = item.MenuItems.filter(function (el) {
            return (el.MenuText.includes(filterText));
        });
        filteredMenuItems.push({
            HeaderText: item.HeaderText,
            ID: item.ID,
            MenuItems: filteredItems
        })
    })
    _templateOnChange(filteredMenuItems);
}


问:
How to get current day in another language than your locale?
I want to get the name of the current day in english, but my locale is Danish, so NSDate() is returning the current day in danish.. How can I get it in english? :-)

Right now im using this code to get the name of the day:

```<code>func dayOfTheWeek() -> String? {
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "EEEE"
    return dateFormatter.stringFromDate(self)
}
</code>```

I've tried looking at the documentations for NSDate, but couldn't really find anything that worked.

I've also looked at Calendar, but still no luck. I guess it is possible - so if anyone knows how, please let me know :-)

答:
You just need to set the formatter's locale:

```<code>func dayOfTheWeek() -> String? {
    let dateFormatter = NSDateFormatter()
    dateFormatter.locale = NSLocale(localeIdentifier: "en_US") // or "en_GB"
    dateFormatter.dateFormat = "EEEE"
    return dateFormatter.stringFromDate(self)
}
</code>```

You seem to be using Swift 2 and I based the NSLocale initializer on Swift 3. Adjust if needed.

Body:
I want to get the name of the current day in english, but my locale is Danish, so NSDate() is returning the current day in danish.. How can I get it in english? :-)

Right now im using this code to get the name of the day:

func dayOfTheWeek() -> String? {
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "EEEE"
    return dateFormatter.stringFromDate(self)
}

I've tried looking at the documentations for NSDate, but couldn't really find anything that worked.

I've also looked at Calendar, but still no luck. I guess it is possible - so if anyone knows how, please let me know :-)

Body:
You just need to set the formatter's locale:

func dayOfTheWeek() -> String? {
    let dateFormatter = NSDateFormatter()
    dateFormatter.locale = NSLocale(localeIdentifier: "en_US") // or "en_GB"
    dateFormatter.dateFormat = "EEEE"
    return dateFormatter.stringFromDate(self)
}

You seem to be using Swift 2 and I based the NSLocale initializer on Swift 3. Adjust if needed.


问:
Define a big array of integers in C
I am trying to define an array of N = 1000000000 integers on the heap. My code is the following:

```<code>#define N 1000000000
int A[N];
</code>```

But I am getting the following error when I try to compile my code:

This works for smaller numbers so why isn't it working now?

EDIT: After suggestions, I have defined A like this:

```<code>int *A = malloc(4000000000ULL);
</code>```

I am now getting the error: Initializer element is not constant. It should also be noted that this is a global array.

答: Assuming an int is 32 bits, you're trying to allocate 4GB of space.  And you're not allocating it on the heap.  You need to call malloc to do that.  If this variable is declared in a function, this space it getting allocated on the stack.  That's way too big.

Title: Define a big array of integers in C

Body:
I am trying to define an array of N = 1000000000 integers on the heap. My code is the following:

#define N 1000000000
int A[N];

But I am getting the following error when I try to compile my code:

This works for smaller numbers so why isn't it working now?

EDIT: After suggestions, I have defined A like this:

int *A = malloc(4000000000ULL);

I am now getting the error: Initializer element is not constant. It should also be noted that this is a global array.