问:
Visitor and double dispatch without overriding "accept" method in c++
Ok: here´s my problem: I have a base composit class which accepts a visitor an then iterates over its nodes. Works like a charm.
But then, I have to used a derived from this composit and recognized that I have to override the "accept()" method in the derived class to have correct double dispatching (which I did not understand).

This brings out two flaws: first, I have to break the hidden structure of the base, and second, I have to duplicate code. To clearify, here´s my pseudo-code:

```<code>struct Visitor
{
    void visit( BaseComposit*)    { throw( "not expected"); };
    void visit( DerivedComposit*) { throw( "ok"); };
};

class BaseComposit
{
private:

    std::vector< BaseComposit*> nodes;

public:

    virtual void accept( Visitor* v)
    {
        v->visit( this);

        for( int i = 0; i < nodes.size(); i++)
            nodes[ i]->accept( v);
    }
};

class DerivedComposit : public BaseComposit
{
public:
};
</code>```

Any ellegant solution on that ?
Thank you !

Edit: added "virtual" to "accept()" to make it more precise...

答:
Any ellegant solution on that ?

Not really. That's what makes the visitor pattern a bit of a pain. Though you could mitigate the duplication a bit with the help of a template:

```<code>class BaseComposit
{
private:

    std::vector<BaseComposit*> nodes;

protected:

    template<class T>
    void accept_impl( Visitor* v, T* this_ )
    {
        v->visit( this_ );

        for(int i = 0; i < nodes.size(); i++)
            nodes[i]->accept(v);
    }

public:

    virtual void accept( Visitor* v ) { accept_impl( v, this ); }
};
</code>```

Now the duplication that accept must incur is smaller.

Also, as @Oliv pointed out, your example really ought to have accept be a virtual function. Otherwise the whole thing won't work.

If you feel really adventurous, you can introduce a macro to ease the "injection" of accept into each class. Like so:

```<code>#define INJECT_ACCEPT() void accept( Visitor* v ) override { accept_impl( v, this ); }
</code>```

But you'd still need to use it in each derived class to make the definition appear.

```<code>class DerivedComposit : public BaseComposit
{
public:
    INJECT_ACCEPT();
};
</code>```

The semi-colon is allowed by a curious feature of the C++ grammar. So I suppose one may argue the above looks "natural".

Body:
Ok: here´s my problem: I have a base composit class which accepts a visitor an then iterates over its nodes. Works like a charm.
But then, I have to used a derived from this composit and recognized that I have to override the "accept()" method in the derived class to have correct double dispatching (which I did not understand).

This brings out two flaws: first, I have to break the hidden structure of the base, and second, I have to duplicate code. To clearify, here´s my pseudo-code:

struct Visitor
{
    void visit( BaseComposit*)    { throw( "not expected"); };
    void visit( DerivedComposit*) { throw( "ok"); };
};

class BaseComposit
{
private:

    std::vector< BaseComposit*> nodes;

public:

    virtual void accept( Visitor* v)
    {
        v->visit( this);

        for( int i = 0; i < nodes.size(); i++)
            nodes[ i]->accept( v);
    }
};

class DerivedComposit : public BaseComposit
{
public:
};

Any ellegant solution on that ?
Thank you !

Edit: added "virtual" to "accept()" to make it more precise...

Body:
Any ellegant solution on that ?

Not really. That's what makes the visitor pattern a bit of a pain. Though you could mitigate the duplication a bit with the help of a template:

class BaseComposit
{
private:

    std::vector<BaseComposit*> nodes;

protected:

    template<class T>
    void accept_impl( Visitor* v, T* this_ )
    {
        v->visit( this_ );

        for(int i = 0; i < nodes.size(); i++)
            nodes[i]->accept(v);
    }

public:

    virtual void accept( Visitor* v ) { accept_impl( v, this ); }
};

Now the duplication that accept must incur is smaller.

Also, as @Oliv pointed out, your example really ought to have accept be a virtual function. Otherwise the whole thing won't work.

If you feel really adventurous, you can introduce a macro to ease the "injection" of accept into each class. Like so:

#define INJECT_ACCEPT() void accept( Visitor* v ) override { accept_impl( v, this ); }

But you'd still need to use it in each derived class to make the definition appear.

class DerivedComposit : public BaseComposit
{
public:
    INJECT_ACCEPT();
};

The semi-colon is allowed by a curious feature of the C++ grammar. So I suppose one may argue the above looks "natural".


来源: stackexchange

问:
My sql Group By case for getting highest paid employee in specific year
there is two table
1 Employee
2 salary

```<code>Employee : eId, ename, salaryId
Salary : salaryId, eId, salary, date
</code>```

salary table contains monthly record of employee salary,
like:

eId date salary

```<code>1       2015-jan-01    10000
1       2015-feb-01    10000
1       2015-mar-01    10000
1       2014-jan-01    10000
1       2014-feb-01    10000
1       2014-mar-01    10000
2       2015-jan-01    10000
2       2015-feb-01    10000
2       2015-mar-01    10000
2       2014-jan-01    10000
2       2014-feb-01    10000
2       2014-mar-01    20000
</code>```

so the query is to give me highest paid employee in specific year for ex: 2014

so here using group by  with date and sum of salary output is :

empid - empname  - sum(salary)

2     - xyz     - 40000

答:
#highest paid emp in specific year
SELECT e.empId,e.empName,SUM(s.salary),s.salDate
FROM emp e INNER JOIN salary s ON e.empId = s.empId
WHERE YEAR(s.salDate)=2009 GROUP BY s.empId ORDER BY SUM(s.salary) DESC LIMIT 1;

ContentLicense: CC BY-SA 3.0

Body:
there is two table
1 Employee
2 salary

Employee : eId, ename, salaryId
Salary : salaryId, eId, salary, date

salary table contains monthly record of employee salary,
like:

eId date salary

1       2015-jan-01    10000
1       2015-feb-01    10000
1       2015-mar-01    10000
1       2014-jan-01    10000
1       2014-feb-01    10000
1       2014-mar-01    10000
2       2015-jan-01    10000
2       2015-feb-01    10000
2       2015-mar-01    10000
2       2014-jan-01    10000
2       2014-feb-01    10000
2       2014-mar-01    20000

so the query is to give me highest paid employee in specific year for ex: 2014

so here using group by  with date and sum of salary output is :

empid - empname  - sum(salary)

2     - xyz     - 40000


问:
How to restrict access to specific resources by client key in wso2 api manager for client credentials flow?
I want to implement server to server communication with wso2 api manager so my api can be used by thirdparty clients that can create their own apps and subscribe on my api. Also these clients should be restricted by specific set of resources - there is a set of organization ids and each specific client should have access only to some subset of ids. I figured out that client keys are stored in IDN_OAUTH_CONSUMER_APPS table of WSO2AM_DB. I can attach to this DB and read client ids from separate service that will implement clientId-to-organizationIds mapping and with help of mediators I can call this service, check if organization id specified in url is allowed and add organization id property in access token so backend service can check one more time if organization is allowed. But I'm not sure if this is correct approach. Maybe there is something in wso2 that can help without such manipulations?</p>

答:
Also these clients should be restricted by specific set of resources

As you found out - the API manager authorizes calls based on the endpoint. The resources (e.g. specific ids) themselves should be authorized by the backend service. I am not sure that it's reasonable to enforce this level of authorization on the API manager (I'm not saying it's not possible, just it may be not flexible enough).

Maybe there is something in wso2 that can help without such manipulations?

What I suggest is following - send a JWT token to the backend service. The backend service should do the authorization (based on the username, application, etc) without hard binding to the product database .

The linked documentation as well describes how to implement own token generator, so you could add additional claims to the jwt token (such as organization id, etc..).


问:
How to convert a query to linq
I have two data tables which are identical i.e. both have a column called EventId as their primary keys.

The first data table (FilteredEvents) contains all events i.e. ones that I don't need as well as ones that I need.

The second data table (EventToBeCreated) contains the events that need to be created.

Here is an example:

FilteredEvents contains IDs:

1
  2
  3
  4
  5

EventToBeCreated contains IDs:

1
  2
  3
  4

In this example, the correct result would be 5, as it is in FilteredEvents, but not in EventToBeCreated.

This SQL query does what I need, but I need the LINQ equivalent:

```<code>SELECT Event_Filtered.EventID
FROM Event_Filtered
LEFT OUTER JOIN Event_ToBeCreated
  ON Event_Filtered.EventID = Event_ToBeCreated.EventID
WHERE (Event_ToBeCreated.EventID IS NULL)
</code>```

答:
You didn't provide entity details and other required informations, it should be something like that;</p>

```<code>var query = from ef in yourContext.Event_Filtered
            join et in yourContext.Event_ToBeCreated on ef.EventID equals et.EventID into ps
            from ps in ps.DefaultIfEmpty()
            where et.EventID == null
            select ef.EventID
</code>```

Title: How to convert a query to linq

Body:
I have two data tables which are identical i.e. both have a column called EventId as their primary keys.

The first data table (FilteredEvents) contains all events i.e. ones that I don't need as well as ones that I need.

The second data table (EventToBeCreated) contains the events that need to be created.

Here is an example:

FilteredEvents contains IDs:

1
  2
  3
  4
  5

EventToBeCreated contains IDs:

1
  2
  3
  4

In this example, the correct result would be 5, as it is in FilteredEvents, but not in EventToBeCreated.

This SQL query does what I need, but I need the LINQ equivalent:

SELECT Event_Filtered.EventID
FROM Event_Filtered
LEFT OUTER JOIN Event_ToBeCreated
  ON Event_Filtered.EventID = Event_ToBeCreated.EventID
WHERE (Event_ToBeCreated.EventID IS NULL)

Body:
You didn't provide entity details and other required informations, it should be something like that;

var query = from ef in yourContext.Event_Filtered
            join et in yourContext.Event_ToBeCreated on ef.EventID equals et.EventID into ps
            from ps in ps.DefaultIfEmpty()
            where et.EventID == null
            select ef.EventID


问:
Nextcloud Uploader
I just got some questions, maybe some of you can answer.

The benefit by Nextcloud / Owncloud and so on is more than just uploading taking files with you and so on.
It does version the files, make them downloadable - as well secure behind.

It would be benefitial for me and most everyone who is dealing with the Question:

"How to upload documents, link them in some kind of Database (which main purpose is to operate with information) and versioning, saving, editing and so on does not need to be implemented by me / others, because it is handled by Nextcloud (in my case prefered)?"

Is there any script outside, or maybe some kind of plugin to have that benefit?

In my vision I would need:

