问:
convert string to date object give sunday web, GMT 00+ time i need in date formate dd/mm/yyyy
I am converting string to date object i have string like
2017/3/30. when i parse into date object it gives
 sunday web, GMT 03 00:00:00 GMT+05:00 2019
Code is </p>

```<code> String dob = "2017/3/30";
     SimpleDateFormat format = new SimpleDateFormat("yyyy/dd/MM");
            try {
                startDate = format.parse(dob);
                endDate = format.parse(formattedDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
</code>```

<p>I need same formate in date object not string . </p>

答:
Stop using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

For a date-only value, parse as LocalDate.

```<code>String input =  "2017/3/30";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu/m/d" );
LocalDate ld = LocalDate.parse( input , f );
</code>```

To assign the first moment of the day, specify a time zone.

```<code>ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z );
</code>```

To generate strings representing these values use DateTimeFormatter. This has been covered hundreds of times already. So search Stack Overflow for more examples and more discussions.

```<code>String output = ld.format( f );
</code>```

Body:
I am converting string to date object i have string like
2017/3/30. when i parse into date object it gives
 sunday web, GMT 03 00:00:00 GMT+05:00 2019
Code is

 String dob = "2017/3/30";
     SimpleDateFormat format = new SimpleDateFormat("yyyy/dd/MM");
            try {
                startDate = format.parse(dob);
                endDate = format.parse(formattedDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }

I need same formate in date object not string .

Body:
Stop using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

For a date-only value, parse as LocalDate.

String input =  "2017/3/30";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu/m/d" );
LocalDate ld = LocalDate.parse( input , f );

To assign the first moment of the day, specify a time zone.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z );

To generate strings representing these values use DateTimeFormatter. This has been covered hundreds of times already. So search Stack Overflow for more examples and more discussions.

String output = ld.format( f );


来源: stackexchange

问:
uncheck parent node when children node is not all checked
I am newbie extJs user. I have using tree panel with checkbox and i want to uncheck the parent node when the children node is not all checked. below is my code, hope you can help me guys, i dont know what to do here.

the structure of my treepanel is something like this:

parentnode1

sub-parentNode1.1

child1.1

child1.2

child1.3

subparentNode1.2

child2.1

child2.2

parentnode2

subparentNode2.1

child2.1.1

```<code>var treeCheck = new Ext.tree.TreePanel({
    //some code here
});

//event here

treeCheck.on('checkchange', function(node, checked) {
    if(node.hasChildNodes()==true) {

        node.eachChild(function(n) {
            n.getUI().toggleCheck(checked);
        });

    } else {

        if(!checked) {
            var _parentNode = node.parentNode;
            //i dont know what to do here...
            //specifically, i want to uncheck the parent node and subparent node
            //when the children/child node is unchecked
        }
    }
});
</code>```

答:
Just for completeness, for this kind of recursion, ExtJS 3.4 has respectively Ext.tree.Node methods cascade and bubble.

```<code>        listeners: {
        'checkchange': function(node, checked){

                var checkChange = function(currentNode, flag) {
                    try{
                        currentNode.attributes.checked  = flag;
                        currentNode.ui.checkbox.checked = flag;
                    }
                    catch(e){
                        // just avoiding error when node has no such attribute
                    }
                };

                /**
                 * Cascades down the tree from this node propagating the 'checkChange' event.
                 */
                 node.cascade(function() {
                    if(this.expanded === false){
                        this.expand(true);
                    }

                    checkChange(this, checked);

                    return true;
                });

                /**
                 * Bubbles up the tree from this node changing parent's state depending on children.
                 */
                node.bubble(function() {
                    if(this.hasChildNodes()){

                        var checkedCount = 0;

                        this.eachChild(function(child) {
                            checkedCount += (child.attributes.checked ? 1 : 0);
                        });

                        var checkedValue = (checkedCount == this.childNodes.length) && checkedCount !== 0;

                        checkChange(this, checkedValue);
                    }
                });
         }
     },
</code>```

A completely functional fiddle can be found here.

Obs: logic for bubble was borrowed from ag0rex

ContentLicense: CC BY-SA 3.0

Body:
I am newbie extJs user. I have using tree panel with checkbox and i want to uncheck the parent node when the children node is not all checked. below is my code, hope you can help me guys, i dont know what to do here.

the structure of my treepanel is something like this:

parentnode1

sub-parentNode1.1

child1.1

child1.2

child1.3

subparentNode1.2

child2.1

child2.2

parentnode2

subparentNode2.1

child2.1.1

var treeCheck = new Ext.tree.TreePanel({
    //some code here
});

//event here

treeCheck.on('checkchange', function(node, checked) {
    if(node.hasChildNodes()==true) {

        node.eachChild(function(n) {
            n.getUI().toggleCheck(checked);
        });

    } else {

        if(!checked) {
            var _parentNode = node.parentNode;
            //i dont know what to do here...
            //specifically, i want to uncheck the parent node and subparent node
            //when the children/child node is unchecked
        }
    }
});

Body:
Just for completeness, for this kind of recursion, ExtJS 3.4 has respectively Ext.tree.Node methods cascade and bubble.

        listeners: {
        'checkchange': function(node, checked){

                var checkChange = function(currentNode, flag) {
                    try{
                        currentNode.attributes.checked  = flag;
                        currentNode.ui.checkbox.checked = flag;
                    }
                    catch(e){
                        // just avoiding error when node has no such attribute
                    }
                };

                /**
                 * Cascades down the tree from this node propagating the 'checkChange' event.
                 */
                 node.cascade(function() {
                    if(this.expanded === false){
                        this.expand(true);
                    }

                    checkChange(this, checked);

                    return true;
                });

                /**
                 * Bubbles up the tree from this node changing parent's state depending on children.
                 */
                node.bubble(function() {
                    if(this.hasChildNodes()){

                        var checkedCount = 0;

                        this.eachChild(function(child) {
                            checkedCount += (child.attributes.checked ? 1 : 0);
                        });

                        var checkedValue = (checkedCount == this.childNodes.length) && checkedCount !== 0;

                        checkChange(this, checkedValue);
                    }
                });
         }
     },

A completely functional fiddle can be found here.

Obs: logic for bubble was borrowed from ag0rex


问:
Big o with recursion python
```<code>def maxnum(l):
    if len(l)==1:
       return l[0]
    else:
        largest=maxnum(l[1:])
        if l[0]>largest:
            return l[0]
        else:
            return largest
</code>```

I wonder the big O notation for this recursion(is that n-1?). Thanks!

答:
The recurrence relation for the sample code is

T(n)=T(n-1)+c

When you solve this relation as

```<code> T(n)=T(n-1)+c
     =(T(n-2)+c)+c
     =((T(n-3)+c)+c)+c
      .
      .
      .
     =T(1)+n*c
     =n*c
</code>```

Therefore time complexity is TC=O(n*c)
 that is equal to O(n)

Title: Big o with recursion python

Body:
def maxnum(l):
    if len(l)==1:
       return l[0]
    else:
        largest=maxnum(l[1:])
        if l[0]>largest:
            return l[0]
        else:
            return largest

I wonder the big O notation for this recursion(is that n-1?). Thanks!

Body:
The recurrence relation for the sample code is

T(n)=T(n-1)+c

When you solve this relation as

 T(n)=T(n-1)+c
     =(T(n-2)+c)+c
     =((T(n-3)+c)+c)+c
      .
      .
      .
     =T(1)+n*c
     =n*c

Therefore time complexity is TC=O(n*c)
 that is equal to O(n)


问:
Laravel - Unable to override the create method for a model
When overriding the base Laravel model create method, the application fails. No errors are sent back to the browser, and the server logs are empty. The strange thing, it works just fine without the override. Not sure what I'm doing wrong.

Simplified controller function:

```<code>public function save(Request $request, $id = 0) {
    $myModel = MyModel::find($id);
    $data = $request->all();

    if (!$myModel) // Create a new row
    {
        $myModel = MyModel::create($data);
    }

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

This works fine until I add this function to the model:

```<code>class MyModel extends Model
{
    // ...

    public static function create($attributes = [])
    {
        return parent::create($attributes);
    }

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

Just to clarify, I'm not looking for a different way to implement this. I just need to know why the parent call is failing for me.

Here's some server info...

Server OS: Windows 7 (personal PC with XAMPP)

Laravel version 5.4.15

PHP version 5.6.30

答:
About errors, you should make sure you have enabled log_errors on your server. About the error, when you extend class and want to override method, it should have same signature, so it should be:

```<code>public static function create(array $attributes = [])
{
    // Your custom code goes here

    return parent::create($attributes);
}
</code>```

(notice array type hinting). Obviously I assume you are going to add something more in this function :)

Body:
When overriding the base Laravel model create method, the application fails. No errors are sent back to the browser, and the server logs are empty. The strange thing, it works just fine without the override. Not sure what I'm doing wrong.

Simplified controller function:

public function save(Request $request, $id = 0) {
    $myModel = MyModel::find($id);
    $data = $request->all();

    if (!$myModel) // Create a new row
    {
        $myModel = MyModel::create($data);
    }

    // ...
}

This works fine until I add this function to the model:

class MyModel extends Model
{
    // ...

    public static function create($attributes = [])
    {
        return parent::create($attributes);
    }

    // ...
}

Just to clarify, I'm not looking for a different way to implement this. I just need to know why the parent call is failing for me.

Here's some server info...

Server OS: Windows 7 (personal PC with XAMPP)

Laravel version 5.4.15

PHP version 5.6.30

Body:
About errors, you should make sure you have enabled log_errors on your server. About the error, when you extend class and want to override method, it should have same signature, so it should be:

public static function create(array $attributes = [])
{
    // Your custom code goes here

    return parent::create($attributes);
}

(notice array type hinting). Obviously I assume you are going to add something more in this function :)

ContentLicense: CC BY-SA 4.0


问:
ExtJs: how to disable fieldset on button click event
I have a fieldset defined on my page. Now I want to enable or disable this field set on button click event. But it is not working properly. Below is the code I have written:

To Disable:

```<code>this.mySettings.query('[name="fieldsetName"]').forEach(function (field) {
    field.disable();
});
</code>```

To Enable:

```<code>this.mySettings.query('[name="fieldsetName"]').forEach(function (field) {
    field.enable();
});
</code>```

Issue-1 : When I disable fieldset, it seems to be disabled visually. But still I can access controls inside it.

Issue-2 : Once it is disabled, I cannot re-enable it.

I need a working sample with these two issues resolved.

Currently I am using version 4.2 of ExtJs

答:
You should call the setDisabled function on the fieldset. It will disable all containing components.

```<code>fieldset.setDisabled(true);
// the fieldset and all inner components are disabled

fieldset.setDisabled(false);
// the fieldset and all inner components are enabled
</code>```

See the Sencha ExtJs 4.2.0 documentation and
the following minimal working example can be found on Sencha Fiddle.

