问:
Using scanf to store string in a structure
I've written a function that stores information on books to a struct Book and everything is working fine except for when the book title has any white spaces. So something like Dracula will be stored and displayed just fine, but something like Lord of the Rings will just skip scanning for the rest of the book's information and proceed to close the program. Is there any way to use scanf to register the string with the white spaces? Here's my code:

```<code>void addBook(struct Book book[], int *size)
{
        if(*size== MAX_BOOKS) {
                printf("the inventory is full.\n");
        }

        else {
                printf("ISBN\n");
                scanf("%d", &book[*size]._isbn);
                printf("Title\n");
                scanf("%s", book[*size]._title);
                printf("Price\n");
                scanf("%f", &book[*size]._price);
                printf("Year\n");
                scanf("%d", &book[*size]._year);
                printf("Qty\n");
                scanf("%d", &book[*size]._qty);
                printf("Book successfully added to inventory\n");

                (*size)++;
                }

}
</code>```

I can update with the full code if necessary.

答: No problem. That's because %s stops at the first space. Use %[^\n] so it reads until he find the enter.</p>

Body:
I've written a function that stores information on books to a struct Book and everything is working fine except for when the book title has any white spaces. So something like Dracula will be stored and displayed just fine, but something like Lord of the Rings will just skip scanning for the rest of the book's information and proceed to close the program. Is there any way to use scanf to register the string with the white spaces? Here's my code:

void addBook(struct Book book[], int *size)
{
        if(*size== MAX_BOOKS) {
                printf("the inventory is full.\n");
        }

        else {
                printf("ISBN\n");
                scanf("%d", &book[*size]._isbn);
                printf("Title\n");
                scanf("%s", book[*size]._title);
                printf("Price\n");
                scanf("%f", &book[*size]._price);
                printf("Year\n");
                scanf("%d", &book[*size]._year);
                printf("Qty\n");
                scanf("%d", &book[*size]._qty);
                printf("Book successfully added to inventory\n");

                (*size)++;
                }

}

I can update with the full code if necessary.


来源: stackexchange

问:
Extract text string from undeliverable email body to Excel
I am trying to extract the email address from each individual undeliverables email body.

The email body would be like:

----------------------------Email----------------------------

Delivery has failed to these recipients or groups:

XXXX@XXXXXX.XXX (XXXX@XXXXXX.XXX)

...no need info...

To: XXXX@XXXXXX.XXX

...no need info...

----------------------------Email-----------------------------

I came up with below code:

```<code>Sub Test()
   Dim myFolder As MAPIFolder
   Dim Item As Outlook.MailItem 'MailItem
   Dim xlApp As Object 'Excel.Application
   Dim xlWB As Object 'Excel.Workbook
   Dim xlSheet As Object 'Excel.Worksheet
   Dim Lines() As String
   Dim i As Integer, x As Integer, P As Integer
   Dim myItem As Variant
   Dim subjectOfEmail As String
   Dim bodyOfEmail As String

'Try access to excel
   On Error Resume Next
   Set xlApp = GetObject(, "Excel.Application")
   If xlApp Is Nothing Then
     Set xlApp = CreateObject("Excel.Application")
     xlApp.Application.Visible = True
     If xlApp Is Nothing Then
       MsgBox "Excel is not accessable"
       Exit Sub
     End If
   End If
   On Error GoTo 0

 'Add a new workbook
   Set xlWB = xlApp.Workbooks.Add
   xlApp.Application.Visible = True
   Set xlSheet = xlWB.ActiveSheet
   Set myFolder = GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
   For Each myItem In myFolder.Items
     subjectOfEmail = myItem.Subject
     bodyOfEmail = myItem.Body

 'Search for Undeliverable email
     If bodyOfEmail Like "*Delivery*" & "*failed*" And indexOfEmail Like "*Undeliverable*" Then
       x = x + 1
 'Extract email address from email body
       Lines = Split(myItem.Body, vbCrLf)
       For i = 0 To UBound(Lines)
         P = InStr(1, Lines(i), "@", vbTextCompare)
         Q = InStr(1, Lines(i), "(", vbTextCompare)
         If P > 0 Then
           xlApp.Range("A" & x) = Trim$(Mid$(Lines(i), 1, Q - 1)) 'extract the email address
           Exit For
         End If
       Next
    End If
  Next
End Sub
</code>```

It worked on my test Email Inbox, which opened an Excel sheet and listed every particular email address within the target emails.

When I ran this code on my work email account, it didn't give me a thing. I found that it had trouble reading "Undeliverables" emails, and every time after I ran it, one of the undeliverables emails turned into Traditional Chinese characters which cannot be read.

格浴㹬格慥㹤਍洼瑥瑨灴攭畱癩∽潃瑮湥⵴祔数•潣瑮湥㵴琢硥⽴瑨汭※档牡敳㵴獵愭捳楩㸢⼼敨摡㰾潢祤ാ㰊㹰戼㰾潦瑮挠汯牯∽〣〰㘰∶猠穩㵥㌢•慦散∽牁慩≬䐾汥癩牥⁹慨⁳慦汩摥琠桴獥敲楣楰湥獴漠⁲牧畯獰㰺是湯㹴⼼㹢⼼㹰਍昼湯⁴潣潬

I feel this code works on only forwarded undeliverable email, in my test email inbox.

It never read from the original undeliverable emails and turned those emails to Chinese characters one by one.

I googled it, it seems there are bugs in Outlook for the failed delivery emails. How to fix this?

答:
There is a problem with the ReportItem.Body property in the Outlook Object Model (present in Outlook 2013 and 2016) - you can see it in OutlookSpy (I am its author): select an NDR message, click Item button, select the Body property - it will be garbled. Worse than that, once the report item is touched with OOM, Outlook will display the same junk in the preview pane.

The report text is stored in various MAPI recipient properties (click IMessage button in OutlookSpy and go to the GetRecipientTable tab). The problem is the ReportItem object does not expose the Recipients collection. The workaround is to either use Extended MAPI (C++ or Delphi) or Redemption (I am its author - any language) - its RDOReportItem.ReportText property does not have this problem:

```<code>set oItem = Application.ActiveExplorer.Selection(1)
set oSession = CreateObject("Redemption.RDOSession")
oSession.MAPIOBJECT = Application.Session.MAPIOBJECT
set rItem = oSession.GetRDOObjectFromOutlookObject(oItem)
MsgBox rItem.ReportText
</code>```

You can also use RDOReportItem.Recipients collection to extract various NDR properties from the recipient table.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to extract the email address from each individual undeliverables email body.

The email body would be like:

----------------------------Email----------------------------

Delivery has failed to these recipients or groups:

XXXX@XXXXXX.XXX (XXXX@XXXXXX.XXX)

...no need info...

To: XXXX@XXXXXX.XXX

...no need info...

----------------------------Email-----------------------------

I came up with below code:

Sub Test()
   Dim myFolder As MAPIFolder
   Dim Item As Outlook.MailItem 'MailItem
   Dim xlApp As Object 'Excel.Application
   Dim xlWB As Object 'Excel.Workbook
   Dim xlSheet As Object 'Excel.Worksheet
   Dim Lines() As String
   Dim i As Integer, x As Integer, P As Integer
   Dim myItem As Variant
   Dim subjectOfEmail As String
   Dim bodyOfEmail As String

'Try access to excel
   On Error Resume Next
   Set xlApp = GetObject(, "Excel.Application")
   If xlApp Is Nothing Then
     Set xlApp = CreateObject("Excel.Application")
     xlApp.Application.Visible = True
     If xlApp Is Nothing Then
       MsgBox "Excel is not accessable"
       Exit Sub
     End If
   End If
   On Error GoTo 0

 'Add a new workbook
   Set xlWB = xlApp.Workbooks.Add
   xlApp.Application.Visible = True
   Set xlSheet = xlWB.ActiveSheet
   Set myFolder = GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
   For Each myItem In myFolder.Items
     subjectOfEmail = myItem.Subject
     bodyOfEmail = myItem.Body

 'Search for Undeliverable email
     If bodyOfEmail Like "*Delivery*" & "*failed*" And indexOfEmail Like "*Undeliverable*" Then
       x = x + 1
 'Extract email address from email body
       Lines = Split(myItem.Body, vbCrLf)
       For i = 0 To UBound(Lines)
         P = InStr(1, Lines(i), "@", vbTextCompare)
         Q = InStr(1, Lines(i), "(", vbTextCompare)
         If P > 0 Then
           xlApp.Range("A" & x) = Trim$(Mid$(Lines(i), 1, Q - 1)) 'extract the email address
           Exit For
         End If
       Next
    End If
  Next
End Sub

It worked on my test Email Inbox, which opened an Excel sheet and listed every particular email address within the target emails.

When I ran this code on my work email account, it didn't give me a thing. I found that it had trouble reading "Undeliverables" emails, and every time after I ran it, one of the undeliverables emails turned into Traditional Chinese characters which cannot be read.

格浴㹬格慥㹤਍洼瑥瑨灴攭畱癩∽潃瑮湥⵴祔数•潣瑮湥㵴琢硥⽴瑨汭※档牡敳㵴獵愭捳楩㸢⼼敨摡㰾潢祤ാ㰊㹰戼㰾潦瑮挠汯牯∽〣〰㘰∶猠穩㵥㌢•慦散∽牁慩≬䐾汥癩牥⁹慨⁳慦汩摥琠桴獥敲楣楰湥獴漠⁲牧畯獰㰺是湯㹴⼼㹢⼼㹰਍昼湯⁴潣潬

I feel this code works on only forwarded undeliverable email, in my test email inbox.

It never read from the original undeliverable emails and turned those emails to Chinese characters one by one.

I googled it, it seems there are bugs in Outlook for the failed delivery emails. How to fix this?

Body:
There is a problem with the ReportItem.Body property in the Outlook Object Model (present in Outlook 2013 and 2016) - you can see it in OutlookSpy (I am its author): select an NDR message, click Item button, select the Body property - it will be garbled. Worse than that, once the report item is touched with OOM, Outlook will display the same junk in the preview pane.

The report text is stored in various MAPI recipient properties (click IMessage button in OutlookSpy and go to the GetRecipientTable tab). The problem is the ReportItem object does not expose the Recipients collection. The workaround is to either use Extended MAPI (C++ or Delphi) or Redemption (I am its author - any language) - its RDOReportItem.ReportText property does not have this problem:

set oItem = Application.ActiveExplorer.Selection(1)
set oSession = CreateObject("Redemption.RDOSession")
oSession.MAPIOBJECT = Application.Session.MAPIOBJECT
set rItem = oSession.GetRDOObjectFromOutlookObject(oItem)
MsgBox rItem.ReportText

You can also use RDOReportItem.Recipients collection to extract various NDR properties from the recipient table.


问:
Why do i get "error: failed to push some refs"?
I have a remote git repository and a local one that i work with. Whenever i do any changes locally, i push them to the remote. Then i sometime do a "git commit" on the remote one to store the changes on the remote files.

I do not edit the remote repository directly at all. I just commit the changes. And i'm a single developer, no one else works on that repos.