One "Drag and Drop" Area for Documents / Pictures etc.

This should have a hidden field, which is filled with a id, with which the system can identify the file.

a onetime Link (with retention of that link by one day or so) what is generated by php (could also be a script) and generates a share Link for given id.

(not needed since now, but nice to have:) some script as in 2, where versions of some given File should be viewed.

Some solution could be:

something similar to an "iframe" for a shared link with public upload.
But Im not very happy of using IFrames... Something better would be nice.

答:
Drag & Drop is available in the Web UI. For additional meta data, use a hook mechanism on postCreate (\OCP\Files\Node $node) within a custom app/module you'd need to deploy. For hooks, see https://docs.nextcloud.com/server/12/developer_manual/app/hooks.html.
About meta data: you don't need to store them in a database necessarily, you can also use custom WebDav properties. I wrote a blog post about it recently: https://medium.com/@mathiasconradt/how-to-assign-custom-meta-data-to-your-documents-on-nextcloud-23356cf3f926

Links with a time limit to be valid can be generated manually via Web UI. If you need it automated on upload, use the same approach as in (1): hook mechanism that listens to file creations, as part of a custom app.

at the moment, you can only restore old versions. I think you cannot diff/view them. Would require a custom app.

General info on how to write your own module / app: https://docs.nextcloud.com/server/12/developer_manual/app/index.html

Title: Nextcloud Uploader


问:
DOM remove a checkbox javascript
I'm quite new to Javascript and don't know where to start for this one. I have a list of checkboxes. I want to achieve when a checkbox is checked, the checkbox is removed from the list. I found some different solutions but they all have a button you need to press to remove the checkbox and i just want the checkbox removed when it's checked.

This is how my HTML looks like:

```<code><ul class="list-group">
                    <li class="list-group-item">
                        <div class="checkbox">
                            <label>
                                <input type="checkbox"> Item 1
                            </label>
                        </div>
                    </li>
                    <li class="list-group-item">
                        <div class="checkbox">
                            <label>
                                <input type="checkbox"> Item 2
                            </label>
                        </div>
                    </li>
                </ul>
</code>```

答:
Depending on how precise you need to be, here is one that will remove the parent LI when clicked

You can add if (this.checked) { ... } if you only want to remove when checked

