问:
Using the JS Google API to add a contact but it never disconnects or signs out
Through many searches I've gotten the script in question to work as expected. If the user clicks on a button on my web page then a contact will be created in their Google Contact list (if authorized).

The problem I'm left with is that the authorization never expires. In that once successfully authorized the user can press the button many times, even come back to the page later in a different session, and it will never ask for authorization again.

Perhaps this is the intended behavior of the GoogleAPI but for my intended purpose I don't expect any more than 1 click and I would expect if the user came back to my page at a later time that they would be asked to authorize again.

Is this possible? I've tried the following ...

```<code>gapi.auth.signOut();
gapi.auth2.signOut();
gapi.auth2.disconnect();
</code>```

revoking the token (see end of post)

... with no success.

Code can be found here:
https://jsfiddle.net/brian_hill/chvtmmjr/7/

```<code>function addContact(entry) {
  var config = {
    'client_id': '403037917634-qproaer1g5gcq83c941heo4q07olol23.apps.googleusercontent.com',
    'scope': 'https://www.google.com/m8/feeds',
    'cookie_policy': 'single_host_origin'
  };
  gapi.auth.authorize(config, function() {
    insert(config, entry);
  });
}

function insert(config, entry) {
  gapi.client.request({
    'method': 'POST',
    'path': '/m8/feeds/contacts/default/full/',
    'headers': {
      'GData-Version': 3.0
    },
    'body': {
      'entry': [entry]
    },
    'callback': function(data) {
      if (data.hasOwnProperty('entry')) {
        var msg = "Your Google Contacts have been updated to include ";
        window.alert(msg.concat(data.entry.title.$t))
      } else {
        var msg = "Contact information could not be added for "
        window.alert(msg.concat(entry.title.$t))
      }
    }
  });
}
</code>```

And the HTML

```<code><script src="https://apis.google.com/js/platform.js" async defer></script>
<script src="https://apis.google.com/js/client.js"></script>

<body style="background-color:rgba(32, 177, 17, 0.3);">
  <p>
    The button below will add a contact to your GMail contacts</p>
  <div style="width:150px">
    <script>
      function addJohn() {
        var entry = {
          "category": [{
            "scheme": "http:\/\/schemas.google.com\/g\/2005#kind",
            "term": "http:\/\/schemas.google.com\/contact\/2008#contact"
          }],
          "title": {
            "type": "text",
            "$t": "John Doe"
          },
          "content": [{
            "type": "text",
            "$t": "[Automatically Created]"
          }],
          "gd$email": [{
            "rel": "http:\/\/schemas.google.com\/g\/2005#other",
            "address": "john.doe@abcd.com",
            "primary": "true"
          }],
          "gd$postalAddress": [{
            "rel": "http:\/\/schemas.google.com\/g\/2005#home",
            "$t": "123 Main Street\nOttawa, ON\nCanada"
          }],
          "gd$phoneNumber": [{
            "rel": "http:\/\/schemas.google.com\/g\/2005#home",
            "$t": "555.123.4567",
            "primary": "true"
          }]
        };
        addContact(entry);
      }
     function addJane() {
        var entry = {
          "category": [{
            "scheme": "http:\/\/schemas.google.com\/g\/2005#kind",
            "term": "http:\/\/schemas.google.com\/contact\/2008#contact"
          }],
          "title": {
            "type": "text",
            "$t": "Jane Doe"
          },
          "content": [{
            "type": "text",
            "$t": "[Automatically Created]"
          }],
          "gd$email": [{
            "rel": "http:\/\/schemas.google.com\/g\/2005#other",
            "address": "jane.doe@abcd.com",
            "primary": "true"
          }],
          "gd$postalAddress": [{
            "rel": "http:\/\/schemas.google.com\/g\/2005#home",
            "$t": "321 Unknown Street\nOttawa, ON\nCanada"
          }],
          "gd$phoneNumber": [{
            "rel": "http:\/\/schemas.google.com\/g\/2005#home",
            "$t": "555.765.4321",
            "primary": "true"
          }]
        };
        addContact(entry);
      }
</script>
    <button onclick="addJohn();">Add Contact - John</button>
    <button onclick="addJane();">Add Contact - Jane</button>
    </div>
</body>
</code>```

(Note: Due to the nature of the GoogleAPI authorization process, it doesn't appear to work through JS Fiddle on either Chrome or Firefox --- I did get it to work on Microsoft Edge).

Thanks in advance,
Brian

PS. Adding my attempt for using the 'revoke' option. Which still doesn't work (I still don't get re-prompted for authorization) but also sometimes it works (updates addresses) and sometimes it doesn't.

```<code>function addContact(entry) {
  var config = {
    'client_id': '403037917634-qproaer1g5gcq83c941heo4q07olol23.apps.googleusercontent.com',
    'scope': 'https://www.google.com/m8/feeds',
    'cookie_policy': 'single_host_origin'
  };
  gapi.auth.authorize(config, function() {
    insert(config, entry);
  }).then(signOut);
}

function signOut() {
   $.ajax({
     'type': 'GET',
     'url': 'https://accounts.google.com/o/oauth2/revoke?token=' +
        gapi.auth.getToken().access_token,
     'async': false,
     'contentType': "application/json",
     'dataType': 'jsonp',
     'success': function (nullResponse) {
         window.alert('Disconnected');
     },
     'error': function (e) {
         // Handle the error
         console.log(e);
     }
   });
}

function insert(config, entry) {
  gapi.client.request({
    'method': 'POST',
    'path': '/m8/feeds/contacts/default/full/',
    'headers': {
      'GData-Version': 3.0
    },
    'body': {
      'entry': [entry]
    },
    'callback': function(data) {
      if (data.hasOwnProperty('entry')) {
        var msg = "Your Google Contacts have been updated to include ";
        window.alert(msg.concat(data.entry.title.$t))
      } else {
        var msg = "Contact information could not be added for "
        window.alert(msg.concat(entry.title.$t))
      }
    }
  });
}
</code>```

答:
Try using the Revoke token instruction in OAuth 2.0:

In some cases a user may wish to revoke access given to an application. A user can revoke access by visiting Account Settings. It is also possible for an application to programmatically revoke the access given to it. Programmatic revocation is important in instances where a user unsubscribes or removes an application. In other words, part of the removal process can include an API request to ensure the permissions granted to the application are removed.\

To programmatically revoke a token, your application makes a request to https://accounts.google.com/o/oauth2/revoke and includes the token as a parameter:

```<code>curl -H "Content-type:application/x-www-form-urlencoded" \
        https://accounts.google.com/o/oauth2/revoke?token={token}
</code>```

Body:
Through many searches I've gotten the script in question to work as expected. If the user clicks on a button on my web page then a contact will be created in their Google Contact list (if authorized).

The problem I'm left with is that the authorization never expires. In that once successfully authorized the user can press the button many times, even come back to the page later in a different session, and it will never ask for authorization again.

Perhaps this is the intended behavior of the GoogleAPI but for my intended purpose I don't expect any more than 1 click and I would expect if the user came back to my page at a later time that they would be asked to authorize again.

Is this possible? I've tried the following ...

gapi.auth.signOut();
gapi.auth2.signOut();
gapi.auth2.disconnect();

revoking the token (see end of post)

... with no success.

Code can be found here:
https://jsfiddle.net/brian_hill/chvtmmjr/7/

function addContact(entry) {
  var config = {
    'client_id': '403037917634-qproaer1g5gcq83c941heo4q07olol23.apps.googleusercontent.com',
    'scope': 'https://www.google.com/m8/feeds',
    'cookie_policy': 'single_host_origin'
  };
  gapi.auth.authorize(config, function() {
    insert(config, entry);
  });
}

function insert(config, entry) {
  gapi.client.request({
    'method': 'POST',
    'path': '/m8/feeds/contacts/default/full/',
    'headers': {
      'GData-Version': 3.0
    },
    'body': {
      'entry': [entry]
    },
    'callback': function(data) {
      if (data.hasOwnProperty('entry')) {
        var msg = "Your Google Contacts have been updated to include ";
        window.alert(msg.concat(data.entry.title.$t))
      } else {
        var msg = "Contact information could not be added for "
        window.alert(msg.concat(entry.title.$t))
      }
    }
  });
}

And the HTML

    The button below will add a contact to your GMail contacts

    <button onclick="addJohn();">Add Contact - John</button>
    <button onclick="addJane();">Add Contact - Jane</button>

(Note: Due to the nature of the GoogleAPI authorization process, it doesn't appear to work through JS Fiddle on either Chrome or Firefox --- I did get it to work on Microsoft Edge).

Thanks in advance,
Brian

PS. Adding my attempt for using the 'revoke' option. Which still doesn't work (I still don't get re-prompted for authorization) but also sometimes it works (updates addresses) and sometimes it doesn't.

function addContact(entry) {
  var config = {
    'client_id': '403037917634-qproaer1g5gcq83c941heo4q07olol23.apps.googleusercontent.com',
    'scope': 'https://www.google.com/m8/feeds',
    'cookie_policy': 'single_host_origin'
  };
  gapi.auth.authorize(config, function() {
    insert(config, entry);
  }).then(signOut);
}

function signOut() {
   $.ajax({
     'type': 'GET',
     'url': 'https://accounts.google.com/o/oauth2/revoke?token=' +
        gapi.auth.getToken().access_token,
     'async': false,
     'contentType': "application/json",
     'dataType': 'jsonp',
     'success': function (nullResponse) {
         window.alert('Disconnected');
     },
     'error': function (e) {
         // Handle the error
         console.log(e);
     }
   });
}

function insert(config, entry) {
  gapi.client.request({
    'method': 'POST',
    'path': '/m8/feeds/contacts/default/full/',
    'headers': {
      'GData-Version': 3.0
    },
    'body': {
      'entry': [entry]
    },
    'callback': function(data) {
      if (data.hasOwnProperty('entry')) {
        var msg = "Your Google Contacts have been updated to include ";
        window.alert(msg.concat(data.entry.title.$t))
      } else {
        var msg = "Contact information could not be added for "
        window.alert(msg.concat(entry.title.$t))
      }
    }
  });
}

Body:
Try using the Revoke token instruction in OAuth 2.0:

In some cases a user may wish to revoke access given to an application. A user can revoke access by visiting Account Settings. It is also possible for an application to programmatically revoke the access given to it. Programmatic revocation is important in instances where a user unsubscribes or removes an application. In other words, part of the removal process can include an API request to ensure the permissions granted to the application are removed.\