Why do i get an error that, from what i know, means that i have to pull first ?

I don't want to pull because the remote repos files are outdated and it will lose my local changes. This is really annoying, why does this happen ? And how can i fix without having to pull or recreate the repository ? (as you can see, this is sort of like a subversion type of version control style here)

EDIT - The error :

```<code>To ssh://...
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'ssh://...'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes (e.g. 'git pull') before pushing again.  See the
'Note about fast-forwards' section of 'git push --help' for details.
</code>```

答:
I faced similar problem, and the following command worked.
git push --set-upstream origin master</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a remote git repository and a local one that i work with. Whenever i do any changes locally, i push them to the remote. Then i sometime do a "git commit" on the remote one to store the changes on the remote files.

I do not edit the remote repository directly at all. I just commit the changes. And i'm a single developer, no one else works on that repos.

Why do i get an error that, from what i know, means that i have to pull first ?

I don't want to pull because the remote repos files are outdated and it will lose my local changes. This is really annoying, why does this happen ? And how can i fix without having to pull or recreate the repository ? (as you can see, this is sort of like a subversion type of version control style here)

EDIT - The error :

To ssh://...
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'ssh://...'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes (e.g. 'git pull') before pushing again.  See the
'Note about fast-forwards' section of 'git push --help' for details.


问:
jquery datatable select not working
I have written this code for my datatable

```<code>$(function(){
    var $oltable=$("#owner-lead-table");
    var oltable=$oltable.DataTable({
        // 'serverSide' : true,
        // 'ajax': {
        //  url:"/getAllTenantLeadsNotInOpportunity",
        //  type:"GET",
        //  contentType:"application/json",
        //  data : function(d){
        //      console.log(d);
        //      return JSON.stringify(d);
        //  },
        //  dataSrc: function (json) {
        //          console.log(json);
  //                   return json;
  //                },
  //           columns: [
  //            { data:'tenantLeadId' },
  //            { data:'name'},
  //            { data:'email'},
  //            { data:'mobileNumber'},
  //            { data:'qualifier'},
  //            { data:'createdOn'},
  //            { data:'comment'}
  //           ],
        // },
        select:"single"
    });

    $.ajax( {
                type: 'GET',
                url: '/getAllTenantLeadsNotInOpportunity',
                success : function(tenant_leads) {
                            console.log("Inside success function");
                            oltable.clear().draw();
                            $.each(tenant_leads, function(i,lead){
                                oltable.row.add([lead.tenantLeadId,lead.name,lead.email,lead.mobileNumber,lead.qualifier,lead.createdOn,lead.comment]).draw(false);

                        });

                }
            });
});
</code>```

The datatable version is 1.10.10.
The fact is select :'single' is not working as it is supposed to select only a single row when table is clicked . By select I mean selection in the user interface. But it is working in other applications . I want the select : ' single' to work as it is supposed to.

答: I fall in the same problem, I solved using the invalidate method instead of clear and add rows again.</p>

Title: jquery datatable select not working

Body:
I have written this code for my datatable

$(function(){
    var $oltable=$("#owner-lead-table");
    var oltable=$oltable.DataTable({
        // 'serverSide' : true,
        // 'ajax': {
        //  url:"/getAllTenantLeadsNotInOpportunity",
        //  type:"GET",
        //  contentType:"application/json",
        //  data : function(d){
        //      console.log(d);
        //      return JSON.stringify(d);
        //  },
        //  dataSrc: function (json) {
        //          console.log(json);
  //                   return json;
  //                },
  //           columns: [
  //            { data:'tenantLeadId' },
  //            { data:'name'},
  //            { data:'email'},
  //            { data:'mobileNumber'},
  //            { data:'qualifier'},
  //            { data:'createdOn'},
  //            { data:'comment'}
  //           ],
        // },
        select:"single"
    });

    $.ajax( {
                type: 'GET',
                url: '/getAllTenantLeadsNotInOpportunity',
                success : function(tenant_leads) {
                            console.log("Inside success function");
                            oltable.clear().draw();
                            $.each(tenant_leads, function(i,lead){
                                oltable.row.add([lead.tenantLeadId,lead.name,lead.email,lead.mobileNumber,lead.qualifier,lead.createdOn,lead.comment]).draw(false);

                        });

                }
            });
});

The datatable version is 1.10.10.
The fact is select :'single' is not working as it is supposed to select only a single row when table is clicked . By select I mean selection in the user interface. But it is working in other applications . I want the select : ' single' to work as it is supposed to.


问:
Sending a list as a parameter but it keeps sending an empty list
Hello I am writing a blackjack game in Python for fun. I am having a problem with a method called calculateTemporaryHandValueWhereAEquals11() in the player class. It is called by a method in the dealer class called drawCard().The problem is the first if statement. If there is an A in the dealers hand then it will call calculateTemporaryHandValueWhereAEquals11(self.player) to check if the value of hand is = 21 assuming that A will equal 11. For some reason the list is empty and nothing happens in the calculateTemporaryHandValueWhereAEquals11() method. But in the elif statement in drawCards() I call a function called calculateTemporaryHandValueWhere() which checks the value of the hand assuming A is equal to 1. This one one works, it gets the list and calculates the value! I dont understand what I am doing that makes one method work and not the other. If anyone can help it would be much appreciated! Thank You!</p>

```<code>import random
class Player(object):
def drawCard(self, hitOrStop):
    if hitOrStop == 'hit':
        playerRecievesCard = RandomCard().selectRandomCard()
        self.myHand.append(playerRecievesCard)
        return True
    else:
        return False

def calculateTemporaryHandValue(self, playersHand = []):
    sumOfAllCards = 0
    for card in playersHand:
        if card == 'A':
            sumOfAllCards += 1
        elif card == 'J' or card == 'K' or card == 'Q':
            sumOfAllCards += 10
        else:
            sumOfAllCards += card
    return sumOfAllCards
def calculateTemporaryHandValueWhereAEquals11(self, playerHand = []):
    sumOfAllCards = 0
    print(playerHand)
    for card in playerHand:
        if card == 'A':
            sumOfAllCards += 11
        elif card == 'J' or card == 'K' or card == 'Q':
            sumOfAllCards += 10
        else:
            sumOfAllCards += card
    return sumOfAllCards

class Dealer(Player):
def __init__(self):
    self.myHand = []
def drawCards(self):
    if 'A' in self.myHand:
        valueOfdeal = Dealer.calculateTemporaryHandValueWhereAEquals11(self.myHand)
        print (valueOfdeal)
        #if Dealer.calculateTemporaryHandValueWhereAEquals11(self.myHand) <= 21 and Player.calculateTemporaryHandValueWhereAEquals11(self.myHand) >= 17:
        print ("he")
        return False
    elif Dealer.calculateTemporaryHandValue(self.myHand) < 17 and len(self.myHand) <=5:
        playerRecievesCard = RandomCard().selectRandomCard()
        self.myHand.append(playerRecievesCard)
        return True
    else:
        return False
</code>```

答:
You shouldn't be calling the method on the class Dealer.calculateTemporaryHandValueWhereAEquals11(self.myHand) but rather the method on the instance self.calculateTemporaryHandValueWhereAEquals11(self.myHand).

When you do that the method gets the argument self.myHand as the first argument self rather than as the second argument playerHand. If the method didn't have a default argument for playerHand = [], you would get a TypeError: [method] takes exactly 2 arguments (1 given).

Body:
Hello I am writing a blackjack game in Python for fun. I am having a problem with a method called calculateTemporaryHandValueWhereAEquals11() in the player class. It is called by a method in the dealer class called drawCard().The problem is the first if statement. If there is an A in the dealers hand then it will call calculateTemporaryHandValueWhereAEquals11(self.player) to check if the value of hand is = 21 assuming that A will equal 11. For some reason the list is empty and nothing happens in the calculateTemporaryHandValueWhereAEquals11() method. But in the elif statement in drawCards() I call a function called calculateTemporaryHandValueWhere() which checks the value of the hand assuming A is equal to 1. This one one works, it gets the list and calculates the value! I dont understand what I am doing that makes one method work and not the other. If anyone can help it would be much appreciated! Thank You!

import random
class Player(object):
def drawCard(self, hitOrStop):
    if hitOrStop == 'hit':
        playerRecievesCard = RandomCard().selectRandomCard()
        self.myHand.append(playerRecievesCard)
        return True
    else:
        return False

def calculateTemporaryHandValue(self, playersHand = []):
    sumOfAllCards = 0
    for card in playersHand:
        if card == 'A':
            sumOfAllCards += 1
        elif card == 'J' or card == 'K' or card == 'Q':
            sumOfAllCards += 10
        else:
            sumOfAllCards += card
    return sumOfAllCards
def calculateTemporaryHandValueWhereAEquals11(self, playerHand = []):
    sumOfAllCards = 0
    print(playerHand)
    for card in playerHand:
        if card == 'A':
            sumOfAllCards += 11
        elif card == 'J' or card == 'K' or card == 'Q':
            sumOfAllCards += 10
        else:
            sumOfAllCards += card
    return sumOfAllCards

class Dealer(Player):
def __init__(self):
    self.myHand = []
def drawCards(self):
    if 'A' in self.myHand:
        valueOfdeal = Dealer.calculateTemporaryHandValueWhereAEquals11(self.myHand)
        print (valueOfdeal)
        #if Dealer.calculateTemporaryHandValueWhereAEquals11(self.myHand) <= 21 and Player.calculateTemporaryHandValueWhereAEquals11(self.myHand) >= 17:
        print ("he")
        return False
    elif Dealer.calculateTemporaryHandValue(self.myHand) < 17 and len(self.myHand) <=5:
        playerRecievesCard = RandomCard().selectRandomCard()
        self.myHand.append(playerRecievesCard)
        return True
    else:
        return False


问:
Append to Select not working in Chrome?
How to make this simple code work in chrome?

```<code> $('#teser').append(new Option('6','OptSix' ,true));
</code>```

https://jsfiddle.net/77c92wyv/

Its working fine in IE and FFX

答:
You can add an option as a jQuery object. It will definitely work anywhere:</p>

```<code>$('#teser').append(buildOption(6, 'OptSix'));

function buildOption(value, text) {
  return $("<option/>", {
    value: value,
    text: text
  })
}
</code>```

Title: Append to Select not working in Chrome?

Body:
How to make this simple code work in chrome?

 $('#teser').append(new Option('6','OptSix' ,true));

https://jsfiddle.net/77c92wyv/

Its working fine in IE and FFX

Body:
You can add an option as a jQuery object. It will definitely work anywhere:

$('#teser').append(buildOption(6, 'OptSix'));

function buildOption(value, text) {
  return $("<option/>", {
    value: value,
    text: text
  })
}


问:
Dapper error: Could not load type 'Dapper.SqlMapper'
I'm new in Dapper. I trying to create new project and map local database by Dapper. Unfortunately I always receive this error:

Could not load type 'Dapper.SqlMapper' from assembly 'Dapper,
  Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'