```<code>Ext.create('Ext.panel.Panel',{
    items: [{
        xtype: 'fieldset',
        itemId: 'fieldsetId',
        items: [{
                    xtype: 'checkbox',
                    fieldLabel: 'Check 1'
                },{
                    xtype: 'checkbox',
                    fieldLabel: 'Check 2'
                },{
                    fieldLabel: 'Combo 1',
                    xtype: 'combobox',
                    store: ['value1','value2','value3']
                }]
    }, {
        xtype: 'button',
        text: 'Disable fieldset',
        handler: function (button) {
            var fieldset = Ext.ComponentQuery.query('panel > #fieldsetId')[0];
            var toggle = !fieldset.isDisabled();
            var text = (toggle ? 'Enable' : 'Disable') + ' fieldset';
            fieldset.setDisabled(toggle);
            button.setText(text);
        }
    }],
    renderTo: Ext.getBody()
});
</code>```

Body:
I have a fieldset defined on my page. Now I want to enable or disable this field set on button click event. But it is not working properly. Below is the code I have written:

To Disable:

this.mySettings.query('[name="fieldsetName"]').forEach(function (field) {
    field.disable();
});

To Enable:

this.mySettings.query('[name="fieldsetName"]').forEach(function (field) {
    field.enable();
});

Issue-1 : When I disable fieldset, it seems to be disabled visually. But still I can access controls inside it.

Issue-2 : Once it is disabled, I cannot re-enable it.

I need a working sample with these two issues resolved.

Currently I am using version 4.2 of ExtJs

Body:
You should call the setDisabled function on the fieldset. It will disable all containing components.

fieldset.setDisabled(true);
// the fieldset and all inner components are disabled

fieldset.setDisabled(false);
// the fieldset and all inner components are enabled

See the Sencha ExtJs 4.2.0 documentation and
the following minimal working example can be found on Sencha Fiddle.

Ext.create('Ext.panel.Panel',{
    items: [{
        xtype: 'fieldset',
        itemId: 'fieldsetId',
        items: [{
                    xtype: 'checkbox',
                    fieldLabel: 'Check 1'
                },{
                    xtype: 'checkbox',
                    fieldLabel: 'Check 2'
                },{
                    fieldLabel: 'Combo 1',
                    xtype: 'combobox',
                    store: ['value1','value2','value3']
                }]
    }, {
        xtype: 'button',
        text: 'Disable fieldset',
        handler: function (button) {
            var fieldset = Ext.ComponentQuery.query('panel > #fieldsetId')[0];
            var toggle = !fieldset.isDisabled();
            var text = (toggle ? 'Enable' : 'Disable') + ' fieldset';
            fieldset.setDisabled(toggle);
            button.setText(text);
        }
    }],
    renderTo: Ext.getBody()
});


问:
How to push data to a running Windows Service
My question is, is there a good way to push an integer value to a running windows service without restarting it and without writing to disk or having it poll some database?

Here's my scenario and a few thoughts:
I need to pass data to a windows service in real time I DO NOT want there to be a delay.  All I need to give it is in integer and it can do the rest.  My predecessor had it set up to poll a database every 10 min but that is no longer an option.  I need the response time to be less than a second.  I suppose technically I could just reduce the poll time to 0.5 sec but I'm thinking that would be bad for the database server.  I know you can pass data to a windows service when it starts but restarting this service isn't an option because of what it's doing.

I would love to use a web service and just call a web method to pass in the data but the tasks require elevated (admin) permissions and almost everything involves file system access so my understanding is that a web service isn't really the best option either.

I've thought of using a hybrid scenario where I run a web service and a windows service on the same machine but then I still have the problem of how to pass the integer from the web service to the windows service... I could technically use a file system watcher but I really don't want to create a file just to pass an integer.  I thought maybe I could use localDb and have the web service just write the value there and have the windows service poll localDb every 0.5 sec, But I'm not sure how much that polling would affect overall performance of other things.  I really want a way to push data to the windows service rather than having the service poll somewhere else.

答:
The project I work on has a front-end UI that communicates with a Windows Service running on the same system.  In the past, I used the Windows Communication Foundation (WCF), but found this to be heavy-weight for what I really needed.  I am now using a TCP socket over the localhost address (127.0.0.1) to exchange data between the UI and the service.

Based on your description, the web service approach seems heavy-weight, kinda like the WCF approach we used to use.  And, as you've noted, it has permissions issues.  A simple application that pushes the integer to your service over a socket would be straightforward in my mind.

If WCF is of interest, here's a couple links that might help:

Creating a user interface for monitoring and interacting with a running windows service

GUI and windows service communication


