问:
Objects are not valid as a React child (found: object with keys)
I create a component like so:

```<code>let bList = bObj.map((obj, index) => {
        let {
            icon, htmlType, onClick } = obj;

        let _b = <Button
                    htmlType = { htmlType }
                    icon = { icon }
                    onClick = { () => {this._onClick()} } />

        if(someVar) {
            return (
                <AnotherComp style = { someVar }
                    key = { index } >
                    { _b }
                </AnotherComp>
            );

        } else {
            return (
                { _b }
            );
        }
    });

bList =
    <div style = { wrap }>
        <myComp style = { grp }>
            { buttonsList }
        </myComp>
    </div>

return bList;
</code>```

That returns me

Uncaught Error: Objects are not valid as a React child (found: object with keys {_bu}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of MyComp.

However, when I write it like this:

```<code>let bList = bObj.map((obj, index) => {
        let {
            icon, htmlType, onClick } = obj;

        if(someVar) {
            return (
                <AnotherComp style = { someVar }
                    key = { index } >
                    <Button
                        htmlType = { htmlType }
                        icon = { icon }
                        onClick = { () => {this._onClick()} } />
                </AnotherComp>
            );

        } else {
            return (
                <Button
                    htmlType = { htmlType }
                    icon = { icon }
                    onClick = { () => {this._onClick()} } />
            );
        }
    });

bList =
    <div style = { wrap }>
        <MyComp style = { grp }>
            { buttonsList }
        </MyComp>
    </div>

return bList;
</code>```

It works. Where is the difference between saving <Button ../> in a variable and writing it in there directly?!

答:
Difference is you are using extra {}, remove that it will work:

```<code>return  _b;
</code>```

Meaning of return ({ _b }) is:

```<code>return ({'_b' : _b});
</code>```

That means you are returning an object with key _b, not the JSX.

Check this snippet:

let a = 5;

let b = { a };

console.log('b = ', b);```

Body:
I create a component like so:

let bList = bObj.map((obj, index) => {
        let {
            icon, htmlType, onClick } = obj;

        let _b = <Button
                    htmlType = { htmlType }
                    icon = { icon }
                    onClick = { () => {this._onClick()} } />

        if(someVar) {
            return (
                <AnotherComp style = { someVar }
                    key = { index } >
                    { _b }
                </AnotherComp>
            );

        } else {
            return (
                { _b }
            );
        }
    });

bList =

        <myComp style = { grp }>
            { buttonsList }
        </myComp>

return bList;

That returns me

Uncaught Error: Objects are not valid as a React child (found: object with keys {_bu}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of MyComp.

However, when I write it like this:

let bList = bObj.map((obj, index) => {
        let {
            icon, htmlType, onClick } = obj;

        if(someVar) {
            return (
                <AnotherComp style = { someVar }
                    key = { index } >
                    <Button
                        htmlType = { htmlType }
                        icon = { icon }
                        onClick = { () => {this._onClick()} } />
                </AnotherComp>
            );

        } else {
            return (
                <Button
                    htmlType = { htmlType }
                    icon = { icon }
                    onClick = { () => {this._onClick()} } />
            );
        }
    });

bList =

        <MyComp style = { grp }>
            { buttonsList }
        </MyComp>

return bList;

It works. Where is the difference between saving <Button ../> in a variable and writing it in there directly?!

Body:
Difference is you are using extra {}, remove that it will work:

return  _b;

Meaning of return ({ _b }) is:

return ({'_b' : _b});

That means you are returning an object with key _b, not the JSX.

Check this snippet:

let a = 5;

let b = { a };

console.log('b = ', b);


来源: stackexchange

问:
i can't hold old entries
```<code>#include <stdio.h>
#include <stdlib.h>

void push(int p)
{
    static int i=0;
    int b;
    int *ptr =(int *)malloc((10)*sizeof(int));
    ptr[i]=p;
    for(b=0;b<=i;b++){
    printf("%d",ptr[b]);
    printf("\n");
    }
    i++;
}
int main()
{
    int a;
    while(1)
    {
    scanf("%d",&a);
    push(a);
    }
}
</code>```

When i put new values , function is not hold old entries.I wait for your helps.

答:
```<code>#include <stdio.h>
#include <stdlib.h>

void push(int p)
{
    static int i = 0;
    static int ptr[10]; // since you are NOT freeing this memory later,
                        // there's no need to use malloc.
    ptr[i] = p;

    int b;
    for (b = 0; b <= i; b++)
    {
        printf("ptr[%d] --> %d\n", b, ptr[b]);
    }

    printf("\n");

    i++;
}

int main()
{
    int a;
    while(1)
    {
        scanf("%d",&a);
        push(a);
    }

    return 0;  // main() expects you to return something, remember?
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: i can't hold old entries

Body:
#include <stdio.h>
#include <stdlib.h>

void push(int p)
{
    static int i=0;
    int b;
    int *ptr =(int *)malloc((10)*sizeof(int));
    ptr[i]=p;
    for(b=0;b<=i;b++){
    printf("%d",ptr[b]);
    printf("\n");
    }
    i++;
}
int main()
{
    int a;
    while(1)
    {
    scanf("%d",&a);
    push(a);
    }
}

When i put new values , function is not hold old entries.I wait for your helps.


问:
The target “ResolveWebJobFiles” does not exist in the project in Azure Website
I have a Windows Azure project consisting of

ASP.NET project (using NancyFX) deployed as Azure Website

Business Logic class library

Unit test class library

2 Console apps

I want those 2 console app to be deployed as Azure WebJobs with the Azure Website. So I right clikec on the ASP.NET project and chose Add | Existing project as Azure WebJob and added both console apps with the right schedule.

Everything seems fine, the 2 console apps now contain a JSON with schedule and the ASP.NET project contains a JSON with WebJobs definition. All the project build just fine.

The problem is, when I try to deploy the ASP.NET project to Azure, I get

```<code>The target “ResolveWebJobFiles” does not exist in the project
</code>```

I found this article when the author solved this problem by adding

```<code><Import Project="..\packages\Microsoft.Web.WebJobs.Publish.1.0.2\tools\webjobs.targets" Condition="Exists('..\packages\Microsoft.Web.WebJobs.Publish.1.0.2\tools\webjobs.targets')" />
</code>```

to his csproj file, but my csproj file for the ASP.NET project already contains this import.

Any ideas what the problem is?

答:
One primary reason could be missing "webjob-publish-settings.json" file in Properties.

Please double check this file exists and included in your project.

ContentLicense: CC BY-SA 3.0

Body:
I have a Windows Azure project consisting of

ASP.NET project (using NancyFX) deployed as Azure Website

Business Logic class library

Unit test class library

2 Console apps

I want those 2 console app to be deployed as Azure WebJobs with the Azure Website. So I right clikec on the ASP.NET project and chose Add | Existing project as Azure WebJob and added both console apps with the right schedule.

Everything seems fine, the 2 console apps now contain a JSON with schedule and the ASP.NET project contains a JSON with WebJobs definition. All the project build just fine.

The problem is, when I try to deploy the ASP.NET project to Azure, I get

The target “ResolveWebJobFiles” does not exist in the project

I found this article when the author solved this problem by adding

<Import Project="..\packages\Microsoft.Web.WebJobs.Publish.1.0.2\tools\webjobs.targets" Condition="Exists('..\packages\Microsoft.Web.WebJobs.Publish.1.0.2\tools\webjobs.targets')" />

to his csproj file, but my csproj file for the ASP.NET project already contains this import.

Any ideas what the problem is?


问:
dynamic_cast to derived type with unknown template argument
I would like to dynamic_cast to a templated derived type, with unknown template argument:

```<code>struct A {
    virtual void f() { };
};

template <std::size_t N>
struct B : public A { };
</code>```

With the known template argument the cast can be performed as:

```<code>const A& base_ref = B<N>();
const B<N>& ref = dynamic_cast<const B<N>&>(base_ref);
</code>```

My question is about the case where the value of the template argument (N) is not known.

I was wondering if there is a way to obtain the object type, in this case B<N> from the base class pointer/reference, such that the dynamic_cast template parameter can be inferred automatically?

P.S. In the considered case the template argument is an integer type, and is used as a template parameter for an std::array.

答:
OK, this is going to be nasty.

You can automate the lookup of a valid dynamic cast, if:

You cap the maximum value of N in B<N> to a value your compiler will be happy with.

You provide a visitor taking a template argument in order to action the result of a successful cast.

You don't mind sequential lookups (although further work here[1] would involve building a cache of successful lookups to improve runtime).

[1] further work would obviously be a waste of time. The time would be better spent working on a better design.

```<code>#include <type_traits>
#include <vector>
#include <iostream>
#include <utility>
#include <array>
#include <algorithm>
#include <stdexcept>

struct A
{
    virtual ~A() = default;
};

template<std::size_t N>
struct B : A
{

};

template<std::size_t I>
struct cast_test
{
    static bool test(A* p) {
        return dynamic_cast<B<I>*>(p) != nullptr;
    }
};

template<std::size_t...Is>
constexpr auto make_cast_tests(std::index_sequence<Is...>)
{
    return std::array<bool(*)(A*), sizeof...(Is)> {
        &cast_test<Is>::test...
    };
}

template<class Visitor, std::size_t I>
struct caller
{
    // figuring out a common return type is a whole new challenge...
    static void call(Visitor& visitor, A* p) {
        return visitor(static_cast<B<I>*>(p));
    }
};

template<class Visitor, std::size_t...Is>
constexpr auto make_callers(std::index_sequence<Is...>)
{
    return std::array<void(*)(Visitor&, A*), sizeof...(Is)> {
        &caller<Visitor, Is>::call...
    };
}

template<std::size_t N, class Visitor, class sequence_type = std::make_index_sequence<N>>
decltype(auto) dynamic_visit(Visitor&& visitor, A*p)
{
    constexpr auto tests = make_cast_tests(sequence_type());
    auto ipos = std::find_if(std::begin(tests), std::end(tests), [&p](auto&& f){ return f(p); });
    if (ipos == std::end(tests))
    {
        throw std::logic_error("increase the range of N");
    }

    constexpr auto callers = make_callers<Visitor>(sequence_type());
    auto icaller = std::begin(callers) + std::distance(std::begin(tests), ipos);
    return (*icaller)(visitor, p);
}

struct visitor
{
    template<std::size_t I>
    void operator()(B<I>* p) const
    {
        std::cout << "I is " << I << std::endl;
    }

};

auto make_an_A(int argc) -> A*
{
    if (argc > 1) {
        return new B<6>;
    }
    else {
        return new B<7>;
    }
}
int main(int argc, char** argv)
{
    A* p = make_an_A(argc);
    dynamic_visit<100>(visitor(), p);
}
</code>```

expected result when invoked with ./a.out:

```<code>I is 7
</code>```

expected result when invoked with ./a.out "foo":

```<code>I is 6
</code>```

Body:
I would like to dynamic_cast to a templated derived type, with unknown template argument:

struct A {
    virtual void f() { };
};

template <std::size_t N>
struct B : public A { };

With the known template argument the cast can be performed as:

const A& base_ref = B<N>();
const B<N>& ref = dynamic_cast<const B<N>&>(base_ref);

My question is about the case where the value of the template argument (N) is not known.

I was wondering if there is a way to obtain the object type, in this case B<N> from the base class pointer/reference, such that the dynamic_cast template parameter can be inferred automatically?

P.S. In the considered case the template argument is an integer type, and is used as a template parameter for an std::array.

Body:
OK, this is going to be nasty.

You can automate the lookup of a valid dynamic cast, if:

You cap the maximum value of N in B<N> to a value your compiler will be happy with.

You provide a visitor taking a template argument in order to action the result of a successful cast.

You don't mind sequential lookups (although further work here[1] would involve building a cache of successful lookups to improve runtime).

[1] further work would obviously be a waste of time. The time would be better spent working on a better design.

#include <type_traits>
#include <vector>
#include <iostream>
#include <utility>
#include <array>
#include <algorithm>
#include <stdexcept>

struct A
{
    virtual ~A() = default;
};

template<std::size_t N>
struct B : A
{

};

template<std::size_t I>
struct cast_test
{
    static bool test(A* p) {
        return dynamic_cast<B<I>*>(p) != nullptr;
    }
};

template<std::size_t...Is>
constexpr auto make_cast_tests(std::index_sequence<Is...>)
{
    return std::array<bool(*)(A*), sizeof...(Is)> {
        &cast_test<Is>::test...
    };
}

template<class Visitor, std::size_t I>
struct caller
{
    // figuring out a common return type is a whole new challenge...
    static void call(Visitor& visitor, A* p) {
        return visitor(static_cast<B<I>*>(p));
    }
};

template<class Visitor, std::size_t...Is>
constexpr auto make_callers(std::index_sequence<Is...>)
{
    return std::array<void(*)(Visitor&, A*), sizeof...(Is)> {
        &caller<Visitor, Is>::call...
    };
}

template<std::size_t N, class Visitor, class sequence_type = std::make_index_sequence<N>>
decltype(auto) dynamic_visit(Visitor&& visitor, A*p)
{
    constexpr auto tests = make_cast_tests(sequence_type());
    auto ipos = std::find_if(std::begin(tests), std::end(tests), [&p](auto&& f){ return f(p); });
    if (ipos == std::end(tests))
    {
        throw std::logic_error("increase the range of N");
    }

    constexpr auto callers = make_callers<Visitor>(sequence_type());
    auto icaller = std::begin(callers) + std::distance(std::begin(tests), ipos);
    return (*icaller)(visitor, p);
}

struct visitor
{
    template<std::size_t I>
    void operator()(B<I>* p) const
    {
        std::cout << "I is " << I << std::endl;
    }

};

auto make_an_A(int argc) -> A*
{
    if (argc > 1) {
        return new B<6>;
    }
    else {
        return new B<7>;
    }
}
int main(int argc, char** argv)
{
    A* p = make_an_A(argc);
    dynamic_visit<100>(visitor(), p);
}

expected result when invoked with ./a.out:

I is 7

expected result when invoked with ./a.out "foo":

I is 6


问:
Change mongo document's id via spring
Is there a way to modify the id of all documents in a Mongo collection with spring mongo?

Trying this in many ways I got error messages like:

```<code>the (immutable) field '_id' was found to have been altered to _id
</code>```

or

```<code>Write errors: [BulkWriteError{index=0, code=16837, message='The _id field cannot be changed from {_id: "xyz"} to {_id: "zxy"}.
</code>```

Is there a way to do this?

答: No, you are not allowed to update the _id field. But you can always set a brand new _id to an existing doc and remove the older _id. </p>

Title: Change mongo document's id via spring

Body:
Is there a way to modify the id of all documents in a Mongo collection with spring mongo?

Trying this in many ways I got error messages like:

the (immutable) field '_id' was found to have been altered to _id

or

Write errors: [BulkWriteError{index=0, code=16837, message='The _id field cannot be changed from {_id: "xyz"} to {_id: "zxy"}.

Is there a way to do this?


问:
Calling Fragment method from Parent Activity
I want to invoke a (tabbed)fragment method to bring the data to activity.

I read this

But I get null object reference

I tried this

But my activity is already implementing the fragment class so it's not a legal expression

So when the tab is changed I want the form of the first tab to send to details to Activity by getDetails() method

```<code>        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            if (tab.getText().equals("Owner")) {
                //invoking method here
                Log.i(TAG, tab.getText().toString() + " unselected");
            }
</code>```

I tried with FragmentManager but no luck, Please help!

EDIT- This is the method I want to invoke

```<code>public Bundle getData() {
    Bundle bundle = new Bundle();
    bundle.putString("area", area);
    bundle.putString("villageTown", villageTown.getSelectedItem().toString());
    bundle.putString("ownerName", ownerName);
    bundle.putString("fatherHusbandName", fatherHusbandName);
    bundle.putString("category", category.getSelectedItem().toString());
    bundle.putString("address", address);
    bundle.putString("mobileNumber", mobileNumber);
    bundle.putString("telephoneNumber", telephoneNumber);

    return bundle;
}
</code>```

答:
I would highly suggest keeping the fragments logic in fragment. Fragment invoking a class from activity can be done with many ways, like interfaces. But, Activity calling a method of fragments will cause problems.When you especially try to reach a fragment's method which is not shown on screen.

Still, you can write your data to shared preferences from fragment when form is filled, and when onTabUnselected called you can read data from shared preferences in your activity. I accept that it is not a nice solution. I hope I understood your problem correctly.

Body:
I want to invoke a (tabbed)fragment method to bring the data to activity.

I read this

But I get null object reference

I tried this

But my activity is already implementing the fragment class so it's not a legal expression

So when the tab is changed I want the form of the first tab to send to details to Activity by getDetails() method

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            if (tab.getText().equals("Owner")) {
                //invoking method here
                Log.i(TAG, tab.getText().toString() + " unselected");
            }

I tried with FragmentManager but no luck, Please help!

EDIT- This is the method I want to invoke

public Bundle getData() {
    Bundle bundle = new Bundle();
    bundle.putString("area", area);
    bundle.putString("villageTown", villageTown.getSelectedItem().toString());
    bundle.putString("ownerName", ownerName);
    bundle.putString("fatherHusbandName", fatherHusbandName);
    bundle.putString("category", category.getSelectedItem().toString());
    bundle.putString("address", address);
    bundle.putString("mobileNumber", mobileNumber);
    bundle.putString("telephoneNumber", telephoneNumber);

    return bundle;
}


问:
model name don't want to override if a same model name using in different fields
I have model and I am binding for two sides. First side is inside of the html p tag.
second side is textarea.
when i change the textarea, inside of the p changes too.
How can i change only textarea?</p>

```<code><div class="title-content">
  <p>{{currentNew.Title}}</p>
</div>
<textarea class="title-textarea" ng-model="currentNew.Title" maxlength="70" style="display:none"></textarea>
</code>```

答:
It is because, you are binding the same scope with textarea and p tag. In angular if we are defining any scope variable and if any change occurs in that scope variable ,it reflects everywhere on the page.

So either you have to use another variable name or you have to use one way data binding of angularJs

Body:
I have model and I am binding for two sides. First side is inside of the html p tag.
second side is textarea.
when i change the textarea, inside of the p changes too.
How can i change only textarea?

{{currentNew.Title}}

<textarea class="title-textarea" ng-model="currentNew.Title" maxlength="70" style="display:none"></textarea>


问:
mongoose- how to sort on multi criteria w population
I am trying to sort a 'role' document populated with 'group.name' first on group.name then on role.name

```<code>return this.find(query, { _group: 1, name: 1, _id:0 } )
  .populate('_group', 'name -_id')
  .sort({ '_group.name': 1, name: 1 })
</code>```

but it does not work as expected , I get sorted only on role.name

```<code>ROLES:[
{"name":"NewRole"},
{"name":"NewRoleInGroup","_group":{"name":"GroupA"}},
{"_group":{"name":"GroupA"},"name":"admin"},
{"_group":{"name":"GroupA"},"name":"employee"},
{"_group":{"name":"GroupB"},"name":"employee"},
{"_group":{"name":"GroupC"},"name":"employee"},
{"_group":{"name":"GroupA"},"name":"manager"},
{"_group":{"name":"GroupB"},"name":"manager"},
{"name":"visitor"}
]
</code>```

I would like to get rather:

```<code>ROLES:[
// NO GROUP
{"name":"NewRole"},
{"name":"visitor"}.
// GroupA
{"_group":{"name":"GroupA"},"name":"admin"},
{"_group":{"name":"GroupA"},"name":"employee"},
{"_group":{"name":"GroupA"},"name":"manager"},
{"name":"NewRoleInGroup","_group":{"name":"GroupA"}},
// GroupB
{"_group":{"name":"GroupB"},"name":"employee"},
{"_group":{"name":"GroupB"},"name":"manager"},
// GroupC
{"_group":{"name":"GroupC"},"name":"employee"}
]
</code>```

Thanks for feedback

UPDATE
As per @Talha comment :

Using aggregate , I am close to what I need... however , I get the group data inside an array, in a many-to-one relationship  there is only one group in this case ... how to project the group as the first object in the array :  "group": {}  or "group": {"name"; ..., "description": ...} ?

```<code>  return this.aggregate([
    { $match: query},
    {
      $lookup: {
        from: 'groups',
        localField: '_group',
        foreignField: '_id',
        as: 'group'
      }
    }
    ,
    {
      $project: {
        'group.name': 1,
        'group.description': 1,
        name: 1,
        description: 1,
        _id: 0
      }
    },
    { $sort: { 'name': 1 } },
    { $limit: limit },
    { $skip: skip }
  ])

 ROLES: [
// NO GROUP
{"name":"NewRole","description":"NewRole description","group":[]},
{"name":"Visitor","description":"no permissions","group":[]},
// GROUP A
{"name":"NewRoleInGroup","description":"NewRoleInGroup description","group":[{"name":"GroupA","description":"Description GroupA"}]},
{"name":"admin","description":"can RW group, user","group":[{"name":"GroupA","description":"Description GroupA"}]},
{"name":"employee","description":"can R group, can read user","group":[{"name":"GroupA","description":"Description GroupA"}]},
{"name":"manager","description":"can R group, can RW user","group":[{"name":"GroupA","description":"Description GroupA"}]},
// GROUP B
{"name":"employee","description":"can R group, can read user","group":[{"name":"GroupB","description":"Description GroupB"}]},
{"name":"manager","description":"can R group, can RW user","group":[{"name":"GroupB","description":"Description GroupB"}]},
// GROUP C
{"name":"employee","description":"can R group, can read user","group":[{"name":"GroupC","description":"Description GroupC"}]}]
</code>```

答:
I should use the following function w aggregate :

```<code>  return this.aggregate([
    { $match: query},
    {
      $lookup: {
        from: 'groups',
        localField: '_group',
        foreignField: '_id',
        as: 'group'
      }
    },
    {
      $project: {
        group: {
          $let:{
            vars:{
              firstGroup:{
                $arrayElemAt:["$group",0]
              }
            },
            in:{
              name:"$$firstGroup.name",
              description:"$$firstGroup.description"
            }
          }
        },
        name: 1,
        description: 1,
        _id: 0
      }
    },
    { $sort: { 'group.name': 1, 'name': 1 } },
    { $limit: limit },
    { $skip: skip }
  ])
  .exec()
  .then((list) => {
    return list;
  })
</code>```

This output the correctly ordered list ( 1/ by group.name 2/ ny role.name ) with the group out of the lookup output array :

```<code>ROLES: [
// NO GROUP
{"name":"NewRole","description":"NewRole description","group":{}},
{"name":"Visitor","description":"no permissions","group":{}},
// GROUP A
{"name":"NewRoleInGroup","description":"NewRoleInGroup description","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"admin","description":"can RW group, user","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"manager","description":"can R group, can RW user","group":{"name":"GroupA","description":"Description GroupA"}},
// GROUP B
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupB","description":"Description GroupB"}},
{"name":"manager","description":"can R group, can RW user","group":{"name":"GroupB","description":"Description GroupB"}},
// GROUP C
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupC","description":"Description GroupC"}}]
</code>```

Body:
I am trying to sort a 'role' document populated with 'group.name' first on group.name then on role.name

return this.find(query, { _group: 1, name: 1, _id:0 } )
  .populate('_group', 'name -_id')
  .sort({ '_group.name': 1, name: 1 })

but it does not work as expected , I get sorted only on role.name

ROLES:[
{"name":"NewRole"},
{"name":"NewRoleInGroup","_group":{"name":"GroupA"}},
{"_group":{"name":"GroupA"},"name":"admin"},
{"_group":{"name":"GroupA"},"name":"employee"},
{"_group":{"name":"GroupB"},"name":"employee"},
{"_group":{"name":"GroupC"},"name":"employee"},
{"_group":{"name":"GroupA"},"name":"manager"},
{"_group":{"name":"GroupB"},"name":"manager"},
{"name":"visitor"}
]

I would like to get rather:

ROLES:[
// NO GROUP
{"name":"NewRole"},
{"name":"visitor"}.
// GroupA
{"_group":{"name":"GroupA"},"name":"admin"},
{"_group":{"name":"GroupA"},"name":"employee"},
{"_group":{"name":"GroupA"},"name":"manager"},
{"name":"NewRoleInGroup","_group":{"name":"GroupA"}},
// GroupB
{"_group":{"name":"GroupB"},"name":"employee"},
{"_group":{"name":"GroupB"},"name":"manager"},
// GroupC
{"_group":{"name":"GroupC"},"name":"employee"}
]

Thanks for feedback

UPDATE
As per @Talha comment :

Using aggregate , I am close to what I need... however , I get the group data inside an array, in a many-to-one relationship  there is only one group in this case ... how to project the group as the first object in the array :  "group": {}  or "group": {"name"; ..., "description": ...} ?

  return this.aggregate([
    { $match: query},
    {
      $lookup: {
        from: 'groups',
        localField: '_group',
        foreignField: '_id',
        as: 'group'
      }
    }
    ,
    {
      $project: {
        'group.name': 1,
        'group.description': 1,
        name: 1,
        description: 1,
        _id: 0
      }
    },
    { $sort: { 'name': 1 } },
    { $limit: limit },
    { $skip: skip }
  ])

 ROLES: [
// NO GROUP
{"name":"NewRole","description":"NewRole description","group":[]},
{"name":"Visitor","description":"no permissions","group":[]},
// GROUP A
{"name":"NewRoleInGroup","description":"NewRoleInGroup description","group":[{"name":"GroupA","description":"Description GroupA"}]},
{"name":"admin","description":"can RW group, user","group":[{"name":"GroupA","description":"Description GroupA"}]},
{"name":"employee","description":"can R group, can read user","group":[{"name":"GroupA","description":"Description GroupA"}]},
{"name":"manager","description":"can R group, can RW user","group":[{"name":"GroupA","description":"Description GroupA"}]},
// GROUP B
{"name":"employee","description":"can R group, can read user","group":[{"name":"GroupB","description":"Description GroupB"}]},
{"name":"manager","description":"can R group, can RW user","group":[{"name":"GroupB","description":"Description GroupB"}]},
// GROUP C
{"name":"employee","description":"can R group, can read user","group":[{"name":"GroupC","description":"Description GroupC"}]}]

Body:
I should use the following function w aggregate :

  return this.aggregate([
    { $match: query},
    {
      $lookup: {
        from: 'groups',
        localField: '_group',
        foreignField: '_id',
        as: 'group'
      }
    },
    {
      $project: {
        group: {
          $let:{
            vars:{
              firstGroup:{
                $arrayElemAt:["$group",0]
              }
            },
            in:{
              name:"$$firstGroup.name",
              description:"$$firstGroup.description"
            }
          }
        },
        name: 1,
        description: 1,
        _id: 0
      }
    },
    { $sort: { 'group.name': 1, 'name': 1 } },
    { $limit: limit },
    { $skip: skip }
  ])
  .exec()
  .then((list) => {
    return list;
  })

This output the correctly ordered list ( 1/ by group.name 2/ ny role.name ) with the group out of the lookup output array :

ROLES: [
// NO GROUP
{"name":"NewRole","description":"NewRole description","group":{}},
{"name":"Visitor","description":"no permissions","group":{}},
// GROUP A
{"name":"NewRoleInGroup","description":"NewRoleInGroup description","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"admin","description":"can RW group, user","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupA","description":"Description GroupA"}},
{"name":"manager","description":"can R group, can RW user","group":{"name":"GroupA","description":"Description GroupA"}},
// GROUP B
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupB","description":"Description GroupB"}},
{"name":"manager","description":"can R group, can RW user","group":{"name":"GroupB","description":"Description GroupB"}},
// GROUP C
{"name":"employee","description":"can R group, can read user","group":{"name":"GroupC","description":"Description GroupC"}}]


问:
Retrieving values from multiple keys in Firebase using AngularFire2
I am just getting started with angularFire2. I have some Firebase data structured as follows:

```<code>{
    "user-friends": {
        "-userkey1": {
            "-userkey2": true,
            "-userkey3": true
        }
    },

    "users": {
        "-userkey1": {
            "uid": "id1",
            "uname": "Jim Yu"
        },
        "-userkey2": {
            "uid": "id2",
            "uname": "Bob Smith"
        },
        "-userkey3": {
            "uid": "id3",
            "uname": "Jane Doe"
        }
    }
}
</code>```

So far, I can retrieve the data in user-friends node for -userkey1, which returns

```<code>   "-userkey1": {
        "-userkey2": true,
        "-userkey3": true
    }
</code>```

Then I want to be able to get theuname of each key, and store that in a variable that would be bind to the view.

I'm a bit unsure of how to go about that last step specifically using angularFire2..or if there is a angular/firebase specific approach/helper method to solving this.

so far this is what I have, however once I loop through each key and attempt to push the username into an array, the console logs the first keys uname but then screamscannot read property 'push' of undefined

```<code>userFriends(userkey: string){
    console.log("userKey=" + userkey)
    var getUsrFriends = this.afDB.list("https://myfirebaseurl.com/user-friends/" + userkey
    ).subscribe( data => {
        data.forEach(friendKey => {
            console.log(friendKey.$key) //my instinct tells me looping through the keys and storing in an array is not a optimal solution
            var getUserInfo = this.afDB.object("https:/myfirebaseurl.com/users/" + friendKey.$key, {
            }).subscribe( u => {
                console.log(u.uname)
                this.friendsList.push(u.uname) // <- undefined error
            })
        });
    })
}

<ng-container  *ngIf="showView == 'friend'">
    <ion-list *ngFor="let friend of friendsList">
        <h3>{{friend}}</h3>
    </ion-list>
</ng-container>
</code>```

EDIT:  The undefined error was actually caused by not initializing the friendsList Array properly.

```<code>export class UserPage {
  friendsList: string[] = []
 // constructor, etc
}
</code>```

答:
Firebase is really quick, so making multiple calls is not too bad.

Using your current data structure, this code will work:

```<code>// Outside firebase calls
let scope = this;

...
var getUserInfo = this.afDB.object("https:/myfirebaseurl.com/users/" + friendKey.$key, {}).take(1).subscribe( u => {
    console.log(u.uname)
    scope.friendsList.push(u.uname) // <- undefined error
})
...
</code>```

this, once inside the Firebase promise is reserved by that promise and means something different than the regularly reserved this of global component variables.

Also, use take(1) before the subscribe because you are only wanting to retrieve those values once and not to continue listening.

An alternate method would be to restructure your database to make faster queries in a tradeoff for more data storage. Instead of storing the just the user reference inside user-friends you can store the whole user. But I would advise the first option.

Body:
I am just getting started with angularFire2. I have some Firebase data structured as follows:

{
    "user-friends": {
        "-userkey1": {
            "-userkey2": true,
            "-userkey3": true
        }
    },

    "users": {
        "-userkey1": {
            "uid": "id1",
            "uname": "Jim Yu"
        },
        "-userkey2": {
            "uid": "id2",
            "uname": "Bob Smith"
        },
        "-userkey3": {
            "uid": "id3",
            "uname": "Jane Doe"
        }
    }
}

So far, I can retrieve the data in user-friends node for -userkey1, which returns

   "-userkey1": {
        "-userkey2": true,
        "-userkey3": true
    }

Then I want to be able to get theuname of each key, and store that in a variable that would be bind to the view.

I'm a bit unsure of how to go about that last step specifically using angularFire2..or if there is a angular/firebase specific approach/helper method to solving this.

so far this is what I have, however once I loop through each key and attempt to push the username into an array, the console logs the first keys uname but then screamscannot read property 'push' of undefined

userFriends(userkey: string){
    console.log("userKey=" + userkey)
    var getUsrFriends = this.afDB.list("https://myfirebaseurl.com/user-friends/" + userkey
    ).subscribe( data => {
        data.forEach(friendKey => {
            console.log(friendKey.$key) //my instinct tells me looping through the keys and storing in an array is not a optimal solution
            var getUserInfo = this.afDB.object("https:/myfirebaseurl.com/users/" + friendKey.$key, {
            }).subscribe( u => {
                console.log(u.uname)
                this.friendsList.push(u.uname) // <- undefined error
            })
        });
    })
}

<ng-container  *ngIf="showView == 'friend'">
    <ion-list *ngFor="let friend of friendsList">

{{friend}}

    </ion-list>
</ng-container>

EDIT:  The undefined error was actually caused by not initializing the friendsList Array properly.

export class UserPage {
  friendsList: string[] = []
 // constructor, etc
}

Body:
Firebase is really quick, so making multiple calls is not too bad.

Using your current data structure, this code will work:

// Outside firebase calls
let scope = this;

...
var getUserInfo = this.afDB.object("https:/myfirebaseurl.com/users/" + friendKey.$key, {}).take(1).subscribe( u => {
    console.log(u.uname)
    scope.friendsList.push(u.uname) // <- undefined error
})
...

this, once inside the Firebase promise is reserved by that promise and means something different than the regularly reserved this of global component variables.

Also, use take(1) before the subscribe because you are only wanting to retrieve those values once and not to continue listening.

An alternate method would be to restructure your database to make faster queries in a tradeoff for more data storage. Instead of storing the just the user reference inside user-friends you can store the whole user. But I would advise the first option.


问:
Numpy only integer scalar arrays can be converted to a scalar index - Upgrading to 3.6
So I'm reading in the .flo as I do some warping. Seems I have no issue with Python2.7 and numpy version 1.11.2, but when I upgrade to Python3.6 and numpy version 1.12.0.

But during the conversion, I know get an error only integer scalar arrays can be converted to a scalar index for the line data2d = np.fromfile(f, np.float32, count=2 * w * h)

```<code>import numpy as np

def read_flow(filename):
        f = open(filename, 'rb')
        magic = np.fromfile(f, np.float32, count=1)
        data2d = None

        if 202021.25 != magic:
            print('Magic number incorrect. Invalid .flo file')
        else:
            w = np.fromfile(f, np.int32, count=1)
            h = np.fromfile(f, np.int32, count=1)
            print("Reading %d x %d flo file" % (h, w))
            data2d = np.fromfile(f, np.float32, count=2 * w * h)
            # reshape data into 3D array (columns, rows, channels)
            data2d = np.resize(data2d, (h, w, 2))
        f.close()
        return data2d
</code>```

Example .flo file can be obtained here

答:
If I run your code using python 2.7 I get the following warning:

VisibleDeprecationWarning: converting an array with ndim > 0 to an index will result in an error in the future return reshape(newshape, order=order)

The reason for this is that np.fromfile() returns a numpy array containing the data instead of just the data - even for single elements. That means w = np.fromfile(f, np.int32, count=1) is something like [512] instead of 512.

The following version should work for python 2.7 and 3.x

```<code>import numpy as np
def read_flow(filename):
        f = open(filename, 'rb')
        magic = np.fromfile(f, np.float32, count=1)
        data2d = None

        if 202021.25 != magic:
            print('Magic number incorrect. Invalid .flo file')
        else:
            w = np.fromfile(f, np.int32, count=1)[0]
            h = np.fromfile(f, np.int32, count=1)[0]
            print("Reading %d x %d flo file" % (h, w))
            data2d = np.fromfile(f, np.float32, count=2 * w * h)
            # reshape data into 3D array (columns, rows, channels)
            data2d = np.resize(data2d, (h, w, 2))
        f.close()
        return data2d
</code>```

Body:
So I'm reading in the .flo as I do some warping. Seems I have no issue with Python2.7 and numpy version 1.11.2, but when I upgrade to Python3.6 and numpy version 1.12.0.

But during the conversion, I know get an error only integer scalar arrays can be converted to a scalar index for the line data2d = np.fromfile(f, np.float32, count=2 * w * h)

import numpy as np

def read_flow(filename):
        f = open(filename, 'rb')
        magic = np.fromfile(f, np.float32, count=1)
        data2d = None

        if 202021.25 != magic:
            print('Magic number incorrect. Invalid .flo file')
        else:
            w = np.fromfile(f, np.int32, count=1)
            h = np.fromfile(f, np.int32, count=1)
            print("Reading %d x %d flo file" % (h, w))
            data2d = np.fromfile(f, np.float32, count=2 * w * h)
            # reshape data into 3D array (columns, rows, channels)
            data2d = np.resize(data2d, (h, w, 2))
        f.close()
        return data2d

Example .flo file can be obtained here

Body:
If I run your code using python 2.7 I get the following warning:

VisibleDeprecationWarning: converting an array with ndim > 0 to an index will result in an error in the future return reshape(newshape, order=order)

The reason for this is that np.fromfile() returns a numpy array containing the data instead of just the data - even for single elements. That means w = np.fromfile(f, np.int32, count=1) is something like [512] instead of 512.

The following version should work for python 2.7 and 3.x

import numpy as np
def read_flow(filename):
        f = open(filename, 'rb')
        magic = np.fromfile(f, np.float32, count=1)
        data2d = None

        if 202021.25 != magic:
            print('Magic number incorrect. Invalid .flo file')
        else:
            w = np.fromfile(f, np.int32, count=1)[0]
            h = np.fromfile(f, np.int32, count=1)[0]
            print("Reading %d x %d flo file" % (h, w))
            data2d = np.fromfile(f, np.float32, count=2 * w * h)
            # reshape data into 3D array (columns, rows, channels)
            data2d = np.resize(data2d, (h, w, 2))
        f.close()
        return data2d


问:
Can't echo data from phpmyadmin
Am was already created form like this and working perfect but on last two forms not working, it displays warning-Undefined variable: reg_no and cost. Am trying to follow algorithm as previous forms but nothing happen. My goal is to update inserted data and here is my form

<!doctype html>

<meta charset="utf-8">
<title>Edit invoice</title>
<link rel="stylesheet"  href="box_style.css" />

<?php

include ("db_con.php");

if(isset($_GET['edit_invoice'])){

        $edit_i_id = $_GET['edit_invoice'];

        $select_invoice = "select * from invoice where i_id='$edit_i_id'";

        $run_query = mysqli_query($con, $select_invoice);

        while ($row_invoice=mysqli_fetch_array($run_query)){

  $i_id = $row_invoice['i_id'];
        $reg_no = $row_invoice['reg_no'];
        $cost = $row_invoice['cost'];

        }
    }

?>

<form action="" method="post" enctype="multipart/form-data" >

EDIT INVOICE:

  Registration Number:
  <input type="text" name="reg_no" id="reg_no" size="35" class="text" placeholder="Registration Number" value="<?php echo $reg_no; ?>" required=""/>

  Cost(Tshs):
  <input type="text" name="cost" id="cost" size="35" class="text" placeholder="Cost" value="<?php echo $cost; ?>" required=""/>

  <input type="submit" name="update" class="submit-button" value="SAVE CHANGES">

</form>

```

答:
Remove while loop from your php code since update is for one record based on id
The code will be as : </p>

```<code>if(isset($_GET['edit_invoice'])){
    $edit_i_id = $_GET['edit_invoice'];
    $select_invoice = "select * from invoice where i_id='$edit_i_id'";
    $run_query = mysqli_query($con, $select_invoice);
    $row_invoice = mysqli_fetch_array($run_query);

    $i_id = $row_invoice['i_id'];
    $reg_no = $row_invoice['reg_no'];
    $cost = $row_invoice['cost'];
}
</code>```

Title: Can't echo data from phpmyadmin

Body:
Remove while loop from your php code since update is for one record based on id
The code will be as :

if(isset($_GET['edit_invoice'])){
    $edit_i_id = $_GET['edit_invoice'];
    $select_invoice = "select * from invoice where i_id='$edit_i_id'";
    $run_query = mysqli_query($con, $select_invoice);
    $row_invoice = mysqli_fetch_array($run_query);

    $i_id = $row_invoice['i_id'];
    $reg_no = $row_invoice['reg_no'];
    $cost = $row_invoice['cost'];
}


问:
How to Find the List of Runtime Variables in IDE
I want to retrieve all the variables and the different values at different intervals in Programming IDE. For example, consider QTP is a testing tool and I have a script which was scripted with 10 variables. During run time the value so often changes and I want to document the variable values whenever it changes. How to access those generically instead of writing the values on own when we know that it changes? Are there any possibilities?</p>

答: You need a debug information. Java API for this: JPDA</p>


问:
Query a field with comma separated values
A table has stored coordinates in a single value field like

```<code>ID  key     value
============================
20  coords  38.5931,-90.2226
21  coords  35.7977,-78.6253
22  coords  37.555,-122.2687
23  coords  41.1412,-73.2637
24  coords  47.4716,8.2925
29  coords  42.3626,-71.0843
30  coords  -27.6333,-48.65
</code>```

What's the best way to query this field?

Basically I would like to get all entries where lat > 38 and lng < 0 like this:

```<code>SELECT * FROM table WHERE key = 'coords' AND my_lat_value > 38 AND my_lng_value < 0
</code>```

Unfortunately there's no way to split them in dedicate fields

答:
You can use the SUBSTRING_INDEX function to parse the field.

https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_substring-index

```<code>SELECT CAST(SUBSTRING_INDEX(value, ',', 1) AS DECIMAL(10,2)),
       CAST(SUBSTRING_INDEX(value, ',', -1) AS DECIMAL(10,2))
FROM MYTABLE
</code>```

Body:
A table has stored coordinates in a single value field like

ID  key     value
============================
20  coords  38.5931,-90.2226
21  coords  35.7977,-78.6253
22  coords  37.555,-122.2687
23  coords  41.1412,-73.2637
24  coords  47.4716,8.2925
29  coords  42.3626,-71.0843
30  coords  -27.6333,-48.65

What's the best way to query this field?

Basically I would like to get all entries where lat > 38 and lng < 0 like this:

SELECT * FROM table WHERE key = 'coords' AND my_lat_value > 38 AND my_lng_value < 0

Unfortunately there's no way to split them in dedicate fields

Body:
You can use the SUBSTRING_INDEX function to parse the field.

https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_substring-index

SELECT CAST(SUBSTRING_INDEX(value, ',', 1) AS DECIMAL(10,2)),
       CAST(SUBSTRING_INDEX(value, ',', -1) AS DECIMAL(10,2))
FROM MYTABLE


问:
GST number validatoin in jquery
I want to do GST validation in javascript or jquery

Its limited to india only.

the structure of GST in India is as follows

GST Number will be of 15 digits having below validations:

a. First two positions will be numeric
b. Third to Sixth positions will be Alphabets
c. Seventh position will be either alphabet or numeric
d. Eighth to Eleventh positions will be numeric
e. Twelfth position will be an alphabet
f. Thirteenth to Fifteenth positions will be alphanumeric```

答:
Here is the regex for GST Number validation which validate for 15 alphanumeric characters :

var regex ="\d{2}[A-Z]{5}\d{4}[A-Z]{1}\d{1}[A-Z]{1}\d{1}"

Title: GST number validatoin in jquery


问:
How to receive an image in a Facebook Messenger bot
How can I receive an attachment in form of an image through the Facebook Messenger API?
Their documentation only provides instructions on how to receive text-based messages. </p>

答:
While in PYTHON to receive and save an image attachment in your facebook chatbot works:

```<code>@app.route('/', methods=['POST'])
def webhook():   # endpoint for processing incoming messaging events

data = request.get_json()

if data["object"] == "page":

    for entry in data["entry"]:
        for messaging_event in entry["messaging"]:
             if messaging_event["message"].get("attachments"):
                 attachment_link = messaging_event["message"]["attachments"][0]["payload"]["url"]
              print("Image received, boss!")
              print(attachment_link)
</code>```

good chatbot-thing!
Marco

Body:
While in PYTHON to receive and save an image attachment in your facebook chatbot works:

@app.route('/', methods=['POST'])
def webhook():   # endpoint for processing incoming messaging events

data = request.get_json()

if data["object"] == "page":

    for entry in data["entry"]:
        for messaging_event in entry["messaging"]:
             if messaging_event["message"].get("attachments"):
                 attachment_link = messaging_event["message"]["attachments"][0]["payload"]["url"]
              print("Image received, boss!")
              print(attachment_link)

good chatbot-thing!
Marco


问:
Plot multiple bars in matplotlib
```<code>def plotbars(hists, bins, labels, filename):
    plt.figure()
    center = (bins[:-1] + bins[1:]) / 2
    width = 0.7 * (bins[1] - bins[0])
    for hist in hists:
        plt.bar(center, hist, align='center', width=width)
    plt.legend(labels)
    plt.savefig(filename)
</code>```

If I plot histograms like this plotbars([hist1, hist2], bins, ['hist1', 'hist2'], 'histo.png'), this plots the histograms on top of each other. I want to the bars of the histogram to be adjacent. The bin width for each are equal.

答:
try using plt.hist instead of plt.bar.

```<code>hist1=[x for x in range(0,10)]*10
hist2= [x for x in range(0,10)]*2
plt.hist([hist1,hist2],bins = 10)
</code>```

Yields this image:

Is this how you would like to see your graph?

Update:

x axis can be properly formatted using the following.

```<code>bin_list = [x for x in range(0,11) ]
plt.hist([hist1,hist2], bins=bin_list ,align='left')
</code>```

Resulting in a proper spaced x axis. For some reason it appears bins must be set as a list for proper spacing of x values.

https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xticks

For further tweaking you can try to play around with plt.xticks().

Title: Plot multiple bars in matplotlib

Body:
def plotbars(hists, bins, labels, filename):
    plt.figure()
    center = (bins[:-1] + bins[1:]) / 2
    width = 0.7 * (bins[1] - bins[0])
    for hist in hists:
        plt.bar(center, hist, align='center', width=width)
    plt.legend(labels)
    plt.savefig(filename)

If I plot histograms like this plotbars([hist1, hist2], bins, ['hist1', 'hist2'], 'histo.png'), this plots the histograms on top of each other. I want to the bars of the histogram to be adjacent. The bin width for each are equal.

Body:
try using plt.hist instead of plt.bar.

hist1=[x for x in range(0,10)]*10
hist2= [x for x in range(0,10)]*2
plt.hist([hist1,hist2],bins = 10)

Yields this image:

Is this how you would like to see your graph?

Update:

x axis can be properly formatted using the following.

bin_list = [x for x in range(0,11) ]
plt.hist([hist1,hist2], bins=bin_list ,align='left')

Resulting in a proper spaced x axis. For some reason it appears bins must be set as a list for proper spacing of x values.

https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xticks

For further tweaking you can try to play around with plt.xticks().


问:
C# Packing multiple signed integers into a single 64-bit value
I need to pack and unpack several values to/from a single 64-bit value. I have 3 signed integers (x,y,z). I would like to pack them into a single 64-bit value (signed or unsigned doesn't matter to me) using 24, 16, and 24 bits for the values respectively. Here are my requirements:

1) I can ensure ahead of times that the values being stored do not exceed the limits of the number of bits I am using to store them into the 64-bit value, so no additional checks need to be made.

2) The initial values are signed, so I'm thinking some kind of bit magic may need to be done in order to ensure that nothing is lost.

3) This conversion is going to take place a LOT, so it needs to be fast. I know in C++ this can pretty easily be done by storing the values in a struct that specifies the integer length, and then establishing a pointer that just points to the first value that can be used for the 64-bit value. With this method, there really isn't any math that needs done, everything is just memory read or right. As far as I can tell, this can't be done quite so simply in C#, but C# is what I have to work with for this project.

4) I don't really care if the 64-bit value is signed or unsigned, so long as I can go both ways with the operation and recover the initial values, and whatever type is used can be used for a Dictionary key.

答:
With this method, there really isn't any math that needs done, everything is just memory read or write.

Not really, the math is done when you set partial integers into bitfields, so there's quite a bit of math going on.

As far as I can tell, this can't be done quite so simply in C#, but C# is what I have to work with for this project.

Correct, in C# you would need to write code that combines bits into a long manually. Assuming that you have taken care of range checking, this is relatively straightforward:

```<code>static long Pack(long a24, long b16, long c24) {
    // a24 can go with no masking, because its MSB becomes
    // the MSB of the 64-bit number. The other two numbers
    // need to be truncated to deal with 1s in the upper bits of negatives.
    return a24<<40 | (b16&0xffffL)<<24 | (c24&0xffffffL);
}
static void Unpack(long packed, out int a24, out int b16, out int c24) {
    a24 = (int)(packed >> 40); // Sign extension is done in the long
    b16 = ((int)(packed >> 8)) >> 16; // Sign extension is done in the int
    c24 = ((int)(packed << 8)) >> 8;  // Sign extension is done in the int
}
</code>```

Demo.

Body:
With this method, there really isn't any math that needs done, everything is just memory read or write.

Not really, the math is done when you set partial integers into bitfields, so there's quite a bit of math going on.

As far as I can tell, this can't be done quite so simply in C#, but C# is what I have to work with for this project.

Correct, in C# you would need to write code that combines bits into a long manually. Assuming that you have taken care of range checking, this is relatively straightforward:

static long Pack(long a24, long b16, long c24) {
    // a24 can go with no masking, because its MSB becomes
    // the MSB of the 64-bit number. The other two numbers
    // need to be truncated to deal with 1s in the upper bits of negatives.
    return a24<<40 | (b16&0xffffL)<<24 | (c24&0xffffffL);
}
static void Unpack(long packed, out int a24, out int b16, out int c24) {
    a24 = (int)(packed >> 40); // Sign extension is done in the long
    b16 = ((int)(packed >> 8)) >> 16; // Sign extension is done in the int
    c24 = ((int)(packed << 8)) >> 8;  // Sign extension is done in the int
}

Demo.


问:
Pass CommandParameter to Command in Silverlight using MVVM
I'm just learning Silverlight and looking at MVVM and Commanding.

Ok, so I have seen the basic RelayCommand implementation:

```<code>public class RelayCommand : ICommand
{
    private readonly Action _handler;
    private bool _isEnabled;

    public RelayCommand(Action handler)
    {
        _handler = handler;
    }

    public bool IsEnabled
    {
        get { return _isEnabled; }
        set
        {
            if (value != _isEnabled)
            {
                _isEnabled = value;
                if (CanExecuteChanged != null)
                {
                    CanExecuteChanged(this, EventArgs.Empty);
                }
            }
        }
    }

    public bool CanExecute(object parameter)
    {
        return IsEnabled;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        _handler();
    }
}
</code>```

How can I pass a parameter down with a Command using this?

I've seen that you can pass a CommandParameter like this:

```<code><Button Command="{Binding SomeCommand}" CommandParameter="{Binding SomeCommandParameter}" ... />
</code>```

In my ViewModel, I need to create the Command, but RelayCommand is expecting an Action delegate. Can I implement RelayCommand<T> using Action<T> - if so, how do I do it and how to I use it?

Can anyone give me any practical examples on CommandParameters with MVVM that don't involve using 3rd-party libraries (e.g. MVVM Light) as I want to understand it fully before using existing libraries.

Thanks.

答:
```<code>public class Command : ICommand
{
    public event EventHandler CanExecuteChanged;

    Predicate<Object> _canExecute = null;
    Action<Object> _executeAction = null;

    public Command(Predicate<Object> canExecute, Action<object> executeAction)
    {
        _canExecute = canExecute;
        _executeAction = executeAction;
    }
    public bool CanExecute(object parameter)
    {
        if (_canExecute != null)
            return _canExecute(parameter);
        return true;
    }

    public void UpdateCanExecuteState()
    {
        if (CanExecuteChanged != null)
            CanExecuteChanged(this, new EventArgs());
    }

    public void Execute(object parameter)
    {
        if (_executeAction != null)
            _executeAction(parameter);
        UpdateCanExecuteState();
    }
}
</code>```

Is the Base Class for Commands

And this is your Command Property in ViewModel:

```<code> private ICommand yourCommand; ....

 public ICommand YourCommand
    {
        get
        {
            if (yourCommand == null)
            {
                yourCommand = new Command(  //class above
                    p => true,    // predicate to check "CanExecute" e.g. my_var != null
                    p => yourCommandFunction(param1, param2));
            }
            return yourCommand;
        }
    }
</code>```

in XAML set Binding to Command Property like:

```<code> <Button Command="{Binding Path=YourCommand}" .../>
</code>```

Body:
I'm just learning Silverlight and looking at MVVM and Commanding.

Ok, so I have seen the basic RelayCommand implementation:

public class RelayCommand : ICommand
{
    private readonly Action _handler;
    private bool _isEnabled;

    public RelayCommand(Action handler)
    {
        _handler = handler;
    }

    public bool IsEnabled
    {
        get { return _isEnabled; }
        set
        {
            if (value != _isEnabled)
            {
                _isEnabled = value;
                if (CanExecuteChanged != null)
                {
                    CanExecuteChanged(this, EventArgs.Empty);
                }
            }
        }
    }

    public bool CanExecute(object parameter)
    {
        return IsEnabled;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        _handler();
    }
}

How can I pass a parameter down with a Command using this?

I've seen that you can pass a CommandParameter like this:

<Button Command="{Binding SomeCommand}" CommandParameter="{Binding SomeCommandParameter}" ... />

In my ViewModel, I need to create the Command, but RelayCommand is expecting an Action delegate. Can I implement RelayCommand<T> using Action<T> - if so, how do I do it and how to I use it?

Can anyone give me any practical examples on CommandParameters with MVVM that don't involve using 3rd-party libraries (e.g. MVVM Light) as I want to understand it fully before using existing libraries.

Thanks.

Body:
public class Command : ICommand
{
    public event EventHandler CanExecuteChanged;

    Predicate<Object> _canExecute = null;
    Action<Object> _executeAction = null;

    public Command(Predicate<Object> canExecute, Action<object> executeAction)
    {
        _canExecute = canExecute;
        _executeAction = executeAction;
    }
    public bool CanExecute(object parameter)
    {
        if (_canExecute != null)
            return _canExecute(parameter);
        return true;
    }

    public void UpdateCanExecuteState()
    {
        if (CanExecuteChanged != null)
            CanExecuteChanged(this, new EventArgs());
    }

    public void Execute(object parameter)
    {
        if (_executeAction != null)
            _executeAction(parameter);
        UpdateCanExecuteState();
    }
}

Is the Base Class for Commands

And this is your Command Property in ViewModel:

 private ICommand yourCommand; ....

 public ICommand YourCommand
    {
        get
        {
            if (yourCommand == null)
            {
                yourCommand = new Command(  //class above
                    p => true,    // predicate to check "CanExecute" e.g. my_var != null
                    p => yourCommandFunction(param1, param2));
            }
            return yourCommand;
        }
    }

in XAML set Binding to Command Property like:

 <Button Command="{Binding Path=YourCommand}" .../>


问:
Need help speeding up a dplyr aggregation
tl.dr. I have an aggregation problem that I haven't seen in documentation before.  I manage to get it done, but it is way too slow for the intended application.  The data I usually work with have around 500 lines (my gut feeling tells me this isn't much for dplyr) and according to system.time it runs for about 4 s.  My dilemma is I want to run it in an optimisation repeatedly and currently I am looking at hours of run time.

Do you see anything where I can shave off some time?

If need be I can also send some data I work with.

Algorithm
I have a data set:

```<code>sample_dataset <- data_frame( starts = c(1000, 1008, 1017, 2000, 2020, 3000),
                          ends   = c(1009, 1015, 1020, 2015, 2030, 3010),
                          v = list(rep(1,10), rep(2,8),rep(3,4),
                                   rep(4,16), rep(5,11), rep(6,11)) )
</code>```

so each line encodes a signal and a start and end index.  I want to aggregate all lines which have less than closeness (e.g. 10) distance into an single line. In case it matters starts is ordered.

The output should be:

```<code>structure(list(inds = 1:3, starts = c(1000, 2000, 3000), ends = c(1020,
2030, 3010), v = list(c(1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 2, 2, 2,
2, 2, 2, 0, 3, 3, 3, 3), c(4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5), c(6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -3L), .Names = c("inds", "starts", "ends",
"v"))
</code>```

So the first three lines in the original data set are aggregated, line 4 and 5 aggregated, 6 unchanged.  For overlaps the numbers should be added, for gaps zeros filled in.  The updated starts value is the first starts, the updated ends should be the last ends (suppose I should fix it to the max).  But by the way these are generated end should be also sorted.  The case that one block is completely surrounded by another block should not occur.

I achieved this by following code:

Code

```<code>library(dplyr)

join_lines <- function(dfi) {
  if (nrow(dfi)==1) return(select(dfi,starts,ends, v))
  else
    with(dfi,{
             start <- starts[[1]]
             end <- ends[[length(ends)]]
             vals <- numeric(end-start+1)
             add_val <- function(ddf)
               with(ddf,{
                      vals[(starts-start+1) : (ends-start+1)] <<-
                        vals[(starts-start+1) : (ends-start+1)] + v })
             dfi %>% rowwise() %>% do(tmp=add_val(.))
             data_frame(starts=start, ends=end, v=list(vals))})
}

simplify_semisparse <- function(aframe, closeness = 10){
  aframe %>%
    mutate( join_pre = lag(ends, default=0)+closeness >= (starts),
           inds = cumsum(!join_pre)
           ) %>%
  group_by(inds) %>% do(join_lines(.)) %>% ungroup()
}

res <- simplify_semisparse(sample_dataset)

dput(res) # see above
</code>```

Background

The data I am dealing with is from mass spectrometry.  It's very peculiar in that a vector has around 500,000 entries and less than 10% of these are not zeros, a typical spectrum has around 500 such dense blocks.   I do need to quickly interpolate values along such a spectrum - my idea was to use approx in the "dense" regions.

Comparison of suggestions

I had the chance of comparing your suggestions.

The results produced by @matt-jewett solution did not agree with my intended ones so I did exclude it.

@jeremycgs solution was closest to my original approach, but also did not produce exactly the same results.

most important is for my the runtime, I am comparing using production data. My original solution took 2.165 s. @tjeremy s suggestion took 0.532 s and @uwe-block 0.012 s.

So wow - I need to learn data.table.

答:
Here's how I would do it. Your use of a list in v is not best practice (in my opinion), so I've used tidyr to unnest to a longer dataframe. I've allso left out your 0s - you could add them back in as with a left join or something on the index:

```<code>library(tidyr)
sample_dataset %>%
 mutate(grouper = cumsum(c(0, na.omit(starts - lag(starts)))>20), id = row_number()) %>% #add a 'grouping' based on your closeness (20 here) and an id for later
 unnest(v) %>% #unnest v into lines - each v now has a line
 group_by(id) %>% #group by line
 mutate(count = row_number()+starts) %>% #get a 'location' per line
 group_by(grouper, count) %>% #group by the 'location' and group
 summarise(starts = starts[1], ends = ends[n()], v = sum(v)) #sum the v
</code>```

which gives:

```<code>Source: local data frame [58 x 5]
Groups: grouper [?]

   grouper count starts  ends     v
     <int> <dbl>  <dbl> <dbl> <dbl>
1        0  1001   1000  1009     1
2        0  1002   1000  1009     1
3        0  1003   1000  1009     1
4        0  1004   1000  1009     1
5        0  1005   1000  1009     1
6        0  1006   1000  1009     1
7        0  1007   1000  1009     1
8        0  1008   1000  1009     1
9        0  1009   1000  1015     3
10       0  1010   1000  1015     3
# ... with 48 more rows
</code>```

Then, if you really want, you can fill the missing values with 0 (out here is the output from the above):

```<code>filled = out %>% group_by(grouper) %>% do(data.frame(count = seq(from = .$starts[1], to = tail(.$ends,1))))

filled = filled %>% left_join(out, by = c('grouper', 'count'))
filled$v[is.na(filled$v)] = 0

Source: local data frame [63 x 5]
Groups: grouper [?]

   grouper count starts  ends     v
     <int> <dbl>  <dbl> <dbl> <dbl>
1        0  1000     NA    NA     0
2        0  1001   1000  1009     1
3        0  1002   1000  1009     1
4        0  1003   1000  1009     1
5        0  1004   1000  1009     1
6        0  1005   1000  1009     1
7        0  1006   1000  1009     1
8        0  1007   1000  1009     1
9        0  1008   1000  1009     1
10       0  1009   1000  1015     3
# ... with 53 more rows
</code>```

Body:
tl.dr. I have an aggregation problem that I haven't seen in documentation before.  I manage to get it done, but it is way too slow for the intended application.  The data I usually work with have around 500 lines (my gut feeling tells me this isn't much for dplyr) and according to system.time it runs for about 4 s.  My dilemma is I want to run it in an optimisation repeatedly and currently I am looking at hours of run time.