I added Dapper by NuGet (Dapper v. 1.39.0.0). This is example of my code:

```<code>public static IEnumerable<TBMobileDetails> Allmobilelisting()
{
     SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=""c:\users\database.mdf"";Integrated Security=True");

     string query = "select * from Mobiledata";
     var result = con.Query<TBMobileDetails>(query);
     return result;
}
</code>```

Where is the problem?

答: My problem was that there was a namespace collision. Maybe a little obvious, but don't name anything "dapper" in your project.</p>

Body:
I'm new in Dapper. I trying to create new project and map local database by Dapper. Unfortunately I always receive this error:

Could not load type 'Dapper.SqlMapper' from assembly 'Dapper,
  Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'

I added Dapper by NuGet (Dapper v. 1.39.0.0). This is example of my code:

public static IEnumerable<TBMobileDetails> Allmobilelisting()
{
     SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=""c:\users\database.mdf"";Integrated Security=True");

     string query = "select * from Mobiledata";
     var result = con.Query<TBMobileDetails>(query);
     return result;
}

Where is the problem?


问:
How to connect to mongodb using docker-compose?
This is my docker-compose.yml:

```<code>mongo:
  image: tutum/mongodb
  environment:
    - AUTH=no
  volumes:
    - /Users/andrey/docker/mongodb:/mongo/db
  ports:
    - "27017:27017"
parser:
  image: nazandr/goparser
</code>```

and Dockerfile goparser:

```<code>FROM golang:1.8

WORKDIR /app

ADD parser.go /app/
    RUN go get github.com/PuerkitoBio/goquery; go get gopkg.in/mgo.v2; go build -o parser

ENTRYPOINT ["./parser"]
</code>```

What address do I need to use to connect to MongoDB?

答:
You can do something like below:

```<code>version: '3'

services:
  mongo:
    image: 'mongo:3.4.1'
    ports:
      - '27017:27017'
    volumes:
      - 'mongo:/data/db'

  puma:
    tty: true
    stdin_open: true
    depends_on:
      - 'mongo'
    build:
      context: .
      dockerfile: Dockerfile.puma
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    ports:
      - '3000:3000'
    volumes:
      - '.:/app'
    environment:
      - SECRET_KEY_BASE=secret
      - MONGO_URL=mongodb://mongo:27017/app_development
volumes:
  mongo:
</code>```

As you might have noticed, you can connect to mongo service running on mongo container from other containers located in the same docker-compose.yml file using the connection string like mongodb://mongo:27017.

In case you want to connect from the host, you can use mongodb://localhost:27017 if you have exposed mongo port as shown above.

Body:
This is my docker-compose.yml:

mongo:
  image: tutum/mongodb
  environment:
    - AUTH=no
  volumes:
    - /Users/andrey/docker/mongodb:/mongo/db
  ports:
    - "27017:27017"
parser:
  image: nazandr/goparser

and Dockerfile goparser:

FROM golang:1.8

WORKDIR /app

ADD parser.go /app/
    RUN go get github.com/PuerkitoBio/goquery; go get gopkg.in/mgo.v2; go build -o parser

ENTRYPOINT ["./parser"]

What address do I need to use to connect to MongoDB?

Body:
You can do something like below:

version: '3'

services:
  mongo:
    image: 'mongo:3.4.1'
    ports:
      - '27017:27017'
    volumes:
      - 'mongo:/data/db'

  puma:
    tty: true
    stdin_open: true
    depends_on:
      - 'mongo'
    build:
      context: .
      dockerfile: Dockerfile.puma
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    ports:
      - '3000:3000'
    volumes:
      - '.:/app'
    environment:
      - SECRET_KEY_BASE=secret
      - MONGO_URL=mongodb://mongo:27017/app_development
volumes:
  mongo:

As you might have noticed, you can connect to mongo service running on mongo container from other containers located in the same docker-compose.yml file using the connection string like mongodb://mongo:27017.

In case you want to connect from the host, you can use mongodb://localhost:27017 if you have exposed mongo port as shown above.


问:
MATLAB: page width line vs. publishing width
When I write code in Matlab I make sure it is within the page width line of demarcation. I thought the purpose of this line was because it signified the width of a page, but when I use the publish option on my code, it wraps about 6 characters to the left of the demarcation line, onto the next line, which makes the publishing ugly.

Is there any way to fix this by either changing the line position or the publishing width (preferably the latter)?

Here's what my editor window looks like:

And here's the resulting PDF page from publishing this code:

(notice the wrap-around in line #2)

答:
Yes, I hit the same ugliness and this is the best I could get:

The first comment was put as line by line in the editor, while the second commented chunk was put as a long single line, and I think the publisher decides where to cut which is a neater result, not perfect though.


问:
Generate largest number of 10 inputs
New to scripting here. Basically, I am needing to write a program to accept 10 input numbers and return the largest in the list.

I have this code, but obviously it is not running:

```<code>class Generator

  def getNumbers
    number = Array.new

    puts "To begin, You will need to enter your numbers."
    print "Press Enter to continue."
    Console_Screen.pause

    10.times do
      print "\nPlease enter any number: "
      input = STDIN.gets
      input.chop!
      list.push
      return list
    end

    list.push(number)
    print list.max
  end
end

Console_Screen.new
Find = Generator.new

end
</code>```

Can anyone help me with what I coded incorrectly?

答:
I had the same assignment and this is what I ended up creating. (I had to get a little more involved with input control and I'm sure there's easier ways of doing this. Also had to utilize the variables as part of the grade. I assume to  prevent me from ripping off the code above.)</p>

```<code>class Screen
  def cls
    puts ("\n" * 25)
    puts "\a"
  end

  def pause
    STDIN.gets
  end
end

Console_Screen = Screen.new

num = [] #array to store user input

$counter = 1
loop do

  puts "Please enter number " + $counter.to_s + " of a series of 10 numbers in order to determine the largest."
  # Console_Screen.pause
  loop do
    print "Enter Number Here:"
    number = gets.chomp
    num << number.to_i if number =~ /[0-9]/ #only writes to the array if it's a number
    break if number =~ /[0-9]/ #only allow numbers
  end

  $counter += 1
  break if $counter == 11

end

puts "Press Enter to have your numbers sorted and the largest presented to you."

Console_Screen.pause

largest = num.max
puts "This is your largest number: " + largest.to_s
Console_Screen.pause
</code>```

Title: Generate largest number of 10 inputs

Body:
New to scripting here. Basically, I am needing to write a program to accept 10 input numbers and return the largest in the list.

I have this code, but obviously it is not running:

class Generator

  def getNumbers
    number = Array.new

    puts "To begin, You will need to enter your numbers."
    print "Press Enter to continue."
    Console_Screen.pause

    10.times do
      print "\nPlease enter any number: "
      input = STDIN.gets
      input.chop!
      list.push
      return list
    end

    list.push(number)
    print list.max
  end
end

Console_Screen.new
Find = Generator.new

end

Can anyone help me with what I coded incorrectly?

Body:
I had the same assignment and this is what I ended up creating. (I had to get a little more involved with input control and I'm sure there's easier ways of doing this. Also had to utilize the variables as part of the grade. I assume to  prevent me from ripping off the code above.)

class Screen
  def cls
    puts ("\n" * 25)
    puts "\a"
  end

  def pause
    STDIN.gets
  end
end

Console_Screen = Screen.new

num = [] #array to store user input

$counter = 1
loop do

  puts "Please enter number " + $counter.to_s + " of a series of 10 numbers in order to determine the largest."
  # Console_Screen.pause
  loop do
    print "Enter Number Here:"
    number = gets.chomp
    num << number.to_i if number =~ /[0-9]/ #only writes to the array if it's a number
    break if number =~ /[0-9]/ #only allow numbers
  end

  $counter += 1
  break if $counter == 11

end

puts "Press Enter to have your numbers sorted and the largest presented to you."

Console_Screen.pause

largest = num.max
puts "This is your largest number: " + largest.to_s
Console_Screen.pause


问:
Will jQuery or AJAX make HTML "required" attribute invalid?
I'm now constructing a registration page and have labeled username and password inputs as required. Simple code as:

Username <input id="username" type="text" required/>
Password <input id="username" type="password" required/>
<button id="register">Register</button>

```

<p>When I just run those code with pure HTML on localhost the "required" would function properly. But once I include a register.js file which I made to get the data and use AJAX to send data to register.php, the required attribute seems not working. In register.js, simple code as:</p>

```$(document).ready(function(){
    $("#register").on("click", function(){

        var username        = $("#username").val();
        var password        = $("#password").val();

        var userData = "username=" + username + "&password=" + password;

        $.ajax({
            method: "post",
            url: "register.php?",
            data: userData,
            success: function(backData){
                $("#registerOutput").html(backData);
            }
        });
    });
});
```

Can anybody tell me the reason why jQuery would override the functionality of required? How to surpass it or if it must override, how should I do the same thing in my jQuery code?

答:
You might want to redesign your code a little bit. There is a way to follow HTML convenience and yet use full power of AJAX.

I edited your example in jsfiddle: https://jsfiddle.net/myezf63b/

So here is modified HTML:

```<code><form id="form">
  Username <input id="username" type="text" required/>
  Password <input id="username" type="password" required/>
  <button type="submit" id="register">Register</button>
</form>

<div id="registerOutput">
</div>
</code>```

Basically I added type="submit" to button and wrapped it inside form.

and this is modified jQuery code:

I added e.preventDefault() which prevents website from redirecting (reloading page) and as event I used submit which follows this pattern.

```<code>$(document).ready(function(){ $("#form").on("submit", function(e){
    e.preventDefault()
    var username        = $("#username").val();
    var password        = $("#password").val();

    var userData = "username=" + username + "&password=" + password;
        console.log('test')
    $.ajax({
        method: "post",
        url: "register.php?",
        data: userData,
        success: function(backData){
            $("#registerOutput").html(backData);
        }
    });
  });

});
</code>```

Body:
I'm now constructing a registration page and have labeled username and password inputs as required. Simple code as:

Username <input id="username" type="text" required/>
Password <input id="username" type="password" required/>
<button id="register">Register</button>

When I just run those code with pure HTML on localhost the "required" would function properly. But once I include a register.js file which I made to get the data and use AJAX to send data to register.php, the required attribute seems not working. In register.js, simple code as:

$(document).ready(function(){
    $("#register").on("click", function(){

        var username        = $("#username").val();
        var password        = $("#password").val();

        var userData = "username=" + username + "&password=" + password;

        $.ajax({
            method: "post",
            url: "register.php?",
            data: userData,
            success: function(backData){
                $("#registerOutput").html(backData);
            }
        });
    });
});

Can anybody tell me the reason why jQuery would override the functionality of required? How to surpass it or if it must override, how should I do the same thing in my jQuery code?

Body:
You might want to redesign your code a little bit. There is a way to follow HTML convenience and yet use full power of AJAX.

I edited your example in jsfiddle: https://jsfiddle.net/myezf63b/

So here is modified HTML:

<form id="form">
  Username <input id="username" type="text" required/>
  Password <input id="username" type="password" required/>
  <button type="submit" id="register">Register</button>
</form>

<div id="registerOutput">
</div>

Basically I added type="submit" to button and wrapped it inside form.

and this is modified jQuery code:

I added e.preventDefault() which prevents website from redirecting (reloading page) and as event I used submit which follows this pattern.

$(document).ready(function(){ $("#form").on("submit", function(e){
    e.preventDefault()
    var username        = $("#username").val();
    var password        = $("#password").val();

    var userData = "username=" + username + "&password=" + password;
        console.log('test')
    $.ajax({
        method: "post",
        url: "register.php?",
        data: userData,
        success: function(backData){
            $("#registerOutput").html(backData);
        }
    });
  });

});


问:
Values are not sent with ajax to mysql
Please help, Variables Min and Max are not being sent to getData.php where filtering with MYSQL query is done.
The variables are displayed in #range and #range2 on index page.

Could you also give comments on the method that is used under "// Updating table data", for example would this be more appropriate:
    success:function(data)
       {
        $('#result').html(data);
       }

```<code><script>
  $(document).ready(function(){
            $( "#slider" ).slider({
                range: "min",
                min: 50,
                max: 300,
                value: [ 60 ],
                slide: function( event, ui ) {
                    var min = ui.value;
                    $('#range').text(min);
                }
            });
            $( "#slider2" ).slider({
                range: "min",
                min: 50,
                max: 300,
                value: [ 300 ],
                slide: function( event, ui ) {
                    var max = ui.value;
                    $('#range2').text(max);
                }
            });
            $.ajax({
                url: 'getData.php',
                type: 'post',
                data: {min:min,max:max},
                success: function(response){
    // Updating table data
                    $('#emp_table tr:not(:first)').remove();
                    $('#emp_table').append(response);
                }
            });
        });
</script>
</code>```

答:
Variables min and max are only persisted in anonymous functions for slide. To persist them, define them outside the slide: function() block:

```<code><script>
  $(document).ready(function(){
            var min = undefined;
            var max = undefined;
            $( "#slider" ).slider({
                range: "min",
                min: 50,
                max: 300,
                value: [ 60 ],
                slide: function( event, ui ) {
                    min = ui.value;
                    $('#range').text(min);
                }
            });
            $( "#slider2" ).slider({
                range: "min",
                min: 50,
                max: 300,
                value: [ 300 ],
                slide: function( event, ui ) {
                    max = ui.value;
                    $('#range2').text(max);
                }
            });
            $.ajax({
                url: 'getData.php',
                type: 'post',
                data: {min:min,max:max},
                success: function(response){
    // Updating table data
                    $('#emp_table tr:not(:first)').remove();
                    $('#emp_table').append(response);
                }
            });
        });
</script>
</code>```

To comment on your remove/append vs html(), either way is fine

Title: Values are not sent with ajax to mysql

Body:
Variables min and max are only persisted in anonymous functions for slide. To persist them, define them outside the slide: function() block:

<script>
  $(document).ready(function(){
            var min = undefined;
            var max = undefined;
            $( "#slider" ).slider({
                range: "min",
                min: 50,
                max: 300,
                value: [ 60 ],
                slide: function( event, ui ) {
                    min = ui.value;
                    $('#range').text(min);
                }
            });
            $( "#slider2" ).slider({
                range: "min",
                min: 50,
                max: 300,
                value: [ 300 ],
                slide: function( event, ui ) {
                    max = ui.value;
                    $('#range2').text(max);
                }
            });
            $.ajax({
                url: 'getData.php',
                type: 'post',
                data: {min:min,max:max},
                success: function(response){
    // Updating table data
                    $('#emp_table tr:not(:first)').remove();
                    $('#emp_table').append(response);
                }
            });
        });
</script>

To comment on your remove/append vs html(), either way is fine


问:
input numbers into char array from file
I am trying to build a rpn calculator which takes input from a file.

the input looks like 7 2 10 + -

I want to put this input a char array which is dynamic memory.
How do i add the numbers into my array ignoring the white spaces?

i tried using fscanf(in,"%c", &input[i]), but it is storing the white spaces as well as treating 10 and 1 and 0.

I am new to C and I have pretty basic knowledge of the subject any help will be deeply appreciated:) thank you

答:
I think that this exercise is not one a beginner should start with; It has a lot of pitfalls to consider, e.g. that a your input has to separate numbers from operators, that a valid number could be -10 or even +10 as well, that dealing with an unknown number of tokens is rather hard at the beginning, and so on.

Anyway, see the following code that solves at least the topic of reading in the file into an array of strings, thereby assuming up to 50 tokens with a length of at most 99 characters each. Other useful functions in this context might be isdigit and atoi; Hope it helps a bit.

```<code>int main(int argc, char* argv[]) {

    FILE *f = fopen("data.txt", "rt");
    if (!f)
        return 0;

    char* tokens[50];
    int nrOfTokens = 0;

    char token[100];
    // fscanf(f, "%s", token) tries to read in the next token (separated by white space);
    // it returns 1 if exactly one token has been read in, otherwise 0
    while (nrOfTokens < 50 && fscanf(f, "%s", token)==1) {
        tokens[nrOfTokens] = strdup(token);  // strdup copies the content of `token` and allocates enough memory for this copy.
        nrOfTokens++;
    }

    for (int i=0; i<nrOfTokens; i++) {
        printf("token: %s\n",tokens[i]);
    }

    return 0;
}
</code>```

Title: input numbers into char array from file

Body:
I think that this exercise is not one a beginner should start with; It has a lot of pitfalls to consider, e.g. that a your input has to separate numbers from operators, that a valid number could be -10 or even +10 as well, that dealing with an unknown number of tokens is rather hard at the beginning, and so on.

Anyway, see the following code that solves at least the topic of reading in the file into an array of strings, thereby assuming up to 50 tokens with a length of at most 99 characters each. Other useful functions in this context might be isdigit and atoi; Hope it helps a bit.

int main(int argc, char* argv[]) {

    FILE *f = fopen("data.txt", "rt");
    if (!f)
        return 0;

    char* tokens[50];
    int nrOfTokens = 0;

    char token[100];
    // fscanf(f, "%s", token) tries to read in the next token (separated by white space);
    // it returns 1 if exactly one token has been read in, otherwise 0
    while (nrOfTokens < 50 && fscanf(f, "%s", token)==1) {
        tokens[nrOfTokens] = strdup(token);  // strdup copies the content of `token` and allocates enough memory for this copy.
        nrOfTokens++;
    }

    for (int i=0; i<nrOfTokens; i++) {
        printf("token: %s\n",tokens[i]);
    }

    return 0;
}


问:
How to rotate a PDF page so that *Box is set (and it doesn't just use rot=90)
Our site written in php receives PDF files from customers.  After processing, the next step is code from a vendor.  That code requires that each page is 8.5x11" in portrait.  The code also requires that the page have data like this (output from pdfinfo):

```<code>Page    1 size: 612 x 792 pts (letter)
Page    1 rot:  0
Page    1 MediaBox:     0.00     0.00   612.00   792.00
Page    1 CropBox:      0.00     0.00   612.00   792.00
Page    1 BleedBox:     0.00     0.00   612.00   792.00
Page    1 TrimBox:      0.00     0.00   612.00   792.00
Page    1 ArtBox:       0.00     0.00   612.00   792.00
</code>```

Sometimes customers give us PDFs with one or more pages in portrait.  We have code that uses FPDI to rewrite the file, rotating the pages that need it by 90 degrees:

```<code>$pdf->AddPage('L', array(215.9, 279.4), 90);
</code>```

The problem is that is just sets rot=90 and the resulting file has this (output from pdfinfo):

```<code>Page    3 size: 792 x 612 pts (letter)
Page    3 rot:  90
Page    3 MediaBox:     0.00     0.00   792.00   612.00
Page    3 CropBox:      0.00     0.00   792.00   612.00
Page    3 BleedBox:     0.00     0.00   792.00   612.00
Page    3 TrimBox:      0.00     0.00   792.00   612.00
Page    3 ArtBox:       0.00     0.00   792.00   612.00
</code>```

Our next step code does not recognize the rot=90 and sees this as a landscape page.

What can I use to change the page characteristics to be like the first set of data (the portrait image)?  In our environment ghostscript is available.   pdftk can be used (with more difficulty).

ADDED
I started with Patrick's pdfrw but ultimately shifted to staying with just FPDF.  One odd thing that I noticed: I lost the rotation fix for most files rotated to be only letter, portrait using FPDF and pdfrw when I concatenated to something else using ghostscript.  Solution: I ran the "fix rotation" code again after concatenating any files with gs.

答:
Here is an example using my Python package pdfrw.  pdfrw may or may not already be installed on your system; if not, you can install it with the usual pip or easy_install (or even possibly apt-get install python-pdfrw), or pull it straight from github.

This example uses a PDF feature called Form XObjects.  If your output processing software doesn't support those, then we could create a version that recreates the math done by pdfrw, but updates the actual page streams.  (I used to do that before I started using Form XObjects, but the latter are usually much cleaner.)

Also note that pdfrw does not support encrypted PDFs, so those would have to be decrypted first.   If this doesn't work on your PDF, send me an example, and I'll look at it.

Those caveats aside, this actually has a bit more functionality than you requested -- it will scale down pages that are too big, and center pages that are too small:

```<code>#!/usr/bin/env python

import sys
import os

from pdfrw import PdfReader, PdfWriter, PageMerge

# Change these constants to change output size or orientation

outbox = 0, 0, 8.5 * 72, 11 * 72

# Generic calculations from box

out_x = outbox[0]
out_y = outbox[1]
out_w = outbox[2] - out_x
out_h = outbox[3] - out_y
out_landscape = out_w > out_h

inpfn, = sys.argv[1:]
outfn = 'normalized.' + os.path.basename(inpfn)
inp = PdfReader(inpfn)
out = PdfWriter()

def fixpage():
    # Figure out the rotation requirement before instantiating
    landscape = bool(rotate % 180) ^ (mbox[2] - mbox[0] > mbox[3] - mbox[1])
    rotation = 0 if landscape == out_landscape else 90

    # Create a canvas, add the page, and get a reference to the page rectangle
    canvas = PageMerge()
    canvas.add(page, rotate=rotation)
    rect = canvas[0]

    # Scale the page rectangle if it doesn't fit our output size
    scaling = max(rect.w / out_w, rect.h / out_h)
    if scaling > 1.0:
        rect.scale(1.0/scaling)

    # Center the page rectangle on the output
    rect.x = out_x + (out_w - rect.w) / 2
    rect.y = out_y + (out_h - rect.h) / 2
    canvas.mbox = outbox
    return canvas.render()

for page in inp.pages:
    rotate = int(page.inheritable.Rotate or 0)
    mbox = tuple(float(x) for x in page.inheritable.MediaBox)
    out.addpage(fixpage() if rotate or mbox != outbox else page)

out.write(outfn)
</code>```

Body:
Our site written in php receives PDF files from customers.  After processing, the next step is code from a vendor.  That code requires that each page is 8.5x11" in portrait.  The code also requires that the page have data like this (output from pdfinfo):

Page    1 size: 612 x 792 pts (letter)
Page    1 rot:  0
Page    1 MediaBox:     0.00     0.00   612.00   792.00
Page    1 CropBox:      0.00     0.00   612.00   792.00
Page    1 BleedBox:     0.00     0.00   612.00   792.00
Page    1 TrimBox:      0.00     0.00   612.00   792.00
Page    1 ArtBox:       0.00     0.00   612.00   792.00

Sometimes customers give us PDFs with one or more pages in portrait.  We have code that uses FPDI to rewrite the file, rotating the pages that need it by 90 degrees:

$pdf->AddPage('L', array(215.9, 279.4), 90);

The problem is that is just sets rot=90 and the resulting file has this (output from pdfinfo):

Page    3 size: 792 x 612 pts (letter)
Page    3 rot:  90
Page    3 MediaBox:     0.00     0.00   792.00   612.00
Page    3 CropBox:      0.00     0.00   792.00   612.00
Page    3 BleedBox:     0.00     0.00   792.00   612.00
Page    3 TrimBox:      0.00     0.00   792.00   612.00
Page    3 ArtBox:       0.00     0.00   792.00   612.00

Our next step code does not recognize the rot=90 and sees this as a landscape page.

What can I use to change the page characteristics to be like the first set of data (the portrait image)?  In our environment ghostscript is available.   pdftk can be used (with more difficulty).

ADDED
I started with Patrick's pdfrw but ultimately shifted to staying with just FPDF.  One odd thing that I noticed: I lost the rotation fix for most files rotated to be only letter, portrait using FPDF and pdfrw when I concatenated to something else using ghostscript.  Solution: I ran the "fix rotation" code again after concatenating any files with gs.

Body:
Here is an example using my Python package pdfrw.  pdfrw may or may not already be installed on your system; if not, you can install it with the usual pip or easy_install (or even possibly apt-get install python-pdfrw), or pull it straight from github.

This example uses a PDF feature called Form XObjects.  If your output processing software doesn't support those, then we could create a version that recreates the math done by pdfrw, but updates the actual page streams.  (I used to do that before I started using Form XObjects, but the latter are usually much cleaner.)

Also note that pdfrw does not support encrypted PDFs, so those would have to be decrypted first.   If this doesn't work on your PDF, send me an example, and I'll look at it.

Those caveats aside, this actually has a bit more functionality than you requested -- it will scale down pages that are too big, and center pages that are too small:

#!/usr/bin/env python

import sys
import os

from pdfrw import PdfReader, PdfWriter, PageMerge

# Change these constants to change output size or orientation

outbox = 0, 0, 8.5 * 72, 11 * 72

# Generic calculations from box

out_x = outbox[0]
out_y = outbox[1]
out_w = outbox[2] - out_x
out_h = outbox[3] - out_y
out_landscape = out_w > out_h

inpfn, = sys.argv[1:]
outfn = 'normalized.' + os.path.basename(inpfn)
inp = PdfReader(inpfn)
out = PdfWriter()

def fixpage():
    # Figure out the rotation requirement before instantiating
    landscape = bool(rotate % 180) ^ (mbox[2] - mbox[0] > mbox[3] - mbox[1])
    rotation = 0 if landscape == out_landscape else 90

    # Create a canvas, add the page, and get a reference to the page rectangle
    canvas = PageMerge()
    canvas.add(page, rotate=rotation)
    rect = canvas[0]

    # Scale the page rectangle if it doesn't fit our output size
    scaling = max(rect.w / out_w, rect.h / out_h)
    if scaling > 1.0:
        rect.scale(1.0/scaling)

    # Center the page rectangle on the output
    rect.x = out_x + (out_w - rect.w) / 2
    rect.y = out_y + (out_h - rect.h) / 2
    canvas.mbox = outbox
    return canvas.render()

for page in inp.pages:
    rotate = int(page.inheritable.Rotate or 0)
    mbox = tuple(float(x) for x in page.inheritable.MediaBox)
    out.addpage(fixpage() if rotate or mbox != outbox else page)

out.write(outfn)


问:
Raw SQL queries in a REST Api
Say I have these 2 tables:

posts

```<code> id | user_id | title | slug | content | views
----+---------+-------+------+---------+-------
</code>```

users

```<code> id | username | email | hash | role | auth
----+----------+-------+------+------+------
</code>```

With these two tables I want to do a SELECT * FROM posts ... query and ultimately end up responding with something like this:

```<code>{[
  {
    "id": "1",
    "user_id": "2",
    "title": "Foo",
    "slug": "foo",
    "content": "bar",
    "views": "0",
    "user": {
      "id": "2",
      "username": "john",
      "email": "john@smith.com",
      "hash": "aeigh*£HAEGhoiaehg",
      "role": "admin",
      "auth": "aeg89hiae9g8hA*H£GA(*EHG"
    }
  }
]}
</code>```

I'm pretty new to SQL, and patterns like this seem pretty common when using an ORM, so I'm wondering what steps I have to do to get a result like this using raw SQL.

Any idea?

答:
Alternatively you could use a thin middle tier - restSQL. It's an open-source, ultra-lightweight persistence layer, with out of the box support for PostgreSQL. It's tested with 9.3 but 9.2 is likely not an issue.

You can deploy in about 10 minutes using the docker image.

Title: Raw SQL queries in a REST Api

Body:
Say I have these 2 tables:

posts

 id | user_id | title | slug | content | views
----+---------+-------+------+---------+-------

users

 id | username | email | hash | role | auth
----+----------+-------+------+------+------

With these two tables I want to do a SELECT * FROM posts ... query and ultimately end up responding with something like this:

{[
  {
    "id": "1",
    "user_id": "2",
    "title": "Foo",
    "slug": "foo",
    "content": "bar",
    "views": "0",
    "user": {
      "id": "2",
      "username": "john",
      "email": "john@smith.com",
      "hash": "aeigh*£HAEGhoiaehg",
      "role": "admin",
      "auth": "aeg89hiae9g8hA*H£GA(*EHG"
    }
  }
]}

I'm pretty new to SQL, and patterns like this seem pretty common when using an ORM, so I'm wondering what steps I have to do to get a result like this using raw SQL.

Any idea?


问:
IPC performance: Named Pipe vs Socket
Everyone seems to say named pipes are faster than sockets IPC. How much faster are they? I would prefer to use sockets because they can do two-way communication and are very flexible but will choose speed over flexibility if it is by considerable amount.</p>

答: You can use lightweight solution like ZeroMQ [ zmq/0mq ]. It is very easy to use and dramatically faster then sockets. </p>

Title: IPC performance: Named Pipe vs Socket


问:
ASP.net: Display PDF in a asp.net web page
User click on a link button and it will direct them to a url that is dynmaically generated which a pdf file. The browser will prompt the user to either save or open it.

I want to know if it is possible to downlaod the pdf file to the server then show the pdf file in the asp.net web page. When i google on this question, 99% of top link are some third party component. Is it a way to do this without purchase any 3rd party component?

thank

答: Regardless of how you generate the PDF, I have found a better user experience if you open the PDF in an IFRAME instead of the full browser window. You can give users instructions and maintain the browser navigation.</p>

OwnerDisplayName: Jack

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: toddb


问:
Having some problems with a json array
```<code>exports.equipp = function(user, User, msg) {

    var itemname = msg.content.slice(8);

    User.find({id: user.id}, function(err, usser) {

        for(i = 0; i < usser[0].inventory.length; i++) {

            if (usser[0].inventory[i].name == itemname) {

                var Item = usser[0].inventory[i];

                for (j = 0; j < usser[0].equipped.length; j++) {

                    if (Item.type == usser[0].equipped[j].type) {

                    }
                    if (j == usser[0].equipped.length -1) {

                    }
                }
            } else {

                if (i == usser[0].inventory.length -1) {

                    msg.reply("You dont have that Item");

                }
            }
        }
    })
}
</code>```

I'm having some porblems with it at the end at the if (j == usser[0].equipped.length -1) it never goes through and hence never adds an item to a empty inventory. I have items which atm only contain Name, Dmg, and Type im checking if the types match then if they do i add the item to the equipped array and remove it from the items array and vice versa for the item already equipped and when there is no item with that type in the array i need to just add it and remvoe it from the other array but my code fails at the point stated above an array of json objects {
            "type": "Healm",
            "armor": 4,
            "name": "Starter Healm"
        },

答:
Instead of this :

```<code>    for(i = 0; i < usser[0].inventory.length; i++) {
        if (usser[0].inventory[i].name == itemname) {
            var Item = usser[0].inventory[i];
            // rest of code ...
        } else {
            if (i == usser[0].inventory.length -1) {
                msg.reply("You dont have that Item");
            }
        }
    }
</code>```

Do:

```<code>    for(i = 0; i < usser[0].inventory.length; i++) {
        if (usser[0].inventory[i].name == itemname) {
            var Item = usser[0].inventory[i];
            // rest of code ...
        }
    }
    if (!Item) {
        msg.reply("You dont have that Item");
    }
</code>```

The determining factor whether you found the item is that you have defined Item. It after the loop you find that Item was not set, you know the item was not in the list. This obviously also works when the list is empty.

Title: Having some problems with a json array

Body:
exports.equipp = function(user, User, msg) {

    var itemname = msg.content.slice(8);

    User.find({id: user.id}, function(err, usser) {

        for(i = 0; i < usser[0].inventory.length; i++) {

            if (usser[0].inventory[i].name == itemname) {

                var Item = usser[0].inventory[i];

                for (j = 0; j < usser[0].equipped.length; j++) {

                    if (Item.type == usser[0].equipped[j].type) {

                    }
                    if (j == usser[0].equipped.length -1) {

                    }
                }
            } else {

                if (i == usser[0].inventory.length -1) {

                    msg.reply("You dont have that Item");

                }
            }
        }
    })
}

I'm having some porblems with it at the end at the if (j == usser[0].equipped.length -1) it never goes through and hence never adds an item to a empty inventory. I have items which atm only contain Name, Dmg, and Type im checking if the types match then if they do i add the item to the equipped array and remove it from the items array and vice versa for the item already equipped and when there is no item with that type in the array i need to just add it and remvoe it from the other array but my code fails at the point stated above an array of json objects {
            "type": "Healm",
            "armor": 4,
            "name": "Starter Healm"
        },

Body:
Instead of this :

    for(i = 0; i < usser[0].inventory.length; i++) {
        if (usser[0].inventory[i].name == itemname) {
            var Item = usser[0].inventory[i];
            // rest of code ...
        } else {
            if (i == usser[0].inventory.length -1) {
                msg.reply("You dont have that Item");
            }
        }
    }

Do:

    for(i = 0; i < usser[0].inventory.length; i++) {
        if (usser[0].inventory[i].name == itemname) {
            var Item = usser[0].inventory[i];
            // rest of code ...
        }
    }
    if (!Item) {
        msg.reply("You dont have that Item");
    }

The determining factor whether you found the item is that you have defined Item. It after the loop you find that Item was not set, you know the item was not in the list. This obviously also works when the list is empty.


问:
Angular 2 How to Apply Multiple Guards with Or-Relationship on the Same Path
My application allows access to contents based on user roles. I wrote a Router Guard for each role. Some contents allow access for role1 or role2 or role3. How should I write that canActivate declaration in the feature-routing.module.ts file? As I understand, if I write

```<code>canActivate:[Role1Guard, Role2Guard, Role3Guard]
</code>```

The access will be denied if any of the guards returns false. But in my case, I should allow access if any of the guards returns true. How to do it? Many thanks in advance!

答:
You could write OrGuard, something like:

```<code>class OrGuard() {
  guards: any[];
  constructor(...guards) { this.guards = guards }

  canActivate() {
    return this.guards.some(Boolean);
  }
}
</code>```

and use it like this:

```<code>canActivate:[new OrGuard(Role1Guard, Role2Guard, Role3Guard)]
</code>```

...just an idea, actual implementation might be different, I didn't try (;

Body:
My application allows access to contents based on user roles. I wrote a Router Guard for each role. Some contents allow access for role1 or role2 or role3. How should I write that canActivate declaration in the feature-routing.module.ts file? As I understand, if I write

canActivate:[Role1Guard, Role2Guard, Role3Guard]

The access will be denied if any of the guards returns false. But in my case, I should allow access if any of the guards returns true. How to do it? Many thanks in advance!

Body:
You could write OrGuard, something like:

class OrGuard() {
  guards: any[];
  constructor(...guards) { this.guards = guards }

  canActivate() {
    return this.guards.some(Boolean);
  }
}

and use it like this:

canActivate:[new OrGuard(Role1Guard, Role2Guard, Role3Guard)]

...just an idea, actual implementation might be different, I didn't try (;


问:
Laravel 5: best way to modify column name in model
What is the best way to modify column name before retrieve data from the model, ex: change id to be uid

```<code>$data = user::all(); //return array('uid'=>1,'uid'=>2 ... etc)
</code>```

thanks,

答:
The easiest option would be to create a custom attribute getter. This will allow you to access the uid value, like you would any other attribute, and the value will also be accessible via the toArray() method.

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

    public $appends = [
        'uid',
    ];

    public function getUidAttribute()
    {
        return $this->attributes['id'];
    }

    // ...
}

$user->uid; // 1
$user->toArray() // [..., 'uid' => 1, ...];
</code>```

Body:
What is the best way to modify column name before retrieve data from the model, ex: change id to be uid

$data = user::all(); //return array('uid'=>1,'uid'=>2 ... etc)

thanks,

Body:
The easiest option would be to create a custom attribute getter. This will allow you to access the uid value, like you would any other attribute, and the value will also be accessible via the toArray() method.

class User extends Model
{
    // ...

    public $appends = [
        'uid',
    ];

    public function getUidAttribute()
    {
        return $this->attributes['id'];
    }

    // ...
}

$user->uid; // 1
$user->toArray() // [..., 'uid' => 1, ...];


问:
How to install wxPython phoenix for python 3.6
I have been trying to install wxPython phoenix for python 3.6 and nothig works.

I have tried:
1) using pip install
2) downloading tar/whl files and extracting its wx folder to installation folder (tried on different types of files).