问:
Extract a dplyr tbl column as a vector
Is there a more succinct way to get one column of a dplyr tbl as a vector, from a tbl with database back-end (i.e. the data frame/table can't be subset directly)?

```<code>require(dplyr)
db <- src_sqlite(tempfile(), create = TRUE)
iris2 <- copy_to(db, iris)
iris2$Species
# NULL
</code>```

That would have been too easy, so

```<code>collect(select(iris2, Species))[, 1]
# [1] "setosa"     "setosa"     "setosa"     "setosa"  etc.
</code>```

But it seems a bit clumsy.

答:
@Luke1018 proposed this solution in one of the comments:

You can also use the magrittr exposition operator (%$%) to pull a vector from a data frame.

For example:

```<code>iris2 %>% select(Species) %>% collect() %$% Species
</code>```

I thought it deserved its own answer.

Title: Extract a dplyr tbl column as a vector

Body:
Is there a more succinct way to get one column of a dplyr tbl as a vector, from a tbl with database back-end (i.e. the data frame/table can't be subset directly)?

require(dplyr)
db <- src_sqlite(tempfile(), create = TRUE)
iris2 <- copy_to(db, iris)
iris2$Species
# NULL

That would have been too easy, so

collect(select(iris2, Species))[, 1]
# [1] "setosa"     "setosa"     "setosa"     "setosa"  etc.

But it seems a bit clumsy.

Body:
@Luke1018 proposed this solution in one of the comments:

You can also use the magrittr exposition operator (%$%) to pull a vector from a data frame.

For example:

iris2 %>% select(Species) %>% collect() %$% Species

I thought it deserved its own answer.


问:
HTML Email Styling Issue
I have the current HTML email template to go out automagically to end user.

But the email that arrives seems to be formatted incorrectly..

Here is HTML code I have:

You've been sent a job opportunity

%EMAIL_YOUR_EMAIL% thought you might be interested the following role, currently being advertised on #

%EMAIL_POST_TITLE% advertised by %EMAIL_POST_AUTHOR%

%EMAIL_POST_CONTENT%

© %EMAIL_BLOG_NAME%, 2017

```

Which should include a grey background behind the email. But when recipient receives the email it doesn't include the grey background.. o_O

Here is an image showing the issue I'm facing

Does anyone have any ideas / can help? :)

答: I have created some newsletter, I recommend you to use Foundation framework to email template so you can create code cross email clients, also you can test you template in different clients and resolution with Litmus</p>

Title: HTML Email Styling Issue

Body:
I have the current HTML email template to go out automagically to end user.

But the email that arrives seems to be formatted incorrectly..

Here is HTML code I have:

You've been sent a job opportunity

%EMAIL_YOUR_EMAIL% thought you might be interested the following role, currently being advertised on #

%EMAIL_POST_TITLE% advertised by %EMAIL_POST_AUTHOR%

%EMAIL_POST_CONTENT%

© %EMAIL_BLOG_NAME%, 2017

Which should include a grey background behind the email. But when recipient receives the email it doesn't include the grey background.. o_O

Here is an image showing the issue I'm facing

Does anyone have any ideas / can help? :)


问:
Proper placement of q.all inside array.map with _.forEach
I have the following code which searches my mongodb using find() using values extracted using array.map. Said search returns an object, which I then used a _.forEach to extract the values.

I used this article as basis, however the difference between his examples and mine was he used only one loop. I'm using two. In this case, where should I put my q.all()?

Here's my code. Please note that is server-side:

```<code>'use strict';
var q = require('q');

exports.downloadEmployee = function (req, res) {
    var tempCtr = [];

    if (req.params.hasdr === "yes") {
        return queries.generateDirectReportsCSV(req.params.id).then(function (directReports) {
            return directReports;
        }).then(function (directReports) {
            var empIDcoll = _.pluck(directReports.Data, "employeenumber");
            return empIDcoll;
        }).then(function (empIDcoll) {
            var promises = [];

            empIDcoll.map(function (id) {

                return EmployeeInfo.find({ employeeID: id }, function (err, results) {
                    if (err) { return err; }

                    _.forEach(results, function (item) {
                        if (item) {
                            tempCtr.push({
                                employeeID: item.employeeID,
                                employeeName: item.employeeName
                            });
                            promises.push(tempCtr);
                        }
                    });
                });

                q.all(promises).then(function (results) {
                    return res.json(results);
                });
            });
        });
    }
</code>```

When I run this, I don't get any result back.

Any answers will be greatly appreciated.

Thank you.

UPDATE: I've decided to revise my code and replaced array.map with the usual for loop:

```<code>.then(function (empIDcoll) {

    for (var i = 0; i <= empIDcoll.length - 1; i++) {
        var promise = EmployeeInfo.find({ employeeID: empIDcoll[i] }, function (err, results) {
            if (err) { return err; }

            _.forEach(results, function (item) {
                if (item) {
                    tempCtr.push({
                        employeeID: item.employeeID,
                        employeeName: item.employeeName,
                        currentShift: item.currentShift,
                        isOpenToIntlAssignment: item.isOpenToIntlAssignment,
                        desiredRole1: item.desiredRole1,
                        desiredRole2: item.desiredRole2,
                        desiredRole3: item.desiredRole3,
                        desiredRoleOther: item.desiredRoleOther,
                        passportInfo: item.passportInfo,
                        visaInfo: item.visaInfo,
                        yrsInIT: item.yrsInIT,
                        yrsAsCustomerPM: item.yrsAsCustomerPM,
                        yrsAsCustomerProgM: item.yrsAsCustomerProgM,
                        primaryDomain: item.primaryDomain,
                        primaryDomainOther: item.primaryDomainOther,
                        primaryIndustry: item.primaryIndustry,
                        primaryIndustryOther: item.primaryIndustryOther,
                        isPMPCertified: item.isPMPCertified,
                        pmpCertExpiryDate: item.pmpCertExpiryDate,
                        isPGMPCertified: item.isPGMPCertified,
                        pgmpCertExpiryDate: item.pgmpCertExpiryDate,
                        isScrumCertified: item.isScrumCertified,
                        scrumCertExpiryDate: item.scrumCertExpiryDate,
                        biggestProjectTCV: item.biggestProjectTCV,
                        biggestTeamSizeManaged: item.biggestTeamSizeManaged,
                        avgTeamSizeManaged: item.avgTeamSizeManaged,
                        biggestBilledFTE: item.biggestBilledFTE,
                        avgBilledFTE: item.avgBilledFTE
                    });
                }
            });
        });
        promises.push(promise);
    }

    return q.all(promises).then(function(data){
        return res.json(data);
    });

});
</code>```

...but it's still not returning anything. What am I doing wrong?

答:
My first suggestion would be to stop looping through the employeeId in the first place.
you can use mongoDB's $in operator like this

```<code>EmployeeInfo.find({ employeeID: {$in: empIDcoll} }, function (err, results) {
     if(err) {
       //handle error
       return err;
     }

     res.json(results);
});
</code>```

But as I dont know about your application I really can't judge maybe you want to loop through empIdColl.

Looping through the empIdColl

Now I'm not sure that your monogdb query will return promise or not so to be on safer side I'll assume that it doesn't

```<code>var promises = empIDcoll.map(function (id) {
    var singleDefer = q.defer(); //create a deferred object which has promise in it

    EmployeeInfo.find({ employeeID: id }, function(err, results) {
         if(err) {
             return singleDefer.reject(err);
         }

         return singleDefer.resolve(results); //resolve whole array
    });

    return singleDefer.promise;
});

q.all(promises)
.then(function (arrayOfResults) {
    var responseData = [];

    arrayOfResuls.forEach(function(results) {
          results.forEach(function(individualResult) {
              if(individualResult) {
                   responseData.push({
                       employeeID: item.employeeID,
                       ...
                       ...
                       avgBilledFTE: item.avgBilledFTE
                   });
              }
          });
    });

    return res.json(responseData);
})
.catch(function(err) {
    //handle error
});
</code>```

Body:
I have the following code which searches my mongodb using find() using values extracted using array.map. Said search returns an object, which I then used a _.forEach to extract the values.

I used this article as basis, however the difference between his examples and mine was he used only one loop. I'm using two. In this case, where should I put my q.all()?

Here's my code. Please note that is server-side:

'use strict';
var q = require('q');

exports.downloadEmployee = function (req, res) {
    var tempCtr = [];

    if (req.params.hasdr === "yes") {
        return queries.generateDirectReportsCSV(req.params.id).then(function (directReports) {
            return directReports;
        }).then(function (directReports) {
            var empIDcoll = _.pluck(directReports.Data, "employeenumber");
            return empIDcoll;
        }).then(function (empIDcoll) {
            var promises = [];

            empIDcoll.map(function (id) {

                return EmployeeInfo.find({ employeeID: id }, function (err, results) {
                    if (err) { return err; }

                    _.forEach(results, function (item) {
                        if (item) {
                            tempCtr.push({
                                employeeID: item.employeeID,
                                employeeName: item.employeeName
                            });
                            promises.push(tempCtr);
                        }
                    });
                });

                q.all(promises).then(function (results) {
                    return res.json(results);
                });
            });
        });
    }

When I run this, I don't get any result back.

Any answers will be greatly appreciated.

Thank you.

UPDATE: I've decided to revise my code and replaced array.map with the usual for loop:

.then(function (empIDcoll) {

    for (var i = 0; i <= empIDcoll.length - 1; i++) {
        var promise = EmployeeInfo.find({ employeeID: empIDcoll[i] }, function (err, results) {
            if (err) { return err; }

            _.forEach(results, function (item) {
                if (item) {
                    tempCtr.push({
                        employeeID: item.employeeID,
                        employeeName: item.employeeName,
                        currentShift: item.currentShift,
                        isOpenToIntlAssignment: item.isOpenToIntlAssignment,
                        desiredRole1: item.desiredRole1,
                        desiredRole2: item.desiredRole2,
                        desiredRole3: item.desiredRole3,
                        desiredRoleOther: item.desiredRoleOther,
                        passportInfo: item.passportInfo,
                        visaInfo: item.visaInfo,
                        yrsInIT: item.yrsInIT,
                        yrsAsCustomerPM: item.yrsAsCustomerPM,
                        yrsAsCustomerProgM: item.yrsAsCustomerProgM,
                        primaryDomain: item.primaryDomain,
                        primaryDomainOther: item.primaryDomainOther,
                        primaryIndustry: item.primaryIndustry,
                        primaryIndustryOther: item.primaryIndustryOther,
                        isPMPCertified: item.isPMPCertified,
                        pmpCertExpiryDate: item.pmpCertExpiryDate,
                        isPGMPCertified: item.isPGMPCertified,
                        pgmpCertExpiryDate: item.pgmpCertExpiryDate,
                        isScrumCertified: item.isScrumCertified,
                        scrumCertExpiryDate: item.scrumCertExpiryDate,
                        biggestProjectTCV: item.biggestProjectTCV,
                        biggestTeamSizeManaged: item.biggestTeamSizeManaged,
                        avgTeamSizeManaged: item.avgTeamSizeManaged,
                        biggestBilledFTE: item.biggestBilledFTE,
                        avgBilledFTE: item.avgBilledFTE
                    });
                }
            });
        });
        promises.push(promise);
    }

    return q.all(promises).then(function(data){
        return res.json(data);
    });

});

...but it's still not returning anything. What am I doing wrong?

Body:
My first suggestion would be to stop looping through the employeeId in the first place.
you can use mongoDB's $in operator like this

EmployeeInfo.find({ employeeID: {$in: empIDcoll} }, function (err, results) {
     if(err) {
       //handle error
       return err;
     }

     res.json(results);
});

But as I dont know about your application I really can't judge maybe you want to loop through empIdColl.

Looping through the empIdColl

Now I'm not sure that your monogdb query will return promise or not so to be on safer side I'll assume that it doesn't

var promises = empIDcoll.map(function (id) {
    var singleDefer = q.defer(); //create a deferred object which has promise in it

    EmployeeInfo.find({ employeeID: id }, function(err, results) {
         if(err) {
             return singleDefer.reject(err);
         }

         return singleDefer.resolve(results); //resolve whole array
    });

    return singleDefer.promise;
});

q.all(promises)
.then(function (arrayOfResults) {
    var responseData = [];

    arrayOfResuls.forEach(function(results) {
          results.forEach(function(individualResult) {
              if(individualResult) {
                   responseData.push({
                       employeeID: item.employeeID,
                       ...
                       ...
                       avgBilledFTE: item.avgBilledFTE
                   });
              }
          });
    });

    return res.json(responseData);
})
.catch(function(err) {
    //handle error
});


问:
ReadDirectoryChangesW does not capture FILE_ACTION_ADDED when copying or creating files
I'm trying to use ReadDirectoryChangesW to track when a file is created, copied or moved to a monitored directory.

My problem is that when I copy or create a file on the monitored directory there is no FILE_ACTION_ADDED event captured by ReadDirectoryChangesW, only FILE_ACTION_MODIFIED events are captured instead.

On the other hand, when I move a file (instead of copying or creating) from another directory to the monitored directory then a FILE_ACTION_ADDED is captured.

I was wondering if someone know a way to make ReadDirectoryChangesW capture FILE_ACTION_ADDED on my 3 cases: create, copy and move.

I call ReadDirectoryChangesW like this:

```<code>ReadDirectoryChangesW(directory_handle, buffer, MAX_EVENTs_BUFFER,
    FALSE, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME |
    FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE,
    NULL, (LPOVERLAPPED)usr_data, FileIOCompletionRoutine)
</code>```

And I use CreateFileA to initialize the directory_handle:

```<code>CreateFileA(directory_path.c_str(),
    FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE |
    FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS |
    FILE_FLAG_OVERLAPPED, NULL);
</code>```

Then, on my FileIOCompletionRoutine I never receive an FILE_ACTION_ADDED when I copy a file to the monitored directory, or when I create a file, only when I move a file. Is this the normal behaviour or am I doing something wrong?

Edit 1:

```<code>VOID CALLBACK FileIOCompletionRoutine(_In_ DWORD err, _In_ DWORD bytes, _Inout_ LPOVERLAPPED lpOverlapped)
{
    CUSTOM_OVERLAPPED* pCustomOverlapped = (CUSTOM_OVERLAPPED*)lpOverlapped;
    char* buffer_offset = (char*)pCustomOverlapped->buffer;
    PFILE_NOTIFY_INFORMATION pInfo = (PFILE_NOTIFY_INFORMATION)buffer_offset;

    do
    {
        pInfo = (PFILE_NOTIFY_INFORMATION)buffer_offset;
        switch (pInfo->Action)
        {
            case FILE_ACTION_ADDED:
            {
                std::cout << "file added!\n";
                break;
            }
            case FILE_ACTION_MODIFIED:
            {
                std::cout << "file modified!\n";
                break;
            }
            // and so on...
        }
        buffer_offset += pInfo->NextEntryOffset;
    } while(pInfo->NextEntryOffset);
}
</code>```

Edit 2:

I found out that if I remove the FILE_NOTIFY_CHANGE_LAST_WRITE from the ReadDirectoryChangesW the FILE_ACTION_ADDED event is captured correctly when I create new files and when I do a cut and paste, but not if I do a copy and paste in which case it fires a FILE_ACTION_MODIFIED. In order to get a FILE_ACTION_ADDED when I do a copy and paste into the monitored directory I need to remove the FILE_NOTIFY_CHANGE_SIZE flag too.

So, this way if a want to track new files (created, copied or moved) inside the monitored directory I only need the flags FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME on the ReadDirectoryChangesW function.
If I want to track modified (already present in the directory) files I need FILE_NOTIFY_CHANGE_SIZE, but I can not use an or of the three flags on the ReadDirectoryChangesW to track new files and modified files.

Has any of you found a way to track all this events with an logical or of the three flags or do I have to call ReadDirectoryChangesW with different flags for each case?

答:
In fact ReadDirectoryChangesW returns a buffer that can contain more than one FILE_NOTIFY_INFORMATION structure. The first one is as expected at the beginning of the buffer, but if the field NextEntryOffset is not null, it is the offset (in the char buffer) for the next structure.

So your callback should be:

```<code>VOID CALLBACK FileIOCompletionRoutine(_In_ DWORD err, _In_ DWORD bytes, _Inout_ LPOVERLAPPED lpOverlapped)
{
    CUSTOM_OVERLAPPED* pCustomOverlapped = (CUSTOM_OVERLAPPED*)lpOverlapped;
    char* buffer_offset = (char*)pCustomOverlapped->buffer;
    PFILE_NOTIFY_INFORMATION pInfo = (PFILE_NOTIFY_INFORMATION)buffer_offset;

    do {
        switch (pInfo->Action)
        {
            case FILE_ACTION_ADDED:
            {
                std::cout << "file added!\n";
                break;
            }
            case FILE_ACTION_MODIFIED:
            {
                std::cout << "file modified!\n";
                break;
            }
            // and so on...
        }
        pInfo = (PFILE_NOTIFY_INFORMATION)(buffer_offset + pInfo->NextEntryOffset);
    } while (0 != pInfo->NextEntryOffset);
}
</code>```

Body:
I'm trying to use ReadDirectoryChangesW to track when a file is created, copied or moved to a monitored directory.

My problem is that when I copy or create a file on the monitored directory there is no FILE_ACTION_ADDED event captured by ReadDirectoryChangesW, only FILE_ACTION_MODIFIED events are captured instead.

On the other hand, when I move a file (instead of copying or creating) from another directory to the monitored directory then a FILE_ACTION_ADDED is captured.

I was wondering if someone know a way to make ReadDirectoryChangesW capture FILE_ACTION_ADDED on my 3 cases: create, copy and move.

I call ReadDirectoryChangesW like this:

ReadDirectoryChangesW(directory_handle, buffer, MAX_EVENTs_BUFFER,
    FALSE, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME |
    FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE,
    NULL, (LPOVERLAPPED)usr_data, FileIOCompletionRoutine)

And I use CreateFileA to initialize the directory_handle:

CreateFileA(directory_path.c_str(),
    FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE |
    FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS |
    FILE_FLAG_OVERLAPPED, NULL);

Then, on my FileIOCompletionRoutine I never receive an FILE_ACTION_ADDED when I copy a file to the monitored directory, or when I create a file, only when I move a file. Is this the normal behaviour or am I doing something wrong?

Edit 1:

VOID CALLBACK FileIOCompletionRoutine(_In_ DWORD err, _In_ DWORD bytes, _Inout_ LPOVERLAPPED lpOverlapped)
{
    CUSTOM_OVERLAPPED* pCustomOverlapped = (CUSTOM_OVERLAPPED*)lpOverlapped;
    char* buffer_offset = (char*)pCustomOverlapped->buffer;
    PFILE_NOTIFY_INFORMATION pInfo = (PFILE_NOTIFY_INFORMATION)buffer_offset;

    do
    {
        pInfo = (PFILE_NOTIFY_INFORMATION)buffer_offset;
        switch (pInfo->Action)
        {
            case FILE_ACTION_ADDED:
            {
                std::cout << "file added!\n";
                break;
            }
            case FILE_ACTION_MODIFIED:
            {
                std::cout << "file modified!\n";
                break;
            }
            // and so on...
        }
        buffer_offset += pInfo->NextEntryOffset;
    } while(pInfo->NextEntryOffset);
}

Edit 2:

I found out that if I remove the FILE_NOTIFY_CHANGE_LAST_WRITE from the ReadDirectoryChangesW the FILE_ACTION_ADDED event is captured correctly when I create new files and when I do a cut and paste, but not if I do a copy and paste in which case it fires a FILE_ACTION_MODIFIED. In order to get a FILE_ACTION_ADDED when I do a copy and paste into the monitored directory I need to remove the FILE_NOTIFY_CHANGE_SIZE flag too.

So, this way if a want to track new files (created, copied or moved) inside the monitored directory I only need the flags FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME on the ReadDirectoryChangesW function.
If I want to track modified (already present in the directory) files I need FILE_NOTIFY_CHANGE_SIZE, but I can not use an or of the three flags on the ReadDirectoryChangesW to track new files and modified files.

Has any of you found a way to track all this events with an logical or of the three flags or do I have to call ReadDirectoryChangesW with different flags for each case?

Body:
In fact ReadDirectoryChangesW returns a buffer that can contain more than one FILE_NOTIFY_INFORMATION structure. The first one is as expected at the beginning of the buffer, but if the field NextEntryOffset is not null, it is the offset (in the char buffer) for the next structure.

So your callback should be:

VOID CALLBACK FileIOCompletionRoutine(_In_ DWORD err, _In_ DWORD bytes, _Inout_ LPOVERLAPPED lpOverlapped)
{
    CUSTOM_OVERLAPPED* pCustomOverlapped = (CUSTOM_OVERLAPPED*)lpOverlapped;
    char* buffer_offset = (char*)pCustomOverlapped->buffer;
    PFILE_NOTIFY_INFORMATION pInfo = (PFILE_NOTIFY_INFORMATION)buffer_offset;

    do {
        switch (pInfo->Action)
        {
            case FILE_ACTION_ADDED:
            {
                std::cout << "file added!\n";
                break;
            }
            case FILE_ACTION_MODIFIED:
            {
                std::cout << "file modified!\n";
                break;
            }
            // and so on...
        }
        pInfo = (PFILE_NOTIFY_INFORMATION)(buffer_offset + pInfo->NextEntryOffset);
    } while (0 != pInfo->NextEntryOffset);
}


问:
Observable and Angular2
I have an issue with Observables in Angular 2

My component calls service function on Init like below:

```<code>delivery: IDeliveryCountry[];

ngOnInit() {
  this.checkoutService._getInfo().subscribe(dev => this.delivery = dev);
}
</code>```

This is how interface looks like IDeliveryCountry:

```<code>export interface IDeliveryCountry {
  iso: string;
  name: string;
}
</code>```

This is how Service looks like:

```<code>_getInfo(): Observable<IDeliveryCountry[]> {
    return this.http.get(this.deliveryCountryUrl)
    .map((response: Response) => <IDeliveryCountry[]>response.json())
}
</code>```

json file with data looks like this:

```<code>[
  {
    "iso":"se",
    "name":"Sweden"
  },
  {
    "iso":"dk",
    "name":"Denmark"
  }
]
</code>```

My html file is just a simple ngFor loop:

```<code><div *ngFor='let dev of delivery'>{{dev.iso}}</div>
</code>```

So far all things works perfect, as expected I get back "se" and "dk" in UI.

The problem appears when I change a structure of data in my json file to following:

```<code>{
  "country": {
    "iso":"se",
    "name":"Sweden"
  }
}
</code>```

I want data to only have one country with iso and name property for it. So my html file looks like following:

```<code><div>{{delivery.iso}}</div>
</code>```

But I am getting iso as undefined all the time

" Cannot read property 'iso' of undefined "

Thank you!

答:
You can just do this without ngFor since it is an Object

```<code><div>{{delivery.country.iso}}</div>
</code>```

After your comments, undefined is because the data is coming async, so use the elvis operator to avoid this:

```<code> {{delivery?.country?.iso}}
</code>```

Title: Observable and Angular2

Body:
I have an issue with Observables in Angular 2

My component calls service function on Init like below:

delivery: IDeliveryCountry[];

ngOnInit() {
  this.checkoutService._getInfo().subscribe(dev => this.delivery = dev);
}

This is how interface looks like IDeliveryCountry:

export interface IDeliveryCountry {
  iso: string;
  name: string;
}

This is how Service looks like:

_getInfo(): Observable<IDeliveryCountry[]> {
    return this.http.get(this.deliveryCountryUrl)
    .map((response: Response) => <IDeliveryCountry[]>response.json())
}

json file with data looks like this:

[
  {
    "iso":"se",
    "name":"Sweden"
  },
  {
    "iso":"dk",
    "name":"Denmark"
  }
]

My html file is just a simple ngFor loop:

{{dev.iso}}

So far all things works perfect, as expected I get back "se" and "dk" in UI.

The problem appears when I change a structure of data in my json file to following:

{
  "country": {
    "iso":"se",
    "name":"Sweden"
  }
}

I want data to only have one country with iso and name property for it. So my html file looks like following:

{{delivery.iso}}

But I am getting iso as undefined all the time

" Cannot read property 'iso' of undefined "

Thank you!

Body:
You can just do this without ngFor since it is an Object

<div>{{delivery.country.iso}}</div>

After your comments, undefined is because the data is coming async, so use the elvis operator to avoid this:

 {{delivery?.country?.iso}}


问:
How to Create Multiple Frequency Tables with Percentages Across Factor Variables using Purrr::map
```<code>library(tidyverse)
library(ggmosaic) for "happy" dataset.
</code>```

I feel like this should be a somewhat simple thing to achieve, but I'm having difficulty with percentages when using purrr::map together with table(). Using the "happy" dataset, I want to create a list of frequency tables for each factor variable. I would also like to have rounded percentages instead of counts, or both if possible.

I can create frequency precentages for each factor variable separately with the code below.

```<code>with(happy,round(prop.table(table(marital)),2))
</code>```

However I can't seem to get the percentages to work correctly when using table() with purrr::map. The code below doesn't work...

```<code>happy%>%select_if(is.factor)%>%map(round(prop.table(table)),2)
</code>```

The second method I tried was using tidyr::gather, and calculating the percentage with dplyr::mutate and then splitting the data and spreading with tidyr::spread.

```<code>TABLE<-happy%>%select_if(is.factor)%>%gather()%>%group_by(key,value)%>%summarise(count=n())%>%mutate(perc=count/sum(count))
</code>```

However, since there are different factor variables, I would have to split the data by "key" before spreading using purrr::map and tidyr::spread, which came close to producing some useful output except for the repeating "key" values in the rows and the NA's.

```<code>TABLE%>%split(TABLE$key)%>%map(~spread(.x,value,perc))
</code>```

So any help on how to make both of the above methods work would be greatly appreciated...

答:
You can use an anonymous function or a formula to get your first option to work.  Here's the formula option.

```<code>happy %>%
    select_if(is.factor) %>%
    map(~round(prop.table(table(.x)), 2))
</code>```

In your second option, removing the NA values and then removing the count variable prior to spreading helps.  The order in the result has changed, however.

```<code>TABLE = happy %>%
    select_if(is.factor) %>%
    gather() %>%
    filter(!is.na(value)) %>%
    group_by(key, value) %>%
    summarise(count = n()) %>%
    mutate(perc = round(count/sum(count), 2), count = NULL)

TABLE %>%
    split(.$key) %>%
    map(~spread(.x, value, perc))
</code>```

Body:
library(tidyverse)
library(ggmosaic) for "happy" dataset.

I feel like this should be a somewhat simple thing to achieve, but I'm having difficulty with percentages when using purrr::map together with table(). Using the "happy" dataset, I want to create a list of frequency tables for each factor variable. I would also like to have rounded percentages instead of counts, or both if possible.

I can create frequency precentages for each factor variable separately with the code below.

with(happy,round(prop.table(table(marital)),2))

However I can't seem to get the percentages to work correctly when using table() with purrr::map. The code below doesn't work...

happy%>%select_if(is.factor)%>%map(round(prop.table(table)),2)

The second method I tried was using tidyr::gather, and calculating the percentage with dplyr::mutate and then splitting the data and spreading with tidyr::spread.

TABLE<-happy%>%select_if(is.factor)%>%gather()%>%group_by(key,value)%>%summarise(count=n())%>%mutate(perc=count/sum(count))

However, since there are different factor variables, I would have to split the data by "key" before spreading using purrr::map and tidyr::spread, which came close to producing some useful output except for the repeating "key" values in the rows and the NA's.

TABLE%>%split(TABLE$key)%>%map(~spread(.x,value,perc))

So any help on how to make both of the above methods work would be greatly appreciated...

Body:
You can use an anonymous function or a formula to get your first option to work.  Here's the formula option.

happy %>%
    select_if(is.factor) %>%
    map(~round(prop.table(table(.x)), 2))

In your second option, removing the NA values and then removing the count variable prior to spreading helps.  The order in the result has changed, however.

TABLE = happy %>%
    select_if(is.factor) %>%
    gather() %>%
    filter(!is.na(value)) %>%
    group_by(key, value) %>%
    summarise(count = n()) %>%
    mutate(perc = round(count/sum(count), 2), count = NULL)

TABLE %>%
    split(.$key) %>%
    map(~spread(.x, value, perc))


问:
FileSystemWatcher OnCreated returning string?
I would like to make the FileSystemWatcher monitor a folder and once there is a file created inside to get the filename so after that file could be read by File.OpenRead() and a StreamReader

I have seen a lot of examples but not my case exactly:

```<code>        public static void FileWatcher()
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = @"C:\Users\";
        watcher.NotifyFilter = NotifyFilters.LastWrite;
        watcher.Filter = "*.txt";
        watcher.Created += new FileSystemEventHandler(OnCreated);
        watcher.EnableRaisingEvents = true;
    }

    public static void OnCreated(object source, FileSystemEventArgs e)
    {
        string filename = Path.GetFileName(e.FullPath);
    }
</code>```

My question is how to get the filename that is going to be created in that folder and pass its path and file to since the event method is a void:

```<code>const string fileName = @"C:\Users\.txt";
        using (var stream = File.OpenRead(fileName))
        using (var reader = new StreamReader(stream))
</code>```

Any help appreciated!

答:
I'd recommend encapsulating your file processing in a separate class.

```<code>public class FileProcessor
{
      public void ProcessFile(string filePath)
       {
           using (var stream = File.OpenRead(filePath))
           //etc...

       }
}
</code>```

Then instance it and call it.

```<code> public static void OnCreated(object source, FileSystemEventArgs e)
    {
       var processor = new FileProcessor();
       processor.ProcessFile(e.FullPath);
    }
</code>```

Or if your method is in the same class as the Created event

```<code>YourMethodName(e.FullPath);
</code>```

And your method should have a signature like this

```<code>void YourMethodName (string filePath)
{
  //Process file
}
</code>```

Body:
I would like to make the FileSystemWatcher monitor a folder and once there is a file created inside to get the filename so after that file could be read by File.OpenRead() and a StreamReader

I have seen a lot of examples but not my case exactly:

        public static void FileWatcher()
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = @"C:\Users\";
        watcher.NotifyFilter = NotifyFilters.LastWrite;
        watcher.Filter = "*.txt";
        watcher.Created += new FileSystemEventHandler(OnCreated);
        watcher.EnableRaisingEvents = true;
    }

    public static void OnCreated(object source, FileSystemEventArgs e)
    {
        string filename = Path.GetFileName(e.FullPath);
    }

My question is how to get the filename that is going to be created in that folder and pass its path and file to since the event method is a void:

const string fileName = @"C:\Users\.txt";
        using (var stream = File.OpenRead(fileName))
        using (var reader = new StreamReader(stream))

Any help appreciated!

Body:
I'd recommend encapsulating your file processing in a separate class.

public class FileProcessor
{
      public void ProcessFile(string filePath)
       {
           using (var stream = File.OpenRead(filePath))
           //etc...

       }
}

Then instance it and call it.

 public static void OnCreated(object source, FileSystemEventArgs e)
    {
       var processor = new FileProcessor();
       processor.ProcessFile(e.FullPath);
    }

Or if your method is in the same class as the Created event

YourMethodName(e.FullPath);

And your method should have a signature like this

void YourMethodName (string filePath)
{
  //Process file
}


问:
Deserializing public property with non-public setter in json.net
Suppose I have the following class -

```<code>public class A
{
   public int P1 { get; internal set; }
}
</code>```

Using json.net, I am able to serialize the type with P1 property. However, during deserialization, P1 is not set. Without modifying class A, is there an in build way to handle this? In my case, I am using a class from a different assembly and cannot modify it.

答:
This is my solution to handle in more general case:

```<code>class CustomResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty result = base.CreateProperty(member, memberSerialization);

        var propInfo = member as PropertyInfo;
        result.Writable |= propInfo != null
             && propInfo.CanWrite
             && !propInfo.IsPrivate;

        return result;
    }
}
</code>```

With class CInternalSetter:

```<code>class CInternalSetter
{
    public CInternalSetter()
    {
        LoggedEmployeeId3 = 10;
    }
    public int LoggedEmployeeId { get; set; }
    public int LoggedEmployeeId2 { get; internal set; }
    public int LoggedEmployeeId3 { get; }
    public override string ToString()
    {
        return JsonConvert.SerializeObject(this, Formatting.Indented);
    }
}
</code>```

Then test it with against this class:

```<code>JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver = new CustomResolver();