To programmatically revoke a token, your application makes a request to https://accounts.google.com/o/oauth2/revoke and includes the token as a parameter:

curl -H "Content-type:application/x-www-form-urlencoded" \
        https://accounts.google.com/o/oauth2/revoke?token={token}


来源: stackexchange

问:
How do I pass a value to a button's click handler in a ListView?
on my page I'am showing some data from database, each item have button to remove this from database.

Here's aspx:

```<code> <asp:ListView ID="productList" runat="server"
                DataKeyNames="id_produkt"
                ItemType="Shop.Models.Produkt" SelectMethod="GetProducts">
                <ItemTemplate>
                    <tr>
                        <td><%#:Item.id_produkt%></td>
                        <td><%#:Item.nazwa_produkt%></td>
                        <td><%#:Item.cena%></td>
                        <td><%#:Item.poprzednia_cena%></td>
                        <td><%#:Item.Ilosc%></td>
                        <td>
                            <asp:Button CssClass="btn btn-info btn-sm" ID="Edytuj" runat="server" Text="Edytuj" OnClick="AddProductButton_Click" CausesValidation="true" />
                            <asp:Button CssClass="btn btn-danger btn-sm" ID="RemoveButton" runat="server" Text="Usuń Produkt" OnClick="RemoveProductButton_Click" CausesValidation="false" />
                            <a href="AdminPage_Details.aspx?productID=<%#:Item.id_produkt%>" class="btn btn-info btn-sm">Szczegóły</a>
                        </td>
                    </tr>
                </ItemTemplate>
                <ItemSeparatorTemplate></ItemSeparatorTemplate>
            </asp:ListView>
</code>```

How can i get Item.id_produkt in code-behind method?

For now it looks like this:

```<code>protected void RemoveProductButton_Click(object sender, EventArgs e)
        {
            using (var _db = new Shop.Models.EgzemplarzContext())
            {
                int productId = Convert.ToInt16();
                var myItem = (from c in _db.Produkty where c.id_produkt == productId select c).FirstOrDefault();

                IQueryable<Egzemplarz> query = _db.Egzemplarze;
                query = query.Where(p => p.id_produkt == productId);

                if (myItem != null && query != null)
                {
                    foreach ( var item in query)
                    {
                        _db.Egzemplarze.Remove(item);
                    }

                    _db.Produkty.Remove(myItem);
                    _db.SaveChanges();

                    // Reload the page.
                    string pageUrl = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.Count() - Request.Url.Query.Count());
                    Response.Redirect(pageUrl + "?ProductAction=remove");
                }
                else
                {
                    LabelAddStatusDanger.Text = "Nie można usunąć produktu.";
                }
            }
        }
</code>```

Somehow I need to get Item.id_produkt from the productlist in this method.

How can I do this ?

答:
Pass it using the CommandArgument property of the button.

Markup:

```<code><asp:Button ID="RemoveButton"
            runat="server"
            Text="Usuń Produkt"
            OnClick="RemoveProductButton_Click"
            CommandArgument='<%#:Item.id_produkt%>' />
</code>```

Code behind:

```<code>protected void RemoveProductButton_Click(object sender, EventArgs e)
{
    var button = (Button)sender;
    var id_produkt = button.CommandArgument;
}
</code>```

This sets the CommandArgument of the buttons in the ListView to have the product ID that you want. Then when the click event handler is get, the sender will be your button. We need to cast it to a button type in order to access the CommandArgument property.

ContentLicense: CC BY-SA 3.0

Body:
on my page I'am showing some data from database, each item have button to remove this from database.

Here's aspx:

 <asp:ListView ID="productList" runat="server"
                DataKeyNames="id_produkt"
                ItemType="Shop.Models.Produkt" SelectMethod="GetProducts">
                <ItemTemplate>

                        <%#:Item.id_produkt%>
                        <%#:Item.nazwa_produkt%>
                        <%#:Item.cena%>
                        <%#:Item.poprzednia_cena%>
                        <%#:Item.Ilosc%>

                            <asp:Button CssClass="btn btn-info btn-sm" ID="Edytuj" runat="server" Text="Edytuj" OnClick="AddProductButton_Click" CausesValidation="true" />
                            <asp:Button CssClass="btn btn-danger btn-sm" ID="RemoveButton" runat="server" Text="Usuń Produkt" OnClick="RemoveProductButton_Click" CausesValidation="false" />
                            <a href="AdminPage_Details.aspx?productID=<%#:Item.id_produkt%>" class="btn btn-info btn-sm">Szczegóły

                </ItemTemplate>
                <ItemSeparatorTemplate></ItemSeparatorTemplate>
            </asp:ListView>

How can i get Item.id_produkt in code-behind method?

For now it looks like this:

protected void RemoveProductButton_Click(object sender, EventArgs e)
        {
            using (var _db = new Shop.Models.EgzemplarzContext())
            {
                int productId = Convert.ToInt16();
                var myItem = (from c in _db.Produkty where c.id_produkt == productId select c).FirstOrDefault();

                IQueryable<Egzemplarz> query = _db.Egzemplarze;
                query = query.Where(p => p.id_produkt == productId);

                if (myItem != null && query != null)
                {
                    foreach ( var item in query)
                    {
                        _db.Egzemplarze.Remove(item);
                    }

                    _db.Produkty.Remove(myItem);
                    _db.SaveChanges();

                    // Reload the page.
                    string pageUrl = Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.Count() - Request.Url.Query.Count());
                    Response.Redirect(pageUrl + "?ProductAction=remove");
                }
                else
                {
                    LabelAddStatusDanger.Text = "Nie można usunąć produktu.";
                }
            }
        }

Somehow I need to get Item.id_produkt from the productlist in this method.

How can I do this ?

Body:
Pass it using the CommandArgument property of the button.

Markup:

<asp:Button ID="RemoveButton"
            runat="server"
            Text="Usuń Produkt"
            OnClick="RemoveProductButton_Click"
            CommandArgument='<%#:Item.id_produkt%>' />

Code behind:

protected void RemoveProductButton_Click(object sender, EventArgs e)
{
    var button = (Button)sender;
    var id_produkt = button.CommandArgument;
}

This sets the CommandArgument of the buttons in the ListView to have the product ID that you want. Then when the click event handler is get, the sender will be your button. We need to cast it to a button type in order to access the CommandArgument property.


问:
Reading words from file with fscanf
I have a file .txt with the following encoding:

```<code>Alpha-Beta-Gamma-Delta-Epsilon
Zeta-Eta-Theta-Iota-Kappa-Lamda-Mi
Ni-Ksi-Pi-Ro-Sigma
</code>```

I want to read those words and store them in an array.
I read those words with fscanf(fp, "%[^-]", word)

But when I put fscanf inside a while, it keeps reading the same word. If I put it inside the while statement it doesn't repeat.

The point is to read every word separately from Alpha to Sigma

I provide you a minimal-verifiable code with the problem:

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(){
    FILE *fp;
    char *word = (char*)malloc(40);
    int count = 0;
    char* Words[30]; //max 30
    fp = fopen("MyWords.txt","r"); //read only
    int r = 1;
    while(1){
        if(fscanf(fp, "%[^-]", word) == EOF) break;
        printf("%s",word);
    }
    fclose(fp);
    return 0;
}
</code>```

Note: I don't want to modify the file. Also how should I handle with the \n characheter

答:
Limit input with a width specifier of 39, 1 less than the 40 bytes available to word as fscanf() will append a null character.  Continue reading as long as successful in that fscanf() returned 1.  Consume the following delimiter be it a '-' or '\n',

```<code>while(fscanf(fp, "%39[^-\n]", word) == 1) {
    printf("<%s>\n",word);
    fscanf(fp, "%*[-\n]"); // consume delimiter, no need to save.
}
</code>```

Note: Use [^-\n] and not [^\n-] as placing the - later looks like the beginning of an incomplete scan-set range.

Title: Reading words from file with fscanf

Body:
I have a file .txt with the following encoding:

Alpha-Beta-Gamma-Delta-Epsilon
Zeta-Eta-Theta-Iota-Kappa-Lamda-Mi
Ni-Ksi-Pi-Ro-Sigma

I want to read those words and store them in an array.
I read those words with fscanf(fp, "%[^-]", word)

But when I put fscanf inside a while, it keeps reading the same word. If I put it inside the while statement it doesn't repeat.

The point is to read every word separately from Alpha to Sigma

I provide you a minimal-verifiable code with the problem:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(){
    FILE *fp;
    char *word = (char*)malloc(40);
    int count = 0;
    char* Words[30]; //max 30
    fp = fopen("MyWords.txt","r"); //read only
    int r = 1;
    while(1){
        if(fscanf(fp, "%[^-]", word) == EOF) break;
        printf("%s",word);
    }
    fclose(fp);
    return 0;
}

Note: I don't want to modify the file. Also how should I handle with the \n characheter

Body:
Limit input with a width specifier of 39, 1 less than the 40 bytes available to word as fscanf() will append a null character.  Continue reading as long as successful in that fscanf() returned 1.  Consume the following delimiter be it a '-' or '\n',

while(fscanf(fp, "%39[^-\n]", word) == 1) {
    printf("<%s>\n",word);
    fscanf(fp, "%*[-\n]"); // consume delimiter, no need to save.
}

Note: Use [^-\n] and not [^\n-] as placing the - later looks like the beginning of an incomplete scan-set range.


问:
Inserting picture from user field into table in powerapps
I have created a powerapps app, and inserted data from a SharePoint list. I can get all the text data I require, but I can't get the profile picture from a user. I have a user field, and if I try to insert ThisItem.User.Picture into a text field, a valid URL shows up, linking to the correct image. The image control still remains white.

I have also tried getting the user image, using User().Image. This only shows the placeholder image, not my actual profile picture. Inserting this into a text field yields a base64 string, and decoding this again gives me the placeholder image.

Is there anything I'm missing?

答:
Are you using O365 or On-Premise SharePoint?
If its O365 then make sure you add the Connection to Office365 Users.</p>


问:
How to avoid HTML Canvas auto-stretching
I have the following piece of HTML:

```<code><style type="text/css">
    #c{width:200px;height:500px}
</style>
<canvas id="c"></canvas>
<script type="text/javascript">
    var i = new Image();
    i.onload = function () {
        var ctx = document.getElementById('c').getContext('2d');
        ctx.drawImage(i, 0, 0);
    }
    i.width = i.height = 20; // actual size of square.png
    i.src = 'square.png';