Both didnt work.
If someone succeded please let me know.

Thank you.

答:
This worked for me on Windows 10 with python installed via Visual Studio 2017 Community:

%LOCALAPPDATA%\Programs\Python\Python36\scripts\pip.exe install --upgrade --trusted-host wxpython.org --pre -f http://wxpython.org/Phoenix/snapshot-builds/ wxPython_Phoenix

(I wanted to put this on a comment on user2470057's reply, but I don't have enough rep to comment)


问:
Check if key exists in memcache cluster using PHP
I'm debugging the caching layer of a PHP application. It uses a cluster of memcache servers to cache values. I want to verify that a specific object gets purged correctly.

My idea was to connect to the right memcache server with telnet and check manually if the key exists.
I know the key that is passed to Memcache::set, but not which server to connect to. How do I know on which memcache server the data gets stored?

答: For future reference: I wrote a small python script that checks a list of memcache servers for a given key https://gist.github.com/721965</p>


问:
autotools: pass constant from configure.ac to python script
I want to pass a constant in a C preprocessor style but with a Python script.

This constant is already declared with AC_DEFINE in my configure.ac file and used in my C program, and now I need to pass it to a Python script too.

I tried with a custom target in my Makefile.am with a sed call to preprocess a specific symbol in my Python script, but it seems dirty-coding to me.