var c = new CInternalSetter()
{
    LoggedEmployeeId = 1,
    LoggedEmployeeId2 = 2
};

var cString = JsonConvert.SerializeObject(c);

Console.WriteLine(cString);
Console.WriteLine(JsonConvert.DeserializeObject<CInternalSetter>(cString).ToString());
Console.WriteLine("-------------------------------------------");
Console.WriteLine(JsonConvert.DeserializeObject<CInternalSetter>(cString, settings).ToString());
</code>```

Body:
Suppose I have the following class -

public class A
{
   public int P1 { get; internal set; }
}

Using json.net, I am able to serialize the type with P1 property. However, during deserialization, P1 is not set. Without modifying class A, is there an in build way to handle this? In my case, I am using a class from a different assembly and cannot modify it.

Body:
This is my solution to handle in more general case:

class CustomResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty result = base.CreateProperty(member, memberSerialization);

        var propInfo = member as PropertyInfo;
        result.Writable |= propInfo != null
             && propInfo.CanWrite
             && !propInfo.IsPrivate;

        return result;
    }
}

With class CInternalSetter:

class CInternalSetter
{
    public CInternalSetter()
    {
        LoggedEmployeeId3 = 10;
    }
    public int LoggedEmployeeId { get; set; }
    public int LoggedEmployeeId2 { get; internal set; }
    public int LoggedEmployeeId3 { get; }
    public override string ToString()
    {
        return JsonConvert.SerializeObject(this, Formatting.Indented);
    }
}

Then test it with against this class:

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver = new CustomResolver();

var c = new CInternalSetter()
{
    LoggedEmployeeId = 1,
    LoggedEmployeeId2 = 2
};

var cString = JsonConvert.SerializeObject(c);

Console.WriteLine(cString);
Console.WriteLine(JsonConvert.DeserializeObject<CInternalSetter>(cString).ToString());
Console.WriteLine("-------------------------------------------");
Console.WriteLine(JsonConvert.DeserializeObject<CInternalSetter>(cString, settings).ToString());


问:
Getting the excel file after df.to_excel(...) with Panda
I am using Pyrebase to upload my files to Firebase.

I have a DataFrame df and convert it to an Excel File as follows:

```<code>writer      = ExcelWriter('results.xlsx')
excelFile   = df.to_excel(writer,'Sheet1')