</script>
</code>```

The issue is that the drawn image is automatically stretched (resized) proportionally with the size of the canvas. I have tried using all available parameters (drawImage(i, 0, 0, 20, 20, 0, 0, 20, 20)) and that didn't help.

What is causing my drawing to stretch and how can I prevent that?

Thanks,

Tom

答:
I found it easier to just put a while loop waiting for timeout within my animation loop, For example:</p>

```<code>function animate() {
    c.clearRect(0, 0, window.innerWidth, window.innerHeight);
    ryuji.draw();
    ryuji.update();
    let now = Date.now();
    then = now + (1000 / fps);
    while (Date.now() < then) {

    }
    requestAnimationFrame(animate);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have the following piece of HTML:

<canvas id="c"></canvas>

The issue is that the drawn image is automatically stretched (resized) proportionally with the size of the canvas. I have tried using all available parameters (drawImage(i, 0, 0, 20, 20, 0, 0, 20, 20)) and that didn't help.

What is causing my drawing to stretch and how can I prevent that?

Thanks,

Tom

Body:
I found it easier to just put a while loop waiting for timeout within my animation loop, For example:

function animate() {
    c.clearRect(0, 0, window.innerWidth, window.innerHeight);
    ryuji.draw();
    ryuji.update();
    let now = Date.now();
    then = now + (1000 / fps);
    while (Date.now() < then) {

    }
    requestAnimationFrame(animate);
}


问:
Two Egg problem confusion
Two Egg problem:

You are given 2 eggs.

You have access to a 100-storey building.

Eggs can be very hard or very fragile means it may break if dropped from the first floor or may not even break if dropped from 100 th floor.Both eggs are identical.

You need to figure out the highest floor of a 100-storey building an egg can be dropped without breaking.

Now the question is how many drops you need to make. You are allowed to break 2 eggs in the process

I am sure the two egg problem ( mentioned above ) has been discussed sufficiently. However could someone help me understand why the following solution is not optimal.

Let's say I use a segment and scan algorithm with the segment size s.
So,

```<code>d ( 100 / s   + (s-1) ) = 0    [ this should give the minima,  I need '(s-1)' scans per segment and there are '100/s' segments]
-
ds

=> -100 / s^2 + 1 = 0
=> s^2 = 100
=> s = 10
</code>```

So according to this I need at most 19 drops. But the optimal solution can do this with 14 drops.

So where lies the problem?

答:
hey what about this approach.

Try this sequence:

1,2,4,8,16,32,64,100

And once you find the egg is broken you well get a space to work on.
lets suppose @ 64 egg breaks. then the answer lies between 32 & 64.

We can use normal binary search between those 2 number.
we will check @ 48 (32+64)/2 and then we will get the upper half or lower half as shortlisted space. and repeat

In this case the worst case is having the floor at 99. which will take 14 tries.

Title: Two Egg problem confusion

Body:
Two Egg problem:

You are given 2 eggs.

You have access to a 100-storey building.

Eggs can be very hard or very fragile means it may break if dropped from the first floor or may not even break if dropped from 100 th floor.Both eggs are identical.

You need to figure out the highest floor of a 100-storey building an egg can be dropped without breaking.

Now the question is how many drops you need to make. You are allowed to break 2 eggs in the process

I am sure the two egg problem ( mentioned above ) has been discussed sufficiently. However could someone help me understand why the following solution is not optimal.

Let's say I use a segment and scan algorithm with the segment size s.
So,

d ( 100 / s   + (s-1) ) = 0    [ this should give the minima,  I need '(s-1)' scans per segment and there are '100/s' segments]
-
ds

=> -100 / s^2 + 1 = 0
=> s^2 = 100
=> s = 10

So according to this I need at most 19 drops. But the optimal solution can do this with 14 drops.

So where lies the problem?


问:
How to use Angularjs to dynamically set spinner after table row bound
I'm updating the table via an ajax call, and want to display a spin.js spinner while the row.status == pending.
Basically I have a row fragment that successfully toggles from

```<code> <div class="spinner">
</code>```

to

```<code> <div class="hide">
</code>```

as the row computation progresses, (via ajax within a controller).
I'm happy with any mechanism that works!
What I'm struggling to do is, when the value is

```<code> <div class="spinner">
</code>```

have a spinner showing, otherwise have it hidden.

```<code>        <table class="table table-hover">
            <thead>
                <tr>
                    <th>url</th>
                    <th>status</th>
                </tr>
            </thead>
            <tbody>
                <tr data-ng-repeat="row in result.results">
                    <td>{{row.link.url}}</td>
                    <td> <div loadingWidget class="{{(row.status == 'pending' ? 'spinner' : 'hide' ) }}"></div>{{row.status}}</td>
                </tr>
            </tbody>
        </table>
</code>```

My latest script - basically I don't really know what I'm doing,

```<code>app.directive('loadingWidget', function ($rootScope) {
    return {
        restrict: 'E',
        scope: {
            field: '=',
            attributes: '=',
            editMode: '='
        },

        link: function (scope, element, attrs) {
            scope.spinit = function() {
                $rootScope.$broadcast('spinit');
            }
        }
    };
});

$scope.$on('spinit', function(element){
    //react to event
    new Spinner().spin(element);
});
</code>```

答:
You should use the ngHide directive. I'm having difficulty determining what you want your show/hide condition to be though. The rule is that if the contents of ng-hide evaluate to true, the element will be set to hidden.

If you absolutely need to switch the active class, not just hide the element, user ng-class. That will set the class based on a variable in scope.

```<code><table class="table table-hover">
    <thead>
        <tr>
            <th>url</th>
            <th>status</th>
        </tr>
    </thead>
    <tbody>
        <tr data-ng-repeat="row in result.results">
            <td>{{row.link.url}}</td>
            <td>
              <div loadingWidget class="spinner" ng-hide="row.status"></div>
              {{row.status}}
            </td>
        </tr>
    </tbody>
</table>
</code>```

Also, using $broadcast on root scope can be incredibly expensive, and is almost never necessary. In your case I don't see why you can't just call the Spinner().spin method directly.

ngHide docs: https://docs.angularjs.org/api/ng/directive/ngHide

ngClass docs: https://docs.angularjs.org/api/ng/directive/ngClass

Edit:
Okay, so I went through your code more thoroughly. You have several issues here.
First, you directives are kebab case in html, camelcase in javascript. That means your directive should look like:
.
Also, you have restrict E on your directive attributes. This means it can only be used as an element, and you are using it as an attribute. To fix this, either remove the restrict option or change it to restrict: 'A'.
You don't need the scope on your loadingWidget directive at all, and honestly any time you include Root Scope you are probably doing something wrong.
All of this results in a directive that looks something like this:

```<code>app.directive('loadingWidget', function() {
    return {
        restrict: 'A',
        scope: {
            field: '=',
            attributes: '=',
            editMode: '='
        },
        link: function (scope, element, attrs) {
            console.log("elm: ", element[0]);
            new Spinner().spin(element[0]);
        }
    };
});
</code>```

Plunkr Link

Also, there are already wrapper modules for Spin.js in Angular, so if you don't mind more dependencies that is a good option (Link).

In terms of the logic for hiding the spinner, I would simply use an ngShow with the value of whatever will be in that cell. When you go to update the value, set it to '' or false or undefined. On page load or when it gets changed to one of the values I just mentioned, the spinner will be hidden. Once the value is set, it will no longer be falsy and the element will show. This works as long as you never expect to store false in the variable. In Angular, don't use events unless you really need to, just manipulate scope variables and wait for the digest cycle. Having some simple state variables and then a combination of ngShow and ngHide can make simple state changes in a view easy.

A core value of getting comfortable with writing good Angular code is knowing that you basically never interact with your application outside of scope or directives. Avoid element selectors, and avoid events unless you are sure you need them. Much of Angular was designed to avoid the JQuery like tools, because they can make your code really hard to read.

Body:
I'm updating the table via an ajax call, and want to display a spin.js spinner while the row.status == pending.
Basically I have a row fragment that successfully toggles from

to

as the row computation progresses, (via ajax within a controller).
I'm happy with any mechanism that works!
What I'm struggling to do is, when the value is

have a spinner showing, otherwise have it hidden.

                    url
                    status

                    {{row.link.url}}

{{row.status}}

My latest script - basically I don't really know what I'm doing,

app.directive('loadingWidget', function ($rootScope) {
    return {
        restrict: 'E',
        scope: {
            field: '=',
            attributes: '=',
            editMode: '='
        },

        link: function (scope, element, attrs) {
            scope.spinit = function() {
                $rootScope.$broadcast('spinit');
            }
        }
    };
});

$scope.$on('spinit', function(element){
    //react to event
    new Spinner().spin(element);
});

Body:
You should use the ngHide directive. I'm having difficulty determining what you want your show/hide condition to be though. The rule is that if the contents of ng-hide evaluate to true, the element will be set to hidden.

If you absolutely need to switch the active class, not just hide the element, user ng-class. That will set the class based on a variable in scope.

<table class="table table-hover">
    <thead>
        <tr>
            <th>url</th>
            <th>status</th>
        </tr>
    </thead>
    <tbody>
        <tr data-ng-repeat="row in result.results">
            <td>{{row.link.url}}</td>
            <td>
              <div loadingWidget class="spinner" ng-hide="row.status"></div>
              {{row.status}}
            </td>
        </tr>
    </tbody>
</table>

Also, using $broadcast on root scope can be incredibly expensive, and is almost never necessary. In your case I don't see why you can't just call the Spinner().spin method directly.

ngHide docs: https://docs.angularjs.org/api/ng/directive/ngHide

ngClass docs: https://docs.angularjs.org/api/ng/directive/ngClass

Edit:
Okay, so I went through your code more thoroughly. You have several issues here.
First, you directives are kebab case in html, camelcase in javascript. That means your directive should look like: <div loading-widget class="spinner" ng-hide="row.status">.
Also, you have restrict E on your directive attributes. This means it can only be used as an element, and you are using it as an attribute. To fix this, either remove the restrict option or change it to restrict: 'A'.
You don't need the scope on your loadingWidget directive at all, and honestly any time you include Root Scope you are probably doing something wrong.
All of this results in a directive that looks something like this:

app.directive('loadingWidget', function() {
    return {
        restrict: 'A',
        scope: {
            field: '=',
            attributes: '=',
            editMode: '='
        },
        link: function (scope, element, attrs) {
            console.log("elm: ", element[0]);
            new Spinner().spin(element[0]);
        }
    };
});

Plunkr Link

Also, there are already wrapper modules for Spin.js in Angular, so if you don't mind more dependencies that is a good option (Link).

In terms of the logic for hiding the spinner, I would simply use an ngShow with the value of whatever will be in that cell. When you go to update the value, set it to '' or false or undefined. On page load or when it gets changed to one of the values I just mentioned, the spinner will be hidden. Once the value is set, it will no longer be falsy and the element will show. This works as long as you never expect to store false in the variable. In Angular, don't use events unless you really need to, just manipulate scope variables and wait for the digest cycle. Having some simple state variables and then a combination of ngShow and ngHide can make simple state changes in a view easy.

A core value of getting comfortable with writing good Angular code is knowing that you basically never interact with your application outside of scope or directives. Avoid element selectors, and avoid events unless you are sure you need them. Much of Angular was designed to avoid the JQuery like tools, because they can make your code really hard to read.


问:
Gwt won't allow external Javascript = blank page
I am trying to include an external javascript file in my gwt project.In the files html page if I put the following with the external script before the gwt projects script I get a blank page and no errors.

```<code><script language="javascript" src="my.js"></script>

<script language="javascript" src="com.mycompany.project.TESTPHONEGAP/com.mycompany.project.TESTPHONEGAP.nocache.js"></script>
</code>```

However if I put the external javascript file after the gwt projects script it works.

```<code><script language="javascript" src="com.mycompany.project.TESTPHONEGAP/com.mycompany.project.TESTPHONEGAP.nocache.js"></script>
<script language="javascript" src="my.js"></script>
</code>```

I need the external script before the gwt script.What is going wrong here?

Body:
I am trying to include an external javascript file in my gwt project.In the files html page if I put the following with the external script before the gwt projects script I get a blank page and no errors.

However if I put the external javascript file after the gwt projects script it works.

I need the external script before the gwt script.What is going wrong here?

Body: You may want to accomplish this using Automatic Resource Inclusion, where you put your <script> tags in your gwt.xml file. On page load GWT will inject this script before your onModuleLoad() method is called.


问:
Error adding SSL Support to a Jetty Server Clojure
I am trying to implement ssl in a jetty server; but the server never starts!!!

I create my server certificate files and this is the code:

```<code>(ns restserver.core
  (:require [ring.adapter.jetty :as jetty]
            [ring.util.response :refer [response])

(defn -main
  "A very simple web server using Ring & Jetty"
  [& args]
  (jetty/run-jetty (-> app wrap-json-response)
                   {:port (Integer. "8123")
                          :join? false
                          :ssl? true
                          :ssl-port 9999
                          :keystore "sitepkcs12.keystore"
                          :key-password "qwerty"}))

(defroutes app ....
</code>```

Do I need to do something more??? I cannot figure out what is wrong!!!

I run

```<code>boot run
</code>```

It tries to start but then nothing

答: It seems that I have to change the join option to true and then the server can run!!!!</p>

Body:
I am trying to implement ssl in a jetty server; but the server never starts!!!

I create my server certificate files and this is the code:

(ns restserver.core
  (:require [ring.adapter.jetty :as jetty]
            [ring.util.response :refer [response])

(defn -main
  "A very simple web server using Ring & Jetty"
  [& args]
  (jetty/run-jetty (-> app wrap-json-response)
                   {:port (Integer. "8123")
                          :join? false
                          :ssl? true
                          :ssl-port 9999
                          :keystore "sitepkcs12.keystore"
                          :key-password "qwerty"}))

(defroutes app ....

Do I need to do something more??? I cannot figure out what is wrong!!!

I run

boot run

It tries to start but then nothing


问:
Authenicate users of our web app against client's active directory using LDAP.
A new client has required us to authenticate login users to our web, iOS and android apps against his active directory using LDAP. He wants to control the grouping of his users so as to control the permissions. i.e. admin, manager, staff. etc. I've searched it and am lost as to even know where to start. Any help?</p>

答: What is the application written in? .net, java, ...</p>


问:
FOR... DO in batch with multiples outputs
I'm trying to create an output file; each line of the output file needs to contain the results from a program (few special characters) plus an explanatory plain string right after, but I'm not able to have a proper output. I'm sure it's something simple, but I just don’t have a lot of experience with cmd.

The first FOR creates the special output from my program (kind of a "#34FF123x" string, it's a barcode program). The second FOR is just an ECHO of the numbers that generated the special string. Of course, with two separate FORs I'm gonna have two separate groups on characters, I put them here just for explanation. Thanks for proposing any solution. The results may be also on two different lines, like alternating one from the Program and the next one being the string that generated the previous one. Cheers.

FOR /L %%G IN (1,1,5) DO Program %%G  >> output.file.txt

FOR /L %%i IN (1,1,5) DO ECHO %%i  >> output.file.txt

答:
> outputfile.txt (
    for /l %%i in (1 1 5) do (
        for /f "delims=" %%a in ('program %%i') do echo %%a %%i
    )
)
```

Probably the easiest way to have both values in the same line is to process the output of the program using a for /f command (that will retrieve the "string" into the replaceable parameter) and then echo the retrieved value and the current index.

Body:
> outputfile.txt (
    for /l %%i in (1 1 5) do (
        for /f "delims=" %%a in ('program %%i') do echo %%a %%i
    )
)

Probably the easiest way to have both values in the same line is to process the output of the program using a for /f command (that will retrieve the "string" into the replaceable parameter) and then echo the retrieved value and the current index.


问:
How To Stop A SSIS Package Step In SQL Server Agent Job
I have a SQL Server Agent job that runs on daily basis and the first step in the job is to execute a SSIS package. For the past a few days the step 1 is being running endlessly. Is there anyway that I can shut down the running step?

答:
If you are using Integration Service Catalogs, right click

Open 'Active Operations', there is 'Stop' button.

You can also pull the 'All Execution' Report from Catalog or run query.

```<code>-- Status = created (1), running (2), canceled (3), failed (4), pending (5), ended unexpectedly (6), succeeded (7), stopping (8), and completed (9)
SELECT * FROM SSISDB.[catalog].[executions]
</code>```

Don't have enough information can help you, what is the 1st step1 message in the job step history? In the job properties, click the step, in the advanced tab, what is the number of Retry attempts? No information how you setup job steps, packages?

Body:
If you are using Integration Service Catalogs, right click

Open 'Active Operations', there is 'Stop' button.

You can also pull the 'All Execution' Report from Catalog or run query.

-- Status = created (1), running (2), canceled (3), failed (4), pending (5), ended unexpectedly (6), succeeded (7), stopping (8), and completed (9)
SELECT * FROM SSISDB.[catalog].[executions]

Don't have enough information can help you, what is the 1st step1 message in the job step history? In the job properties, click the step, in the advanced tab, what is the number of Retry attempts? No information how you setup job steps, packages?


问:
How to compare a local Git branch with its remote branch
How can I see the diff between a local branch and a remote branch?

答:
Here is a shorthand answer if you are comparing your current branch and to something you want to git pull.

```<code>git fetch
git diff FETCH_HEAD
</code>```

The first command will figure out which remote branch corresponds to your current branch. An artefact of that calculation in the FETCH_HEAD reference. Then the second command uses that reference to compare versus what your current branch has.

ContentLicense: CC BY-SA 4.0

Body:
Here is a shorthand answer if you are comparing your current branch and to something you want to git pull.

git fetch
git diff FETCH_HEAD

The first command will figure out which remote branch corresponds to your current branch. An artefact of that calculation in the FETCH_HEAD reference. Then the second command uses that reference to compare versus what your current branch has.


问:
implementing an abstract base class function in another template base class
I have a Visual Studio 2008 C++ project where I have a class that inherits from an abstract base class and another template class that implements a function in the abstract base class. For example:

```<code>class Foo;

struct Buzz
{
    virtual ~Buzz() {};
    virtual void Buzz_Do( Foo* ) = 0;
};

class Base
{
public:
    virtual ~Base() {};
    virtual void Base_Do( Buzz* ) = 0;
};

template< class T >
class Bar
{
public:
    virtual void Base_Do( Buzz* v )
    {
        v->Buzz_Do( static_cast< T* >( this ) );
    };
};

class Foo : public Base, public Bar< Foo >
{
};

int _tmain(int argc, _TCHAR* argv[])
{
    Foo c;
    return 0;
}
</code>```

Unfortunately, this yields the compiler error:

```<code>1>MyApp.cpp(39) : error C2259: 'Foo' : cannot instantiate abstract class
1>        due to following members:
1>        'void Base::Base_Do(Buzz *)' : is abstract
1>        MyApp.cpp(17) : see declaration of 'Base::Base_Do'
</code>```

I've tried adding a public using Bar< Foo >::Base_Do; to class Foo, but that did not help.

Is there a way to make this work or will I need to put a concrete Base_Do() implementation in Foo and not use Bar<>?

Thanks,
PaulH

答:
As far as the compiler can tell, your template function doesn't actually implement the function from the base class. The compiler thinks that Base::Base_Do and Bar<T>::Base_Do are two completely unrelated functions, NOT an implementation of one.

What the compiler sees is that Foo winds up with two functions of (almost) the same name: Base::Base_Do and Bar<T>::Base_Do. Bar doesn't implement Base's interface at all.

I think what you really want is for Bar<T> to inherit from Base and implement Base_Do. Then have Foo inherit just from Bar<Foo>.

But even with all that, can you tell us more clearly what problem you're actually trying to solve? Then we can offer advice on how to solve that. The relationship between Buzz and Foo, and Foo to Bar and Base confuses me.

EDIT:
Also see http://www.parashift.com/c++-faq-lite/multiple-inheritance.html#faq-25.10 as that might offer an alternative mechanism that still allows you to use the mixin.

Body:
I have a Visual Studio 2008 C++ project where I have a class that inherits from an abstract base class and another template class that implements a function in the abstract base class. For example:

class Foo;

struct Buzz
{
    virtual ~Buzz() {};
    virtual void Buzz_Do( Foo* ) = 0;
};

class Base
{
public:
    virtual ~Base() {};
    virtual void Base_Do( Buzz* ) = 0;
};

template< class T >
class Bar
{
public:
    virtual void Base_Do( Buzz* v )
    {
        v->Buzz_Do( static_cast< T* >( this ) );
    };
};

class Foo : public Base, public Bar< Foo >
{
};

int _tmain(int argc, _TCHAR* argv[])
{
    Foo c;
    return 0;
}

Unfortunately, this yields the compiler error:

1>MyApp.cpp(39) : error C2259: 'Foo' : cannot instantiate abstract class
1>        due to following members:
1>        'void Base::Base_Do(Buzz *)' : is abstract
1>        MyApp.cpp(17) : see declaration of 'Base::Base_Do'

I've tried adding a public using Bar< Foo >::Base_Do; to class Foo, but that did not help.

Is there a way to make this work or will I need to put a concrete Base_Do() implementation in Foo and not use Bar<>?

Thanks,
PaulH


问:
How to use csrf_token in django template included with limited context
Django templates allow you to include other templates to compose your page. This is particularly useful when you want to render the entire page, but might want to re-load part of it using AJAX, and don't want to move all render logic into javascript (or worse: duplicate it in javascript).

Including a template can look like this:

```<code>{% include "template.html" %}
</code>```

However, if that template might be used by different views, it's likely that your context isn't just a superset of the context for that template. So Django lets you specify the context for the template too.

Because I want to avoid accidentally introducing different behaviour when the template is rendered by being included in another template, and when the template is rendered as the primary template for a view, it also makes sense to me to use the only option to avoid it accessing the parent template's context.

So my include looks like this:

```<code>{% include "sub_template.html" foo=sub_context.foo bar=sub_context.bar only %}
</code>```

However, adding that only causes a problem: {% csrf_token %} no longer works in that template because I guess some of the hidden magic that Django does has been excluded.

The error that Django logs is

UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value.  This is usually caused by not using RequestContext.

The parent template is rendered with a RequestContext, and when the sub template is rendered as the primary template, and not included, the error doesn't occur.

The most obvious work-around to this problem is to not using the only option to include, which seems a shame. Is there a better way of working around this problem?

答:
I had the same issue, and agree that not using only is not an ideal solution.

Turns out {{csrf_token}} works just fine in the parent template so you can use this to send the naked csrf_token across to the included template:

```<code>{% include "sub_template.html" foo=sub_context.foo csrf_token=csrf_token only %}
</code>```

Then the {% csrf_token %} tag works fine on the other side and uses that value to output the full hidden input element. And you still get the advantages of using only in the include.

My answer was found from experimenting with the answers to this question:
Django's {{ csrf_token }} is outputting the token value only, without the hidden input markup

Body:
Django templates allow you to include other templates to compose your page. This is particularly useful when you want to render the entire page, but might want to re-load part of it using AJAX, and don't want to move all render logic into javascript (or worse: duplicate it in javascript).

Including a template can look like this:

{% include "template.html" %}

However, if that template might be used by different views, it's likely that your context isn't just a superset of the context for that template. So Django lets you specify the context for the template too.

Because I want to avoid accidentally introducing different behaviour when the template is rendered by being included in another template, and when the template is rendered as the primary template for a view, it also makes sense to me to use the only option to avoid it accessing the parent template's context.

So my include looks like this:

{% include "sub_template.html" foo=sub_context.foo bar=sub_context.bar only %}

However, adding that only causes a problem: {% csrf_token %} no longer works in that template because I guess some of the hidden magic that Django does has been excluded.

The error that Django logs is

UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value.  This is usually caused by not using RequestContext.

The parent template is rendered with a RequestContext, and when the sub template is rendered as the primary template, and not included, the error doesn't occur.

The most obvious work-around to this problem is to not using the only option to include, which seems a shame. Is there a better way of working around this problem?

Body:
I had the same issue, and agree that not using only is not an ideal solution.

Turns out {{csrf_token}} works just fine in the parent template so you can use this to send the naked csrf_token across to the included template:

{% include "sub_template.html" foo=sub_context.foo csrf_token=csrf_token only %}

Then the {% csrf_token %} tag works fine on the other side and uses that value to output the full hidden input element. And you still get the advantages of using only in the include.

My answer was found from experimenting with the answers to this question:
Django's {{ csrf_token }} is outputting the token value only, without the hidden input markup


问:
How to define an integer vector containing scientific notation correctly in C++?
The code

```<code>#include <iostream>
#include <vector>

int main () { std::vector<int> N = {3e6, 4e6}; }
</code>```

Gives an error

```<code>error: narrowing conversion of ‘3.0e+6’ from ‘double’ to ‘int’ inside { } [-Wnarrowing]|||.
</code>```

Whereas

```<code>#include <iostream>
#include <vector>

int main () {
   std::vector<int> N = {3*10^6, 4*10^6};
   for (int n: N ){ std::cout << n << std::endl; }
}
</code>```

prints

```<code>24
46.
</code>```

How to define this vector as an integer vector correctly?

If have found while writing this question that setting

```<code>int n1 = 3e6, n2 = 4e6;
vector<int> N = {n1, n2};
</code>```

does work, but is there a better way? The type is still converted from double to int in declarations of n1 and n2.

答:
If you insist on using that notation, you can perform an explicit cast to shut the compiler up, but it's not a good idea:</p>

```<code>#include <iostream>
#include <vector>

int main () { std::vector<int> N = {int(3e6), int(4e6)}; }
</code>```

Body:
The code

#include <iostream>
#include <vector>

int main () { std::vector<int> N = {3e6, 4e6}; }

Gives an error

error: narrowing conversion of ‘3.0e+6’ from ‘double’ to ‘int’ inside { } [-Wnarrowing]|||.

Whereas

#include <iostream>
#include <vector>

int main () {
   std::vector<int> N = {3*10^6, 4*10^6};
   for (int n: N ){ std::cout << n << std::endl; }
}

prints

24
46.

How to define this vector as an integer vector correctly?

If have found while writing this question that setting

int n1 = 3e6, n2 = 4e6;
vector<int> N = {n1, n2};

does work, but is there a better way? The type is still converted from double to int in declarations of n1 and n2.

Body:
If you insist on using that notation, you can perform an explicit cast to shut the compiler up, but it's not a good idea:

#include <iostream>
#include <vector>

int main () { std::vector<int> N = {int(3e6), int(4e6)}; }


问:
Extracting Numeric Values in R (from a Free text)
I am trying to extract the age(numeric values) from a vector , tryied the following but dint worked

Example:-

```<code>    a <- "age-32 agge32 age 45 aage 56 agee 34"
    b <- gsub("[Aa]g.e?"," age ",a)
    sa <- strsplit(x=b, split="\\s")
    age <- stringr::str_extract(sa, "(age?)(\\s[^\\s]+){1}")
     (or)
    age <- grep("(([^\\s]+\\s){0}(age)(\\s[^\\s]+){1})",sel,value = TRUE)
</code>```

答:
Is this what you wanted:

```<code>library(stringr)

as.numeric(str_extract_all(a,"\\d+")[[1]])
</code>```

OR using gregexpr and regmatches BASE R:

```<code>as.numeric(regmatches(a,gregexpr("\\d+",a))[[1]])
</code>```

OR use grep and strsplit in BASE R:

```<code>as.numeric(grep("\\d+",strsplit(a,split=" |-|[a-zA-Z]")[[1]],value=T))
</code>```

Output:

```<code>[1] 32 32 45 56 34
</code>```

Body:
I am trying to extract the age(numeric values) from a vector , tryied the following but dint worked

Example:-

    a <- "age-32 agge32 age 45 aage 56 agee 34"
    b <- gsub("[Aa]g.e?"," age ",a)
    sa <- strsplit(x=b, split="\\s")
    age <- stringr::str_extract(sa, "(age?)(\\s[^\\s]+){1}")
     (or)
    age <- grep("(([^\\s]+\\s){0}(age)(\\s[^\\s]+){1})",sel,value = TRUE)

Body:
Is this what you wanted:

library(stringr)

as.numeric(str_extract_all(a,"\\d+")[[1]])

OR using gregexpr and regmatches BASE R:

as.numeric(regmatches(a,gregexpr("\\d+",a))[[1]])

OR use grep and strsplit in BASE R:

as.numeric(grep("\\d+",strsplit(a,split=" |-|[a-zA-Z]")[[1]],value=T))

Output:

[1] 32 32 45 56 34


问:
Go + Azure: Calling a method return undefined
Am trying to use Go Azure SDK to call the notification hub api

I have installed the SDK and imported to the GO file :

```<code>package hub

import (

    "fmt"

    "github.com/Azure/azure-sdk-for-go/arm/notificationhubs"
)

func GetHub() {
    if resourceType, err := notificationhubs.Get("sourceGroupName", "NameSpaceValue", "NameOfTheHub"); err != nil {
        fmt.Println("Error occured")
        return
    }
    fmt.Println("Success")

}
</code>```

However when am trying to runt he code i got this error

```<code>undefined: notificationhubs.Get
</code>```

And am not sure what it means since my IDE don't complain about importing the Azure SDK so am assuming the SDK is imported correctly.

答:
@cd1 is correct! The Get method doesn't belong directly to namespace that you've imported, but rather a client that exists in that namespace. In order to interact with NotificationsHub in this manner, instantiate a GroupClient then run a Get command.

```<code>import (
    hubs "github.com/Azure/azure-sdk-for-go/arm/notificationshub"
)

func main() {
    // Implementation details of your program ...
    client := hubs.NewGroupClient("<YOUR SUBSCRIPTION ID>")
    client.Authorizer = // Your initialized Service Principal Token

    results, err := client.Get("<RESOURCE GROUP NAME>", "<NAMESPACE NAME>", "<NOTIFICATION HUB NAME>")
    if err != nil {
        return
    }
}
</code>```

Body:
Am trying to use Go Azure SDK to call the notification hub api

I have installed the SDK and imported to the GO file :

package hub

import (

    "fmt"

    "github.com/Azure/azure-sdk-for-go/arm/notificationhubs"
)

func GetHub() {
    if resourceType, err := notificationhubs.Get("sourceGroupName", "NameSpaceValue", "NameOfTheHub"); err != nil {
        fmt.Println("Error occured")
        return
    }
    fmt.Println("Success")

}

However when am trying to runt he code i got this error

undefined: notificationhubs.Get

And am not sure what it means since my IDE don't complain about importing the Azure SDK so am assuming the SDK is imported correctly.

Body:
@cd1 is correct! The Get method doesn't belong directly to namespace that you've imported, but rather a client that exists in that namespace. In order to interact with NotificationsHub in this manner, instantiate a GroupClient then run a Get command.

import (
    hubs "github.com/Azure/azure-sdk-for-go/arm/notificationshub"
)

func main() {
    // Implementation details of your program ...
    client := hubs.NewGroupClient("<YOUR SUBSCRIPTION ID>")
    client.Authorizer = // Your initialized Service Principal Token

    results, err := client.Get("<RESOURCE GROUP NAME>", "<NAMESPACE NAME>", "<NOTIFICATION HUB NAME>")
    if err != nil {
        return
    }
}


问:
Merge statement on a single record table
I need to write a single statement to insert or update a record in a single record table

the merge statement allows me to write this:

```<code>create table t1 (n int)

-- insert into t1 (n) Values (1);  -- uncomment to test the matched branch

MERGE t1 AS P
USING (SELECT 3 AS n) AS S
ON 1 = 1
WHEN MATCHED THEN
    UPDATE SET n = S.n
WHEN NOT MATCHED THEN
    INSERT (n)
    VALUES (S.n);

select * from t1
</code>```

this work, but I think that the 1=1 condition purpose is not very easy to understand.
Is there a different syntax to insert a record when the table is empty or update the record when it does already exist?

答:
Replace

```<code>ON 1 = 1
</code>```

with

```<code>ON S.n = P.n
</code>```

Body:
I need to write a single statement to insert or update a record in a single record table

the merge statement allows me to write this:

create table t1 (n int)

-- insert into t1 (n) Values (1);  -- uncomment to test the matched branch

MERGE t1 AS P
USING (SELECT 3 AS n) AS S
ON 1 = 1
WHEN MATCHED THEN
    UPDATE SET n = S.n
WHEN NOT MATCHED THEN
    INSERT (n)
    VALUES (S.n);

select * from t1

this work, but I think that the 1=1 condition purpose is not very easy to understand.
Is there a different syntax to insert a record when the table is empty or update the record when it does already exist?

Body:
Replace

ON 1 = 1

with

ON S.n = P.n


问:
Why can I not open my crontab? Laravel 5 task schedular
I just started working on an artisan command which outputs "hello" every minute with the Laravel task schedular.

My command 'php artisan DeleteInActiveEvents:deleteevents' outputs what is should in the terminal: "hello".

My Command:

```<code>class deleteInActiveEvents extends Command
{
/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'DeleteInActiveEvents:deleteevents';

/**
 * The console command description.
 *
 * @var string
 */
protected $description = 'Command description';

/**
 * Create a new command instance.
 *
 * @return void
 */
public function __construct()
{
    parent::__construct();
}

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
  echo "hello";
}
</code>```

My Kernel.php

```<code>class Kernel extends ConsoleKernel
{
/**
 * The Artisan commands provided by your application.
 *
 * @var array
 */
protected $commands = [
   \einkdisplay\Console\Commands\DeleteInActiveEvents::class
];

/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
  $schedule->command('DeleteInActiveEvents:deleteevents')->everyMinute();
}

/**
 * Register the Closure based commands for the application.
 *
 * @return void
 */
protected function commands()
{
    require base_path('routes/console.php');
}
</code>```

So everything is still working at this point. But I want to do this command every minute. When I run php artisan schedule:run it is not running the command. The laravel docs say that I need to add:

php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1

to my crontab. But when I use crontab -e in the terminal I'm not getting my crontab and I cannot add this line of code.
Probably a very noob question but I can't figure it out. Some help in the right direction would be much appreciated!

答: My best guess is that  you don't have permission to save crontab. Have you try to sudo crontab -e.

Body:
I just started working on an artisan command which outputs "hello" every minute with the Laravel task schedular.

My command 'php artisan DeleteInActiveEvents:deleteevents' outputs what is should in the terminal: "hello".

My Command:

class deleteInActiveEvents extends Command
{
/**
 * The name and signature of the console command.
 *
 * @var string
 */
protected $signature = 'DeleteInActiveEvents:deleteevents';

/**
 * The console command description.
 *
 * @var string
 */
protected $description = 'Command description';

/**
 * Create a new command instance.
 *
 * @return void
 */
public function __construct()
{
    parent::__construct();
}

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
  echo "hello";
}

My Kernel.php

class Kernel extends ConsoleKernel
{
/**
 * The Artisan commands provided by your application.
 *
 * @var array
 */
protected $commands = [
   \einkdisplay\Console\Commands\DeleteInActiveEvents::class
];

/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
  $schedule->command('DeleteInActiveEvents:deleteevents')->everyMinute();
}

/**
 * Register the Closure based commands for the application.
 *
 * @return void
 */
protected function commands()
{
    require base_path('routes/console.php');
}

So everything is still working at this point. But I want to do this command every minute. When I run php artisan schedule:run it is not running the command. The laravel docs say that I need to add:

php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1

to my crontab. But when I use crontab -e in the terminal I'm not getting my crontab and I cannot add this line of code.
Probably a very noob question but I can't figure it out. Some help in the right direction would be much appreciated!


问:
Update SQL Server database' s values quickly C#
I need to update a lot of rows in a database.

Currently I'm using the following code:

```<code>string cmd = "";
cmd = "UPDATE [" + symb + "] SET V1='" + v1.ToString() + "',V2 ='" + v2.ToString() + "',V3='" + v3.ToString() + "' Where V4='" + v4.ToString("yyyyMMdd HH:mm:ss.mmm") + "' AND V5='" + v5.ToString() + "'";

l_Cmd = new SqlCommand(cmd, access_connection);
l_Cmd.ExecuteNonQuery();
</code>```

Since I have to update 500/700k rows, it takes a lot of time.

Have you got any advice?

Sorry for previous post, but all values are different:

```<code>for (int a = 0; a < tot_rows; a++)
{
    string cmd = "";
    cmd = "UPDATE [" + symb + "] SET V1='" + v1[a].ToString() + "',V2 ='" + v2[a].ToString() + "',V3='" + v3[a].ToString() + "' Where V4='" + v4[a].ToString("yyyyMMdd HH:mm:ss.mmm") + "' AND V5='" + v5[a].ToString() + "'";

    l_Cmd = new SqlCommand(cmd, access_connection);
    l_Cmd.ExecuteNonQuery();
}
</code>```

答: Add your array V1 datas in a tempary table on SQL Server, then you will can do an update between your 'symb' table  and your temprary table.</p>

Body:
I need to update a lot of rows in a database.

Currently I'm using the following code:

string cmd = "";
cmd = "UPDATE [" + symb + "] SET V1='" + v1.ToString() + "',V2 ='" + v2.ToString() + "',V3='" + v3.ToString() + "' Where V4='" + v4.ToString("yyyyMMdd HH:mm:ss.mmm") + "' AND V5='" + v5.ToString() + "'";

l_Cmd = new SqlCommand(cmd, access_connection);
l_Cmd.ExecuteNonQuery();

Since I have to update 500/700k rows, it takes a lot of time.

Have you got any advice?

Sorry for previous post, but all values are different:

for (int a = 0; a < tot_rows; a++)
{
    string cmd = "";
    cmd = "UPDATE [" + symb + "] SET V1='" + v1[a].ToString() + "',V2 ='" + v2[a].ToString() + "',V3='" + v3[a].ToString() + "' Where V4='" + v4[a].ToString("yyyyMMdd HH:mm:ss.mmm") + "' AND V5='" + v5[a].ToString() + "'";

    l_Cmd = new SqlCommand(cmd, access_connection);
    l_Cmd.ExecuteNonQuery();
}


问:
XQuery transform multiple xml elements into one target element concatenated
I am looking to transform source xml and combine couple of fields into single target string element in comma separated text.

Conditions Source Inputs (Engg1 to 5) are boolean type, only if value true it should be included in target list

E.g. XML

```<code><Root-Element>
<EnggTypes>
<EnggFN>ABC<EnggFN>
<EnggLN>XYZ<EnggLN>
<EnggEML>abc.xyz@junk.com</EnggEML>
<Engg1>true</Engg1>
<Engg2>true</Engg2>
<Engg3>false</Engg3>
<Engg4>false</Engg4>
<Engg5>true</Engg5>
</EnggTypes>
</Root-Element>
</code>```

Expected Transform

```<code><Root-Element>
<EnggFN>ABC<EnggFN>
<EnggLN>XYZ<EnggLN>
<EnggEML>abc.xyz@junk.com</EnggEML>
<RoleTypes>Role1,Role2,Role5</RoleTypes>
</Root-Element>
</code>```

Looking to achieve same in XQuery 1.0

I started overthinking and tried to use a local variable to see if I can do some if then else if to construct the string using previous value and concatenate but seems like that will not work as variable value cannot be changed once set!

```<code>{ if (Engg1/text()="true")
                      then (let $roleType:='Role1' return roleType)
                  else if (Engg2/text()="true")
                      then (let $roleType:=fn:concat($roleType,",","Role2") return roleType)
                  else if (Engg3/text()="true")
                      then (let $roleType:=fn:concat($roleType,",","Role3") return roleType)
                  else if (Engg4/text()="true")
                      then (let $roleType:=fn:concat($roleType,",","Role4") return roleType)
                  else if (Engg5/text()="true")
                      then (let $roleType:=fn:concat($roleType,",","Role5") return roleType)
                  else (fn:data($roleType))
                  }
</code>```

Any inputs appreciated.

Thanks in advance

答:
You can form the RoleTypes as</p>

```<code><RoleTypes>{
      string-join($x/*[matches(local-name(), 'Engg[0-9]')]
                      [.='true']
                    /concat('Role', substring(local-name(), 5, 1)), ',')
}</RoleTypes>
</code>```

Body:
I am looking to transform source xml and combine couple of fields into single target string element in comma separated text.

Conditions Source Inputs (Engg1 to 5) are boolean type, only if value true it should be included in target list

E.g. XML

<Root-Element>
<EnggTypes>
<EnggFN>ABC<EnggFN>
<EnggLN>XYZ<EnggLN>
<EnggEML>abc.xyz@junk.com</EnggEML>
<Engg1>true</Engg1>
<Engg2>true</Engg2>
<Engg3>false</Engg3>
<Engg4>false</Engg4>
<Engg5>true</Engg5>
</EnggTypes>
</Root-Element>

Expected Transform

<Root-Element>
<EnggFN>ABC<EnggFN>
<EnggLN>XYZ<EnggLN>
<EnggEML>abc.xyz@junk.com</EnggEML>
<RoleTypes>Role1,Role2,Role5</RoleTypes>
</Root-Element>

Looking to achieve same in XQuery 1.0

I started overthinking and tried to use a local variable to see if I can do some if then else if to construct the string using previous value and concatenate but seems like that will not work as variable value cannot be changed once set!

{ if (Engg1/text()="true")
                      then (let $roleType:='Role1' return roleType)
                  else if (Engg2/text()="true")
                      then (let $roleType:=fn:concat($roleType,",","Role2") return roleType)
                  else if (Engg3/text()="true")
                      then (let $roleType:=fn:concat($roleType,",","Role3") return roleType)
                  else if (Engg4/text()="true")
                      then (let $roleType:=fn:concat($roleType,",","Role4") return roleType)
                  else if (Engg5/text()="true")
                      then (let $roleType:=fn:concat($roleType,",","Role5") return roleType)
                  else (fn:data($roleType))
                  }

Any inputs appreciated.

Thanks in advance

Body:
You can form the RoleTypes as

<RoleTypes>{
      string-join($x/*[matches(local-name(), 'Engg[0-9]')]
                      [.='true']
                    /concat('Role', substring(local-name(), 5, 1)), ',')
}</RoleTypes>


问:
Get whole dataset for each unique combination of two columns and their max and min values
I'm desperately searching a query which gives me all datasets to the following query:

```<code>SELECT col1, col2, MAX(col3), MIN(col4) FROM table1 GROUP BY col1, col2
</code>```

This returns a Table like the following

```<code>col 1  | col2   | max(col3) | min(col4)
------ | ------ | --------- | ------
10     | 0.5    | 20        | -5
10     | 0.9    | 30        | -2
</code>```

What I need is the dataset(the whole row) for each max and min and each entity. I could do this programatically with a query like

SELECT * FROM table1 WHERE col1 = 10 AND (col2 = 0.5 OR col2 = 0.9) AND ((col3 = 20 OR col4 = -5) OR (col3 = 30 OR col4 = -2 ))
```

<p>which returns me 4 datasets,</p>

<p>but the Query gets more ugly with each added MAX or MIN or GROUP BY(this is what the users do with the program).</p>

<p>Let me try to explain it in one sentence: I'm searching a way of displaying the dataset to each max and min value(not col1,col2) of each unique combination of values of col1 and col2. </p>

<p>Is there a way, to do this in one query? </p>

<p>If you need further details don't fear to comment. </p>

<h2>Edit 1</h2>

<p><strong>Dataset</strong></p>

```id   | col 1  | col2   | col3   | col4
---- | ------ | ------ | ------ | ------
  0  |   10   |  0.5   |  20    |  0
  1  |   10   |  0.5   |  15    | -1
  2  |   10   |  0.5   |  17    | 12
  3  |   10   |  0.5   |  11    |  3
  4  |   10   |  0.5   |   5    | -5
  5  |   10   |  0.9   |  10    |  1
  6  |   10   |  0.9   |  22    | -1
  7  |   10   |  0.9   |  15    | -2
  8  |   10   |  0.9   |  30    |  3
```

<p><strong>Desired Output</strong></p>

```id   |  col 1  | col2   | col3   | col4
---- |  ------ | ------ | ------ | ------
  0  |   10    |  0.5   |  20    |  0
  4  |   10    |  0.5   |  5     | -5
  7  |   10    |  0.9   |  15    | -2
  8  |   10    |  0.9   |  30    |  3
```

答:
if you know your two column values: this would be the dataset for when col3 is maximum and col 4 minimum at those two colum values. keep in mind your constraint to the query is the two column values. compound query should be like:</p>

```<code> select * from table1 as A where col1 = '$value1' and col2 = '$value2' and    col3=(select MAX(col3) FROM table1 as B where A.col1 = B.col1 and A.col2 = B.col2) and col4=(select MIN(col4) FROM table1 as C where A.col1 = C.col1 and A.col2 = C.col2)";
</code>```

Body:
I'm desperately searching a query which gives me all datasets to the following query:

SELECT col1, col2, MAX(col3), MIN(col4) FROM table1 GROUP BY col1, col2

This returns a Table like the following

col 1  | col2   | max(col3) | min(col4)
------ | ------ | --------- | ------
10     | 0.5    | 20        | -5
10     | 0.9    | 30        | -2

What I need is the dataset(the whole row) for each max and min and each entity. I could do this programatically with a query like

SELECT * FROM table1 WHERE col1 = 10 AND (col2 = 0.5 OR col2 = 0.9) AND ((col3 = 20 OR col4 = -5) OR (col3 = 30 OR col4 = -2 ))

which returns me 4 datasets,

but the Query gets more ugly with each added MAX or MIN or GROUP BY(this is what the users do with the program).

Let me try to explain it in one sentence: I'm searching a way of displaying the dataset to each max and min value(not col1,col2) of each unique combination of values of col1 and col2.

Is there a way, to do this in one query?

If you need further details don't fear to comment.

Edit 1

Dataset

id   | col 1  | col2   | col3   | col4
---- | ------ | ------ | ------ | ------
  0  |   10   |  0.5   |  20    |  0
  1  |   10   |  0.5   |  15    | -1
  2  |   10   |  0.5   |  17    | 12
  3  |   10   |  0.5   |  11    |  3
  4  |   10   |  0.5   |   5    | -5
  5  |   10   |  0.9   |  10    |  1
  6  |   10   |  0.9   |  22    | -1
  7  |   10   |  0.9   |  15    | -2
  8  |   10   |  0.9   |  30    |  3

Desired Output

id   |  col 1  | col2   | col3   | col4
---- |  ------ | ------ | ------ | ------
  0  |   10    |  0.5   |  20    |  0
  4  |   10    |  0.5   |  5     | -5
  7  |   10    |  0.9   |  15    | -2
  8  |   10    |  0.9   |  30    |  3

Body:
if you know your two column values: this would be the dataset for when col3 is maximum and col 4 minimum at those two colum values. keep in mind your constraint to the query is the two column values. compound query should be like:

 select * from table1 as A where col1 = '$value1' and col2 = '$value2' and    col3=(select MAX(col3) FROM table1 as B where A.col1 = B.col1 and A.col2 = B.col2) and col4=(select MIN(col4) FROM table1 as C where A.col1 = C.col1 and A.col2 = C.col2)";


问:
Add files to classpath or loops in batch files?
I have this script in BASH (linux) shells script that adds all *.jar files into the classpath automatically. Is there a way to do the in window's batch file or do I have to add all the files manually?

```<code>CLASSPATH=.
for file in ./libs/*.jar; do
    CLASSPATH=$CLASSPATH:$file
done
</code>```

Thanks!

答:
Use the forfiles command to loop over the file names.

```<code>forfiles /M .\libs\*.jar /C "cmd /c set CLASSPATH=%CLASSPATH%;@file"
</code>```

Body:
I have this script in BASH (linux) shells script that adds all *.jar files into the classpath automatically. Is there a way to do the in window's batch file or do I have to add all the files manually?

CLASSPATH=.
for file in ./libs/*.jar; do
    CLASSPATH=$CLASSPATH:$file
done

Thanks!

Body:
Use the forfiles command to loop over the file names.

forfiles /M .\libs\*.jar /C "cmd /c set CLASSPATH=%CLASSPATH%;@file"


问:
Put 2 columns of recycler view every row
I would like to put 2 columns of recyclerview every row.

Right now my design is like this:

and i would like to put 2 so the scroll is not to long.

I have this view inside a fragment and I use a recyclerview adapter but I have no clue how to tell it to use its parent with, so it can fill the width of the screen. In the fragment I recive a JSON from an online database using an AsyncTask and fill in the recyclerview on the onPostExecute of the AsyncTask.

If anyone has any Idea how i can do it, I can't seem to find this anywhere

Thx!

My recyclerview Adapter:

package com.example.juanfri.seguridadmainactivity;

/**
 * Created by jlira on 30/05/2017.
 */

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;

/**
 * Created by Juanfri on 29/05/2017.
 */

public class RecyclerAdapterSerie extends RecyclerView.Adapter<RecyclerAdapterSerie.SerieHolder> {
    private ArrayList<Serie> mSerie;
    @Override
    public RecyclerAdapterSerie.SerieHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View inflatedView = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.recyclerview_card, viewGroup, false);
        return new SerieHolder(inflatedView);
    }

    @Override
    public void onBindViewHolder(RecyclerAdapterSerie.SerieHolder holder, int i) {
        Serie itemPhoto = mSerie.get(i);
        holder.bindPhoto(itemPhoto);
    }

    @Override
    public int getItemCount() {
        return mSerie.size();
    }

    public RecyclerAdapterSerie(ArrayList<Serie> serie) {
        mSerie = serie;
    }
    public static class SerieHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        //2
        private ImageView mItemImage;
        private TextView mItemDate;
        private TextView mItemDescription;
        private Serie serie;

        //3
        private static final String PHOTO_KEY = "PHOTO";

        //4
        public SerieHolder(View v) {
            super(v);

            mItemImage = (ImageView) v.findViewById(R.id.item_image);
            mItemDate = (TextView) v.findViewById(R.id.item_date);
            mItemDescription = (TextView) v.findViewById(R.id.item_description);
            v.setOnClickListener(this);
        }

        //5
        @Override
        public void onClick(View v) {
            /*Context context = itemView.getContext();
            Intent showPhotoIntent = new Intent(context, Pelicula.class);
            showPhotoIntent.putExtra(PHOTO_KEY, peli);
            context.startActivity(showPhotoIntent);*/
        }
        public void bindPhoto(Serie mserie) {
            serie = mserie;
            String Nombre = mserie.getNombreSerie();
            if(Nombre.length() >= 25)
            {
                Nombre = Nombre.substring(0,22);
                Nombre = Nombre + "...";
            }
            Picasso.with(mItemImage.getContext()).load(mserie.getPoster()).into(mItemImage);
            mItemDate.setText(Nombre);
            mItemDescription.setText(Integer.toString(mserie.getIdTMDB()));
        }
    }
}```
</div>
</div>
</p>

<p>My fragment (where i create the recyclerview)</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>package com.example.juanfri.seguridadmainactivity;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import static android.content.ContentValues.TAG;

/**
 * Created by jlira on 06/06/2017.
 */

public class FragmentoSeriesPelis extends Fragment {

    public final String API = "5e2780b2117b40f9e4dfb96572a7bc4d";
    public final String URLFOTO ="https://image.tmdb.org/t/p/original/";
    private ProgressDialog pDialog;
    private RecyclerView recyclerView;
    private LinearLayoutManager mLinearLayoutManager;
    private ArrayList<Serie> series;
    private ArrayList<Pelicula> Pelis;
    private RecyclerAdapterSerie mAdapterSerie;
    private RecyclerAdapterPelicula mAdapterPeli;
    private int pagina;
    private String url;
    private Button CargarMas;
    private String tipo;
    private int MaxPag;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.series_pelis_layout, container, false);
        view.setTag(TAG);
        Bundle args = getArguments();
        series = new ArrayList<>();
        Pelis = new ArrayList<>();
        MaxPag = 2;
        pagina = args.getInt("Page");
        url = args.getString("url");
        tipo = args.getString("Tipo");
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerViewSerieshoy);
        //mLinearLayoutManagerSerie = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        //recyclerViewSerie.setLayoutManager(mLinearLayoutManagerSerie);
        //mAdapterSerie = new RecyclerAdapterSerie(seriesHoy);
        //recyclerViewSerie.setAdapter(mAdapterSerie);
        new GetSeriesHoy().execute();
        CargarMas = (Button) view.findViewById(R.id.buttonCargarMas);
        CargarMas.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if(pagina+1<=MaxPag)
                {
                    pagina++;
                    new GetSeriesHoy().execute();
                }
                else
                {
                    Toast.makeText(getActivity(), "No hay mas resultados", Toast.LENGTH_LONG).show();
                }
            }
        });

        return view;

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getActivity().setTitle("Series de Hoy");
    }
    private class GetSeriesHoy extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            //url = "https://api.themoviedb.org/3/tv/airing_today?api_key="+API+"&language=en-US&page="+pagina;

            String aux = url+pagina;
            String jsonStr = sh.makeServiceCall(aux);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    // Getting JSON Array node
                    MaxPag = jsonObj.getInt("total_pages");
                    JSONArray contacts = jsonObj.getJSONArray("results");

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);
                        int IdSerie = i;
                        int idTMDB = c.getInt("id");
                        String nombreSerie;
                        String poster =URLFOTO + c.getString("poster_path");
                        if(tipo.equalsIgnoreCase("Series"))
                        {
                            nombreSerie = c.getString("name");
                            Serie nuevo = new Serie();
                            nuevo.setIdSerie(IdSerie);
                            nuevo.setNombreSerie(nombreSerie);
                            nuevo.setIdTMDB(idTMDB);
                            nuevo.setPoster(poster);
                            series.add(nuevo);
                        }
                        else
                        {
                            nombreSerie = c.getString("title");
                            Pelicula nuevo = new Pelicula();
                            nuevo.setIdPelicula(IdSerie);
                            nuevo.setNombrePelicula(nombreSerie);
                            nuevo.setIdTMDB(idTMDB);
                            nuevo.setPoster(poster);
                            Pelis.add(nuevo);
                        }
                    }
                } catch (final JSONException e) {
                    Toast.makeText(getActivity(),
                            "Json parsing error: " + e.getMessage(),
                            Toast.LENGTH_LONG)
                            .show();
                }
            } else {
                Toast.makeText(getActivity(),
                        "Couldn't get json from server. Check LogCat for possible errors!",
                        Toast.LENGTH_LONG)
                        .show();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            //Aqui Realizar la RecycleView BuildUp
            if(tipo.equalsIgnoreCase("Series"))
            {
                mLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
                recyclerView.setLayoutManager(mLinearLayoutManager);
                mAdapterSerie = new RecyclerAdapterSerie(series);
                recyclerView.setAdapter(mAdapterSerie);
            }else
            {
                mLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
                recyclerView.setLayoutManager(mLinearLayoutManager);
                mAdapterPeli = new RecyclerAdapterPelicula(Pelis);
                recyclerView.setAdapter(mAdapterPeli);
            }

        }

    }

}</code>```

答:
Replace your LinearLayoutManager for a GridLayoutManager like this:

private GridLayoutManager mGridLayoutManager;
// ...
mGridLayoutManager = new GridLayoutManager(getActivity(), 2);
```

Then you can use it the same way as the LinearLayoutManager.

Body:
I would like to put 2 columns of recyclerview every row.

Right now my design is like this:

and i would like to put 2 so the scroll is not to long.

I have this view inside a fragment and I use a recyclerview adapter but I have no clue how to tell it to use its parent with, so it can fill the width of the screen. In the fragment I recive a JSON from an online database using an AsyncTask and fill in the recyclerview on the onPostExecute of the AsyncTask.

If anyone has any Idea how i can do it, I can't seem to find this anywhere

Thx!

My recyclerview Adapter:

package com.example.juanfri.seguridadmainactivity;

/**
 * Created by jlira on 30/05/2017.
 */

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;

/**
 * Created by Juanfri on 29/05/2017.
 */

public class RecyclerAdapterSerie extends RecyclerView.Adapter<RecyclerAdapterSerie.SerieHolder> {
    private ArrayList<Serie> mSerie;
    @Override
    public RecyclerAdapterSerie.SerieHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View inflatedView = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.recyclerview_card, viewGroup, false);
        return new SerieHolder(inflatedView);
    }

    @Override
    public void onBindViewHolder(RecyclerAdapterSerie.SerieHolder holder, int i) {
        Serie itemPhoto = mSerie.get(i);
        holder.bindPhoto(itemPhoto);
    }

    @Override
    public int getItemCount() {
        return mSerie.size();
    }

    public RecyclerAdapterSerie(ArrayList<Serie> serie) {
        mSerie = serie;
    }
    public static class SerieHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        //2
        private ImageView mItemImage;
        private TextView mItemDate;
        private TextView mItemDescription;
        private Serie serie;

        //3
        private static final String PHOTO_KEY = "PHOTO";

        //4
        public SerieHolder(View v) {
            super(v);

            mItemImage = (ImageView) v.findViewById(R.id.item_image);
            mItemDate = (TextView) v.findViewById(R.id.item_date);
            mItemDescription = (TextView) v.findViewById(R.id.item_description);
            v.setOnClickListener(this);
        }

        //5
        @Override
        public void onClick(View v) {
            /*Context context = itemView.getContext();
            Intent showPhotoIntent = new Intent(context, Pelicula.class);
            showPhotoIntent.putExtra(PHOTO_KEY, peli);
            context.startActivity(showPhotoIntent);*/
        }
        public void bindPhoto(Serie mserie) {
            serie = mserie;
            String Nombre = mserie.getNombreSerie();
            if(Nombre.length() >= 25)
            {
                Nombre = Nombre.substring(0,22);
                Nombre = Nombre + "...";
            }
            Picasso.with(mItemImage.getContext()).load(mserie.getPoster()).into(mItemImage);
            mItemDate.setText(Nombre);
            mItemDescription.setText(Integer.toString(mserie.getIdTMDB()));
        }
    }
}

My fragment (where i create the recyclerview)

package com.example.juanfri.seguridadmainactivity;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import static android.content.ContentValues.TAG;

/**
 * Created by jlira on 06/06/2017.
 */

public class FragmentoSeriesPelis extends Fragment {

    public final String API = "5e2780b2117b40f9e4dfb96572a7bc4d";
    public final String URLFOTO ="https://image.tmdb.org/t/p/original/";
    private ProgressDialog pDialog;
    private RecyclerView recyclerView;
    private LinearLayoutManager mLinearLayoutManager;
    private ArrayList<Serie> series;
    private ArrayList<Pelicula> Pelis;
    private RecyclerAdapterSerie mAdapterSerie;
    private RecyclerAdapterPelicula mAdapterPeli;
    private int pagina;
    private String url;
    private Button CargarMas;
    private String tipo;
    private int MaxPag;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.series_pelis_layout, container, false);
        view.setTag(TAG);
        Bundle args = getArguments();
        series = new ArrayList<>();
        Pelis = new ArrayList<>();
        MaxPag = 2;
        pagina = args.getInt("Page");
        url = args.getString("url");
        tipo = args.getString("Tipo");
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerViewSerieshoy);
        //mLinearLayoutManagerSerie = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        //recyclerViewSerie.setLayoutManager(mLinearLayoutManagerSerie);
        //mAdapterSerie = new RecyclerAdapterSerie(seriesHoy);
        //recyclerViewSerie.setAdapter(mAdapterSerie);
        new GetSeriesHoy().execute();
        CargarMas = (Button) view.findViewById(R.id.buttonCargarMas);
        CargarMas.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if(pagina+1<=MaxPag)
                {
                    pagina++;
                    new GetSeriesHoy().execute();
                }
                else
                {
                    Toast.makeText(getActivity(), "No hay mas resultados", Toast.LENGTH_LONG).show();
                }
            }
        });

        return view;

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getActivity().setTitle("Series de Hoy");
    }
    private class GetSeriesHoy extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            //url = "https://api.themoviedb.org/3/tv/airing_today?api_key="+API+"&language=en-US&page="+pagina;

            String aux = url+pagina;
            String jsonStr = sh.makeServiceCall(aux);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    // Getting JSON Array node
                    MaxPag = jsonObj.getInt("total_pages");
                    JSONArray contacts = jsonObj.getJSONArray("results");

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);
                        int IdSerie = i;
                        int idTMDB = c.getInt("id");
                        String nombreSerie;
                        String poster =URLFOTO + c.getString("poster_path");
                        if(tipo.equalsIgnoreCase("Series"))
                        {
                            nombreSerie = c.getString("name");
                            Serie nuevo = new Serie();
                            nuevo.setIdSerie(IdSerie);
                            nuevo.setNombreSerie(nombreSerie);
                            nuevo.setIdTMDB(idTMDB);
                            nuevo.setPoster(poster);
                            series.add(nuevo);
                        }
                        else
                        {
                            nombreSerie = c.getString("title");
                            Pelicula nuevo = new Pelicula();
                            nuevo.setIdPelicula(IdSerie);
                            nuevo.setNombrePelicula(nombreSerie);
                            nuevo.setIdTMDB(idTMDB);
                            nuevo.setPoster(poster);
                            Pelis.add(nuevo);
                        }
                    }
                } catch (final JSONException e) {
                    Toast.makeText(getActivity(),
                            "Json parsing error: " + e.getMessage(),
                            Toast.LENGTH_LONG)
                            .show();
                }
            } else {
                Toast.makeText(getActivity(),
                        "Couldn't get json from server. Check LogCat for possible errors!",
                        Toast.LENGTH_LONG)
                        .show();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            //Aqui Realizar la RecycleView BuildUp
            if(tipo.equalsIgnoreCase("Series"))
            {
                mLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
                recyclerView.setLayoutManager(mLinearLayoutManager);
                mAdapterSerie = new RecyclerAdapterSerie(series);
                recyclerView.setAdapter(mAdapterSerie);
            }else
            {
                mLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
                recyclerView.setLayoutManager(mLinearLayoutManager);
                mAdapterPeli = new RecyclerAdapterPelicula(Pelis);
                recyclerView.setAdapter(mAdapterPeli);
            }

        }

    }

}

Body:
Replace your LinearLayoutManager for a GridLayoutManager like this:

private GridLayoutManager mGridLayoutManager;
// ...
mGridLayoutManager = new GridLayoutManager(getActivity(), 2);

Then you can use it the same way as the LinearLayoutManager.