How can I achieve this?

答:
Create a config.py.in with some contents like MYVAR = '''@MYVAR@''' and add it to AC_CONFIG_FILES in your configure.ac. You can then import config in your other Python scripts.

This fulfills much the same function as config.h does for C programs.


问:
ClassNotFoundException android.widget.ViewStub while launching android application in debug mode
I am attempting to debug an Android application with a fresh install of Android Studio 2.3 and the SDK on a new computer with fresh install of Windows 10, I receive a number of ClassNotFoundExceptions for android.widget.ViewStub upon starting the application. The application loads fine if I just continue through them all.

I am also able to launch the application without debugging and then attach to it without any issue.

The exception

```<code>java.lang.ClassNotFoundException: Didn't find class "android.widget.ViewStub" on path:
DexPathList[[zip file "/data/app/com.my.applicaton-2/base.apk"],
nativeLibraryDirectories=[/data/app/com.my.application-2/lib/x86, /system/lib, /vendor/lib]]
</code>```

I've cleared all settings in Android Studio and also deleted all AVDs and started fresh. I've tried disabling Instant-Run, cleaned and rebuilt the project.

I've tried this using both the API 25 x86 and API 24 x86 images with the same result.

I've seen this posted about an old version of Android Studio from 2015, with no solution at Android Studio 1.2.2 ClassNotFoundException android.widget.viewstub

Worth noting is that this application ran fine on my previous computer under Android Studio 2.3, with no changes done since.

Does anyone know how to resolve this?

答:
I finally figured out the issue, and this was due to me having a typo in the package name inside of one of the gradle.build files. As I looked through the debugging output, I found 1 line that was missing an e in the package name.

This was not caught by the compiler nor by Android Studio.

Also Android Studio does not seem to search all files even if you do Edit > Find in Path... and choose Whole project.

I ended up using Notepad++ to search my source code directory and found the typo.

Body:
I am attempting to debug an Android application with a fresh install of Android Studio 2.3 and the SDK on a new computer with fresh install of Windows 10, I receive a number of ClassNotFoundExceptions for android.widget.ViewStub upon starting the application. The application loads fine if I just continue through them all.

I am also able to launch the application without debugging and then attach to it without any issue.

The exception

java.lang.ClassNotFoundException: Didn't find class "android.widget.ViewStub" on path:
DexPathList[[zip file "/data/app/com.my.applicaton-2/base.apk"],
nativeLibraryDirectories=[/data/app/com.my.application-2/lib/x86, /system/lib, /vendor/lib]]

I've cleared all settings in Android Studio and also deleted all AVDs and started fresh. I've tried disabling Instant-Run, cleaned and rebuilt the project.

I've tried this using both the API 25 x86 and API 24 x86 images with the same result.

I've seen this posted about an old version of Android Studio from 2015, with no solution at Android Studio 1.2.2 ClassNotFoundException android.widget.viewstub

Worth noting is that this application ran fine on my previous computer under Android Studio 2.3, with no changes done since.

Does anyone know how to resolve this?


问:
Why is the first output for the deposit shown in scientific notation?
```<code>void readAccountInfo()
{
    ifstream fin;
    fin.open("Accounts.dat");
    string tempID;
    string tempFirst;
    string tempLast;
    string tempDeposit;
    string tempRate;
    string tempYear;
    int i = 0;
    while (fin >> tempID >> tempFirst >> tempLast >> tempDeposit >> tempRate
            >> tempYear)
    {
        accounts[i] =
        {   tempID, tempFirst, tempLast, stof(tempDeposit), stof(tempRate), stoi(tempYear)};
        i++;
    }
}

void writeAccountInfo()
{
    ofstream fout;
    fout.open("test.dat");
    int i = 0;
    while (i < 30 && accounts[i].yearTerm != 0)
    {
        fout << accounts[i].ID << "      " << accounts[i].firstName << "      "
                << accounts[i].lastName << "                    ";
        fout.precision(2);
        fout << accounts[i].deposit << fixed;
        fout.precision(1);
        fout << "             " << accounts[i].rate << fixed;
        fout.precision(0);
        fout << "         " << accounts[i].yearTerm << endl << fixed;
        i++;
    }
}
</code>```

The output dat file is supposed to have the deposit have two decimals but the first line always ends up in scientific notation. example 1000.00 is supposed to come out like that but instead comes out as 1 e+3.

答:
If you want a specific format for the output, you have to add the specifiers before the value. For example:

```<code> fout << fixed << accounts[i].deposit;
</code>```

What you add after a value only affects the next output.

Body:
void readAccountInfo()
{
    ifstream fin;
    fin.open("Accounts.dat");
    string tempID;
    string tempFirst;
    string tempLast;
    string tempDeposit;
    string tempRate;
    string tempYear;
    int i = 0;
    while (fin >> tempID >> tempFirst >> tempLast >> tempDeposit >> tempRate
            >> tempYear)
    {
        accounts[i] =
        {   tempID, tempFirst, tempLast, stof(tempDeposit), stof(tempRate), stoi(tempYear)};
        i++;
    }
}

void writeAccountInfo()
{
    ofstream fout;
    fout.open("test.dat");
    int i = 0;
    while (i < 30 && accounts[i].yearTerm != 0)
    {
        fout << accounts[i].ID << "      " << accounts[i].firstName << "      "
                << accounts[i].lastName << "                    ";
        fout.precision(2);
        fout << accounts[i].deposit << fixed;
        fout.precision(1);
        fout << "             " << accounts[i].rate << fixed;
        fout.precision(0);
        fout << "         " << accounts[i].yearTerm << endl << fixed;
        i++;
    }
}

The output dat file is supposed to have the deposit have two decimals but the first line always ends up in scientific notation. example 1000.00 is supposed to come out like that but instead comes out as 1 e+3.

Body:
If you want a specific format for the output, you have to add the specifiers before the value. For example:

 fout << fixed << accounts[i].deposit;

What you add after a value only affects the next output.


问:
How do you handle complex JavaScript objects on the client?
EDIT: I am going to break this into two more specific questions.

I am trying to understand best practices and patterns for client side JavaScript development. In particular, what do you do to manage more complex data models on the client?

As an example, say you where managing some sort of store catalog online, and had a Product, with it’s pretty typical properties: { id, description, price, etc… }. But the product also has a set of categories that it could be associated with, and therefore two more lists needed to be fetched: AvailableCategories and AssociatedCategories. Of course, to make matters more complex, your association of categories to tables is not a simple join, but has meta-data like a scalar number from 1-10 that describes how strongly associated the product is to the category. And then say there are four or five other associations, of which one has an “Available” table that might require paging (for instance, maybe you associate the product with something that has a million items in the table, and you want to pull down only 100 of them at a time, searchable and sortable, of course).