print(excelFile)

# Save to firebase
childRef        = "path/to/results.xlsx"

storage         = firebase.storage()
storage.child(childRef).put(excelFile)
</code>```

However, this stores the Excel file as an Office Spreadsheet with zero bytes. If I run writer.save() then I do get the appropriate filetype (xlsx), but it is stored on my Server (which I want to avoid). How can I generate the right filetype as one would do with writer.save()?

Note: print(excelFile) returns None

答:
It can be solved by using local memory:</p>

```<code># init writer
bio         = BytesIO()
writer      = pd.ExcelWriter(bio, engine='xlsxwriter')
filename    = "output.xlsx"

# sheets
dfValue.to_excel(writer, "sheetname")

# save the workbook
writer.save()
bio.seek(0)

# get the excel file (answers my question)
workbook    = bio.read()
excelFile   = workbook

# save the excelfile to firebase
# see also issue: https://github.com/thisbejim/Pyrebase/issues/142
timestamp       = str(int(time.time()*1000));
childRef        = "/path/to/" + filename

storage         = firebase.storage()
storage.child(childRef).put(excelFile)
fileUrl         = storage.child(childRef).get_url(None)
</code>```

Body:
I am using Pyrebase to upload my files to Firebase.

I have a DataFrame df and convert it to an Excel File as follows:

writer      = ExcelWriter('results.xlsx')
excelFile   = df.to_excel(writer,'Sheet1')

print(excelFile)

# Save to firebase
childRef        = "path/to/results.xlsx"

storage         = firebase.storage()
storage.child(childRef).put(excelFile)

However, this stores the Excel file as an Office Spreadsheet with zero bytes. If I run writer.save() then I do get the appropriate filetype (xlsx), but it is stored on my Server (which I want to avoid). How can I generate the right filetype as one would do with writer.save()?

Note: print(excelFile) returns None

Body:
It can be solved by using local memory:

# init writer
bio         = BytesIO()
writer      = pd.ExcelWriter(bio, engine='xlsxwriter')
filename    = "output.xlsx"

# sheets
dfValue.to_excel(writer, "sheetname")

# save the workbook
writer.save()
bio.seek(0)

# get the excel file (answers my question)
workbook    = bio.read()
excelFile   = workbook

# save the excelfile to firebase
# see also issue: https://github.com/thisbejim/Pyrebase/issues/142
timestamp       = str(int(time.time()*1000));
childRef        = "/path/to/" + filename

storage         = firebase.storage()
storage.child(childRef).put(excelFile)
fileUrl         = storage.child(childRef).get_url(None)


问:
Conversion of ByteBuffer in Xamarin.Android
How to convert the following code to C# from Android (Java)?

```<code>ByteBuffer bb;

Type = bb.GetInt();
</code>```

I tried to change this to C# as

```<code>Type = bb.Int;
</code>```

but I am getting wrong values. Please let me know how to convert Java code to C# code

答:
See here:

https://developer.xamarin.com/api/type/Java.Nio.ByteBuffer/

You can use

```<code>(int)(bb.Get());
</code>```

Get the value as a sbyte and cast to integer.

Body:
How to convert the following code to C# from Android (Java)?

ByteBuffer bb;

Type = bb.GetInt();

I tried to change this to C# as

Type = bb.Int;

but I am getting wrong values. Please let me know how to convert Java code to C# code

Body:
See here:

https://developer.xamarin.com/api/type/Java.Nio.ByteBuffer/

You can use

(int)(bb.Get());

Get the value as a sbyte and cast to integer.


问:
Using Application Insights with Unit Tests?
I have an MVC web app, and I'm using Simple Injector for DI.  Almost all my code is covered by unit tests.  However, now that I've added some telemetry calls in some controllers, I'm having trouble setting up the dependencies.

The telemetry calls are for sending metrics to the Microsoft Azure-hosted Application Insights service.  The app is not running in Azure, just a server with ISS. The AI portal tells you all kinds of things about your application, including any custom events you send using the telemetry library.  As a result, the controller requires an instance of Microsoft.ApplicationInsights.TelemetryClient, which has no Interface and is a sealed class, with 2 constructors.  I tried registering it like so (the hybrid lifestyle is unrelated to this question, I just included it for completeness):

```<code>// hybrid lifestyle that gives precedence to web api request scope
var requestOrTransientLifestyle = Lifestyle.CreateHybrid(
    () => HttpContext.Current != null,
    new WebRequestLifestyle(),
    Lifestyle.Transient);