$(function() {
  $("input[type=checkbox]").on("click",function() {
    $(this).closest("li").remove(); // $(this).remove(); to remove the checkbox only
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<ul class="list-group">
  <li class="list-group-item">
    <div class="checkbox">
      <label><input type="checkbox"> Item 1</label>
    </div>
  </li>
  <li class="list-group-item">
    <div class="checkbox">
      <label><input type="checkbox"> Item 2</label>
    </div>
  </li>
</ul></code>```

Title: DOM remove a checkbox javascript

Body:
I'm quite new to Javascript and don't know where to start for this one. I have a list of checkboxes. I want to achieve when a checkbox is checked, the checkbox is removed from the list. I found some different solutions but they all have a button you need to press to remove the checkbox and i just want the checkbox removed when it's checked.

This is how my HTML looks like:

                                <input type="checkbox"> Item 1

                                <input type="checkbox"> Item 2

Body:
Depending on how precise you need to be, here is one that will remove the parent LI when clicked

You can add if (this.checked) { ... } if you only want to remove when checked

$(function() {
  $("input[type=checkbox]").on("click",function() {
    $(this).closest("li").remove(); // $(this).remove(); to remove the checkbox only
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<ul class="list-group">
  <li class="list-group-item">
    <div class="checkbox">
      <label><input type="checkbox"> Item 1</label>
    </div>
  </li>
  <li class="list-group-item">
    <div class="checkbox">
      <label><input type="checkbox"> Item 2</label>
    </div>
  </li>
</ul>


问:
Disallow editing of tables in ASP.NET Dynamic Data
What is the best way to disallow editing of existing entries in ASP.NET Dynamic Data while it should still be possible to add new entries? If possible, I would prefer a solution without custom templates.</p>

答: I think I found a possible solution myself: http://csharpbits.notaclue.net/2008/05/introduction-this-project-is-going-to.html</p>

ContentLicense: CC BY-SA 2.5


问:
Debian 9: the php5 packages is not installed
I need to install some packages to prepare the workspace for a project in the Debian 9 OS runs in a VB. I have the instruction:

```<code>----------------------------------------------------------------------
The following Debian 8 packages are required to run [X-Product]:

sudo apt-get install exim4 ntp pwgen curl php5-dev php-pear pkg-config nmap libzmq3 libzmq3-dev libapache2-mod-php5 apache2 percona-server-server-5.6 php5-cli php5-mysql php5-curl php5-intl daemontools-run oracle-java8-installer ant ruby-compass libtool-bin
----------------------------------------------------------------------
</code>```

When I run the command, I get the following terminal stack,

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
Package php5-cli is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

Package php5-mysql is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

Package php5-curl is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

Package libapache2-mod-php5 is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Unable to locate package php5-dev
E: Unable to locate package libzmq3
E: Package 'libapache2-mod-php5' has no installation candidate
E: Package 'php5-cli' has no installation candidate
E: Package 'php5-mysql' has no installation candidate
E: Package 'php5-curl' has no installation candidate
E: Unable to locate package php5-intl
</code>```

I did some research on the internet, did the following at next,

```<code>sudo add-apt-repository ppa:ondrej/php
sudo apt-get update
</code>```

It doesn't help me at all. What do I need to fix this? I have very little knowledge about Debian if you ask

Note: I followed the instructions in the answer provided, the issue is still not solved like I cant see the php version

When I run the command of
sudo apt-get install php5.6

It prints in the terminal,

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
Note, selecting 'php5.6-json' for regex 'php5.6'
Note, selecting 'php5.6-common' for regex 'php5.6'
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
</code>```

To look for the PHP version,

```<code>sudo php -v
</code>```

It prints in the terminal,

```<code>sudo: php: command not found
</code>```

More info like if I run it

sudo apt-get install php5-dev
I get error
E: Unable to locate package php5-dev

But, the command
sudo apt-get install php-dev is successful

The command
dpkg -l | grep php| awk '{print $2}' |tr "\n" " " returns value,

Is that mean I hvae php7 installed and that blocks other operations?

```<code>dh-php php-cli php-common php-dev php-gd php-pear php-xml php7.0-cli php7.0-common php7.0-dev php7.0-gd php7.0-json php7.0-opcache php7.0-readline php7.0-xml pkg-php-tools
</code>```

答:
Open the terminal and run the following command:

apt-get install apt-transport-https lsb-release ca-certificates

Get the gpg key:

wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg

Add the new repository to your sources:

echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list

Install PHP5.6

apt-get update
apt-get install php5.6

Update

Workaround for line echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list:

Run this, and take note of the output:

lsb_release -sc

Open up /etc/apt/sources.list.d/php.list in your editor of choice and append this to the bottom:

deb https://packages.sury.org/php/ OUTPUT_FROM_LSC_COMMAND main

Body:
I need to install some packages to prepare the workspace for a project in the Debian 9 OS runs in a VB. I have the instruction:

----------------------------------------------------------------------
The following Debian 8 packages are required to run [X-Product]:

sudo apt-get install exim4 ntp pwgen curl php5-dev php-pear pkg-config nmap libzmq3 libzmq3-dev libapache2-mod-php5 apache2 percona-server-server-5.6 php5-cli php5-mysql php5-curl php5-intl daemontools-run oracle-java8-installer ant ruby-compass libtool-bin
----------------------------------------------------------------------

When I run the command, I get the following terminal stack,

Reading package lists... Done
Building dependency tree
Reading state information... Done
Package php5-cli is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

Package php5-mysql is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

Package php5-curl is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

Package libapache2-mod-php5 is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Unable to locate package php5-dev
E: Unable to locate package libzmq3
E: Package 'libapache2-mod-php5' has no installation candidate
E: Package 'php5-cli' has no installation candidate
E: Package 'php5-mysql' has no installation candidate
E: Package 'php5-curl' has no installation candidate
E: Unable to locate package php5-intl

I did some research on the internet, did the following at next,

sudo add-apt-repository ppa:ondrej/php
sudo apt-get update

It doesn't help me at all. What do I need to fix this? I have very little knowledge about Debian if you ask

Note: I followed the instructions in the answer provided, the issue is still not solved like I cant see the php version

When I run the command of
sudo apt-get install php5.6

It prints in the terminal,

Reading package lists... Done
Building dependency tree
Reading state information... Done
Note, selecting 'php5.6-json' for regex 'php5.6'
Note, selecting 'php5.6-common' for regex 'php5.6'
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

To look for the PHP version,

sudo php -v

It prints in the terminal,

sudo: php: command not found

More info like if I run it

sudo apt-get install php5-dev
I get error
E: Unable to locate package php5-dev

But, the command
sudo apt-get install php-dev is successful

The command
dpkg -l | grep php| awk '{print $2}' |tr "\n" " " returns value,

Is that mean I hvae php7 installed and that blocks other operations?

dh-php php-cli php-common php-dev php-gd php-pear php-xml php7.0-cli php7.0-common php7.0-dev php7.0-gd php7.0-json php7.0-opcache php7.0-readline php7.0-xml pkg-php-tools


问:
How to check if partials does not exist? (handlebars)?
When "MY BLOCK", was not registered with Handlebars.registerPartial
How to check if it not exist and throw error.  </p>

```<code>{{#"MY BLOCK"}}
'123',
{{/"MY BLOCK"}}'
</code>```

答:
In javascript i could check</p>

```<code>if(!("MY BLOCK" in Handlebars.helpers)){
 throw "error";
}
</code>```

Body:
When "MY BLOCK", was not registered with Handlebars.registerPartial
How to check if it not exist and throw error.

{{#"MY BLOCK"}}
'123',
{{/"MY BLOCK"}}'

Body:
In javascript i could check

if(!("MY BLOCK" in Handlebars.helpers)){
 throw "error";
}


问:
How to create full horizontal row with Split.js?
I want to use Split.js for creating my specific layout like

```<code><div id="a" class="split split-horizontal">
</div>
<div id="b" class="split split-horizontal">
    <div id="d" class="split content"></div>
    <div id="e" class="split content"></div>
    <div id="f" class="split content"></div>
</div>
<div id="c" class="split split-horizontal">
</div>

<script>
    Split(['#a', '#b', '#c'], {
        gutterSize: 20,
        cursor: 'pointer'
    });
    Split(['#d', '#e', '#f'], {
        direction: 'vertical',
        sizes: [15, 70, 15],
        gutterSize: 20,
        cursor: 'row-resize'
    });
</script>
</code>```

but above code does not work.

Can anyone help me?
How can I create the layout with Split.js because does not exist any sample like that in their site?

Classic sample in JSFiddle

My Sample in JSFiddle

答:
You where pretty close. First of all you didn't add content class to the left/right pain, so they didn't show. Then you mixed up the horizontal split. Here's a working fiddle.

```<code><div id="a" class="split content"></div>
<div id="b" class="split">
    <div id="d" class="split content split-horizontal"></div>
    <div id="e" class="split content split-horizontal"></div>
    <div id="f" class="split content split-horizontal"></div>
</div>
<div id="c" class="split content"></div>

Split(['#a', '#b', '#c'], {
    gutterSize: 20,
    cursor: 'pointer',
    direction: 'vertical',
});
Split(['#d', '#e', '#f'], {
    sizes: [15, 70, 15],
    gutterSize: 20,
    cursor: 'row-resize',
});
</code>```

Body:
I want to use Split.js for creating my specific layout like

but above code does not work.

Can anyone help me?
How can I create the layout with Split.js because does not exist any sample like that in their site?

Classic sample in JSFiddle

My Sample in JSFiddle

Body:
You where pretty close. First of all you didn't add content class to the left/right pain, so they didn't show. Then you mixed up the horizontal split. Here's a working fiddle.

<div id="a" class="split content"></div>
<div id="b" class="split">
    <div id="d" class="split content split-horizontal"></div>
    <div id="e" class="split content split-horizontal"></div>
    <div id="f" class="split content split-horizontal"></div>
</div>
<div id="c" class="split content"></div>

Split(['#a', '#b', '#c'], {
    gutterSize: 20,
    cursor: 'pointer',
    direction: 'vertical',
});
Split(['#d', '#e', '#f'], {
    sizes: [15, 70, 15],
    gutterSize: 20,
    cursor: 'row-resize',
});


问:
What is the difference between Array.function and Array.prototype.function?
I've found that some functions like concat() push() every() both exist in Array and Array.prototype(with firefox 57.0.1 console)

It's confusing since prototype methods exist in Array.

Additionally, where does staic method(Array.from(), Array.isArray() etc) exists in?

I think I've understood concepts of javascript prototype to some extent, so what I'm curious about is why prototype methods(concat() push() ...) apear both in Array and Array.prototype

答:
Firefox's Array function appears to have additional (non-conformant) "static" methods that replicate the prototype methods except that they take the array as the first parameter instead of via the implicit this context.

To see those methods and properties of Array, use:

```<code>Object.getOwnPropertyNames(Array)
</code>```

In Firefox you'll (mostly) see the same list as in your first screenshot.   I haven't yet figured out why Array.isArray is missing in your list, but it does appear in my Firefox 57.

In Chrome you'll only see the ES6 mandated "static" methods (i.e. Array.from, Array.isArray, Array.of) and the standard properties.

Body:
Firefox's Array function appears to have additional (non-conformant) "static" methods that replicate the prototype methods except that they take the array as the first parameter instead of via the implicit this context.

To see those methods and properties of Array, use:

Object.getOwnPropertyNames(Array)

In Firefox you'll (mostly) see the same list as in your first screenshot.   I haven't yet figured out why Array.isArray is missing in your list, but it does appear in my Firefox 57.

In Chrome you'll only see the ES6 mandated "static" methods (i.e. Array.from, Array.isArray, Array.of) and the standard properties.


问:
Mongoose - finding in subdocument by criteria
I've just got stuck with this problem. I've got two Mongoose schemas:

```<code>let userSchema = new mongoose.Schema({
            username: { type:String, default:null },
            email: { type:String, required:true },
            role: { type: mongoose.Schema.Types.ObjectId, ref: 'Role', required: true },
        });

let roleSchema = new mongoose.Schema({
        name: { type:String, default:"Player" },
        privileges:
            [
                {
                    resource: String ,
                    actions: [ String ]
                },
            ],

    });
</code>```

Question si how to find users with specific criteria for exemple Get All Users with Role Name = "super Admin" I try this by no result

```<code>User.find({'role.name':'Super Admin'}).populate('role')
    .exec()
    .then(results => {
        res.success(results);
    }, error => {
        res.error(error);
    })
</code>```

答:
This should give all the users with the desired schema:

```<code>db.roleSchema.aggregate([
    {$match:{name:'Super Admin'},
    {$lookup: {from: "userSchema",localField: "_id",foreignField: "role",as: "userSchema"}},
    {$unwind : "$userSchema"},
    {$group:{
          _id:'$users._id',
          username:{$first:'$users.username'},
          email:{$first:'$users.email'}
    }}
])
</code>```

Hope my answer was helpful

Body:
I've just got stuck with this problem. I've got two Mongoose schemas:

let userSchema = new mongoose.Schema({
            username: { type:String, default:null },
            email: { type:String, required:true },
            role: { type: mongoose.Schema.Types.ObjectId, ref: 'Role', required: true },
        });

let roleSchema = new mongoose.Schema({
        name: { type:String, default:"Player" },
        privileges:
            [
                {
                    resource: String ,
                    actions: [ String ]
                },
            ],

    });

Question si how to find users with specific criteria for exemple Get All Users with Role Name = "super Admin" I try this by no result

User.find({'role.name':'Super Admin'}).populate('role')
    .exec()
    .then(results => {
        res.success(results);
    }, error => {
        res.error(error);
    })

Body:
This should give all the users with the desired schema:

db.roleSchema.aggregate([
    {$match:{name:'Super Admin'},
    {$lookup: {from: "userSchema",localField: "_id",foreignField: "role",as: "userSchema"}},
    {$unwind : "$userSchema"},
    {$group:{
          _id:'$users._id',
          username:{$first:'$users.username'},
          email:{$first:'$users.email'}
    }}
])

Hope my answer was helpful


问:
Papa Parse single column error Unable to auto-detect delimiting character; defaulted to ','
I have a csv where only one column exists and I am using Papa Parse library to parse the csv.
I receive the following error Unable to auto-detect delimiting character; defaulted to ','

Since it is only a single column it is not comma separated value. I tried to set delimeter config property to auto delimiter: "", but still the same problem

答:
CSV is far from being a standard. Even though there's a RFC, the format itself pre-dates the document, which anyway starts with:

It does not specify an Internet standard of any kind.

Plus CSV is often created by quick and dirty tools that couldn't care less about interoperability. In particular, even a well-known tool like Microsoft Excel generates different file formats depending on the regional settings of the computer where it runs!

All this means that, in order to parse a CSV file, you need to determine the exact file format and, in particular, which character is being used to separate different columns: despite the fact that the C in CSV stands for comma, it's just as common to find semicolons. Depending on the software capabilities options include:

Tell the program

Let the program guess

In your case, guessing goes wrong because you only have one column, thus there aren't any separators in the file that the library can find. The error message is confusing, though, because it suggests there's a default separator (,) but it isn't actually defaulting to it.

Since guessing is neither possible nor needed, just tell it explicitly to use ,:

```<code>{
    delimiter: "",  // auto-detect <--------- We don't want this!
    newline: "",    // auto-detect
    quoteChar: '"',
    header: false,
    dynamicTyping: false,
    preview: 0,
    encoding: "",
    worker: false,
    comments: false,
    step: undefined,
    complete: undefined,
    error: undefined,
    download: false,
    skipEmptyLines: false,
    chunk: undefined,
    fastMode: undefined,
    beforeFirstChunk: undefined,
    withCredentials: undefined
}
</code>```

Body:
CSV is far from being a standard. Even though there's a RFC, the format itself pre-dates the document, which anyway starts with:

It does not specify an Internet standard of any kind.

Plus CSV is often created by quick and dirty tools that couldn't care less about interoperability. In particular, even a well-known tool like Microsoft Excel generates different file formats depending on the regional settings of the computer where it runs!

All this means that, in order to parse a CSV file, you need to determine the exact file format and, in particular, which character is being used to separate different columns: despite the fact that the C in CSV stands for comma, it's just as common to find semicolons. Depending on the software capabilities options include:

Tell the program

Let the program guess

In your case, guessing goes wrong because you only have one column, thus there aren't any separators in the file that the library can find. The error message is confusing, though, because it suggests there's a default separator (,) but it isn't actually defaulting to it.

Since guessing is neither possible nor needed, just tell it explicitly to use ,:

{
    delimiter: "",  // auto-detect <--------- We don't want this!
    newline: "",    // auto-detect
    quoteChar: '"',
    header: false,
    dynamicTyping: false,
    preview: 0,
    encoding: "",
    worker: false,
    comments: false,
    step: undefined,
    complete: undefined,
    error: undefined,
    download: false,
    skipEmptyLines: false,
    chunk: undefined,
    fastMode: undefined,
    beforeFirstChunk: undefined,
    withCredentials: undefined
}


问:
Vue.js bind v-model input with prop initial value
I am trying to pass down a initial value to a select input bound by v-model. I cannot figure out why this doesn't work:

```<code>props: ['team'],
data() {
    form: {
        data: {
            country: this.team.country
        }
    }
}
</code>```

The form.data.country is undefined. Although, the props data is actually passed down. I can access it with Vue Devtools like $vm0.team.country and I can print other data from the props. However, it is not registred in the data().

Also, when trying to debug using mounted(), the property, team, is not defined.

```<code>mounted() {
    console.log(this.team);
}
</code>```

But, as I stated earlier, it is defined when the template is rendered, and can be used like this.

```<code><input class="input" type="text" name="name" :value="team.name" disabled>
</code>```

Why is the properties I am passing not beinged recognized in data()?

答:
The asynchronous loading is not the problem. Even if team is hardcoded above, it's still undefined when data is created in the component. (The component needs to be created before the root Vue that passes the prop.)

There is, perhaps someone will correct me, never a good reason to reference props in your data. Something is either data (the current component knows where to find what it wants) or it's a prop (the component will let it's context supply the info).

Then, as you've discovered, your data is created once. Vue watches everything for changes, but you're vulnerable to changes of the root value. If the thing referenced as a value when data is created, changes, the reactive pipe is broken. The answer to this is the store pattern. You watch a variable in global scope, that never gets replaced, even though it's contents may change.

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

Body:
I am trying to pass down a initial value to a select input bound by v-model. I cannot figure out why this doesn't work:

props: ['team'],
data() {
    form: {
        data: {
            country: this.team.country
        }
    }
}

The form.data.country is undefined. Although, the props data is actually passed down. I can access it with Vue Devtools like $vm0.team.country and I can print other data from the props. However, it is not registred in the data().

Also, when trying to debug using mounted(), the property, team, is not defined.

mounted() {
    console.log(this.team);
}

But, as I stated earlier, it is defined when the template is rendered, and can be used like this.

<input class="input" type="text" name="name" :value="team.name" disabled>

Why is the properties I am passing not beinged recognized in data()?

Body:
The asynchronous loading is not the problem. Even if team is hardcoded above, it's still undefined when data is created in the component. (The component needs to be created before the root Vue that passes the prop.)

There is, perhaps someone will correct me, never a good reason to reference props in your data. Something is either data (the current component knows where to find what it wants) or it's a prop (the component will let it's context supply the info).

Then, as you've discovered, your data is created once. Vue watches everything for changes, but you're vulnerable to changes of the root value. If the thing referenced as a value when data is created, changes, the reactive pipe is broken. The answer to this is the store pattern. You watch a variable in global scope, that never gets replaced, even though it's contents may change.

code


问:
how to list out only specific files in S3 bucket
I have n-number of files in a s3-bucket, where I want to download only specific pattern type of files w.r.t their naming conventions

Code:

```<code>BUCKET_NAME = "MYBucket"
s3_conn  = boto.connect_s3(AWS_keys)
bucket = s3_conn.get_bucket(BUCKET_NAME)

#goto through the list of files
bucket_list = bucket.list(prefix='Test_folder/OUT/abc_')

for l in bucket_list:
    key_string = str(l.key)
    s3_path = DOWNLOAD_LOCATION_PATH + key_string
    try:
       print ("Current File is ", s3_path)
       l.get_contents_to_filename(s3_path)
    except (OSError,S3ResponseError) as e:
         pass
</code>```

Above code works fine for only one type of File Naming ie: abc_

What if I want list of files with pattern like: abc_, axy_, xa_ya_zf_, gelnique_

Any Suggestion?

答:
A delimiter can be specified together with prefix. AWS S3 builds a common prefix from these two and returns content in the bucket matching the common prefix.

```<code>bucket_list = bucket.list(prefix='Test_folder/OUT/', delimiter='_')
</code>```

Common prefixes is a substring from the beginning of the key to the first occurrence of the specified delimiter after the prefix. This doesn't guarantee only matches like 'Test_folder/OUT/abc_' but also 'Test_folder/OUT/mydir/abc_'.

Body:
I have n-number of files in a s3-bucket, where I want to download only specific pattern type of files w.r.t their naming conventions

Code:

BUCKET_NAME = "MYBucket"
s3_conn  = boto.connect_s3(AWS_keys)
bucket = s3_conn.get_bucket(BUCKET_NAME)

#goto through the list of files
bucket_list = bucket.list(prefix='Test_folder/OUT/abc_')

for l in bucket_list:
    key_string = str(l.key)
    s3_path = DOWNLOAD_LOCATION_PATH + key_string
    try:
       print ("Current File is ", s3_path)
       l.get_contents_to_filename(s3_path)
    except (OSError,S3ResponseError) as e:
         pass

Above code works fine for only one type of File Naming ie: abc_

What if I want list of files with pattern like: abc_, axy_, xa_ya_zf_, gelnique_

Any Suggestion?

Body:
A delimiter can be specified together with prefix. AWS S3 builds a common prefix from these two and returns content in the bucket matching the common prefix.

bucket_list = bucket.list(prefix='Test_folder/OUT/', delimiter='_')

Common prefixes is a substring from the beginning of the key to the first occurrence of the specified delimiter after the prefix. This doesn't guarantee only matches like 'Test_folder/OUT/abc_' but also 'Test_folder/OUT/mydir/abc_'.


答: Debian 9 does not contain PHP 5.x (see https://wiki.debian.org/PHP). To install it from the ppa, install the package php5.6 and accordingly named other packages  (like libapache2-mod-php5.6 instead of libapache2-mod-php5)

Title: Debian 9: the php5 packages is not installed


问:
Android Packaging Problem: resources.ap_ does not exist
I am trying to fix a problem in Eclipse for like 3 hours and I haven't made any progress. Tomorrow is the customer coming to look at my app, and I have no time left. This is really frustrating!

This morning when I was coding and I wanted to run my app on my device Eclipse crashed all of a sudden. 'aapt.exe has stopped working'

After this Eclipse wasn't starting anymore. It froze at the splash image.

I looked on the internet and tried different solutions like going back to Java SE 6 update 20, changing .ini file etc. in the end reinstalling Eclipse did the job.

Shortly after that the 'aapt.exe has stopped working' returned. I found a solution by changing my projects target. 1.5, 1.6, 2.2 doesn't matter, as long as it's different than the one before.

Now I get the Error generating final archive: java.io.FileNotFoundException: C:\xxx\bin\resources.ap_ does not exist error.

I tried clean but that doesn't work. Deleting and automatically regenarting R.java also didn't work.

I ran the same code in Netbeans with the Android plugin and there it gives me the 'aapt.exe has stopped working' again :(

Please guys, how can I fix this?

Edit:

I think I may have found the reason. These are the error lines in the console:

```<code>org.xmlpull.v1.XmlPullParserException: Binary XML file line #3: <bitmap> requires a valid src attribute
at android.graphics.drawable.BitmapDrawable.inflate(BitmapDrawable.java:341)
at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:779)
at android.graphics.drawable.Drawable.createFromXml(Drawable.java:720)
at com.android.layoutlib.bridge.ResourceHelper.getDrawable(ResourceHelper.java:150)
at com.android.layoutlib.bridge.BridgeTypedArray.getDrawable(BridgeTypedArray.java:668)
at android.view.View.<init>(View.java:1846)
at android.view.View.<init>(View.java:1795)
at android.view.ViewGroup.<init>(ViewGroup.java:282)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:619)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:574)
at org.eclipse.equinox.launcher.Main.run(Main.java:1407)
at org.eclipse.equinox.launcher.Main.main(Main.java:1383)
[2011-01-17 16:37:20 - gegevens.xml] Unable to resolve drawable "com.android.layoutlib.utils.ResourceValue@267e33de" in attribute "background"
</code>```

The file it's talking about is 'bg.png'. It's a small png file which I repeat in a .xml file.

```<code><?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/bg" android:tileMode="repeat" />
</code>```

This file has worked from the first time without any problems.
I deleted it from the drawable folder, waited for an error message, and then added it back. The red x next to the foldername got away, but still nothing different...

答: I just ran into this same problem after importing my project from another machine, but didn't have any errors in the console like the OP. I unchecked Project->Build Automatically and then did Project->Clean and this solved my problem. I was actually missing several files in the bin/ directory for my project and this fixed them all.</p>

Body:
I am trying to fix a problem in Eclipse for like 3 hours and I haven't made any progress. Tomorrow is the customer coming to look at my app, and I have no time left. This is really frustrating!

This morning when I was coding and I wanted to run my app on my device Eclipse crashed all of a sudden. 'aapt.exe has stopped working'

After this Eclipse wasn't starting anymore. It froze at the splash image.

I looked on the internet and tried different solutions like going back to Java SE 6 update 20, changing .ini file etc. in the end reinstalling Eclipse did the job.

Shortly after that the 'aapt.exe has stopped working' returned. I found a solution by changing my projects target. 1.5, 1.6, 2.2 doesn't matter, as long as it's different than the one before.

Now I get the Error generating final archive: java.io.FileNotFoundException: C:\xxx\bin\resources.ap_ does not exist error.

I tried clean but that doesn't work. Deleting and automatically regenarting R.java also didn't work.

I ran the same code in Netbeans with the Android plugin and there it gives me the 'aapt.exe has stopped working' again :(

Please guys, how can I fix this?

Edit:

I think I may have found the reason. These are the error lines in the console:

org.xmlpull.v1.XmlPullParserException: Binary XML file line #3: <bitmap> requires a valid src attribute
at android.graphics.drawable.BitmapDrawable.inflate(BitmapDrawable.java:341)
at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:779)
at android.graphics.drawable.Drawable.createFromXml(Drawable.java:720)
at com.android.layoutlib.bridge.ResourceHelper.getDrawable(ResourceHelper.java:150)
at com.android.layoutlib.bridge.BridgeTypedArray.getDrawable(BridgeTypedArray.java:668)
at android.view.View.<init>(View.java:1846)
at android.view.View.<init>(View.java:1795)
at android.view.ViewGroup.<init>(ViewGroup.java:282)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:619)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:574)
at org.eclipse.equinox.launcher.Main.run(Main.java:1407)
at org.eclipse.equinox.launcher.Main.main(Main.java:1383)
[2011-01-17 16:37:20 - gegevens.xml] Unable to resolve drawable "com.android.layoutlib.utils.ResourceValue@267e33de" in attribute "background"

The file it's talking about is 'bg.png'. It's a small png file which I repeat in a .xml file.

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/bg" android:tileMode="repeat" />

This file has worked from the first time without any problems.
I deleted it from the drawable folder, waited for an error message, and then added it back. The red x next to the foldername got away, but still nothing different...


问:
Separate QByteArray hex values to separate int's
How can I parse these "\" separated HEX values in the QByteArray into 8 separate int's?

```<code>QByteArray mainArray = "\xFF\xFF\x01\x04\x01\x0B\x03\xEC";
int num1;
int num2;
int num3;
...
</code>```

答:
The \x escape sequence represents a hexadecimal value within string literals and character literals. The two hexadecimal digits following the \x will be parsed as a single byte. For example:

```<code>QByteArray foo1 = "\x46\x6f\x6f";
QByteArray foo2 = "Foo";

Q_ASSERT(foo1 == foo2); // 'foo1' and 'foo2' are equal
</code>```

If you wish to access the hexadecimally represented values in your mainArray, simply use the QByteArray::at or the subscript operator as follows:

```<code>QByteArray mainArray = "\xFF\xFF\x01\x04\x01\x0B\x03\xEC";
int num1 = mainArray[0]; // 0xFF
int num2 = mainArray[1]; // 0xFF
int num3 = mainArray[2]; // 0x01
// ...
</code>```

One thing to keep in mind, the value type of QByteArray is char which is a signed type, therefore the \xFF on most systems will be -1 insead of 255. To fix the mentioned issue, here is a possible solution:

```<code>QByteArray mainArray = "\xFF\xFF\x01\x04\x01\x0B\x03\xEC";
int num1 = 0xff & mainArray[0];
int num2 = 0xff & mainArray[1];
int num3 = 0xff & mainArray[2];
// ...
</code>```

Body:
How can I parse these "\" separated HEX values in the QByteArray into 8 separate int's?

QByteArray mainArray = "\xFF\xFF\x01\x04\x01\x0B\x03\xEC";
int num1;
int num2;
int num3;
...

Body:
The \x escape sequence represents a hexadecimal value within string literals and character literals. The two hexadecimal digits following the \x will be parsed as a single byte. For example:

QByteArray foo1 = "\x46\x6f\x6f";
QByteArray foo2 = "Foo";

Q_ASSERT(foo1 == foo2); // 'foo1' and 'foo2' are equal

If you wish to access the hexadecimally represented values in your mainArray, simply use the QByteArray::at or the subscript operator as follows:

QByteArray mainArray = "\xFF\xFF\x01\x04\x01\x0B\x03\xEC";
int num1 = mainArray[0]; // 0xFF
int num2 = mainArray[1]; // 0xFF
int num3 = mainArray[2]; // 0x01
// ...

One thing to keep in mind, the value type of QByteArray is char which is a signed type, therefore the \xFF on most systems will be -1 insead of 255. To fix the mentioned issue, here is a possible solution:

QByteArray mainArray = "\xFF\xFF\x01\x04\x01\x0B\x03\xEC";
int num1 = 0xff & mainArray[0];
int num2 = 0xff & mainArray[1];
int num3 = 0xff & mainArray[2];
// ...


答:
See this code , this is removing current checkbox while you are clicking on checkbo

Code Here

$( '.checkbox input[type="checkbox"]' ).change( function(){
  $(this).remove();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list-group">
                    <li class="list-group-item">
                        <div class="checkbox">
                            <label>
                                <input type="checkbox" class="checkbox">
                            </label>
                        </div>
                    </li>
                    <li class="list-group-item">
                        <div class="checkbox">
                            <label>
                                <input type="checkbox" class="checkbox">
                            </label>
                        </div>
                    </li>
                </ul></code>```

Title: DOM remove a checkbox javascript

Body:
I'm quite new to Javascript and don't know where to start for this one. I have a list of checkboxes. I want to achieve when a checkbox is checked, the checkbox is removed from the list. I found some different solutions but they all have a button you need to press to remove the checkbox and i just want the checkbox removed when it's checked.

This is how my HTML looks like:

                                <input type="checkbox"> Item 1

                                <input type="checkbox"> Item 2

Body:
See this code , this is removing current checkbox while you are clicking on checkbo

Code Here

$( '.checkbox input[type="checkbox"]' ).change( function(){
  $(this).remove();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list-group">
                    <li class="list-group-item">
                        <div class="checkbox">
                            <label>
                                <input type="checkbox" class="checkbox">
                            </label>
                        </div>
                    </li>
                    <li class="list-group-item">
                        <div class="checkbox">
                            <label>
                                <input type="checkbox" class="checkbox">
                            </label>
                        </div>
                    </li>
                </ul>


问:
Stripe Java integration payment process using Spring MVC
I am completely new to Stripe API. I want to embedded a payment gateway in my java J2EE application using Spring MVC. I am using stripe for it.

What I have done so far is I have included checkout.js in my checkout page and hit the pay with card button. It then successfully opens a popup which contains the necessary card details.

When clicking on pay button it should go to the stripe and generate a token for me, then redirect to the success page. But I am unable to hold that token in my back-end and do the necessary stuff.

Can you please provide me the sample codes in Spring MVC which meet my entire requirements?

Thanks in advance.

答:
this is my service class to charge the card
public class StripeApiImpl implements StripeApi{</p>

```<code>@Override
public Charge charge(ChargeRequest chargeRequest) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException  {

    Map<String, Object> chargeParams = new HashMap<>();
    chargeParams.put("amount", chargeRequest.getAmount());
    chargeParams.put("currency", chargeRequest.getCurrency());
    chargeParams.put("description", chargeRequest.getDescription());
    chargeParams.put("source", chargeRequest.getStripeToken());

    return Charge.create(chargeParams);

}
</code>```

Body:
this is my service class to charge the card
public class StripeApiImpl implements StripeApi{

@Override
public Charge charge(ChargeRequest chargeRequest) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException  {

    Map<String, Object> chargeParams = new HashMap<>();
    chargeParams.put("amount", chargeRequest.getAmount());
    chargeParams.put("currency", chargeRequest.getCurrency());
    chargeParams.put("description", chargeRequest.getDescription());
    chargeParams.put("source", chargeRequest.getStripeToken());

    return Charge.create(chargeParams);

}


问:
Sending http GET request using boost::asio, similar to cURL
I'm trying to send a http GET request using the REST API of some domain.
Basically what I'm trying to do is to replace following curl request:

```<code>    curl -k  -H "Content-Type: application/json" -X GET
--data '{"username":"user@name.co", "password":"test"}' https:/domain.name/api/login/
</code>```

with some c++ code using boost::asio.
I do not what to find all c++ code here , but some checkpoints would be great.

答:
I found myself also working with boost in order to send some "customized" HTTP GET request - I ran the server locally on my Ubuntu machine (16.04).

In my case the request was of some proprietary API my server implemented (related to words it kept in its data base), but you can modify the queryStr variable to hold whatever query string you wish for.

Also, change the argv[1] and argv[2] when you ran the program to hold your required values (IP address, query, and port if needed - default is 80).

```<code>#include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;
using namespace std;

int main(int argc, char* argv[])
{
    cout << "main -start" << endl;
    try
    {
        boost::asio::io_service io_service;
        string ipAddress = argv[1]; //"localhost" for loop back or ip address otherwise, i.e.- www.boost.org;
        string portNum = argv[2]; //"8000" for instance;
        string hostAddress;
        if (portNum.compare("80") != 0) // add the ":" only if the port number is not 80 (proprietary port number).
        {
             hostAddress = ipAddress + ":" + portNum;
        }
        else
        {
            hostAddress = ipAddress;
        }
        string wordToQuery = "aha";
        string queryStr = argv[3]; //"/api/v1/similar?word=" + wordToQuery;

        // Get a list of endpoints corresponding to the server name.
        tcp::resolver resolver(io_service);
        tcp::resolver::query query(ipAddress, portNum);
        tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

        // Try each endpoint until we successfully establish a connection.
        tcp::socket socket(io_service);
        boost::asio::connect(socket, endpoint_iterator);

        // Form the request. We specify the "Connection: close" header so that the
        // server will close the socket after transmitting the response. This will
        // allow us to treat all data up until the EOF as the content.
        boost::asio::streambuf request;
        std::ostream request_stream(&request);
        request_stream << "GET " << queryStr << " HTTP/1.1\r\n";  // note that you can change it if you wish to HTTP/1.0
        request_stream << "Host: " << hostAddress << "\r\n";
        request_stream << "Accept: */*\r\n";
        request_stream << "Connection: close\r\n\r\n";

        // Send the request.
        boost::asio::write(socket, request);

        // Read the response status line. The response streambuf will automatically
        // grow to accommodate the entire line. The growth may be limited by passing
        // a maximum size to the streambuf constructor.
        boost::asio::streambuf response;
        boost::asio::read_until(socket, response, "\r\n");

        // Check that response is OK.
        std::istream response_stream(&response);
        std::string http_version;
        response_stream >> http_version;
        unsigned int status_code;
        response_stream >> status_code;
        std::string status_message;
        std::getline(response_stream, status_message);
        if (!response_stream || http_version.substr(0, 5) != "HTTP/")
        {
            std::cout << "Invalid response\n";
            return 1;
        }
        if (status_code != 200)
        {
            std::cout << "Response returned with status code " << status_code << "\n";
            return 1;
        }

        // Read the response headers, which are terminated by a blank line.
        boost::asio::read_until(socket, response, "\r\n\r\n");

        // Process the response headers.
        std::string header;
        while (std::getline(response_stream, header) && header != "\r")
        {
            std::cout << header << "\n";
        }

        std::cout << "\n";

        // Write whatever content we already have to output.
        if (response.size() > 0)
        {
            std::cout << &response;
        }

        // Read until EOF, writing data to output as we go.
        boost::system::error_code error;
        while (boost::asio::read(socket, response,boost::asio::transfer_at_least(1), error))
        {
              std::cout << &response;
        }

        if (error != boost::asio::error::eof)
        {
              throw boost::system::system_error(error);
        }
    }
    catch (std::exception& e)
    {
        std::cout << "Exception: " << e.what() << "\n";
    }

    return 0;
}
</code>```

The original example I followed is here: Boost-simple-http-get-request-sync-client

Body:
I'm trying to send a http GET request using the REST API of some domain.
Basically what I'm trying to do is to replace following curl request:

    curl -k  -H "Content-Type: application/json" -X GET
--data '{"username":"user@name.co", "password":"test"}' https:/domain.name/api/login/

with some c++ code using boost::asio.
I do not what to find all c++ code here , but some checkpoints would be great.

Body:
I found myself also working with boost in order to send some "customized" HTTP GET request - I ran the server locally on my Ubuntu machine (16.04).

In my case the request was of some proprietary API my server implemented (related to words it kept in its data base), but you can modify the queryStr variable to hold whatever query string you wish for.

Also, change the argv[1] and argv[2] when you ran the program to hold your required values (IP address, query, and port if needed - default is 80).

#include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;
using namespace std;

int main(int argc, char* argv[])
{
    cout << "main -start" << endl;
    try
    {
        boost::asio::io_service io_service;
        string ipAddress = argv[1]; //"localhost" for loop back or ip address otherwise, i.e.- www.boost.org;
        string portNum = argv[2]; //"8000" for instance;
        string hostAddress;
        if (portNum.compare("80") != 0) // add the ":" only if the port number is not 80 (proprietary port number).
        {
             hostAddress = ipAddress + ":" + portNum;
        }
        else
        {
            hostAddress = ipAddress;
        }
        string wordToQuery = "aha";
        string queryStr = argv[3]; //"/api/v1/similar?word=" + wordToQuery;

        // Get a list of endpoints corresponding to the server name.
        tcp::resolver resolver(io_service);
        tcp::resolver::query query(ipAddress, portNum);
        tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

        // Try each endpoint until we successfully establish a connection.
        tcp::socket socket(io_service);
        boost::asio::connect(socket, endpoint_iterator);

        // Form the request. We specify the "Connection: close" header so that the
        // server will close the socket after transmitting the response. This will
        // allow us to treat all data up until the EOF as the content.
        boost::asio::streambuf request;
        std::ostream request_stream(&request);
        request_stream << "GET " << queryStr << " HTTP/1.1\r\n";  // note that you can change it if you wish to HTTP/1.0
        request_stream << "Host: " << hostAddress << "\r\n";
        request_stream << "Accept: */*\r\n";
        request_stream << "Connection: close\r\n\r\n";

        // Send the request.
        boost::asio::write(socket, request);

        // Read the response status line. The response streambuf will automatically
        // grow to accommodate the entire line. The growth may be limited by passing
        // a maximum size to the streambuf constructor.
        boost::asio::streambuf response;
        boost::asio::read_until(socket, response, "\r\n");

        // Check that response is OK.
        std::istream response_stream(&response);
        std::string http_version;
        response_stream >> http_version;
        unsigned int status_code;
        response_stream >> status_code;
        std::string status_message;
        std::getline(response_stream, status_message);
        if (!response_stream || http_version.substr(0, 5) != "HTTP/")
        {
            std::cout << "Invalid response\n";
            return 1;
        }
        if (status_code != 200)
        {
            std::cout << "Response returned with status code " << status_code << "\n";
            return 1;
        }

        // Read the response headers, which are terminated by a blank line.
        boost::asio::read_until(socket, response, "\r\n\r\n");

        // Process the response headers.
        std::string header;
        while (std::getline(response_stream, header) && header != "\r")
        {
            std::cout << header << "\n";
        }

        std::cout << "\n";

        // Write whatever content we already have to output.
        if (response.size() > 0)
        {
            std::cout << &response;
        }

        // Read until EOF, writing data to output as we go.
        boost::system::error_code error;
        while (boost::asio::read(socket, response,boost::asio::transfer_at_least(1), error))
        {
              std::cout << &response;
        }

        if (error != boost::asio::error::eof)
        {
              throw boost::system::system_error(error);
        }
    }
    catch (std::exception& e)
    {
        std::cout << "Exception: " << e.what() << "\n";
    }

    return 0;
}

The original example I followed is here: Boost-simple-http-get-request-sync-client

ContentLicense: CC BY-SA 4.0


问:
service worker we are facing cache issue
I am a fresher for service worker. I am trying to implement static and dynamic caching.

When I add the single file to the static cache request, it is taking all the files whatever I have. Currently, all the files are running from the service worker when I started from the offline mode. Please someone help me.

This is the code I have in index.html.

```<code>       self.addEventListener('install',function(event)
      {
      console.log('[service worker]Installing service
       worker....',event);
      event.waitUntil(caches.open('static')
      .then(function(cache)
      {
          console.log('[Service Worker] Precaching App Shell');
          cache.addAll([
                       '/',
                       '/signin.html',
                       ]);
    })
  )
});
</code>```

答:
In Static caching some of the requests(pages) are cached(saved in Browser's local storage), it is generally done in install event of Service Worker. Whereas in Dynamic caching pages & files are cached whenever you request(fetch) for them hence, it makes use of fetch event of Service Worker.

So, in your install event when you add '/' in cache.addAll service worker adds all the files and resources needed to display '/' ie root directory.

Now, to make use of those cached files and to implement Dynamic Caching you'll need to implement something like this:

```<code>self.addEventListener('fetch', function (event) {

    event.respondWith(
      caches.match(event.request)       // if data has been cached already
        .then(function (response) {
          if (response) {
            return response;
          } else {              // else fetch from internet & cache in DYNAMIC cache
            return fetch(event.request)
              .then(function (res) {
                return caches.open(CACHE_DYNAMIC_NAME)
                  .then(function (cache) {
                    cache.put(event.request.url, res.clone());
                    return res;
                  })
              })
              .catch(function (err) {           //fallback mechanism
                return caches.open(CACHE_STATIC_NAME)
                  .then(function (cache) {
                    if (event.request.headers.get('accept').includes('text/html')) {
                      return cache.match('/offline.html');
                    }
                  });
              });
          }
        })
    );
});
</code>```

NOTE: To avoid over crowding your local storage you might wanna implement some strategy before actually saving the file in storage.

For more info read this to learn more about strategies.

Body:
I am a fresher for service worker. I am trying to implement static and dynamic caching.

When I add the single file to the static cache request, it is taking all the files whatever I have. Currently, all the files are running from the service worker when I started from the offline mode. Please someone help me.

This is the code I have in index.html.

       self.addEventListener('install',function(event)
      {
      console.log('[service worker]Installing service
       worker....',event);
      event.waitUntil(caches.open('static')
      .then(function(cache)
      {
          console.log('[Service Worker] Precaching App Shell');
          cache.addAll([
                       '/',
                       '/signin.html',
                       ]);
    })
  )
});

Body:
In Static caching some of the requests(pages) are cached(saved in Browser's local storage), it is generally done in install event of Service Worker. Whereas in Dynamic caching pages & files are cached whenever you request(fetch) for them hence, it makes use of fetch event of Service Worker.

So, in your install event when you add '/' in cache.addAll service worker adds all the files and resources needed to display '/' ie root directory.

Now, to make use of those cached files and to implement Dynamic Caching you'll need to implement something like this:

self.addEventListener('fetch', function (event) {

    event.respondWith(
      caches.match(event.request)       // if data has been cached already
        .then(function (response) {
          if (response) {
            return response;
          } else {              // else fetch from internet & cache in DYNAMIC cache
            return fetch(event.request)
              .then(function (res) {
                return caches.open(CACHE_DYNAMIC_NAME)
                  .then(function (cache) {
                    cache.put(event.request.url, res.clone());
                    return res;
                  })
              })
              .catch(function (err) {           //fallback mechanism
                return caches.open(CACHE_STATIC_NAME)
                  .then(function (cache) {
                    if (event.request.headers.get('accept').includes('text/html')) {
                      return cache.match('/offline.html');
                    }
                  });
              });
          }
        })
    );
});

NOTE: To avoid over crowding your local storage you might wanna implement some strategy before actually saving the file in storage.

For more info read this to learn more about strategies.


问:
Conditional Left Join SQL
```<code>table A
    ----------------------------
    NAME   | CODE  | BRANCH
    ----------------------------
    bob    | PL    | B
    david  | AA    | B
    susan  | PL    | C
    joe    | AB    | C
    alfred | PL    | B

table B
    ----------------------------
    CODE | DESCRIPTION
    ----------------------------
    PL   | code 1
    PB   | code 2
    PC   | code 3

table C
    ----------------------------
    CODE | DESCRIPTION
    ----------------------------
    AA   | code 4
    AB   | code 5
    AC   | code 6
</code>```

Is there any way to join table A, B and C. without join all the table?

```<code>select A.*, COALESCE(B.DESCRIPTION, C.DESCRIPTION) AS DESCRIPTION  from A
left join B on A.CODE = B.CODE
left join C on A.CODE = C.CODE
</code>```

In my real case there will be more than 10 to join with the same column.
So I need conditional left join, something like this

```<code>SELECT A* , DESCRIPTION
FROM A  LEFT JOIN (
     CASE
        WHEN A.CODE = 'B' THEN SELECT * FROM B
        WHEN A.CODE = 'C' THEN SELECT * FROM C
      END
    ) BC ON A.CODE = BC.CODE
</code>```

答:
You cannot use CASE to implement flow control. In SQL CASE is an expression that returns a single value.

You can instead use the following query:

```<code>select A.*,
       CASE A.BRANCH
          WHEN 'B' THEN B.DESCRIPTION
          WHEN 'C' THEN C.DESCRIPTION
       END AS DESCRIPTION
from A
left join B on A.CODE = B.CODE AND A.BRANCH = 'B'
left join C on A.CODE = C.CODE AND A.BRANCH = 'C'
</code>```

Title: Conditional Left Join SQL

Body:
table A
    ----------------------------
    NAME   | CODE  | BRANCH
    ----------------------------
    bob    | PL    | B
    david  | AA    | B
    susan  | PL    | C
    joe    | AB    | C
    alfred | PL    | B

table B
    ----------------------------
    CODE | DESCRIPTION
    ----------------------------
    PL   | code 1
    PB   | code 2
    PC   | code 3

table C
    ----------------------------
    CODE | DESCRIPTION
    ----------------------------
    AA   | code 4
    AB   | code 5
    AC   | code 6

Is there any way to join table A, B and C. without join all the table?

select A.*, COALESCE(B.DESCRIPTION, C.DESCRIPTION) AS DESCRIPTION  from A
left join B on A.CODE = B.CODE
left join C on A.CODE = C.CODE

In my real case there will be more than 10 to join with the same column.
So I need conditional left join, something like this

SELECT A* , DESCRIPTION
FROM A  LEFT JOIN (
     CASE
        WHEN A.CODE = 'B' THEN SELECT * FROM B
        WHEN A.CODE = 'C' THEN SELECT * FROM C
      END
    ) BC ON A.CODE = BC.CODE

Body:
You cannot use CASE to implement flow control. In SQL CASE is an expression that returns a single value.

You can instead use the following query:

select A.*,
       CASE A.BRANCH
          WHEN 'B' THEN B.DESCRIPTION
          WHEN 'C' THEN C.DESCRIPTION
       END AS DESCRIPTION
from A
left join B on A.CODE = B.CODE AND A.BRANCH = 'B'
left join C on A.CODE = C.CODE AND A.BRANCH = 'C'


问:
How to save generic object to an array in swift
I have on class

```<code>class SomeClass<T>: AsyncOperation, NetworkOperationProtocol {

    /// The resource model object that conforms to Parsable Response
    public typealias Resource = T
}
</code>```

I want to save instance of this class to an array, and want retrieve it later.
How can I achieve this?

答:
It should be simple
You can declare an array like this

```<code>var anArray = [SomeClass<Parsable>]()
</code>```

Please note that while declaring the array I have defined the Parsable instead of T.

If you don't know the type of T while creating array. You can go following way

```<code>var anArray = [AnyObject]()

let anObject = SomeClass<Parsable>()
anArray.append(anObject)

if anArray[0] is SomeClass<Parsable> {
    print(true)
}
</code>```

Body:
I have on class

class SomeClass<T>: AsyncOperation, NetworkOperationProtocol {

    /// The resource model object that conforms to Parsable Response
    public typealias Resource = T
}

I want to save instance of this class to an array, and want retrieve it later.
How can I achieve this?

Body:
It should be simple
You can declare an array like this

var anArray = [SomeClass<Parsable>]()

Please note that while declaring the array I have defined the Parsable instead of T.

If you don't know the type of T while creating array. You can go following way

var anArray = [AnyObject]()

let anObject = SomeClass<Parsable>()
anArray.append(anObject)

if anArray[0] is SomeClass<Parsable> {
    print(true)
}


问:
Why are cellspacing and cellpadding not CSS styles
I don't know why this bothers me so much, but when I create websites, I always try to do all my styling with CSS.  However one thing I always have to remember to do when I'm working with tables is add cellspacing="0" and cellpadding="0"

Why is there not a CSS property to override these antiquated HTML 4 attributes?

答:
Eric Myer's reset stylesheet contains the following 'reset' style for table :

```<code>/* tables still need 'cellspacing="0"' in the markup */
table {
    border-collapse: collapse;
    border-spacing: 0;
}
</code>```

In addition TD, TR are reset :

```<code>thead, tr, th, td {
    margin: 0;
    padding: 0;
    border: 0;
    outline: 0;
    font-size: 100%;
    vertical-align: baseline;
    background: transparent;
}
</code>```

The reason I mention this is that he has a comment 'tables still need cellpadding=0'. I assume he put this in here for a reason - probably needed by some old browsers. Judging by the fact that this is one of the very few comments he included I'm guessing its important and that there's a good reason for it.

Based on this comment - and this comment alone! - i'm continuing to use cellspacing="0" in the markup unless someone tells me definitively (below) why I dont need to. It could however likely be unnecessary in any modern browser worth supporting these days.

OwnerDisplayName: Ryan Smith

Body:
Eric Myer's reset stylesheet contains the following 'reset' style for table :

/* tables still need 'cellspacing="0"' in the markup */
table {
    border-collapse: collapse;
    border-spacing: 0;
}

In addition TD, TR are reset :

thead, tr, th, td {
    margin: 0;
    padding: 0;
    border: 0;
    outline: 0;
    font-size: 100%;
    vertical-align: baseline;
    background: transparent;
}

The reason I mention this is that he has a comment 'tables still need cellpadding=0'. I assume he put this in here for a reason - probably needed by some old browsers. Judging by the fact that this is one of the very few comments he included I'm guessing its important and that there's a good reason for it.

Based on this comment - and this comment alone! - i'm continuing to use cellspacing="0" in the markup unless someone tells me definitively (below) why I dont need to. It could however likely be unnecessary in any modern browser worth supporting these days.

OwnerDisplayName: Simon


问:
Xamarin.forms Device contact is not getting updated
I have a Xamarin.Forms based application which uses operation with device contact like adding new contact and updating existing contact. Adding new contacts works, but update contact is not working. I used DependencyService of Xamarin.forms to update contacts on android. First i lookup for that contact and get its' Id if it exist.
Below is my code

```<code>void OnUpdate(){
 var Id = LookupByPhone(phoneNumber,   companyName+ " " + teamName);
        if(Id!="0")
        {
            UpdateContact(phoneNumber, Id,companyName,teamName);
            return;
        }
    }

string LookupByPhone(string phoneNumber, string query = "")
    {
        var Id = "0";
        try
        {
            var context = MainActivity.Instance;

            var uri = ContactsContract.Contacts.ContentUri;
            uri = ContactsContract.CommonDataKinds.Phone.ContentUri;

            string[] projection = {
                ContactsContract.Contacts.InterfaceConsts.Id,

                InterfaceConsts.DisplayName,
                ContactsContract.CommonDataKinds.Phone.Number
                };

            var cursor = context.ContentResolver.Query(uri, projection, null, null, null);

            if (cursor.MoveToFirst())
            {
                do
                {
                    var id = cursor.GetString(cursor.GetColumnIndex(projection[0]));
                    var nm = cursor.GetString(cursor.GetColumnIndex(projection[1]));
                    var number = cursor.GetString(cursor.GetColumnIndex(projection[2]));

                    Id = id;
                    if (nm == query)
                        break;

                    //break;
                } while (cursor.MoveToNext());
            }
            cursor.Close();
        }
        catch (Exception ex)
        {
            LogController.LogError(ex);
        }
        return Id;
    }

void UpdateContact(string phonenumber, string id, string givenName, string familyName)
    {
        ContentProviderOperation.Builder builder = ContentProviderOperation.NewUpdate(ContactsContract.Data.ContentUri);

        List<ContentProviderOperation> ops = new List<ContentProviderOperation>();

        if (!string.IsNullOrWhiteSpace(givenName) && !string.IsNullOrWhiteSpace(familyName))
        {
            // Name
            String nameSelection = ContactsContract.Data.InterfaceConsts.ContactId + " = ? AND "
                                   + ContactsContract.Data.InterfaceConsts.Mimetype + " = ? ";
            String[] nameSelectionArgs = {
                                            id.ToString(),
                                            ContactsContract.CommonDataKinds.StructuredName.ContentItemType
            };

            builder.WithSelection(nameSelection, nameSelectionArgs);
            builder.WithValue(ContactsContract.CommonDataKinds.StructuredName.GivenName, givenName);
            builder.WithValue(ContactsContract.CommonDataKinds.StructuredName.FamilyName, familyName);
            builder.WithValue(ContactsContract.CommonDataKinds.StructuredName.DisplayName, givenName + " " + familyName);

            ops.Add(builder.Build());
        }

        #region Phone update
        // CellPhone
        String phoneSelection = ContactsContract.Data.InterfaceConsts.ContactId + " = ? AND " +
                                   ContactsContract.Data.InterfaceConsts.Mimetype + " = ? AND " +
                                   ContactsContract.CommonDataKinds.Phone.InterfaceConsts.Type + " = ?";

        String[] phoneselectionArgs = {
               id.ToString(),
                   ContactsContract.CommonDataKinds.Phone.ContentItemType,
               PhoneDataKind.Mobile.ToString()
            };

        builder = ContentProviderOperation.NewUpdate(ContactsContract.Data.ContentUri);
        builder.WithSelection(phoneSelection, phoneselectionArgs);

        builder.WithValue(ContactsContract.CommonDataKinds.Phone.Number, phonenumber);
        builder.WithValue(ContactsContract.CommonDataKinds.Phone.InterfaceConsts.Type, PhoneDataKind.Mobile.ToString());
        ops.Add(builder.Build());
        #endregion

        // Update the contact
        ContentProviderResult[] result;
        try
        {
        // the result return count{0}
        var result = MainActivity.Instance.ContentResolver.ApplyBatch(ContactsContract.Authority, ops);

        }
        catch (Exception ex)
        {
            LogController.LogError("Error updating phone:" + phonenumber,ex);
        }
    }
</code>```

There are no error or exception. Any thought on this.

答:
The method which gets the id should be like this (I removed the first parameter since it's not used in your method):

```<code>string LookupByPhone(string name)
{
    string id = "0";
    var uri = ContactsContract.Contacts.ContentUri;
    var cursor = this.ContentResolver.Query(
                 uri,
                 new String[] { ContactsContract.Contacts.InterfaceConsts.Id },
                 ContactsContract.Contacts.InterfaceConsts.DisplayName +
                 "='" + name + "'", null, null);
    if (cursor.MoveToNext())
    {
        id = cursor.GetString(cursor.GetColumnIndex(ContactsContract.Contacts.InterfaceConsts.Id));
    }
    cursor.Close();
    return id;
 }
</code>```

You can see I get the id by query the name that is what you are using companyName + " " + teamName

Body:
I have a Xamarin.Forms based application which uses operation with device contact like adding new contact and updating existing contact. Adding new contacts works, but update contact is not working. I used DependencyService of Xamarin.forms to update contacts on android. First i lookup for that contact and get its' Id if it exist.
Below is my code

void OnUpdate(){
 var Id = LookupByPhone(phoneNumber,   companyName+ " " + teamName);
        if(Id!="0")
        {
            UpdateContact(phoneNumber, Id,companyName,teamName);
            return;
        }
    }

string LookupByPhone(string phoneNumber, string query = "")
    {
        var Id = "0";
        try
        {
            var context = MainActivity.Instance;

            var uri = ContactsContract.Contacts.ContentUri;
            uri = ContactsContract.CommonDataKinds.Phone.ContentUri;

            string[] projection = {
                ContactsContract.Contacts.InterfaceConsts.Id,

                InterfaceConsts.DisplayName,
                ContactsContract.CommonDataKinds.Phone.Number
                };

            var cursor = context.ContentResolver.Query(uri, projection, null, null, null);

            if (cursor.MoveToFirst())
            {
                do
                {
                    var id = cursor.GetString(cursor.GetColumnIndex(projection[0]));
                    var nm = cursor.GetString(cursor.GetColumnIndex(projection[1]));
                    var number = cursor.GetString(cursor.GetColumnIndex(projection[2]));

                    Id = id;
                    if (nm == query)
                        break;

                    //break;
                } while (cursor.MoveToNext());
            }
            cursor.Close();
        }
        catch (Exception ex)
        {
            LogController.LogError(ex);
        }
        return Id;
    }

void UpdateContact(string phonenumber, string id, string givenName, string familyName)
    {
        ContentProviderOperation.Builder builder = ContentProviderOperation.NewUpdate(ContactsContract.Data.ContentUri);

        List<ContentProviderOperation> ops = new List<ContentProviderOperation>();

        if (!string.IsNullOrWhiteSpace(givenName) && !string.IsNullOrWhiteSpace(familyName))
        {
            // Name
            String nameSelection = ContactsContract.Data.InterfaceConsts.ContactId + " = ? AND "
                                   + ContactsContract.Data.InterfaceConsts.Mimetype + " = ? ";
            String[] nameSelectionArgs = {
                                            id.ToString(),
                                            ContactsContract.CommonDataKinds.StructuredName.ContentItemType
            };

            builder.WithSelection(nameSelection, nameSelectionArgs);
            builder.WithValue(ContactsContract.CommonDataKinds.StructuredName.GivenName, givenName);
            builder.WithValue(ContactsContract.CommonDataKinds.StructuredName.FamilyName, familyName);
            builder.WithValue(ContactsContract.CommonDataKinds.StructuredName.DisplayName, givenName + " " + familyName);

            ops.Add(builder.Build());
        }

        #region Phone update
        // CellPhone
        String phoneSelection = ContactsContract.Data.InterfaceConsts.ContactId + " = ? AND " +
                                   ContactsContract.Data.InterfaceConsts.Mimetype + " = ? AND " +
                                   ContactsContract.CommonDataKinds.Phone.InterfaceConsts.Type + " = ?";

        String[] phoneselectionArgs = {
               id.ToString(),
                   ContactsContract.CommonDataKinds.Phone.ContentItemType,
               PhoneDataKind.Mobile.ToString()
            };

        builder = ContentProviderOperation.NewUpdate(ContactsContract.Data.ContentUri);
        builder.WithSelection(phoneSelection, phoneselectionArgs);

        builder.WithValue(ContactsContract.CommonDataKinds.Phone.Number, phonenumber);
        builder.WithValue(ContactsContract.CommonDataKinds.Phone.InterfaceConsts.Type, PhoneDataKind.Mobile.ToString());
        ops.Add(builder.Build());
        #endregion

        // Update the contact
        ContentProviderResult[] result;
        try
        {
        // the result return count{0}
        var result = MainActivity.Instance.ContentResolver.ApplyBatch(ContactsContract.Authority, ops);

        }
        catch (Exception ex)
        {
            LogController.LogError("Error updating phone:" + phonenumber,ex);
        }
    }

There are no error or exception. Any thought on this.

Body:
The method which gets the id should be like this (I removed the first parameter since it's not used in your method):

string LookupByPhone(string name)
{
    string id = "0";
    var uri = ContactsContract.Contacts.ContentUri;
    var cursor = this.ContentResolver.Query(
                 uri,
                 new String[] { ContactsContract.Contacts.InterfaceConsts.Id },
                 ContactsContract.Contacts.InterfaceConsts.DisplayName +
                 "='" + name + "'", null, null);
    if (cursor.MoveToNext())
    {
        id = cursor.GetString(cursor.GetColumnIndex(ContactsContract.Contacts.InterfaceConsts.Id));
    }
    cursor.Close();
    return id;
 }

You can see I get the id by query the name that is what you are using companyName + " " + teamName


问:
How make prod and dev envs using git
I’d like to improve my workflow so I decided myself use git.

Till now for my projects, on my web server, I had 2 folders which are prod and dev.

Once modifications are over I sync both of my folders.

I tried to use git like this way :

```<code>// on my prod folder
$ git init
$ git add *
$ git commit -a
</code>```

Then on parent folder

```<code>$ git clone prod dev
</code>```

Works like a charm I got my dev folder as perfect cot of prod
But now once my modifications are ok I can’t commit to prod. How can I achieve that ?! Thx

EDIT

Here is my organization tree on my web server :

```<code>home
|--git
   |--.ssh
   |--repositories
      |-- myfirstrepo.git
          |-- index.html
</code>```

What I'm trying to achieve is from /var/www

```<code>$ git clone /home/git/repositories/myfirstrepo.git
Initialized empty Git repository in /var/www/myfirstrepo_wc/.git/
</code>```

I got the clone of my repo in

```<code>var
|--www
   |--myfirstrepo_wc
      |--index.html
</code>```

So now I make change to my index.html file in /var/www/myfirstrepo_wc then

```<code>$ git status
# On branch master
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   www/index.html
#
no changes added to commit (use "git add" and/or "git commit -a")
</code>```

Make commit

```<code>$ git commit -a
[master d19749d] first commit from working copy
Committer: root <root@localhost.localdomain>
Your name and email address were configured automatically based
on your username and hostname. Please check that they are accurate.
You can suppress this message by setting them explicitly:

    git config --global user.name "Your Name"
    git config --global user.email you@example.com

If the identity used for this commit is wrong, you can fix it with:

git commit --amend --author='Your Name <you@example.com>'

1 files changed, 1 insertions(+), 0 deletions(-)
</code>```

then want to pull to my repo who is in /home/git/repositories/myfirstrepo.git

```<code>$ git pull origin master
Counting objects: 7, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (4/4), 358 bytes, done.
Total 4 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (4/4), done.
remote: error: refusing to update checked out branch: refs/heads/master
remote: error: By default, updating the current branch in a non-bare repository
remote: error: is denied, because it will make the index and work tree inconsistent
remote: error: with what you pushed, and will require 'git reset --hard' to match
remote: error: the work tree to HEAD.
remote: error:
remote: error: You can set 'receive.denyCurrentBranch' configuration variable to
remote: error: 'ignore' or 'warn' in the remote repository to allow pushing into
remote: error: its current branch; however, this is not recommended unless you
remote: error: arranged to update its work tree to match what you pushed in some
remote: error: other way.
remote: error:
remote: error: To squelch this message and still keep the default behaviour, set
remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'.
To /git/myfirstrepo.git
! [remote rejected] master -> master (branch is currently checked out)
error: failed to push some refs to '/git/myfirstrepo.git'
</code>```

答:
Ok i found the solution : </p>

```<code>$git remote add origin git@localhost:path/to/myfirstrepo.git
$git push origin master
</code>```

Title: How make prod and dev envs using git

Body:
I’d like to improve my workflow so I decided myself use git.

Till now for my projects, on my web server, I had 2 folders which are prod and dev.

Once modifications are over I sync both of my folders.

I tried to use git like this way :

// on my prod folder
$ git init
$ git add *
$ git commit -a

Then on parent folder

$ git clone prod dev

Works like a charm I got my dev folder as perfect cot of prod
But now once my modifications are ok I can’t commit to prod. How can I achieve that ?! Thx

EDIT

Here is my organization tree on my web server :

home
|--git
   |--.ssh
   |--repositories
      |-- myfirstrepo.git
          |-- index.html

What I'm trying to achieve is from /var/www

$ git clone /home/git/repositories/myfirstrepo.git
Initialized empty Git repository in /var/www/myfirstrepo_wc/.git/

I got the clone of my repo in

var
|--www
   |--myfirstrepo_wc
      |--index.html

So now I make change to my index.html file in /var/www/myfirstrepo_wc then

$ git status
# On branch master
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   www/index.html
#
no changes added to commit (use "git add" and/or "git commit -a")

Make commit

$ git commit -a
[master d19749d] first commit from working copy
Committer: root <root@localhost.localdomain>
Your name and email address were configured automatically based
on your username and hostname. Please check that they are accurate.
You can suppress this message by setting them explicitly:

    git config --global user.name "Your Name"
    git config --global user.email you@example.com

If the identity used for this commit is wrong, you can fix it with:

git commit --amend --author='Your Name <you@example.com>'

1 files changed, 1 insertions(+), 0 deletions(-)

then want to pull to my repo who is in /home/git/repositories/myfirstrepo.git

$ git pull origin master
Counting objects: 7, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (4/4), 358 bytes, done.
Total 4 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (4/4), done.
remote: error: refusing to update checked out branch: refs/heads/master
remote: error: By default, updating the current branch in a non-bare repository
remote: error: is denied, because it will make the index and work tree inconsistent
remote: error: with what you pushed, and will require 'git reset --hard' to match
remote: error: the work tree to HEAD.
remote: error:
remote: error: You can set 'receive.denyCurrentBranch' configuration variable to
remote: error: 'ignore' or 'warn' in the remote repository to allow pushing into
remote: error: its current branch; however, this is not recommended unless you
remote: error: arranged to update its work tree to match what you pushed in some
remote: error: other way.
remote: error:
remote: error: To squelch this message and still keep the default behaviour, set
remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'.
To /git/myfirstrepo.git
! [remote rejected] master -> master (branch is currently checked out)
error: failed to push some refs to '/git/myfirstrepo.git'

Body:
Ok i found the solution :

$git remote add origin git@localhost:path/to/myfirstrepo.git
$git push origin master


问:
change of all immediate elements of the corrosponding class using jquery
my html content

```<code> <li class="info"> info<li>
 <li class="other"> info<li>
 <li class="other"> info<li>

 <li class="Error"> error<li>
 <li class="other"> error<li>
 <li class="warning"> warning<li>
 <li class="other"> warning<li>
 <li class="other"> warning<li>
 <li class="info"> info<li>
 <li class="other"> info<li>
 <li class="other"> info<li>
</code>```

based on the li element class, I want to filter only the immediate li.other class item css to be changed using jquery;

I followed the below approach: when I select info elements:

```<code>  $('.info').prevAll('li.other').css({});
</code>```

It worked but it will all the previous li.other elements changed. Instead I want only specific to that particular html(info) element li.other element. rest all to be ignored.
 Please any one provide the possible approach

答:
You need to use prevUntil() method with :not() pseudo-class selector to achieve the result.

```<code>$('.info').prevUntil(':not(li.other)').css({});
</code>```

$('.info').prevUntil(':not(li.other)').css({
  color: 'red'
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="info"> info</li>
  <li class="other"> info</li>
  <li class="other"> info</li>
  <li class="Error"> error</li>
  <li class="other"> error</li>
  <li class="warning"> warning</li>
  <li class="other"> warning</li>
  <li class="other"> warning</li>
  <li class="info"> info</li>
  <li class="other"> info</li>
  <li class="other"> info</li>
</ul></code>```

In case you need the three warning then you need to get the last element and add it to the selector using addBack() method.

```<code>$('.info').prevUntil(':not(li.other)').prev().addBack().css({});
</code>```

$('.info').prevUntil(':not(li.other)').prev().addBack().css({
  color: 'red'
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="info"> info</li>
  <li class="other"> info</li>
  <li class="other"> info</li>
  <li class="Error"> error</li>
  <li class="other"> error</li>
  <li class="warning"> warning</li>
  <li class="other"> warning</li>
  <li class="other"> warning</li>
  <li class="info"> info</li>
  <li class="other"> info</li>
  <li class="other"> info</li>
</ul></code>```

Body:
my html content

 info

 info

 info

 error

 error

 warning

 warning

 warning

 info

 info

 info

based on the li element class, I want to filter only the immediate li.other class item css to be changed using jquery;

I followed the below approach: when I select info elements:

  $('.info').prevAll('li.other').css({});

It worked but it will all the previous li.other elements changed. Instead I want only specific to that particular html(info) element li.other element. rest all to be ignored.
 Please any one provide the possible approach

Body:
You need to use prevUntil() method with :not() pseudo-class selector to achieve the result.

$('.info').prevUntil(':not(li.other)').css({});

$('.info').prevUntil(':not(li.other)').css({
  color: 'red'
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="info"> info</li>
  <li class="other"> info</li>
  <li class="other"> info</li>
  <li class="Error"> error</li>
  <li class="other"> error</li>
  <li class="warning"> warning</li>
  <li class="other"> warning</li>
  <li class="other"> warning</li>
  <li class="info"> info</li>
  <li class="other"> info</li>
  <li class="other"> info</li>
</ul>

In case you need the three warning then you need to get the last element and add it to the selector using addBack() method.

$('.info').prevUntil(':not(li.other)').prev().addBack().css({});

$('.info').prevUntil(':not(li.other)').prev().addBack().css({
  color: 'red'
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="info"> info</li>
  <li class="other"> info</li>
  <li class="other"> info</li>
  <li class="Error"> error</li>
  <li class="other"> error</li>
  <li class="warning"> warning</li>
  <li class="other"> warning</li>
  <li class="other"> warning</li>
  <li class="info"> info</li>
  <li class="other"> info</li>
  <li class="other"> info</li>
</ul>