My point is, there are lots of models, along with join associations with meta information, some data can be pre-fetched or statically downloaded on the page load, while some has to be dynamically fetched. And of course, you don’t just want the base models, but “observables” as well, so that if someone chooses a color to associate with your product, you would be notified (for free) someplace else on the page of the changes.

I am thinking of moving to a client side MVC framework, like SproutCore, but would like to see some lighter weight options and patterns. I would appreciate hearing what you use, why you use it, and any other thoughts on this problem space.

Thanks.

答:
When I build javascript apps, I don't start by looking at the data model, but rather the user interactions that the app will support. Then I design those interactions by making very specific ajax RPC calls that only populate exactly the view I'm looking at. Same with the operations in that view, I have very specific ajax RPC calls that does exactly what that view requires.

In some cases I do end up with more generic RPC calls, where more views can share similar data, but I refactor that when I reach it, I don't start modelling like that.

So far I typically, as you say, have some static categories etc to read up at start of the application, but I've managed to avoid having huge complicated cached data models in javascript memory that needs syncing with the backend.

In this I've found the MVP pattern to be a much better choice than MVC - driving all my application code with events.


问:
Extracting text from link in python
I have a script in python 2.7 that scrapes the table in this page:
http://www.the-numbers.com/movie/budgets/all

I want to extract each of the columns, the problem is that my code doesn't recognize the columns that have links (2nd and 3rd columns).

```<code>budgeturl = "http://www.the-numbers.com/movie/budgets/all"
s = urllib.urlopen(budgeturl).read()
htmlpage = etree.HTML(s)
htmltable = htmlpage.xpath("//td[@class='data']/text()")
</code>```

With this code htmltable[0] is the rank, htmltable[1] is Production Budget and continues from there onwards.
From the ones I am missing, I need the text not the link.

答:
You need to amend your xpath since not all td elements have class="data".
Try this xpath expression: //td//text().

```<code>import urllib
from lxml import etree

budgeturl = "http://www.the-numbers.com/movie/budgets/all"
s = urllib.urlopen(budgeturl).read()
htmlpage = etree.HTML(s)
htmltable = htmlpage.xpath("//td//text()")
</code>```

Output:

Title: Extracting text from link in python

Body:
I have a script in python 2.7 that scrapes the table in this page:
http://www.the-numbers.com/movie/budgets/all

I want to extract each of the columns, the problem is that my code doesn't recognize the columns that have links (2nd and 3rd columns).

budgeturl = "http://www.the-numbers.com/movie/budgets/all"
s = urllib.urlopen(budgeturl).read()
htmlpage = etree.HTML(s)
htmltable = htmlpage.xpath("//td[@class='data']/text()")

With this code htmltable[0] is the rank, htmltable[1] is Production Budget and continues from there onwards.
From the ones I am missing, I need the text not the link.

Body:
You need to amend your xpath since not all td elements have class="data".
Try this xpath expression: //td//text().

import urllib
from lxml import etree

budgeturl = "http://www.the-numbers.com/movie/budgets/all"
s = urllib.urlopen(budgeturl).read()
htmlpage = etree.HTML(s)
htmltable = htmlpage.xpath("//td//text()")

Output:


问:
Access the Request object on Loopback
I am using Loopback(based on Express) and I need to get the request object on a hook as shown below:

```<code>Model.observe('access', function(ctx, next) {
    console.log(ctx.Model.app.response);
    if(ctx.query && ctx.query && ctx.query.where && ctx.query.where.id == 1){
      next();
      return;
    }
    next(new Error('Model does not exist'))

  });
</code>```

The only problem is that the response contains the app as:

```<code>IncomingMessage { app: [Circular] },
</code>```

How can I access the request object such as headers?

答: Use context.args.id to access a HTTP request

Title: Access the Request object on Loopback

Body:
I am using Loopback(based on Express) and I need to get the request object on a hook as shown below:

Model.observe('access', function(ctx, next) {
    console.log(ctx.Model.app.response);
    if(ctx.query && ctx.query && ctx.query.where && ctx.query.where.id == 1){
      next();
      return;
    }
    next(new Error('Model does not exist'))

  });

The only problem is that the response contains the app as:

IncomingMessage { app: [Circular] },

How can I access the request object such as headers?


问:
Global Variable with two values in different functions Arduino
I'm using a global String variable called IDCartao to save the id from rfid card. After reading the id I search for them on a server with the enc28j60, if the id is on server I make a beep, if not I make two beeps.

But, I'm having problems with the global String IDCartao which in function loop it has the correct value of ID, but when I search for this value in another function called my_callback I don't have the correct value, I just have the empty string "".

```<code>/**
 * Pinagem Leitor RFID:
 * CLK     - Pino 13
 * MISO    - Pino 12
 * MOSI    - Pino 11
 * SDA     - Pino 10
 * RST     - Pino 09
 * GND     - GND Arduino
 * 3.3     - 3.3v do Arduino
 * NC      - Não Conectado
 */

/**
 * Pinagem Módulo Ethernet:
 * 5v     - Não Conectado
 * LNT    - Não Conectado
 * CLK    - Não Conectado
 * SO     - Pino 12
 * WOL    - Não Conectado
 * SCK    - Pino 13
 * ST     - Pino 11
 * RST    - Não Conectado
 * CS     - Pino 8
 * Q3     - 3.3v do Arduino
 * GND    - GND Arduino
 */

/**
 * Pinagem de Outros componentes:
 * BUZZER  - Pino 7
 */

//DECLARAÇÃO DAS BIBLIOTECAS UTILIZADAS NO PROJETO
#include <SPI.h> //Biblioteca que permite a comunicação com dispositivos SPI (Serial Peripheral Interface), sendo o Arduino como dispositivo principal
#include <MFRC522.h> //Biblioteca do Leitor RFID
#include <EtherCard.h> //Biblioteca do Módulo Ethernet

//DECLARAÇÃO DOS PINOS UTILIZADOS NO ARDUINO
#define PINO_SDA 10 //Constante que define onde o pino SDA do leitor RFID está ligado
#define PINO_RST 9
#define BUZZER 7

MFRC522 mfrc522 (PINO_SDA, PINO_RST); //Cria instância MFRC522
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 }; //mac do módulo ethernet
byte Ethernet::buffer[500];
static uint32_t timer;
const char website[] PROGMEM = "192.168.0.103"; //endereço IP do servidor no Raspberry Pi
String conteudo;        //Armazena nessa variável todas as informações contidas no servidor
unsigned int tamanho;   //variável para guardar o tamanho do retorno do servidor
static char *IDCartao;

//ESCOPO DAS FUNÇÕES
void lerID ();
void my_callback (byte status, word off, word len);
void acessoLiberado();
void acessoNegado();
void testaValor();

void setup() {
  Serial.begin(9600);
  Serial.println ("Iniciando setup");

  SPI.begin();
  pinMode (BUZZER, OUTPUT);
  mfrc522.PCD_Init(); //Inicia MFRC522 (Leitor RFID)
  delay(100);
  if (ether.begin(sizeof Ethernet::buffer, mymac, 8) == 0) {
    Serial.println("Falha ao acessar o Modulo Ethernet");
  }
  else {
    Serial.println("Modulo Ethernet conectado!");
  }
  if (!ether.dhcpSetup()) {
    Serial.println("DHCP failed");
  }
  ether.printIp("IP:  ", ether.myip);
  ether.printIp("GW:  ", ether.gwip);
  ether.printIp("DNS: ", ether.dnsip);

  if (!ether.dnsLookup(website)) {
    Serial.println("DNS failed");
  }
  ether.printIp("SRV: ", ether.hisip);
  delay(100);
  IDCartao = (char*) calloc (12, sizeof(char));
  Serial.println("Setup finalizado!");
  Serial.println ("Aproxima");
  *IDCartao = "WAGNER";
}

void loop() {
  ether.packetLoop(ether.packetReceive());
  //String card = lerID();
  //card.toCharArray(IDCartao, card.length()+1);
  //*IDCartao = lerID();
  lerID();
  if (IDCartao[0] != '\0') { //Se um cartão tiver sido aproximado e sua ID lida com sucesso
    //Serial.print ("ID DO CARTAO: ");
    //Serial.write (IDCartao);
    delay(100);
    if (millis() > timer) {
      Serial.println("VAI LER SITE");
      timer = millis() + 5000;
      Serial.println();
      testaValor();
      ether.browseUrl(PSTR("/"), "", website, my_callback);
    }
    delay(5000);
    testaValor3();
    Serial.println("CONTEUDO:");
    Serial.print(conteudo);
  }

}

void testaValor() {
  Serial.println ("DENTRO DO TESTA VALOR");
  Serial.write(IDCartao);
  Serial.println ("\nSUCESSO");
}
void testaValor2() {
  Serial.println ("DENTRO DO TESTA VALOR 2");
  Serial.write(IDCartao);
  Serial.println ("\nSUCESSO");
}
void testaValor3() {
  Serial.println ("DENTRO DO TESTA VALOR 3");
  Serial.write(IDCartao);
  Serial.println ("\nSUCESSO");
}

void lerID () {
     if (mfrc522.PICC_IsNewCardPresent ()) {
       if (mfrc522.PICC_ReadCardSerial ()) {
         String conteudorfid = "";
         byte letra;
         for (byte i = 0; i < mfrc522.uid.size; i++) {
           conteudorfid.concat (String (mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
           conteudorfid.concat (String (mfrc522.uid.uidByte[i], HEX));
         }
         conteudorfid.toUpperCase ();
         int i;
         for (i = 0; i < conteudorfid.substring(1).length(); i++) {
          IDCartao[i] = conteudorfid.substring(1)[i];
         }
         i++;
         IDCartao[i] = '\0';
       }

     //Serial.println(IDCartao); //ID do cartão lida com sucesso
     }
     else {
      IDCartao[0] = '\0';
     }
}

/**
 * Função que faz a leitura do servidor armazenando seu conteudo numa String
 */
void my_callback (byte status, word off, word len) {
  testaValor2();
  Ethernet::buffer[off+500] = 0;

  conteudo = (const char*) Ethernet::buffer + off;

  String verifica(IDCartao);

  if (conteudo.indexOf(verifica) > 0) { //procura pela ID do cartão no servidor
    Serial.println("Acesso liberado");
    Serial.println(verifica);
    Serial.print ("POSICAO: ");
    Serial.println (conteudo.indexOf(verifica));
    acessoLiberado();
  }
  else {
    Serial.println ("ACESSO NEGADO!");
    Serial.print ("CARTAO VERIFICA: ");
    Serial.println (verifica);
    Serial.print ("IDCartao: ");
    Serial.write (IDCartao);
    acessoNegado();
  }
}

void acessoLiberado() {
  tone(BUZZER, 1000); //1kHz
  //digitalWrite (LED_VERDE, HIGH);
  delay (300);
  noTone (BUZZER);
  //digitalWrite (LED_VERDE, LOW);
  *IDCartao = "";
}

void acessoNegado() {
  tone (BUZZER, 1000);
  //digitalWrite (LED_VERMELHO, HIGH);
  delay (150);
  noTone (BUZZER);
  delay (150);
  tone (BUZZER, 1000);
  delay (150);
  noTone (BUZZER);
  //digitalWrite (LED_VERMELHO, LOW);
  *IDCartao = "";
}
</code>```