container.Register<TelemetryClient>(requestOrTransientLifestyle);
</code>```

The problem is that since TelemetryClient has 2 constructors, SI complains and fails validation.  I found a post showing how to override the container's constructor resolution behavior, but that seems pretty complicated. First I wanted to back up and ask this question:

If I don't make the TelemetryClient an injected dependency (just create a New one in the class), will that telemetry get sent to Azure on every run of the unit test, creating lots of false data?  Or is Application Insights smart enough to know it is running in a unit test, and not send the data?

Any "Insights" into this issue would be much appreciated!

Thanks

答:
If you don't want to go down the abstraction / wrapper path. In your tests you could simply direct the AppInsights endpoint to a mock lightweight http server (which is trivial in ASP.NET Core).

appInsightsSettings.json

```<code>    "ApplicationInsights": {
    "Endpoint": "http://localhost:8888/v2/track"
}
</code>```

How to set up "TestServer" in ASP.NET Core http://josephwoodward.co.uk/2016/07/integration-testing-asp-net-core-middleware

Body:
I have an MVC web app, and I'm using Simple Injector for DI.  Almost all my code is covered by unit tests.  However, now that I've added some telemetry calls in some controllers, I'm having trouble setting up the dependencies.

The telemetry calls are for sending metrics to the Microsoft Azure-hosted Application Insights service.  The app is not running in Azure, just a server with ISS. The AI portal tells you all kinds of things about your application, including any custom events you send using the telemetry library.  As a result, the controller requires an instance of Microsoft.ApplicationInsights.TelemetryClient, which has no Interface and is a sealed class, with 2 constructors.  I tried registering it like so (the hybrid lifestyle is unrelated to this question, I just included it for completeness):

// hybrid lifestyle that gives precedence to web api request scope
var requestOrTransientLifestyle = Lifestyle.CreateHybrid(
    () => HttpContext.Current != null,
    new WebRequestLifestyle(),
    Lifestyle.Transient);

container.Register<TelemetryClient>(requestOrTransientLifestyle);

The problem is that since TelemetryClient has 2 constructors, SI complains and fails validation.  I found a post showing how to override the container's constructor resolution behavior, but that seems pretty complicated. First I wanted to back up and ask this question:

If I don't make the TelemetryClient an injected dependency (just create a New one in the class), will that telemetry get sent to Azure on every run of the unit test, creating lots of false data?  Or is Application Insights smart enough to know it is running in a unit test, and not send the data?

Any "Insights" into this issue would be much appreciated!

Thanks

Body:
If you don't want to go down the abstraction / wrapper path. In your tests you could simply direct the AppInsights endpoint to a mock lightweight http server (which is trivial in ASP.NET Core).

appInsightsSettings.json

    "ApplicationInsights": {
    "Endpoint": "http://localhost:8888/v2/track"
}

How to set up "TestServer" in ASP.NET Core http://josephwoodward.co.uk/2016/07/integration-testing-asp-net-core-middleware


问:
PHP Get Time From X Percentage of Total Time
I don't know if this will make sense but I would like to get the time from percentage of a value, I have the following as an input example:

```<code>mypercentage = 50;
mytime = "00:59:59"
</code>```

As you can see, my time is 60 minutes (1 hour) and 50% of that is 30 minutes therefore from the 2 above inputs I would like to get the following output
(50 % of an hour):

```<code>00:30:00
</code>```

答:
Explode the string into an array

Convert the 3 elements into numbers

Find the value in seconds. $array[0]*3600+$array[1]*60+$array[2]

Calculate the time from the value in step 3 and the percentage.

Use /3600 and /60 to find the hour and minutes and %60 to find the seconds.

put the values in an array and implode to a string, or just use

$hour.":".$minute.":".$second

Body:
I don't know if this will make sense but I would like to get the time from percentage of a value, I have the following as an input example:

mypercentage = 50;
mytime = "00:59:59"

As you can see, my time is 60 minutes (1 hour) and 50% of that is 30 minutes therefore from the 2 above inputs I would like to get the following output
(50 % of an hour):

00:30:00


问:
Issues using Oracle case function
i'm trying to find the create a query that will return a set of staff's last name with their attached grade level (which is in another table with no foreign key relationship available with the staff one).

So far i have this but it is returning a "missing keyword" error on it. What is wrong with it?/ have i got my logic very wrong?

The last name and salary are in the staff/employee table.
The grade level is in a Job grades table.

```<code>    select last_name, salary,
CASE grade_level
WHEN  lowest_sal >= 1000 THEN 'A'
WHEN lowest_sal >= 3000  THEN 'B'
WHEN lowest_sal >= 6000 THEN 'C'
WHEN lowest_sal >= 10000 THEN 'D'
WHEN lowest_sal >= 15000  THEN 'E'
ELSE 'F'
END
FROM employees, job_grades
WHERE department_id > 50;
</code>```

答:
You just converted the SQL from Non-ANSI standard to ANSI standard. But the same could be achieved using non-ANSI standard. I see in your original query, you were trying to join to tables but did not define the joining criteria. It does not matter if there is a Relational Integrity (foreign Key) between those tables. While joining 2 tables, you must use the joining criteria.

```<code>                SELECT
                LAST_NAME,
                SALARY,
                CASE GRADE_LEVEL
                    WHEN  LOWEST_SAL >= 1000 THEN 'A'
                    WHEN LOWEST_SAL >= 3000  THEN 'B'
                    WHEN LOWEST_SAL >= 6000 THEN 'C'
                    WHEN LOWEST_SAL >= 10000 THEN 'D'
                    WHEN LOWEST_SAL >= 15000  THEN 'E'
                ELSE 'F'
                END
            FROM
                EMPLOYEES EMP, JOB_GRADES JOBS --**MISSING Joining Criteria**
            WHERE
               DEPARTMENT_ID > 50;
</code>```

In order to fix this, you need to have it like below

```<code>                SELECT
                LAST_NAME,
                SALARY,
                CASE GRADE_LEVEL
                    WHEN  LOWEST_SAL >= 1000 THEN 'A'
                    WHEN LOWEST_SAL >= 3000  THEN 'B'
                    WHEN LOWEST_SAL >= 6000 THEN 'C'
                    WHEN LOWEST_SAL >= 10000 THEN 'D'
                    WHEN LOWEST_SAL >= 15000  THEN 'E'
                ELSE 'F'
                END
            FROM
                EMPLOYEES EMP, JOB_GRADES JOBS
            WHERE
                 EMP.EMPLOYEES.ID = JOB_GRADES.EMP_ID --**This is the FIX**
               AND DEPARTMENT_ID > 50;
</code>```

Title: Issues using Oracle case function

Body:
i'm trying to find the create a query that will return a set of staff's last name with their attached grade level (which is in another table with no foreign key relationship available with the staff one).

So far i have this but it is returning a "missing keyword" error on it. What is wrong with it?/ have i got my logic very wrong?

The last name and salary are in the staff/employee table.
The grade level is in a Job grades table.

    select last_name, salary,
CASE grade_level
WHEN  lowest_sal >= 1000 THEN 'A'
WHEN lowest_sal >= 3000  THEN 'B'
WHEN lowest_sal >= 6000 THEN 'C'
WHEN lowest_sal >= 10000 THEN 'D'
WHEN lowest_sal >= 15000  THEN 'E'
ELSE 'F'
END
FROM employees, job_grades
WHERE department_id > 50;

Body:
You just converted the SQL from Non-ANSI standard to ANSI standard. But the same could be achieved using non-ANSI standard. I see in your original query, you were trying to join to tables but did not define the joining criteria. It does not matter if there is a Relational Integrity (foreign Key) between those tables. While joining 2 tables, you must use the joining criteria.

                SELECT
                LAST_NAME,
                SALARY,
                CASE GRADE_LEVEL
                    WHEN  LOWEST_SAL >= 1000 THEN 'A'
                    WHEN LOWEST_SAL >= 3000  THEN 'B'
                    WHEN LOWEST_SAL >= 6000 THEN 'C'
                    WHEN LOWEST_SAL >= 10000 THEN 'D'
                    WHEN LOWEST_SAL >= 15000  THEN 'E'
                ELSE 'F'
                END
            FROM
                EMPLOYEES EMP, JOB_GRADES JOBS --**MISSING Joining Criteria**
            WHERE
               DEPARTMENT_ID > 50;

In order to fix this, you need to have it like below

                SELECT
                LAST_NAME,
                SALARY,
                CASE GRADE_LEVEL
                    WHEN  LOWEST_SAL >= 1000 THEN 'A'
                    WHEN LOWEST_SAL >= 3000  THEN 'B'
                    WHEN LOWEST_SAL >= 6000 THEN 'C'
                    WHEN LOWEST_SAL >= 10000 THEN 'D'
                    WHEN LOWEST_SAL >= 15000  THEN 'E'
                ELSE 'F'
                END
            FROM
                EMPLOYEES EMP, JOB_GRADES JOBS
            WHERE
                 EMP.EMPLOYEES.ID = JOB_GRADES.EMP_ID --**This is the FIX**
               AND DEPARTMENT_ID > 50;


问:
Buttons not working with onclick and JavaScript
I am trying to make buttons that adds 10, 100, and 1000 to an input and that can clear the input field, but i can't get it to work. I have tried alle the different ways i know to add the script to my document(inline and external) but i can't seem to crack the code. The debug console tells me that The functions is not defined

EDIT:

The problem seems to be that when clicking the buttons the site redirects to the index file

var bet = document.getElementById('coincredits');
var cur = document.getElementById('coincredits').value;
var coins = document.getElementById('coins').value;

function clear() {
 bet.value = "";
}
function ten() {
 bet.value = cur + 10;
}
function hundred() {
 bet.value = cur + 100;
}
function thousand() {
 bet.value = cur + 1000;
}
function xtwo() {
 bet.value = cur * 2;
}
function max() {
 bet.value = coins;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h4>Coins:</h4><p id="coins">123456789</p>

<input type="number" name="coincredits" id="coincredits" required="" parsley-type="text" data-parsley-id="40">

<div>
  <button onclick="clear()">Clear</button>
  <button onclick="ten()">+10</button>
  <button onclick="hundred()">+100</button>
  <button onclick="thousand()">+1000</button>
  <button onclick="xtwo()">x2</button>
  <button onclick="max()">Max</button>
</div></code>```