Do you see anything where I can shave off some time?

If need be I can also send some data I work with.

Algorithm
I have a data set:

sample_dataset <- data_frame( starts = c(1000, 1008, 1017, 2000, 2020, 3000),
                          ends   = c(1009, 1015, 1020, 2015, 2030, 3010),
                          v = list(rep(1,10), rep(2,8),rep(3,4),
                                   rep(4,16), rep(5,11), rep(6,11)) )

so each line encodes a signal and a start and end index.  I want to aggregate all lines which have less than closeness (e.g. 10) distance into an single line. In case it matters starts is ordered.

The output should be:

structure(list(inds = 1:3, starts = c(1000, 2000, 3000), ends = c(1020,
2030, 3010), v = list(c(1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 2, 2, 2,
2, 2, 2, 0, 3, 3, 3, 3), c(4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5), c(6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -3L), .Names = c("inds", "starts", "ends",
"v"))

So the first three lines in the original data set are aggregated, line 4 and 5 aggregated, 6 unchanged.  For overlaps the numbers should be added, for gaps zeros filled in.  The updated starts value is the first starts, the updated ends should be the last ends (suppose I should fix it to the max).  But by the way these are generated end should be also sorted.  The case that one block is completely surrounded by another block should not occur.

I achieved this by following code:

Code

library(dplyr)

join_lines <- function(dfi) {
  if (nrow(dfi)==1) return(select(dfi,starts,ends, v))
  else
    with(dfi,{
             start <- starts[[1]]
             end <- ends[[length(ends)]]
             vals <- numeric(end-start+1)
             add_val <- function(ddf)
               with(ddf,{
                      vals[(starts-start+1) : (ends-start+1)] <<-
                        vals[(starts-start+1) : (ends-start+1)] + v })
             dfi %>% rowwise() %>% do(tmp=add_val(.))
             data_frame(starts=start, ends=end, v=list(vals))})
}

simplify_semisparse <- function(aframe, closeness = 10){
  aframe %>%
    mutate( join_pre = lag(ends, default=0)+closeness >= (starts),
           inds = cumsum(!join_pre)
           ) %>%
  group_by(inds) %>% do(join_lines(.)) %>% ungroup()
}

res <- simplify_semisparse(sample_dataset)

dput(res) # see above

Background

The data I am dealing with is from mass spectrometry.  It's very peculiar in that a vector has around 500,000 entries and less than 10% of these are not zeros, a typical spectrum has around 500 such dense blocks.   I do need to quickly interpolate values along such a spectrum - my idea was to use approx in the "dense" regions.

Comparison of suggestions

I had the chance of comparing your suggestions.

The results produced by @matt-jewett solution did not agree with my intended ones so I did exclude it.

@jeremycgs solution was closest to my original approach, but also did not produce exactly the same results.

most important is for my the runtime, I am comparing using production data. My original solution took 2.165 s. @tjeremy s suggestion took 0.532 s and @uwe-block 0.012 s.

So wow - I need to learn data.table.

Body:
Here's how I would do it. Your use of a list in v is not best practice (in my opinion), so I've used tidyr to unnest to a longer dataframe. I've allso left out your 0s - you could add them back in as with a left join or something on the index:

library(tidyr)
sample_dataset %>%
 mutate(grouper = cumsum(c(0, na.omit(starts - lag(starts)))>20), id = row_number()) %>% #add a 'grouping' based on your closeness (20 here) and an id for later
 unnest(v) %>% #unnest v into lines - each v now has a line
 group_by(id) %>% #group by line
 mutate(count = row_number()+starts) %>% #get a 'location' per line
 group_by(grouper, count) %>% #group by the 'location' and group
 summarise(starts = starts[1], ends = ends[n()], v = sum(v)) #sum the v

which gives:

Source: local data frame [58 x 5]
Groups: grouper [?]

   grouper count starts  ends     v
     <int> <dbl>  <dbl> <dbl> <dbl>
1        0  1001   1000  1009     1
2        0  1002   1000  1009     1
3        0  1003   1000  1009     1
4        0  1004   1000  1009     1
5        0  1005   1000  1009     1
6        0  1006   1000  1009     1
7        0  1007   1000  1009     1
8        0  1008   1000  1009     1
9        0  1009   1000  1015     3
10       0  1010   1000  1015     3
# ... with 48 more rows

Then, if you really want, you can fill the missing values with 0 (out here is the output from the above):

filled = out %>% group_by(grouper) %>% do(data.frame(count = seq(from = .$starts[1], to = tail(.$ends,1))))

filled = filled %>% left_join(out, by = c('grouper', 'count'))
filled$v[is.na(filled$v)] = 0

Source: local data frame [63 x 5]
Groups: grouper [?]

   grouper count starts  ends     v
     <int> <dbl>  <dbl> <dbl> <dbl>
1        0  1000     NA    NA     0
2        0  1001   1000  1009     1
3        0  1002   1000  1009     1
4        0  1003   1000  1009     1
5        0  1004   1000  1009     1
6        0  1005   1000  1009     1
7        0  1006   1000  1009     1
8        0  1007   1000  1009     1
9        0  1008   1000  1009     1
10       0  1009   1000  1015     3
# ... with 53 more rows


问:
Calculate the average of the n-th number of elements in the column in pandas
I have the following dataframe:

```<code>             df1
index   year   week   a     b     c
 -10    2017    10   45    26    19
  -9    2017    11   37    23    14
  -8    2017    12   21    66    19
  -7    2017    13   47    36    92
  -6    2017    14   82    65    18
  -5    2017    15   68    68    19
  -4    2017    16   30    95    24
  -3    2017    17   21    15    94
  -2    2017    18   67    30    16
  -1    2017    19   10    13    13
   0    2017    20   26    22    18
   1    2017    21   NaN   NaN   NaN
   2    2017    22   NaN   NaN   NaN
   3    2017    23   NaN   NaN   NaN
   4    2017    24   NaN   NaN   NaN
   ...
   53   2018    20   NaN   NaN   NaN
</code>```

I need for each empty cell to calculate the average of the previous nth values in a column and write this value into a cell. n is equal to the number of indexes from zero and up. For example, for the first empty cell in the column a I must calculate the average between the indexes 0 and -10. Then for the next cell between 1 and -9 and so on. And so do for columns a, b and c. And calculations always begin where the index = 1.

And the problem is that the number of columns such as a, b, c can be different. But I know that these columns will always be after the column week. Is it possible to apply these calculations to an indefinite number of columns, but if it is known that these columns will be located after the column week?

I tried hard to find anything, but I could not find anything suitable.

UPD: If this helps, the maximum number of rows from index = 0 and down will be 53.

答:
You can do something like this by playing around a bit with pandas and numpy. Assuming that you know what the index of the week column will be(even if you don't, a simple search will get you the index), like example, the week column is 3rd you can do something like

```<code>import numpy as np
import pandas as pd
#data is your dataframe name
column_list = list(data.columns.values)[3:]
for column_name in column_list :
    column = data[column_name].values
    #converted pandas series to numpy series
    for index in xrange(0,column.shape[0]):
        #iterating over entries in the column
        if np.isnan(column[index]):
            column[index] = np.nanmean(column.take(range(index-10,index+1),mode='wrap'))
</code>```

This is a bad unvectorized solution, but should work fine. It will replace all NaN entries with the previous 10 entries wrapped around. If you instead wanted only the previous 10 without a wrap around, you  simply take the first n for n lesser than 10, like

new_df[index] = np.nanmean(new_df[max(0,index-10):index+1])

Hope this helps!

Body:
I have the following dataframe:

             df1
index   year   week   a     b     c
 -10    2017    10   45    26    19
  -9    2017    11   37    23    14
  -8    2017    12   21    66    19
  -7    2017    13   47    36    92
  -6    2017    14   82    65    18
  -5    2017    15   68    68    19
  -4    2017    16   30    95    24
  -3    2017    17   21    15    94
  -2    2017    18   67    30    16
  -1    2017    19   10    13    13
   0    2017    20   26    22    18
   1    2017    21   NaN   NaN   NaN
   2    2017    22   NaN   NaN   NaN
   3    2017    23   NaN   NaN   NaN
   4    2017    24   NaN   NaN   NaN
   ...
   53   2018    20   NaN   NaN   NaN

I need for each empty cell to calculate the average of the previous nth values in a column and write this value into a cell. n is equal to the number of indexes from zero and up. For example, for the first empty cell in the column a I must calculate the average between the indexes 0 and -10. Then for the next cell between 1 and -9 and so on. And so do for columns a, b and c. And calculations always begin where the index = 1.

And the problem is that the number of columns such as a, b, c can be different. But I know that these columns will always be after the column week. Is it possible to apply these calculations to an indefinite number of columns, but if it is known that these columns will be located after the column week?

I tried hard to find anything, but I could not find anything suitable.

UPD: If this helps, the maximum number of rows from index = 0 and down will be 53.

Body:
You can do something like this by playing around a bit with pandas and numpy. Assuming that you know what the index of the week column will be(even if you don't, a simple search will get you the index), like example, the week column is 3rd you can do something like

import numpy as np
import pandas as pd
#data is your dataframe name
column_list = list(data.columns.values)[3:]
for column_name in column_list :
    column = data[column_name].values
    #converted pandas series to numpy series
    for index in xrange(0,column.shape[0]):
        #iterating over entries in the column
        if np.isnan(column[index]):
            column[index] = np.nanmean(column.take(range(index-10,index+1),mode='wrap'))

This is a bad unvectorized solution, but should work fine. It will replace all NaN entries with the previous 10 entries wrapped around. If you instead wanted only the previous 10 without a wrap around, you  simply take the first n for n lesser than 10, like

new_df[index] = np.nanmean(new_df[max(0,index-10):index+1])

Hope this helps!


问:
c# uwp pointer position
In UWP I am trying to get position of pointer.

I have managed to do it with next Event:

```<code>    private void Grid_PointerMoved(object sender, PointerRoutedEventArgs e)
    {
        PointerPoint point = e.GetCurrentPoint(mainGrid);
        var x = point.Position.X;
        var y = point.Position.Y;
    }
</code>```

And with this way it will be fired all the time. So, I needed some property to get that position. I have found this:

```<code>var pointerPosition = Windows.UI.Core.CoreWindow.GetForCurrentThread().PointerPosition;
</code>```

But it doesn't always return correct position.

Any other property to get current mouse location?

答:
```<code>var pointerPosition = Windows.UI.Core.CoreWindow.GetForCurrentThread().PointerPosition;
</code>```

pointerPosition gives you the client coordinates which are the cursor position X & Y of the screen, not relative to your app Window.

So you just need to use Window.Current.Bounds to find the coordinates of your app Window first, and then -

```<code>var x = pointerPosition.X - Window.Current.Bounds.X;
var y = pointerPosition.Y - Window.Current.Bounds.Y;
</code>```

Title: c# uwp pointer position

Body:
In UWP I am trying to get position of pointer.

I have managed to do it with next Event:

    private void Grid_PointerMoved(object sender, PointerRoutedEventArgs e)
    {
        PointerPoint point = e.GetCurrentPoint(mainGrid);
        var x = point.Position.X;
        var y = point.Position.Y;
    }

And with this way it will be fired all the time. So, I needed some property to get that position. I have found this:

var pointerPosition = Windows.UI.Core.CoreWindow.GetForCurrentThread().PointerPosition;

But it doesn't always return correct position.

Any other property to get current mouse location?

Body:
var pointerPosition = Windows.UI.Core.CoreWindow.GetForCurrentThread().PointerPosition;

pointerPosition gives you the client coordinates which are the cursor position X & Y of the screen, not relative to your app Window.

So you just need to use Window.Current.Bounds to find the coordinates of your app Window first, and then -

var x = pointerPosition.X - Window.Current.Bounds.X;
var y = pointerPosition.Y - Window.Current.Bounds.Y;


问:
Reset class member
```<code>#include <iostream>
#include <map>

using namespace std;

class A
{
public:
    void SetData(std::string key, int value)
    {
        if(m_data.find(key) != m_data.end()) m_data.at(key) = value;
        else m_data.insert(std::make_pair(key,value));
    }
    int GetData(std::string key)
    {
        if(m_data.find(key) != m_data.end()) return m_data.at(key);
        return 0;
    }
    void ResetData()
    {
        for(auto item : m_data)
            item.second = 0;
    }
    void ResetData2()
    {
        for(auto it=m_data.begin(); it!=m_data.end(); it++)
            (*it).second = 0;
    }

private:
    std::map<std::string, int> m_data;
};

int main()
{
    A a;
    a.SetData("KEY1", 10);
    std::cout << "Key1: " << a.GetData("KEY1") << std::endl;
    a.ResetData();
    std::cout << "Key1: " << a.GetData("KEY1") << std::endl;
    a.ResetData2();
    std::cout << "Key1: " << a.GetData("KEY1") << std::endl;

    return 0;
}
</code>```

Output:

```<code>Key1: 10
Key1: 10
Key1: 0
</code>```

Live demo: https://ideone.com/GH3Ft8

What's the difference between the two reset methods here?
Resetting the class member std::map<std::string, int> m_data with iterator approach (ResetData2()) works like expected but not range based loop (ResetData())!

答:
The first method should modify a reference to each item

```<code>void ResetData()
{
    for(auto& item : m_data)
        item.second = 0;
}
</code>```

Otherwise you are setting the value to zero for a copy of each item in your map.

Title: Reset class member

Body:
#include <iostream>
#include <map>

using namespace std;

class A
{
public:
    void SetData(std::string key, int value)
    {
        if(m_data.find(key) != m_data.end()) m_data.at(key) = value;
        else m_data.insert(std::make_pair(key,value));
    }
    int GetData(std::string key)
    {
        if(m_data.find(key) != m_data.end()) return m_data.at(key);
        return 0;
    }
    void ResetData()
    {
        for(auto item : m_data)
            item.second = 0;
    }
    void ResetData2()
    {
        for(auto it=m_data.begin(); it!=m_data.end(); it++)
            (*it).second = 0;
    }

private:
    std::map<std::string, int> m_data;
};

int main()
{
    A a;
    a.SetData("KEY1", 10);
    std::cout << "Key1: " << a.GetData("KEY1") << std::endl;
    a.ResetData();
    std::cout << "Key1: " << a.GetData("KEY1") << std::endl;
    a.ResetData2();
    std::cout << "Key1: " << a.GetData("KEY1") << std::endl;

    return 0;
}

Output:

Key1: 10
Key1: 10
Key1: 0

Live demo: https://ideone.com/GH3Ft8

What's the difference between the two reset methods here?
Resetting the class member std::map<std::string, int> m_data with iterator approach (ResetData2()) works like expected but not range based loop (ResetData())!

Body:
The first method should modify a reference to each item

void ResetData()
{
    for(auto& item : m_data)
        item.second = 0;
}

Otherwise you are setting the value to zero for a copy of each item in your map.


问:
JaxB Marshaling in camel
I am new to Apache camel and Jax b concept in java.
I have a list of java objects in a camel queue. I want to Marshall it to an xml with Javs DSL(without using spring).
Could any one guide me to do that?

I have the following POJO class

```<code>public class MyPojo {
private int groupId;
private int memberId;
private String details;
public int getgroupId() {
    return groupId;
}
public void setgroupId(int groupId) {
    this.groupId = groupId;
}
public int getMemberId() {
    return memberId;
}
public void setMemberId(int memberId) {
    this.memberId = memberId;
}
public String getdetails() {
    return details;
}
public void setdetails(String details) {
    this.details = details;
}}
</code>```

following is my camel code for jaxb implementation

```<code>JaxbDataFormat jaxbMarshal = new JaxbDataFormat();
    jaxbMarshal.setContextPath("com.test");
    jaxbMarshal.setPartClass("com.test.MyPojo");

from("direct:javaObjects") //this direct having the list of MYPojo Objects
    .marshal(jaxbMarshal)
     .to("src/output");
</code>```

I am getting below exception(I added maven dependency for jaxb in classpath)

```<code>Failed to create route route4 at: >>> Marshal[org.apache.camel.model.dataformat.JaxbDataFormat@3feb2dda] <<< in route: Route(route4)[[From[direct:javaObjects]] -> [Marshal[org.apa... because of Data format 'jaxb' could not be created. Ensure that the data format is valid and the associated Camel component is present on the classpath
</code>```

答:
I have created the jaxb.index file(new->File from eclipse). the content of the file should be annotation class name

In our case it should be
        MyPojo

and its needs to be placed in context path. in our case it should be placed in
        com.test location

and the annotated Pojo class is

```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
 public class MyPojo {
@XmlElement
private int groupId;
@XmlElement
private int memberId;
@XmlElement
private String details;
public int getgroupId() {
    return groupId;
}
public void setgroupId(int groupId) {
    this.groupId = groupId;
}
public int getMemberId() {
    return memberId;
}
public void setMemberId(int memberId) {
    this.memberId = memberId;
}
public String getdetails() {
    return details;
}
public void setdetails(String details) {
    this.details = details;
}}
</code>```

Title: JaxB Marshaling in camel

Body:
I am new to Apache camel and Jax b concept in java.
I have a list of java objects in a camel queue. I want to Marshall it to an xml with Javs DSL(without using spring).
Could any one guide me to do that?

I have the following POJO class

public class MyPojo {
private int groupId;
private int memberId;
private String details;
public int getgroupId() {
    return groupId;
}
public void setgroupId(int groupId) {
    this.groupId = groupId;
}
public int getMemberId() {
    return memberId;
}
public void setMemberId(int memberId) {
    this.memberId = memberId;
}
public String getdetails() {
    return details;
}
public void setdetails(String details) {
    this.details = details;
}}

following is my camel code for jaxb implementation

JaxbDataFormat jaxbMarshal = new JaxbDataFormat();
    jaxbMarshal.setContextPath("com.test");
    jaxbMarshal.setPartClass("com.test.MyPojo");

from("direct:javaObjects") //this direct having the list of MYPojo Objects
    .marshal(jaxbMarshal)
     .to("src/output");

I am getting below exception(I added maven dependency for jaxb in classpath)

Failed to create route route4 at: >>> Marshal[org.apache.camel.model.dataformat.JaxbDataFormat@3feb2dda] <<< in route: Route(route4)[[From[direct:javaObjects]] -> [Marshal[org.apa... because of Data format 'jaxb' could not be created. Ensure that the data format is valid and the associated Camel component is present on the classpath

Body:
I have created the jaxb.index file(new->File from eclipse). the content of the file should be annotation class name

In our case it should be
        MyPojo

and its needs to be placed in context path. in our case it should be placed in
        com.test location

and the annotated Pojo class is

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
 public class MyPojo {
@XmlElement
private int groupId;
@XmlElement
private int memberId;
@XmlElement
private String details;
public int getgroupId() {
    return groupId;
}
public void setgroupId(int groupId) {
    this.groupId = groupId;
}
public int getMemberId() {
    return memberId;
}
public void setMemberId(int memberId) {
    this.memberId = memberId;
}
public String getdetails() {
    return details;
}
public void setdetails(String details) {
    this.details = details;
}}


问:
Sessions and storing objects
If return an object from the session (HttpContext.Current.Session) to a private member of the objects type and then modify it, e.g. you rename an attribute or add something to the objects internal list member. Are those changes persisted if on another page you request the same object from the session...will it be updated with the values updated on the previous page. In other words is the object persisted, or do you have to re-save the object back to the session once you change anything on every page. Any help is much appreciated. Thanks</p>

答:
If it is an actual object then yes, you are modifying the version that is maintained by session and it's values will be saved.

If it is not a reference type, like String, then you have to reference the actual session value to modify it (ie: session["key"] = value).

However, I would caution you against storing real objects in session.  Session works by serializing and deserializing the values on every single page load.  The more you put into session the more work the framework has to perform before even beginning to execute your page.

Because of how it works you really should only put values in session that you truly need across the entire site.

Before even considering putting something in session I ask myself the following:

Is this something needed for the entire site or close to it?

Is the time to load this information straight from the database on an as needed basis more than pulling it from the web servers memory?

Is this site load balanced or has the potential of being load balanced in the future?

If 1 is yes, then using session is a "maybe"

If 2 is yes, then session is also a maybe, but I'd probably use a different caching mechanism.

If 3 is a yes then I don't use session at all (and completely turn it off).  Load balancing requires a session state server, which is usually a sql server.  Which leads us back to the initial problem with session: namely, the values are loaded and saved for every single page request.

Title: Sessions and storing objects


问:
davfs2 package not found on CENTOS 7.3 x86_64
I'm having some issues trying to install davfs2 on my CentOS server, I run

```<code> yum install davfs2
</code>```

but I get this:

```<code> Loaded plugins: fastestmirror, langpacks, priorities, universal-hooks
 Loading mirror speeds from cached hostfile
  * EA4: 91.197.228.252
  * cpanel-addons-production-feed: 91.197.228.252
  * base: centos.quelquesmots.fr
  * centosplus: centos.mirror.fr.planethoster.net
  * extras: centos.quelquesmots.fr
  * rpmforge: mirrors.ircam.fr
   * updates: centos.quelquesmots.fr
  Nothing to do
</code>```

Not sure but maybe I need add more mirrors to my distro, if it's not possible install davfs2 I'd like to know other alternative for mount webdav routes as folder in CentOS, cadaver is a webdav client but I can't mount folders with it...

thank you guys, have a nice day

答:
You have to enable the EPEL repo in order to install that package:

```<code>yum -y install epel-release
yum -y install davfs2
</code>```

After you're done installing the required packages please disable the epel repo since you are on a cPanel server and this additional repo, at some point might break some package dependencies when cPanel/WHM nightly update is running.

To disable the EPEL repo you can edit /etc/yum.repos.d/epel.repo file and replace enabled=1 with enabled=0

Body:
I'm having some issues trying to install davfs2 on my CentOS server, I run

 yum install davfs2

but I get this:

 Loaded plugins: fastestmirror, langpacks, priorities, universal-hooks
 Loading mirror speeds from cached hostfile
  * EA4: 91.197.228.252
  * cpanel-addons-production-feed: 91.197.228.252
  * base: centos.quelquesmots.fr
  * centosplus: centos.mirror.fr.planethoster.net
  * extras: centos.quelquesmots.fr
  * rpmforge: mirrors.ircam.fr
   * updates: centos.quelquesmots.fr
  Nothing to do

Not sure but maybe I need add more mirrors to my distro, if it's not possible install davfs2 I'd like to know other alternative for mount webdav routes as folder in CentOS, cadaver is a webdav client but I can't mount folders with it...

thank you guys, have a nice day

Body:
You have to enable the EPEL repo in order to install that package:

yum -y install epel-release
yum -y install davfs2

After you're done installing the required packages please disable the epel repo since you are on a cPanel server and this additional repo, at some point might break some package dependencies when cPanel/WHM nightly update is running.

To disable the EPEL repo you can edit /etc/yum.repos.d/epel.repo file and replace enabled=1 with enabled=0


问:
R 3.4.1 "Single Candle" Personal Library Path Error: unable to create ‘NA’
I just updated to R (3.4.1 "Single Candle") on my Linux Mint 18.1 Cinnamon machine and I attempted to install a package. R returned the following:

```<code>> install.packages('ggplot2')
Installing package into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
Warning in install.packages("ggplot2") :
  'lib = "/usr/local/lib/R/site-library"' is not writable
Would you like to use a personal library instead?  (y/n) y
Would you like to create a personal library
NA
to install packages into?  (y/n) y
Error in install.packages("ggplot2") : unable to create ‘NA’
</code>```

I have encountered the 'lib not writable' output before but typically it offers a solution like this one:

```<code>Would you like to create a personal library
~/R/x86_64-pc-linux-gnu-library/3.4
to install packages into?  (y/n) y
</code>```

Any ideas why the personal library is suggesting NA? Is there a way to manually override this?

答:
My solution was the following:

In the file /usr/lib/R/etc/Renviron there is a configuration of R.

In lines 43-45 there is:

```<code># edd Jun 2017  Comment-out R_LIBS_USER
#R_LIBS_USER=${R_LIBS_USER-'~/R/x86_64-pc-linux-gnu-library/3.4'}
##R_LIBS_USER=${R_LIBS_USER-'~/Library/R/3.4/library'}
</code>```

I have uncommented R_LIBS_USER=${R_LIBS_USER-'~/R/x86_64-pc-linux-gnu-library/3.4'}, restarted RStudio and now it works.

EDIT: Looking at the comments, it seems like a planned behaviour. Here is another solution.

Body:
I just updated to R (3.4.1 "Single Candle") on my Linux Mint 18.1 Cinnamon machine and I attempted to install a package. R returned the following:

> install.packages('ggplot2')
Installing package into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
Warning in install.packages("ggplot2") :
  'lib = "/usr/local/lib/R/site-library"' is not writable
Would you like to use a personal library instead?  (y/n) y
Would you like to create a personal library
NA
to install packages into?  (y/n) y
Error in install.packages("ggplot2") : unable to create ‘NA’

I have encountered the 'lib not writable' output before but typically it offers a solution like this one:

Would you like to create a personal library
~/R/x86_64-pc-linux-gnu-library/3.4
to install packages into?  (y/n) y

Any ideas why the personal library is suggesting NA? Is there a way to manually override this?

Body:
My solution was the following:

In the file /usr/lib/R/etc/Renviron there is a configuration of R.

In lines 43-45 there is:

# edd Jun 2017  Comment-out R_LIBS_USER
#R_LIBS_USER=${R_LIBS_USER-'~/R/x86_64-pc-linux-gnu-library/3.4'}
##R_LIBS_USER=${R_LIBS_USER-'~/Library/R/3.4/library'}

I have uncommented R_LIBS_USER=${R_LIBS_USER-'~/R/x86_64-pc-linux-gnu-library/3.4'}, restarted RStudio and now it works.

EDIT: Looking at the comments, it seems like a planned behaviour. Here is another solution.


问:
How to Schedule unclearable or non-removable Local Notification?
I want add simple local notification which unclearable for particular time. like 10 minutes you can not clear it. if solution is possible through other way suggestion appreciated.
Anyone having idea about it?</p>

答:
what you can do is when you are dismissing all pending notification reset the particular notification again or you can remove other notifications by their identifier and keep the particular notification

here is the code to fetch all pending notifications.

```<code>   let center = UNUserNotificationCenter.current()
    center.getPendingNotificationRequests(completionHandler: { requests in

        print(requests)

        for request in requests {

            srrNotification.append(request)
            print(request)
        }
    })
</code>```

Body:
what you can do is when you are dismissing all pending notification reset the particular notification again or you can remove other notifications by their identifier and keep the particular notification

here is the code to fetch all pending notifications.

   let center = UNUserNotificationCenter.current()
    center.getPendingNotificationRequests(completionHandler: { requests in

        print(requests)

        for request in requests {

            srrNotification.append(request)
            print(request)
        }
    })