This is what happens. Look at the function testaValor2(), is the second function which is called but she is called after testaValor3(). I don't know why this is happening. Sorry for the bad quality

答:
When multiple functions are editing the global variable, you need to make them volatile. For instance, instantiate IDCartao like this:

```<code>volatile String IDCartao;
</code>```

This forces Arduino to get the latest value of IDCartao from memory every time it is requested.

More info here: https://www.arduino.cc/en/reference/volatile

Body:
I'm using a global String variable called IDCartao to save the id from rfid card. After reading the id I search for them on a server with the enc28j60, if the id is on server I make a beep, if not I make two beeps.

But, I'm having problems with the global String IDCartao which in function loop it has the correct value of ID, but when I search for this value in another function called my_callback I don't have the correct value, I just have the empty string "".

/**
 * Pinagem Leitor RFID:
 * CLK     - Pino 13
 * MISO    - Pino 12
 * MOSI    - Pino 11
 * SDA     - Pino 10
 * RST     - Pino 09
 * GND     - GND Arduino
 * 3.3     - 3.3v do Arduino
 * NC      - Não Conectado
 */

/**
 * Pinagem Módulo Ethernet:
 * 5v     - Não Conectado
 * LNT    - Não Conectado
 * CLK    - Não Conectado
 * SO     - Pino 12
 * WOL    - Não Conectado
 * SCK    - Pino 13
 * ST     - Pino 11
 * RST    - Não Conectado
 * CS     - Pino 8
 * Q3     - 3.3v do Arduino
 * GND    - GND Arduino
 */

/**
 * Pinagem de Outros componentes:
 * BUZZER  - Pino 7
 */

//DECLARAÇÃO DAS BIBLIOTECAS UTILIZADAS NO PROJETO
#include <SPI.h> //Biblioteca que permite a comunicação com dispositivos SPI (Serial Peripheral Interface), sendo o Arduino como dispositivo principal
#include <MFRC522.h> //Biblioteca do Leitor RFID
#include <EtherCard.h> //Biblioteca do Módulo Ethernet

//DECLARAÇÃO DOS PINOS UTILIZADOS NO ARDUINO
#define PINO_SDA 10 //Constante que define onde o pino SDA do leitor RFID está ligado
#define PINO_RST 9
#define BUZZER 7

MFRC522 mfrc522 (PINO_SDA, PINO_RST); //Cria instância MFRC522
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 }; //mac do módulo ethernet
byte Ethernet::buffer[500];
static uint32_t timer;
const char website[] PROGMEM = "192.168.0.103"; //endereço IP do servidor no Raspberry Pi
String conteudo;        //Armazena nessa variável todas as informações contidas no servidor
unsigned int tamanho;   //variável para guardar o tamanho do retorno do servidor
static char *IDCartao;

//ESCOPO DAS FUNÇÕES
void lerID ();
void my_callback (byte status, word off, word len);
void acessoLiberado();
void acessoNegado();
void testaValor();

void setup() {
  Serial.begin(9600);
  Serial.println ("Iniciando setup");

  SPI.begin();
  pinMode (BUZZER, OUTPUT);
  mfrc522.PCD_Init(); //Inicia MFRC522 (Leitor RFID)
  delay(100);
  if (ether.begin(sizeof Ethernet::buffer, mymac, 8) == 0) {
    Serial.println("Falha ao acessar o Modulo Ethernet");
  }
  else {
    Serial.println("Modulo Ethernet conectado!");
  }
  if (!ether.dhcpSetup()) {
    Serial.println("DHCP failed");
  }
  ether.printIp("IP:  ", ether.myip);
  ether.printIp("GW:  ", ether.gwip);
  ether.printIp("DNS: ", ether.dnsip);

  if (!ether.dnsLookup(website)) {
    Serial.println("DNS failed");
  }
  ether.printIp("SRV: ", ether.hisip);
  delay(100);
  IDCartao = (char*) calloc (12, sizeof(char));
  Serial.println("Setup finalizado!");
  Serial.println ("Aproxima");
  *IDCartao = "WAGNER";
}

void loop() {
  ether.packetLoop(ether.packetReceive());
  //String card = lerID();
  //card.toCharArray(IDCartao, card.length()+1);
  //*IDCartao = lerID();
  lerID();
  if (IDCartao[0] != '\0') { //Se um cartão tiver sido aproximado e sua ID lida com sucesso
    //Serial.print ("ID DO CARTAO: ");
    //Serial.write (IDCartao);
    delay(100);
    if (millis() > timer) {
      Serial.println("VAI LER SITE");
      timer = millis() + 5000;
      Serial.println();
      testaValor();
      ether.browseUrl(PSTR("/"), "", website, my_callback);
    }
    delay(5000);
    testaValor3();
    Serial.println("CONTEUDO:");
    Serial.print(conteudo);
  }

}

void testaValor() {
  Serial.println ("DENTRO DO TESTA VALOR");
  Serial.write(IDCartao);
  Serial.println ("\nSUCESSO");
}
void testaValor2() {
  Serial.println ("DENTRO DO TESTA VALOR 2");
  Serial.write(IDCartao);
  Serial.println ("\nSUCESSO");
}
void testaValor3() {
  Serial.println ("DENTRO DO TESTA VALOR 3");
  Serial.write(IDCartao);
  Serial.println ("\nSUCESSO");
}

void lerID () {
     if (mfrc522.PICC_IsNewCardPresent ()) {
       if (mfrc522.PICC_ReadCardSerial ()) {
         String conteudorfid = "";
         byte letra;
         for (byte i = 0; i < mfrc522.uid.size; i++) {
           conteudorfid.concat (String (mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
           conteudorfid.concat (String (mfrc522.uid.uidByte[i], HEX));
         }
         conteudorfid.toUpperCase ();
         int i;
         for (i = 0; i < conteudorfid.substring(1).length(); i++) {
          IDCartao[i] = conteudorfid.substring(1)[i];
         }
         i++;
         IDCartao[i] = '\0';
       }

     //Serial.println(IDCartao); //ID do cartão lida com sucesso
     }
     else {
      IDCartao[0] = '\0';
     }
}

/**
 * Função que faz a leitura do servidor armazenando seu conteudo numa String
 */
void my_callback (byte status, word off, word len) {
  testaValor2();
  Ethernet::buffer[off+500] = 0;

  conteudo = (const char*) Ethernet::buffer + off;

  String verifica(IDCartao);

  if (conteudo.indexOf(verifica) > 0) { //procura pela ID do cartão no servidor
    Serial.println("Acesso liberado");
    Serial.println(verifica);
    Serial.print ("POSICAO: ");
    Serial.println (conteudo.indexOf(verifica));
    acessoLiberado();
  }
  else {
    Serial.println ("ACESSO NEGADO!");
    Serial.print ("CARTAO VERIFICA: ");
    Serial.println (verifica);
    Serial.print ("IDCartao: ");
    Serial.write (IDCartao);
    acessoNegado();
  }
}

void acessoLiberado() {
  tone(BUZZER, 1000); //1kHz
  //digitalWrite (LED_VERDE, HIGH);
  delay (300);
  noTone (BUZZER);
  //digitalWrite (LED_VERDE, LOW);
  *IDCartao = "";
}

void acessoNegado() {
  tone (BUZZER, 1000);
  //digitalWrite (LED_VERMELHO, HIGH);
  delay (150);
  noTone (BUZZER);
  delay (150);
  tone (BUZZER, 1000);
  delay (150);
  noTone (BUZZER);
  //digitalWrite (LED_VERMELHO, LOW);
  *IDCartao = "";
}

This is what happens. Look at the function testaValor2(), is the second function which is called but she is called after testaValor3(). I don't know why this is happening. Sorry for the bad quality

Body:
When multiple functions are editing the global variable, you need to make them volatile. For instance, instantiate IDCartao like this:

volatile String IDCartao;

This forces Arduino to get the latest value of IDCartao from memory every time it is requested.

More info here: https://www.arduino.cc/en/reference/volatile


问:
Combining sqlite data into second table when grouped by name
I have a database that is the output for a python script involving a basic game. When the code saves to the database, it saves it to a table called points with the data: name, account_name, time, score. What I want is for the data be saved into a second table when sorted by name, I will then do the same with account_name. Some of the points table:

name   |account_name | time                | score
 oliver |Oliver       | 10:29:14-01:04:2017 | 250
 oliver |Oliver       | 10:29:20-01:04:2017 | 500
 dave   |Oliver       | 10:29:34-01:04:2017 | 250

What I want is for the data to be sorted into a table called name, where the score is totalled for all records with the same name and a column keeps track of how many entries have been merged(In this case, it will be equal to number of games played). For example:

```<code>name  | totalpoints | totalgames
oliver| 750         | 2
dave  | 250         | 1
</code>```

I will use this format to do the same with account_name. I have found information on how to group and sum the data but not into a second table. Thank you in advance.

答:
first, create your table by:

```<code>CREATE TABLE `stats` (
    `name`  TEXT PRIMARY KEY ON CONFLICT REPLACE,
    `totalpoints`   INTEGER,
    `totalgames`    INTEGER
);
</code>```

then insert into your table with:

```<code>INSERT INTO stats
SELECT games.name, SUM(games.score) AS totalpoints, COUNT(*) AS totalgames
FROM games
GROUP BY games.name
</code>```

Body:
I have a database that is the output for a python script involving a basic game. When the code saves to the database, it saves it to a table called points with the data: name, account_name, time, score. What I want is for the data be saved into a second table when sorted by name, I will then do the same with account_name. Some of the points table:

name   |account_name | time                | score
 oliver |Oliver       | 10:29:14-01:04:2017 | 250
 oliver |Oliver       | 10:29:20-01:04:2017 | 500
 dave   |Oliver       | 10:29:34-01:04:2017 | 250

What I want is for the data to be sorted into a table called name, where the score is totalled for all records with the same name and a column keeps track of how many entries have been merged(In this case, it will be equal to number of games played). For example:

name  | totalpoints | totalgames
oliver| 750         | 2
dave  | 250         | 1

I will use this format to do the same with account_name. I have found information on how to group and sum the data but not into a second table. Thank you in advance.

Body:
first, create your table by:

CREATE TABLE `stats` (
    `name`  TEXT PRIMARY KEY ON CONFLICT REPLACE,
    `totalpoints`   INTEGER,
    `totalgames`    INTEGER
);

then insert into your table with:

INSERT INTO stats
SELECT games.name, SUM(games.score) AS totalpoints, COUNT(*) AS totalgames
FROM games
GROUP BY games.name