答:
you have an problem on

```<code>var coins = document.getElementById('coins').value;
</code>```

its have to be .innerHTML.

i try to rewrite your function here the complete.

/*declare a function call hAddCoin with parameter hValue for value and option for option +,x2,clear or max*/
function hAddCoin(hValue, option){
    var bet   = document.getElementById('coincredits'); /*get the element*/
    var coins = document.getElementById('coins').innerHTML;/*get the inner of id coins*/
    var cur   = parseInt(bet.value); /*get the coincredit and convert to integer*/
    var res   = 0; /*declare res variable for result*/
    /*we need to check bet is empty or not*/
    if(typeof bet.value === "undefined" || bet.value ==""){
        cur = 0;
    }
    /*cek the option, it's will be +, X2 or max and default to 0*/
    switch(option){
      case 1:{
        res = cur + hValue;
      }break;
      case 2:{
        res = cur * option;
      }break;
      case 3:{
        res = parseInt(coins);
      }break;
      default:{
        res = 0;
      }break;
    }

      bet.value = res;/*set value coin creadit to result*/
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h4>Coins:</h4><p id="coins">123456789</p>

<input type="number" name="coincredits" id="coincredits" required="" parsley-type="text" data-parsley-id="40">

<div>
  <button onclick="hAddCoin(0,0)">Clear</button>
  <button onclick="hAddCoin(10,1)">+10</button>
  <button onclick="hAddCoin(100,1)">+100</button>
  <button onclick="hAddCoin(1000,1)">+1000</button>
  <button onclick="hAddCoin(0,2)">x2</button>
  <button onclick="hAddCoin(0,3)">Max</button>
</div></code>```

Body:
I am trying to make buttons that adds 10, 100, and 1000 to an input and that can clear the input field, but i can't get it to work. I have tried alle the different ways i know to add the script to my document(inline and external) but i can't seem to crack the code. The debug console tells me that The functions is not defined

EDIT:

The problem seems to be that when clicking the buttons the site redirects to the index file

var bet = document.getElementById('coincredits');
var cur = document.getElementById('coincredits').value;
var coins = document.getElementById('coins').value;

function clear() {
 bet.value = "";
}
function ten() {
 bet.value = cur + 10;
}
function hundred() {
 bet.value = cur + 100;
}
function thousand() {
 bet.value = cur + 1000;
}
function xtwo() {
 bet.value = cur * 2;
}
function max() {
 bet.value = coins;
}

Coins:

123456789

<input type="number" name="coincredits" id="coincredits" required="" parsley-type="text" data-parsley-id="40">

  <button onclick="clear()">Clear</button>
  <button onclick="ten()">+10</button>
  <button onclick="hundred()">+100</button>
  <button onclick="thousand()">+1000</button>
  <button onclick="xtwo()">x2</button>
  <button onclick="max()">Max</button>

Body:
you have an problem on

var coins = document.getElementById('coins').value;

its have to be .innerHTML.

i try to rewrite your function here the complete.

/*declare a function call hAddCoin with parameter hValue for value and option for option +,x2,clear or max*/
function hAddCoin(hValue, option){
    var bet   = document.getElementById('coincredits'); /*get the element*/
    var coins = document.getElementById('coins').innerHTML;/*get the inner of id coins*/
    var cur   = parseInt(bet.value); /*get the coincredit and convert to integer*/
    var res   = 0; /*declare res variable for result*/
    /*we need to check bet is empty or not*/
    if(typeof bet.value === "undefined" || bet.value ==""){
        cur = 0;
    }
    /*cek the option, it's will be +, X2 or max and default to 0*/
    switch(option){
      case 1:{
        res = cur + hValue;
      }break;
      case 2:{
        res = cur * option;
      }break;
      case 3:{
        res = parseInt(coins);
      }break;
      default:{
        res = 0;
      }break;
    }

      bet.value = res;/*set value coin creadit to result*/
  }

<h4>Coins:</h4><p id="coins">123456789</p>

<input type="number" name="coincredits" id="coincredits" required="" parsley-type="text" data-parsley-id="40">

<div>
  <button onclick="hAddCoin(0,0)">Clear</button>
  <button onclick="hAddCoin(10,1)">+10</button>
  <button onclick="hAddCoin(100,1)">+100</button>
  <button onclick="hAddCoin(1000,1)">+1000</button>
  <button onclick="hAddCoin(0,2)">x2</button>
  <button onclick="hAddCoin(0,3)">Max</button>
</div>


问:
apache2 mod_wsgi crashes when importing pyodbc
Operating system - Ubuntu Server 14.04 on Azure VM

Tried with different versions of python (3.4.3, 3.6.0), apache and mod_wsgi.

Installed MS Native ODBC driver using instructions from here
 https://gist.github.com/joecampo/6f777a659b8132b9d6fe1c3589df394c , while pyodbc was installed using pip.

To debug the wsgi_module I have set up the django application to run in embedded mode and:

```<code>gdb /usr/local/apache2/bin/httpd
run -X
</code>```

When I access any function which imports pyodbc, the wsgi fails with the following error:

```<code>Program received signal SIGSEGV, Segmentation fault.
import_types () at src/pyodbcmodule.cpp:223
223 src/pyodbcmodule.cpp: No such file or directory.
</code>```

Importing module works fine when I run the django app from the command line:

```<code>python3 manage.py runserver
</code>```

Is there a workaround?

答: This has been fixed in 4.0.16 by adding support for subinterpreters.</p>

Body:
Operating system - Ubuntu Server 14.04 on Azure VM

Tried with different versions of python (3.4.3, 3.6.0), apache and mod_wsgi.

Installed MS Native ODBC driver using instructions from here
 https://gist.github.com/joecampo/6f777a659b8132b9d6fe1c3589df394c , while pyodbc was installed using pip.

To debug the wsgi_module I have set up the django application to run in embedded mode and:

gdb /usr/local/apache2/bin/httpd
run -X

When I access any function which imports pyodbc, the wsgi fails with the following error:

Program received signal SIGSEGV, Segmentation fault.
import_types () at src/pyodbcmodule.cpp:223
223 src/pyodbcmodule.cpp: No such file or directory.

Importing module works fine when I run the django app from the command line:

python3 manage.py runserver

Is there a workaround?


问:
Amazon Logstash Usage
What is the use of Logstash, and how can I use in my project of containing the dynamodb database. Without using Lambda, we can use Logstash. Was the Logstash work as Lambda or in different process. Please guide me.</p>

答:
Logstash is an open source, server-side data processing pipeline that ingests data from a multitude of sources simultaneously, transforms it, and then sends it to your favorite “stash.” (Ours is Elasticsearch, naturally.).
Link

You can use logstash to collect your data logs, process, and send it to a server for centralized and view it with a tool like Kibana

Title: Amazon Logstash Usage


问:
How to pass values to directive in angular
My code,

```<code>  <modal *ngIf='showModal' [imageValue]="imageId"></modal>
</code>```

My model component,

```<code>@Component({
  selector: 'modal',
  templateUrl: './app/modal/modal.component.html',
  providers: [HeaderClass]
})

export class ModalComponent  {
  imageValue:any;
</code>```

I want to get the value of this 'imageValue' but I dont know how to do it.Can anyone please help me.Thanks.

答: Use @input and pass value from parent component, where this component was used like [imgval]="val"

Body:
My code,

  <modal *ngIf='showModal' [imageValue]="imageId"></modal>

My model component,

@Component({
  selector: 'modal',
  templateUrl: './app/modal/modal.component.html',
  providers: [HeaderClass]
})

export class ModalComponent  {
  imageValue:any;

I want to get the value of this 'imageValue' but I dont know how to do it.Can anyone please help me.Thanks.


问:
overload of template template function - explicit call
So, first consider the following where template parameters are known implicitly from the function arguments:

```<code>#include <iostream>
using namespace std;

class A {};
class B {};

template <class T1, class T2>
class C {
    T1 a;
    T2 b;
};

template <class T1>
class D {
    T1 a;
};

template <template<class, class> class TC, class TA, class TB>
void foo(TC<TA, TB> c) {
    std::cout << "T<T,T>" << std::endl;
};

template <template<class> class TD, class TA>
void foo(TD<TA> d){
    std::cout << "T<T>" << std::endl;
};

int main() {
    C<A,B> c;
    D<A> d;

    foo(c);
    foo(d);
}
</code>```

And output is as you'd expect:

```<code>T<T,T>
T<T>
</code>```

However, what if I don't have an instance of class C and D so I need to explicitly call the correct overload?  How would this be done?  i.e., have a main() that consists of:

```<code>int main() {
    foo<C<A,B> >();
    foo<D<A> >();
}
</code>```

I've experimented with a few overloads of foo() as shown below:

```<code>template <template<class, class> class TC>
void foo() {
    std::cout << "T<T,T>" << std::endl;
};

template <template<class> class TD>
void foo(){
    std::cout << "T<T>" << std::endl;
};

template <template<class, class> class TC, class TA, class TB>
void foo() {
    std::cout << "T<T,T>" << std::endl;
};

template <template<class> class TD, class TA>
void foo(){
    std::cout << "T<T>" << std::endl;
};
</code>```

However, this (and all permutations I've been able to think of) simply results in a series of errors along the lines of the (abbreviated) output shown below

```<code>prog.cpp: In function 'int main()':
prog.cpp:44:18: error: no matching function for call to 'foo()'
     foo<C<A,B> >();
                  ^
prog.cpp:44:18: note: candidates are:
prog.cpp:19:6: note: template<template<class, class> class TC> void foo()
 void foo() {
      ^
prog.cpp:19:6: note:   template argument deduction/substitution failed:
prog.cpp:24:6: note: template<template<class> class TD> void foo()
 void foo(){
      ^
prog.cpp:24:6: note:   template argument deduction/substitution failed:
</code>```

Is what I'm looking to do even allowable?  If so, where am I messing up?

---- EDIT ----

So as apple apple pointed out if my main() is as follows:

```<code>int main() {
    foo<C, A, B>();
    foo<D, A>();
}
</code>```

I get the output as expected.

However, my real-world case winds up being more complex.  I'll expand a bit here.  The legacy code has (hundreds) of typedefs defined in headers elsewhere along the lines of:

```<code>typedef C<A, B> type_117;
typedef D<A>    type_252;
</code>```

The class I'm working on is templated and is instantiated with one of those typedefs as the templating argument.  So something along the lines of:

```<code>template <class Type>
class Test
{
public:
   Test();
   SomeClass mSC;
}
Test::Test()
  : mSC(foo<Type>())
{
};
</code>```

where Test was instantiated as

```<code>Test<type_117> aTest;
</code>```

So I've been trying to figure out how to write foo() for this context.  At the point I call foo() within my Test's initializer am I able to "decompose" it to produce the <C,A,B> form?  Or have I hit a roadblock and need to rework some of the existing framework?

答:
Take in count that partial specialization is forbidden for functions; so is difficult to do what do you exactly asked.

The suggestion from apple apple (chenge the calling as foo<C, A, B>() is a good one but, if you want to maintain the original call (foo<C>()) you can use the fact that the partial specialization is allowed for structs/classes and create a partial specialization for a functor; something like

```<code>template <typename>
struct bar;

template <template<typename, typename> class Tc, typename Ta, typename Tb>
struct bar<Tc<Ta,Tb>>
 {
   void operator() ()
    { std::cout << "bar<Tc<Ta, Tb>>()" << std::endl; }
 };

template <template<typename> class Tc, typename Ta>
struct bar<Tc<Ta>>
 {
   void operator() ()
    { std::cout << "bar<Tc<Ta>>()" << std::endl; }
 };
</code>```

The problem (?) is that, calling it, you can't call as bar<C>() od bar<D>() but you have to add a couple of parentheses:

```<code>bar<C<A,B>>()();
bar<D<A>>()();
</code>```

or

```<code>bar<C<A,B>>{}();
bar<D<A>>{}();
</code>```

I suppose that the functor solution can solve also the problem of the Edit part of your question.

If the added couple of parentheses is a problem, you can (as suggested by Jarod42 (thanks!)) wrap the call in a template function, as follows

```<code>template <typename T>
void bar ()
 { bar<T>{}(); }
</code>```

So you can call the bar<C>() function and manage the call in the specialized bar<C> struct.

Observe also the solution from Jarod42: depending on your requirements, you could develop only a version of the partial specialization of bar.

-- EDIT --

The OP ask

I'm not that familiar with partial specialization; could you expand a bit on how what I was trying was?

Specialization (partial and full) is a big, big topic.

Just some example, to give an idea.

Given a template class/struct

```<code>template <typename X, typename Y>
struct foo
 { };
</code>```

you can partial specialize it as follows (by example)

```<code>template <typename X>
struct foo<X, X>
 { };
</code>```

when the specialization maintain a template variable, or you can full specialize as follow (by example)

```<code>template <>
struct foo<int, long>
 { };
</code>```

where all template argument are fixed.

Well: with function you can full specialize but not partial specialize.

So you can write a template function

```<code> template <typename X, template Y>
 void foo ()
  { }
</code>```

and full specialize it

```<code> template <>
 void foo<int, long> ()
  { }
</code>```

but you can't partial specialize it; so you can't write (is an error)

```<code> template <typename X>
 void foo<X, X> ()
  { }
</code>```

Body:
So, first consider the following where template parameters are known implicitly from the function arguments:

#include <iostream>
using namespace std;

class A {};
class B {};

template <class T1, class T2>
class C {
    T1 a;
    T2 b;
};

template <class T1>
class D {
    T1 a;
};

template <template<class, class> class TC, class TA, class TB>
void foo(TC<TA, TB> c) {
    std::cout << "T<T,T>" << std::endl;
};

template <template<class> class TD, class TA>
void foo(TD<TA> d){
    std::cout << "T<T>" << std::endl;
};

int main() {
    C c;
    D d;

    foo(c);
    foo(d);
}

And output is as you'd expect:

T<T,T>
T<T>

However, what if I don't have an instance of class C and D so I need to explicitly call the correct overload?  How would this be done?  i.e., have a main() that consists of:

int main() {
    foo<C >();
    foo<D >();
}

I've experimented with a few overloads of foo() as shown below:

template <template<class, class> class TC>
void foo() {
    std::cout << "T<T,T>" << std::endl;
};

template <template<class> class TD>
void foo(){
    std::cout << "T<T>" << std::endl;
};

template <template<class, class> class TC, class TA, class TB>
void foo() {
    std::cout << "T<T,T>" << std::endl;
};

template <template<class> class TD, class TA>
void foo(){
    std::cout << "T<T>" << std::endl;
};

However, this (and all permutations I've been able to think of) simply results in a series of errors along the lines of the (abbreviated) output shown below

prog.cpp: In function 'int main()':
prog.cpp:44:18: error: no matching function for call to 'foo()'
     foo<C >();
                  ^
prog.cpp:44:18: note: candidates are:
prog.cpp:19:6: note: template<template<class, class> class TC> void foo()
 void foo() {
      ^
prog.cpp:19:6: note:   template argument deduction/substitution failed:
prog.cpp:24:6: note: template<template<class> class TD> void foo()
 void foo(){
      ^
prog.cpp:24:6: note:   template argument deduction/substitution failed:

Is what I'm looking to do even allowable?  If so, where am I messing up?

---- EDIT ----

So as apple apple pointed out if my main() is as follows:

int main() {
    foo<C, A, B>();
    foo<D, A>();
}

I get the output as expected.

However, my real-world case winds up being more complex.  I'll expand a bit here.  The legacy code has (hundreds) of typedefs defined in headers elsewhere along the lines of:

typedef C type_117;
typedef D    type_252;

The class I'm working on is templated and is instantiated with one of those typedefs as the templating argument.  So something along the lines of:

template <class Type>
class Test
{
public:
   Test();
   SomeClass mSC;
}
Test::Test()
  : mSC(foo<Type>())
{
};

where Test was instantiated as

Test<type_117> aTest;

So I've been trying to figure out how to write foo() for this context.  At the point I call foo() within my Test's initializer am I able to "decompose" it to produce the <C,A,B> form?  Or have I hit a roadblock and need to rework some of the existing framework?

Body:
Take in count that partial specialization is forbidden for functions; so is difficult to do what do you exactly asked.

The suggestion from apple apple (chenge the calling as foo<C, A, B>() is a good one but, if you want to maintain the original call (foo<C<A, B>>()) you can use the fact that the partial specialization is allowed for structs/classes and create a partial specialization for a functor; something like

template <typename>
struct bar;

template <template<typename, typename> class Tc, typename Ta, typename Tb>
struct bar<Tc<Ta,Tb>>
 {
   void operator() ()
    { std::cout << "bar<Tc<Ta, Tb>>()" << std::endl; }
 };

template <template<typename> class Tc, typename Ta>
struct bar<Tc<Ta>>
 {
   void operator() ()
    { std::cout << "bar<Tc<Ta>>()" << std::endl; }
 };

The problem (?) is that, calling it, you can't call as bar<C<A,B>>() od bar<D<A>>() but you have to add a couple of parentheses:

bar<C<A,B>>()();
bar<D<A>>()();

or

bar<C<A,B>>{}();
bar<D<A>>{}();

I suppose that the functor solution can solve also the problem of the Edit part of your question.

If the added couple of parentheses is a problem, you can (as suggested by Jarod42 (thanks!)) wrap the call in a template function, as follows

template <typename T>
void bar ()
 { bar<T>{}(); }

So you can call the bar<C<A, B>>() function and manage the call in the specialized bar<C<A, B>> struct.

Observe also the solution from Jarod42: depending on your requirements, you could develop only a version of the partial specialization of bar.

-- EDIT --

The OP ask

I'm not that familiar with partial specialization; could you expand a bit on how what I was trying was?

Specialization (partial and full) is a big, big topic.

Just some example, to give an idea.

Given a template class/struct

template <typename X, typename Y>
struct foo
 { };

you can partial specialize it as follows (by example)

template <typename X>
struct foo<X, X>
 { };

when the specialization maintain a template variable, or you can full specialize as follow (by example)

template <>
struct foo<int, long>
 { };

where all template argument are fixed.

Well: with function you can full specialize but not partial specialize.

So you can write a template function

 template <typename X, template Y>
 void foo ()
  { }

and full specialize it

 template <>
 void foo<int, long> ()
  { }

but you can't partial specialize it; so you can't write (is an error)

 template <typename X>
 void foo<X, X> ()
  { }


问:
String types not allowed (at 'spacing' with value '8db')
This is my first question. Beforehand, excuse my poor english. I want to ask you, because I have had problems with this bug for several days until now. Thanks. This line is in the file values.xml

<dimen name="spacing">8db</dimen>

Then, when the project is syncing with Gradle, it does appear this error.

```<code>String types not allowed (at 'spacing' with value '8db').
</code>```

Help me, please. :)

答: Here, you need to change "8db" to "8dp": <dimen name="spacing">8dp</dimen>

Body:
This is my first question. Beforehand, excuse my poor english. I want to ask you, because I have had problems with this bug for several days until now. Thanks. This line is in the file values.xml

<dimen name="spacing">8db</dimen>

Then, when the project is syncing with Gradle, it does appear this error.

String types not allowed (at 'spacing' with value '8db').

Help me, please. :)


问:
How do I alert the latitude in this Google Maps javascript?
As you can see, there is a line in there that does an alert. It's "undefined".  Whereas if I just alert results[0].geometry.location, it alerts (41.321, 41.556).

I just want to alert it and set it (as an int) to one of my id_lat and id_longs...

```<code>$("#geocodesubmit").click(function(){
        $("#id_lat").val("");
        $("#id_long").val("");
        var address = $("#addressinput").val();
        geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            $("#badlocation_holder").hide();
            $("#map_canvas").show();
            $("#map_canvas_holder").show().css("background-color", "#E6E6FA").animate({"background-color":"#f5f5f5"}, 800);
            ;
            var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            map.setCenter(results[0].geometry.location);

            alert(results[0].geometry.location[1]); //this is undefined.

            $("#id_lat").val(results[0].geometry.location[0]);
            $("#id_long").val(results[0].geometry.location[1]);

            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location,
                draggable:true
            });
          } else {
              $("#map_canvas_holder").hide();
              $("#badlocation_holder").show().css("background-color","#F08080").animate(
              {"background-color":"#f5f5f5"},800);
          }
        });
        return false;
    });
</code>```

答: Use results[0].geometry.location.lat() to get the latitude and results[0].geometry.location.lng() for the longitude.

ContentLicense: CC BY-SA 2.5

Body:
As you can see, there is a line in there that does an alert. It's "undefined".  Whereas if I just alert results[0].geometry.location, it alerts (41.321, 41.556).

I just want to alert it and set it (as an int) to one of my id_lat and id_longs...

$("#geocodesubmit").click(function(){
        $("#id_lat").val("");
        $("#id_long").val("");
        var address = $("#addressinput").val();
        geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            $("#badlocation_holder").hide();
            $("#map_canvas").show();
            $("#map_canvas_holder").show().css("background-color", "#E6E6FA").animate({"background-color":"#f5f5f5"}, 800);
            ;
            var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            map.setCenter(results[0].geometry.location);

            alert(results[0].geometry.location[1]); //this is undefined.

            $("#id_lat").val(results[0].geometry.location[0]);
            $("#id_long").val(results[0].geometry.location[1]);

            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location,
                draggable:true
            });
          } else {
              $("#map_canvas_holder").hide();
              $("#badlocation_holder").show().css("background-color","#F08080").animate(
              {"background-color":"#f5f5f5"},800);
          }
        });
        return false;
    });