问:
Writing Fragments for Polymorphic Associations in RelayJS and GraphQL
My backend schema has a model, Request, that uses a polymorphic association such that several different models all have-many Requests and a Request can belong to any one of those different models.

I've got a React Component, RequestList, that I want to be able to use in any of it's potential parent models.

Here's some sample code:

FooShowView.js

```<code>class FooShowView extends Component {
  render() {
    return (
      <RequestList router={this.props.router} />
    )
  }
}

export default Relay.createContainer(ShowView, {
  initialVariables: {
    FooId: null
  },
  fragments: {
    viewer: (variables) => {
      return Relay.QL`
        fragment on Viewer {
          Foo(id: $FooId) {
            id${ RequestList.getFragment('Foo') }
          }
        }`
      `
    }
  }
});
</code>```

RequestList.js

```<code>class RequestList extends Component {

  renderRows = () => {
    return this.props.requests.edges.map(edge => edge.node).map((intReq, i) => {
      return (
        <RequestRow
          request={ intReq }
          key={ i }
        />
      );
    });
  }

  render() {
    return (
      <Table>
        { this.renderRows() }
      </Table>
    );
  }
};

export default Relay.createContainer(RequestList, {
  fragments: {
    foo: () => Relay.QL`
      fragment on Foo {
        requests(first: 10) {
          edges {
            node {
              ${ RequestRow.getFragment('request') }
            }
          }
        }
      }
    `,
  }
})
</code>```

The problem is that now to render the RequestTable for another one of Request's parents, say in the BarShowView, I'd need to add a new fragment to RequestList:

```<code>bar: () => Relay.QL`
  fragment on Bar {
    requests(first: 10) {
      edges {
        node {
          ${ RequestRow.getFragment('request') }
        }
      }
    }
  }
`,
</code>```

And then Relay will spit out warnings that I need to provide both bar and foo as props to my List, even if it's not relevant to the current view.

Since Request is associated with roughly 8 different models in my schema, this will quickly become unreasonable.

What is the correct way to create a reusable react component that will render the polymorphic children of whatever record I'm looking at?

答:
What I ended up doing (in case someone runs into this) is just putting the RequestList fragment on the root and just passing in variables so it only queries for the appropriate associated records. Much simpler than having to write a half dozen fragments. So my createContainer call now looks like:

```<code>export default Relay.createContainer(RequestList, {
  initialVariables: {
    fooId: null,
    barId: null
  }
  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        requests(
          first: 10,
          fooId: $fooId,
          barId: $barId
        ) {
          edges {
            node {
              ${ RequestRow.getFragment('request') }
            }
          }
        }
      }
    `,
  }
})
</code>```

Note: if you're wondering why I'm passing up both fooID and barId instead of "requestableType" and "requestableID" it's because I'm using Elixir which doesn't support that type of polymorphism.

Body:
My backend schema has a model, Request, that uses a polymorphic association such that several different models all have-many Requests and a Request can belong to any one of those different models.

I've got a React Component, RequestList, that I want to be able to use in any of it's potential parent models.

Here's some sample code:

FooShowView.js

class FooShowView extends Component {
  render() {
    return (
      <RequestList router={this.props.router} />
    )
  }
}

export default Relay.createContainer(ShowView, {
  initialVariables: {
    FooId: null
  },
  fragments: {
    viewer: (variables) => {
      return Relay.QL`
        fragment on Viewer {
          Foo(id: $FooId) {
            id${ RequestList.getFragment('Foo') }
          }
        }`
      `
    }
  }
});

RequestList.js

class RequestList extends Component {

  renderRows = () => {
    return this.props.requests.edges.map(edge => edge.node).map((intReq, i) => {
      return (
        <RequestRow
          request={ intReq }
          key={ i }
        />
      );
    });
  }

  render() {
    return (

        { this.renderRows() }

    );
  }
};

export default Relay.createContainer(RequestList, {
  fragments: {
    foo: () => Relay.QL`
      fragment on Foo {
        requests(first: 10) {
          edges {
            node {
              ${ RequestRow.getFragment('request') }
            }
          }
        }
      }
    `,
  }
})

The problem is that now to render the RequestTable for another one of Request's parents, say in the BarShowView, I'd need to add a new fragment to RequestList:

bar: () => Relay.QL`
  fragment on Bar {
    requests(first: 10) {
      edges {
        node {
          ${ RequestRow.getFragment('request') }
        }
      }
    }
  }
`,

And then Relay will spit out warnings that I need to provide both bar and foo as props to my List, even if it's not relevant to the current view.

Since Request is associated with roughly 8 different models in my schema, this will quickly become unreasonable.

What is the correct way to create a reusable react component that will render the polymorphic children of whatever record I'm looking at?

Body:
What I ended up doing (in case someone runs into this) is just putting the RequestList fragment on the root and just passing in variables so it only queries for the appropriate associated records. Much simpler than having to write a half dozen fragments. So my createContainer call now looks like:

export default Relay.createContainer(RequestList, {
  initialVariables: {
    fooId: null,
    barId: null
  }
  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        requests(
          first: 10,
          fooId: $fooId,
          barId: $barId
        ) {
          edges {
            node {
              ${ RequestRow.getFragment('request') }
            }
          }
        }
      }
    `,
  }
})

Note: if you're wondering why I'm passing up both fooID and barId instead of "requestableType" and "requestableID" it's because I'm using Elixir which doesn't support that type of polymorphism.


来源: stackexchange

问:
Should I specify a fill factor on my tables?
I am working on a new system with a SQL Server 2005 database which will soon be going into production. A colleague recently mentioned to me that I should always be specifying the fill factor on my tables. Currently I don't specify fill factor on any of my tables.

My application is OLTP with a mix of reads and writes. A couple of my tables are "reference" tables i.e. read-only but most are read-write. The read-only tables are low volume ( < 50000 rows ).

From what I've read in the SQL Server documentation I should be sticking with the default fill-factor unless the table is read only.

Can anyone comment on this, both for read-only and read-write tables?

答:
No, you shouldn't specify a fill factor on your tables. The fill factor is always ignored by the engine, except for one and only one operation: index build (which includes initial build of an index on a populated table and/or a rebuild of an index). So the fill factor makes sense to be specified only in the ALTER TABLE ...  REBUILD and ALTER INDEX ... REBUILD operations.

See also A SQL Server DBA myth a day: (25/30) fill factor.

ContentLicense: CC BY-SA 2.5


问:
[Selenium][geckodriver] How to change firefox profile preference fields like "security.insecure_field_warning.contextual.enabled"
geckodriver Version

0.16.1

Firefox Version

53.0.2 (32-bit)

What happens:

When I try to automate login on an unsafe page, the firefox opens a new tab "https://support.mozilla.org/1/firefox/53.0.2/WINNT/pt-PT/insecure-password".

How can I disable this? I think that property "security.insecure_field_warning.contextual.enabled" is related to this behavior but i don't know how i could disable it by python code.

I try the following code but without success:

```<code>[...]
firefox_driver = path_drivers + "geckodriver.exe"
profile = webdriver.FirefoxProfile()
profile.set_preference("security.insecure_field_warning.contextual.enabled", False)
return webdriver.Firefox(executable_path=firefox_driver, firefox_profile=profile)
</code>```

The preference doesn't change, remains with True value on about:config.

Any idea?

Best regards,

Ruben Santos

答:
I found simpler solution:</p>

```<code>from selenium.webdriver import Firefox, FirefoxProfile

profile = FirefoxProfile()
profile.set_preference('security.insecure_field_warning.contextual.enabled', False)
profile.set_preference('security.insecure_password.ui.enabled', False)
driver = Firefox(firefox_profile=profile)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
geckodriver Version

0.16.1

Firefox Version

53.0.2 (32-bit)

What happens:

When I try to automate login on an unsafe page, the firefox opens a new tab "https://support.mozilla.org/1/firefox/53.0.2/WINNT/pt-PT/insecure-password".

How can I disable this? I think that property "security.insecure_field_warning.contextual.enabled" is related to this behavior but i don't know how i could disable it by python code.

I try the following code but without success:

[...]
firefox_driver = path_drivers + "geckodriver.exe"
profile = webdriver.FirefoxProfile()
profile.set_preference("security.insecure_field_warning.contextual.enabled", False)
return webdriver.Firefox(executable_path=firefox_driver, firefox_profile=profile)

The preference doesn't change, remains with True value on about:config.

Any idea?

Best regards,

Ruben Santos

Body:
I found simpler solution:

from selenium.webdriver import Firefox, FirefoxProfile

profile = FirefoxProfile()
profile.set_preference('security.insecure_field_warning.contextual.enabled', False)
profile.set_preference('security.insecure_password.ui.enabled', False)
driver = Firefox(firefox_profile=profile)


问:
InvalidCastException in constructor when passing the right parameters
So I've got this method that creates an object fom a DataRow:

```<code>public Comment CreateComment(DataRow row)
{
    if (row == null) return null;
    var id = (int) row["CommentPk"];
    var song = (int) row["SongFk"];
    var user = (int) row["AuthorFk"];
    var text = (string) row["Content"];
    var parent = (int?) row["ParentFk"];
    return new Comment(_provider, id, song, user, text, parent);
}
</code>```

And the constructor of Comment is:

```<code>public Comment(Provider provider, int id, int songid, int userid, string content, int? parentId)
</code>```

It does crash on the constructor line. I can step (F11) to it:

答:
So it seems to be a problem with the nullable column ParentFk.
Instead of

```<code>var parent = (int?) row["ParentFk"]
</code>```

I used:

```<code>var parent = row["ParentFk"] == DBNull.Value ? null : (int?)row["ParentFk"];
</code>```

I've used DataRows with nullable columns before but this weird exeption never happened, and it always became null.

Edit:

Use this:

```<code>var parent = row.IsNull("ParentFk") ? null : (int?)row["ParentFk"]
</code>```

Body:
So I've got this method that creates an object fom a DataRow:

public Comment CreateComment(DataRow row)
{
    if (row == null) return null;
    var id = (int) row["CommentPk"];
    var song = (int) row["SongFk"];
    var user = (int) row["AuthorFk"];
    var text = (string) row["Content"];
    var parent = (int?) row["ParentFk"];
    return new Comment(_provider, id, song, user, text, parent);
}

And the constructor of Comment is:

public Comment(Provider provider, int id, int songid, int userid, string content, int? parentId)

It does crash on the constructor line. I can step (F11) to it:

Body:
So it seems to be a problem with the nullable column ParentFk.
Instead of

var parent = (int?) row["ParentFk"]

I used:

var parent = row["ParentFk"] == DBNull.Value ? null : (int?)row["ParentFk"];

I've used DataRows with nullable columns before but this weird exeption never happened, and it always became null.

Edit:

Use this:

var parent = row.IsNull("ParentFk") ? null : (int?)row["ParentFk"]


问:
Create new variable based on the order of values in other columns
I have a data frame relative to accesses to a website. Several accesses per day, with different possible actions and descriptions of the actions

```<code>People | Date       | Time  | Action | Descr  |
       |            |       |        |        |
j      | 01/01/2010 | 10:13 | X      | A      |
j      | 01/01/2010 | 10:15 | Y      | B      |
j      | 02/01/2010 | 14:15 | Z      | C      |
j      | 03/01/2010 | 11:45 | X      | D      |
j      | 03/01/2010 | 13:56 | X      | E      |
j      | 03/01/2010 | 18:43 | Z      | F      |
j      | 03/01/2010 | 18:44 | X      | A      |
</code>```

After reducing the data frame to a balanced daily panel data, I need to create variables such that:

-the value of the first variable (FirstX) must be equal to the description (Descr) of the first Action = X of the day (if available) and zero otherwise

-the value of the second variable must be equal to the description of the second Action = X of the day and zero otherwise

-so on

Once I transformed it into a balanced daily panel (which I can do) I need to have a final result which looks like this:

```<code>People | Date       |Accesses| First X|Second X| Third X| Fourth X |
       |            |        |        |        |        |          |
j      | 01/01/2010 |    2   |   A    |   0    |    0   |    0     |
j      | 02/01/2010 |    1   |   0    |   0    |    0   |    0     |
j      | 03/01/2010 |    4   |   D    |   E    |    A   |    0     |
</code>```

答:
I found a solution myself. I post it here in case this is useful to somebody.</p>

```<code># create temp variables to be used for the count(just a vector of all the
numbers from 1 to N)
subset$temp_var1<-c(1:N)

# generate a variable which starts counting from one and starts again
# every time "date" or "people" change
subset$count<-ave(subset$temp_var1 , subset$date ,
subset$people ,  FUN = seq_along)

#drop variable "Action"
subset<-subset( subset, select=c("people" , "date" ,
"descr" , "count"))

#reshape
subset_comuni<-reshape(subset_comuni , idvar=c("nome_utente" , "date") ,
timevar = "count" , direction = "wide")
</code>```

Body:
I have a data frame relative to accesses to a website. Several accesses per day, with different possible actions and descriptions of the actions

People | Date       | Time  | Action | Descr  |
       |            |       |        |        |
j      | 01/01/2010 | 10:13 | X      | A      |
j      | 01/01/2010 | 10:15 | Y      | B      |
j      | 02/01/2010 | 14:15 | Z      | C      |
j      | 03/01/2010 | 11:45 | X      | D      |
j      | 03/01/2010 | 13:56 | X      | E      |
j      | 03/01/2010 | 18:43 | Z      | F      |
j      | 03/01/2010 | 18:44 | X      | A      |

After reducing the data frame to a balanced daily panel data, I need to create variables such that:

-the value of the first variable (FirstX) must be equal to the description (Descr) of the first Action = X of the day (if available) and zero otherwise

-the value of the second variable must be equal to the description of the second Action = X of the day and zero otherwise

-so on

Once I transformed it into a balanced daily panel (which I can do) I need to have a final result which looks like this:

People | Date       |Accesses| First X|Second X| Third X| Fourth X |
       |            |        |        |        |        |          |
j      | 01/01/2010 |    2   |   A    |   0    |    0   |    0     |
j      | 02/01/2010 |    1   |   0    |   0    |    0   |    0     |
j      | 03/01/2010 |    4   |   D    |   E    |    A   |    0     |

Body:
I found a solution myself. I post it here in case this is useful to somebody.

# create temp variables to be used for the count(just a vector of all the
numbers from 1 to N)
subset$temp_var1<-c(1:N)

# generate a variable which starts counting from one and starts again
# every time "date" or "people" change
subset$count<-ave(subset$temp_var1 , subset$date ,
subset$people ,  FUN = seq_along)

#drop variable "Action"
subset<-subset( subset, select=c("people" , "date" ,
"descr" , "count"))

#reshape
subset_comuni<-reshape(subset_comuni , idvar=c("nome_utente" , "date") ,
timevar = "count" , direction = "wide")

ContentLicense: CC BY-SA 4.0


问:
Share .h file issue Objective-C
I have 2 project (test and pods in the image) and my problem is this:

in the Test project I created a Today widget called WidgetNotificationCenter and in TodayViewController.h file I have to import a .h file which is located in the pods project, so when I try to import this .h in TodayViewController.h I get an error that tell me that it doesn't find this .h file.

Can you help me to solve this problem?

答:
Most likely you don't have the pod available in extension target and your pods are defined for main target.
You can change your pod file like this</p>

```<code>target '[Main App Target Name]' do
        pod ...
        pod ...
        pod ...
end

target '[Extension Target Name]' do
        pod ...
end
</code>```

Title: Share .h file issue Objective-C

Body:
Most likely you don't have the pod available in extension target and your pods are defined for main target.
You can change your pod file like this

target '[Main App Target Name]' do
        pod ...
        pod ...
        pod ...
end

target '[Extension Target Name]' do
        pod ...
end


问:
response.write is not working asp.net
On button click event after inserting data I want to show message that data is inserted successfully.
Here is my code

```<code>if (com2.ExecuteNonQuery() >= 1)
        {
            Response.Write("<script LANGUAGE='JavaScript' >alert('Request Submitted Successfully!')</script>");
        }
        else
        {
            Response.Write("<script LANGUAGE='JavaScript' >alert('There is some error. Please enter again')</script>");
        }
</code>```

It was working fine until I put code for empty textboxs after insertion in same event soon after above code. here is code

```<code>foreach (var control in this.Controls)
        {
            TextBox tb = control as TextBox;
            if (tb != null)
            {
                tb.Text = string.Empty;
            }
        }
        Response.Redirect("Default.aspx");
</code>```

now textbox empty after data insertion, data is also inserting but no popup message is showing. Where is problem

答:
I'm not 100% sure on your logic, but instead of having the server perform the redirect, do it on the client side after the call to alert:

```<code>if (com2.ExecuteNonQuery() >= 1) {
    Response.Write("<script LANGUAGE='JavaScript' >alert('Request Submitted Successfully!');window.location='Default.aspx';</script>");
} else {
    Response.Write("<script LANGUAGE='JavaScript' >alert('There is some error. Please enter again');window.location='Default.aspx';</script>");
}
</code>```

Title: response.write is not working asp.net

Body:
On button click event after inserting data I want to show message that data is inserted successfully.
Here is my code

if (com2.ExecuteNonQuery() >= 1)
        {
            Response.Write("");
        }
        else
        {
            Response.Write("");
        }

It was working fine until I put code for empty textboxs after insertion in same event soon after above code. here is code

foreach (var control in this.Controls)
        {
            TextBox tb = control as TextBox;
            if (tb != null)
            {
                tb.Text = string.Empty;
            }
        }
        Response.Redirect("Default.aspx");

now textbox empty after data insertion, data is also inserting but no popup message is showing. Where is problem

Body:
I'm not 100% sure on your logic, but instead of having the server perform the redirect, do it on the client side after the call to alert:

if (com2.ExecuteNonQuery() >= 1) {
    Response.Write("<script LANGUAGE='JavaScript' >alert('Request Submitted Successfully!');window.location='Default.aspx';</script>");
} else {
    Response.Write("<script LANGUAGE='JavaScript' >alert('There is some error. Please enter again');window.location='Default.aspx';</script>");
}


问:
How to flush nodejs child_process stdin.write
I need to run a 'C' program for a client on the server side. this program can be interactive.

I am using  Node.js child_process class. But I see a problem here : since I need to keep the program interactive there will be message exchanged back and forth between client and node.js server .

1.program says : Enter value of x :

send this message to client and get some value as input

2. When the Nodejs server receives the input from client it does   child_process.stdin.write

But the problem is that the program does not execute until I mark the end of the stream. What could be a work around for this ?

Like flushing the values to the program as and when available from the user.

Update :

test1.c

    #include

```<code>int main() {

int x, y;

printf("Enter x : ");
fflush(stdout);
scanf("%d", &x);

printf("Enter y : ");
fflush(stdout);
scanf("%d", &y);

printf("Value entered y is %d\n", y);
printf("Value entered x is %d", x);
}
</code>```

Compile the above code to generate the executable a.out

```<code>var spawn = require('child_process').spawn;
var count = 0;
var exec = spawn('./a.out');

exec.on('error', function (err){
   console.log("Error" + err );
});

exec.stdout.on('data', function(data){
    console.log("in stdout.on.data : " + data.toString());
    if (count == 0) {
        exec.stdin.write('44\n');
        count++;
    }
    else if (count == 1) {
        exec.stdin.write('54');
        count++;
    }
    if (count == 2) {
        exec.stdin.end();
    }

});

exec.stderr.on('data', function(data) {
    console.log("in stderr.on.data : " + data);
});

exec.on('close', function (code) {
    if (code != 0) {
        console.log("Program ended with a error code : " + code);
    }

});
</code>```

in the above node.js code if I comment  exec.stdin.end(); it does not work and it waits until the stream is closed. How can I work around this ? since I want clients to have a continuous interaction it will be difficult for me to predict when to end the stream.

答:
You forgot to "press Enter".

```<code>exec.stdin.write('54' + "\n");
OR
exec.stdin.write("54\n");
</code>```

You also can lookup a bit about Quotes in JavaScript

Body:
I need to run a 'C' program for a client on the server side. this program can be interactive.

I am using  Node.js child_process class. But I see a problem here : since I need to keep the program interactive there will be message exchanged back and forth between client and node.js server .

1.program says : Enter value of x :

send this message to client and get some value as input

2. When the Nodejs server receives the input from client it does   child_process.stdin.write

But the problem is that the program does not execute until I mark the end of the stream. What could be a work around for this ?

Like flushing the values to the program as and when available from the user.

Update :

test1.c

    #include

int main() {

int x, y;

printf("Enter x : ");
fflush(stdout);
scanf("%d", &x);

printf("Enter y : ");
fflush(stdout);
scanf("%d", &y);

printf("Value entered y is %d\n", y);
printf("Value entered x is %d", x);
}

Compile the above code to generate the executable a.out

var spawn = require('child_process').spawn;
var count = 0;
var exec = spawn('./a.out');

exec.on('error', function (err){
   console.log("Error" + err );
});

exec.stdout.on('data', function(data){
    console.log("in stdout.on.data : " + data.toString());
    if (count == 0) {
        exec.stdin.write('44\n');
        count++;
    }
    else if (count == 1) {
        exec.stdin.write('54');
        count++;
    }
    if (count == 2) {
        exec.stdin.end();
    }

});

exec.stderr.on('data', function(data) {
    console.log("in stderr.on.data : " + data);
});

exec.on('close', function (code) {
    if (code != 0) {
        console.log("Program ended with a error code : " + code);
    }

});

in the above node.js code if I comment  exec.stdin.end(); it does not work and it waits until the stream is closed. How can I work around this ? since I want clients to have a continuous interaction it will be difficult for me to predict when to end the stream.

Body:
You forgot to "press Enter".

exec.stdin.write('54' + "\n");
OR
exec.stdin.write("54\n");

You also can lookup a bit about Quotes in JavaScript


问:
How to get random value from specific ranges of dictionary content
If this way I can get random value from given range:

```<code> int r = ran.Next(1, 4);
 string v;
 if (dict.TryGetValue(r, out v))
 {
    ///...
 }
</code>```

how to properly get random value of <int, string> dictionary content from specific range, for example only from 4 to 6 and 1 and 2 and avoid look for 3:

```<code>Dictionary<int, string> dict = new Dictionary<int, string>()
{
    { 1, "word1" },
    { 2, "word2" },
    { 3, "word3" },
    { 4, "word4" },
    { 5, "word5" },
    { 6, "word6" }
};
</code>```

答:
Create HashSet with excluded values then

```<code>HashSet<int> excludedValues = ....
List<int> values = dict.Where(x=> excludedValues.Contains(x.Key) == false).Select(x=>x.Key).ToList();

int index = rand.Next(1, values.Count);
string value = dict[index];
</code>```

This way you are not limited to excluding value 3. You can put anything in this collection. If your collections are big you should use hashset which is much faster then List.

Body:
If this way I can get random value from given range:

 int r = ran.Next(1, 4);
 string v;
 if (dict.TryGetValue(r, out v))
 {
    ///...
 }

how to properly get random value of <int, string> dictionary content from specific range, for example only from 4 to 6 and 1 and 2 and avoid look for 3:

Dictionary<int, string> dict = new Dictionary<int, string>()
{
    { 1, "word1" },
    { 2, "word2" },
    { 3, "word3" },
    { 4, "word4" },
    { 5, "word5" },
    { 6, "word6" }
};

Body:
Create HashSet with excluded values then

HashSet<int> excludedValues = ....
List<int> values = dict.Where(x=> excludedValues.Contains(x.Key) == false).Select(x=>x.Key).ToList();

int index = rand.Next(1, values.Count);
string value = dict[index];

This way you are not limited to excluding value 3. You can put anything in this collection. If your collections are big you should use hashset which is much faster then List.


问:
How do I catch "Index out of range" in Swift?
I would really like to use a more simple classic try catch block in my Swift code but I can't find anything that does it.

I just need:

```<code>try {
// some code that causes a crash.
}
catch {
// okay well that crashed, so lets ignore this block and move on.
}
</code>```

Here's my dilema, when the TableView is reloaded with new data, some information is still siting in RAM which calls didEndDisplayingCell on a tableView with a freshly empty datasource to crash.

So I frequently thrown the exception Index out of range

I've tried this:

```<code>func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

    do {
        let imageMessageBody = msgSections[indexPath.section].msg[indexPath.row] as? ImageMessageBody
        let cell = tableView.dequeueReusableCellWithIdentifier("ImageUploadCell", forIndexPath: indexPath) as! ImageCell
        cell.willEndDisplayingCell()
    } catch {
        print("Swift try catch is confusing...")
    }
}
</code>```

I've also tried this:

```<code>func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    print(indexPath.section)
    print(indexPath.row)

    if msgSections.count != 0 {
        if let msg = msgSections[indexPath.section].msg[indexPath.row] as? ImageMessageBody {
            let cell = tableView.dequeueReusableCellWithIdentifier("ImageUploadCell", forIndexPath: indexPath) as! ImageCell
            cell.willEndDisplayingCell()
        }
    }
}
</code>```

This is a very low priority block of code, and I have wasted a lot of time with trial and error figuring out which error handler built into swift works for what seems to be extremely unique situations when I have tons of scenarios just like this one where the code can crash and it will not have any effect on the user experience.

In short, I don't need anything fancy but Swift seems to have extremely specific error handlers that differ based on whether I'm getting a value from a functions return value or getting a value from an array's index which may not exist.

Is there a simple try catch on Swift like every other popular programming language?

答:
You can try a different approach to this. Will surely work!</p>

```<code>if msgSections != nil {
    for msg in msgSections[indexPath.section] {
        if msgSections[indexPath.section].index(of: msg) == indexPath.row {
            (Code)
        }
}
</code>```

Body:
I would really like to use a more simple classic try catch block in my Swift code but I can't find anything that does it.

I just need:

try {
// some code that causes a crash.
}
catch {
// okay well that crashed, so lets ignore this block and move on.
}

Here's my dilema, when the TableView is reloaded with new data, some information is still siting in RAM which calls didEndDisplayingCell on a tableView with a freshly empty datasource to crash.

So I frequently thrown the exception Index out of range

I've tried this:

func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {

    do {
        let imageMessageBody = msgSections[indexPath.section].msg[indexPath.row] as? ImageMessageBody
        let cell = tableView.dequeueReusableCellWithIdentifier("ImageUploadCell", forIndexPath: indexPath) as! ImageCell
        cell.willEndDisplayingCell()
    } catch {
        print("Swift try catch is confusing...")
    }
}

I've also tried this:

func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    print(indexPath.section)
    print(indexPath.row)

    if msgSections.count != 0 {
        if let msg = msgSections[indexPath.section].msg[indexPath.row] as? ImageMessageBody {
            let cell = tableView.dequeueReusableCellWithIdentifier("ImageUploadCell", forIndexPath: indexPath) as! ImageCell
            cell.willEndDisplayingCell()
        }
    }
}

This is a very low priority block of code, and I have wasted a lot of time with trial and error figuring out which error handler built into swift works for what seems to be extremely unique situations when I have tons of scenarios just like this one where the code can crash and it will not have any effect on the user experience.

In short, I don't need anything fancy but Swift seems to have extremely specific error handlers that differ based on whether I'm getting a value from a functions return value or getting a value from an array's index which may not exist.

Is there a simple try catch on Swift like every other popular programming language?

Body:
You can try a different approach to this. Will surely work!

if msgSections != nil {
    for msg in msgSections[indexPath.section] {
        if msgSections[indexPath.section].index(of: msg) == indexPath.row {
            (Code)
        }
}


问:
Fetch cursor from multiple tables view PostgreSQL
I try until couple of hours to fetch all the row from a view, created from multiple tables.

I have two tables (Position, and Vector) to which correspond respectively two custom composite types , type_position and type_vector

Position (id, sys_time, lat, lon)

Vector   (id, sys_time, speed)

I want to create a temporary VIEW in plpgsql procedure to bring together all Position and Vector and order them by sys_time so i wrote :

```<code>CREATE TEMP VIEW posAndVectView AS
                    SELECT * from position
                    UNION ALL
                    SELECT * from vector;
</code>```

I need to iterate over this view and made some work depends on Position and Vector attributes.

So i think i should use a cursor :

```<code>DECLARE
 manyRows refcursor;
BEGIN

OPEN manyRows FOR
SELECT * FROM posAndVectView ORDER BY sys_time ASC;
LOOP
FETCH manyRows INTO posOrVect;
EXIT WHEN NOT FOUND;
...
END LOOP;
CLOSE manyRows;
</code>```

So my question is what should the type of the posOrVect variable be in the DECLARE section ?

It seems to be sometimes a type_vector, sometimes a type_position...

答:
I found the answer it is pretty simple.
I need to declare the posOrVect variable with the record type as its mentionned in the PostgreSQL documentation :

Record variables are similar to row-type variables, but they have no
  predefined structure. They take on the actual row structure of the row
  they are assigned during a SELECT or FOR command. The substructure of
  a record variable can change each time it is assigned to. A
  consequence of this is that until a record variable is first assigned
  to, it has no substructure, and any attempt to access a field in it
  will draw a run-time error.

Body:
I try until couple of hours to fetch all the row from a view, created from multiple tables.

I have two tables (Position, and Vector) to which correspond respectively two custom composite types , type_position and type_vector

Position (id, sys_time, lat, lon)

Vector   (id, sys_time, speed)

I want to create a temporary VIEW in plpgsql procedure to bring together all Position and Vector and order them by sys_time so i wrote :

CREATE TEMP VIEW posAndVectView AS
                    SELECT * from position
                    UNION ALL
                    SELECT * from vector;

I need to iterate over this view and made some work depends on Position and Vector attributes.

So i think i should use a cursor :

DECLARE
 manyRows refcursor;
BEGIN

OPEN manyRows FOR
SELECT * FROM posAndVectView ORDER BY sys_time ASC;
LOOP
FETCH manyRows INTO posOrVect;
EXIT WHEN NOT FOUND;
...
END LOOP;
CLOSE manyRows;

So my question is what should the type of the posOrVect variable be in the DECLARE section ?

It seems to be sometimes a type_vector, sometimes a type_position...


问:
Rails 5 - has_many through and nested attributes forms
I have two models Request and TableLocation with both having a has_many through relationship joined by RequestLocation table.

I am trying to create a nested form and the table_location data is not being saved to the database.

As you can see the table_locations"=>["1"] parameter is being passed to the create action but not being saved.

Appreciate any help.

Console Output

```<code>Started POST "/requests" for 127.0.0.1 at 2017-06-07 10:35:26 -0400
Processing by RequestsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"mHV/xbmdfHmCAsi16KXlW+0bWVSkEo9SRVchdyPpL60o3m3SuKEt4nuUT4PJNEyCsWq3Nj4IWiCMlDbhiPewdA==", "request"=>{"concierge_name"=>"Alex", "concierge_number"=>"954-123-4567", "concierge_email"=>"alex@email.com", "client_name"=>"Adam", "client_number"=>"954-765-4321", "client_email"=>"adam@email.com", "hotel_employee"=>"0", "concierge_service"=>"0", "vip_promoter"=>"0", "arriving_with_client"=>"1", "client_alone"=>"0", "males"=>"", "females"=>"1", "table_minimum"=>"1000", "arrival_time(1i)"=>"2017", "arrival_time(2i)"=>"6", "arrival_time(3i)"=>"7", "arrival_time(4i)"=>"14", "arrival_time(5i)"=>"35", "table_locations"=>["1"], "comments"=>""}, "commit"=>"Submit"}
   (0.1ms)  BEGIN
  SQL (0.4ms)  INSERT INTO "requests" ("concierge_name", "concierge_number", "concierge_email", "client_name", "client_number", "client_email", "arriving_with_client", "people", "females", "table_minimum", "arrival_time", "comments", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14) RETURNING "id"  [["concierge_name", "Alex"], ["concierge_number", "954-123-4567"], ["concierge_email", "alex@email.com"], ["client_name", "Adam"], ["client_number", "954-765-4321"], ["client_email", "adam@email.com"], ["arriving_with_client", "t"], ["people", 1], ["females", 1], ["table_minimum", 1000], ["arrival_time", "2017-06-07 14:35:00"], ["comments", ""], ["created_at", "2017-06-07 14:35:26.658718"], ["updated_at", "2017-06-07 14:35:26.658718"]]
   (0.3ms)  COMMIT
Redirected to http://localhost:3000/thanks
Completed 302 Found in 8ms (ActiveRecord: 0.8ms)
</code>```

app/models/request.rb

```<code>class Request < ApplicationRecord
    has_many :request_locations
    has_many :table_locations, through: :request_locations
end
</code>```

app/models/table_locations.rb

```<code>class TableLocation < ApplicationRecord
    has_many :request_locations
    has_many :requests, through: :request_locations
end
</code>```

app/models/request_location.rb

```<code>class RequestLocation < ApplicationRecord
    belongs_to :request
    belongs_to :table_location
end
</code>```

app/controllers/requests_controller.rb

```<code>class RequestsController < ApplicationController
  before_action :set_request, only: [:show,
                                     :edit,
                                     :update,
                                     :destroy]

  before_action :authenticate_admin!, except: [:index,
                                               :new,
                                               :create]

  def index
    redirect_to root_path unless admin_signed_in?
    @requests = Request.search(params[:term], params[:filter], params[:page])
  end

  def show
  end

  def new
    @request = Request.new
  end

  def edit
  end

  def create
    @request = Request.new(request_params)
    @request.people = (@request.males || 0) + (@request.females || 0)

    respond_to do |format|
      if @request.save
        format.html { redirect_to thanks_path, notice: 'Request was successfully created.' }
        format.json { render :show, status: :created, location: @request }
      else
        format.html { render :new }
        format.json { render json: @request.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @request.update(request_params)
        format.html { redirect_to @request, notice: 'Request was successfully updated.' }
        format.json { render :show, status: :ok, location: @request }
      else
        format.html { render :edit }
        format.json { render json: @request.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @request.destroy
    respond_to do |format|
      format.html { redirect_to requests_url, notice: 'Request was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

    def set_request
      @request = Request.find(params[:id])
    end

    def request_params
      params.require(:request).permit(:concierge_name,
                                      :concierge_number,
                                      :concierge_email,
                                      :client_name,
                                      :client_number,
                                      :client_email,
                                      :hotel_employee,
                                      :concierge_service,
                                      :vip_promoter,
                                      :arriving_with_client,
                                      :client_alone,
                                      :people,
                                      :males,
                                      :females,
                                      :table_minimum,
                                      :arrival_time,
                                      :comments,
                                      table_locations: [:id]
      )
    end
end
</code>```

app/views/requests/_form.html.erb

```<code>...
<% TableLocation.all.each do |t| %>
    <%= check_box_tag "request[table_locations][]", t.id, @request.table_locations.include?(t.id) %>
    <%= t.location %>
    <br />
<% end %>
...
</code>```

答:
Explanations:

Your request_params permits table_locations: [:id], but this only permits the following format:

```<code>Parameters: {"utf8"=>"✓", ... "request"=>{"table_locations"=>{"id"=>"1"}, "comments"=>""}, "commit"=>"Submit"}
</code>```

but yours is showing to be:

```<code>Parameters: {"utf8"=>"✓", ... "request"=>{"table_locations"=>["1"], "comments"=>""}, "commit"=>"Submit"}
</code>```

therefore, try this: puts request_params inside the create method, and you'll notice that it doesn't have table_locations values (even though you thought it's there, but it's not), because it is not "properly" whitelisted in your strong params request_params.

To be able to associate multiple TableLocations objects to a newly built Request object, the format should be something like below

```<code>request = Request.new(table_location_ids: [1,2,3,4,5])
</code>```

but from your implementation, you're doing it like this (which won't work):

```<code>request = Request.new(table_locations: [1,2,3,4,5])
# => this will raise an error:
# ActiveRecord::AssociationTypeMismatch: TableLocation expected, got Fixnum
# however yours didn't raise an error, because it was not whitelisted in the request_params in the first place
</code>```

Solution:

requests_controller.rb

```<code>def request_params
  params.require(:request).permit(..., table_location_ids: [])
end
</code>```

_form.html.erb

```<code><% TableLocation.all.each do |t| %>
  <%= check_box_tag "request[table_location_ids][]", t.id %>
  <%= t.location %>
  <br />
<% end %>
</code>```

Recommendation:

just in case you don't know yet that you can do the following in this way, I'll be refactoring your code to look something like this:

requests_controller.rb

```<code>def create
  @table_locations = TableLocation.all
end
</code>```

_form.html.erb

```<code><%= form_for @request do |f| %>
  <% @table_locations.each do |table_location| %>
    <%= f.check_box :table_location_ids, multiple: true, table_location.id %>
  <% end %>
<% end %>
</code>```

Body:
I have two models Request and TableLocation with both having a has_many through relationship joined by RequestLocation table.

I am trying to create a nested form and the table_location data is not being saved to the database.

As you can see the table_locations"=>["1"] parameter is being passed to the create action but not being saved.

Appreciate any help.

Console Output

Started POST "/requests" for 127.0.0.1 at 2017-06-07 10:35:26 -0400
Processing by RequestsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"mHV/xbmdfHmCAsi16KXlW+0bWVSkEo9SRVchdyPpL60o3m3SuKEt4nuUT4PJNEyCsWq3Nj4IWiCMlDbhiPewdA==", "request"=>{"concierge_name"=>"Alex", "concierge_number"=>"954-123-4567", "concierge_email"=>"alex@email.com", "client_name"=>"Adam", "client_number"=>"954-765-4321", "client_email"=>"adam@email.com", "hotel_employee"=>"0", "concierge_service"=>"0", "vip_promoter"=>"0", "arriving_with_client"=>"1", "client_alone"=>"0", "males"=>"", "females"=>"1", "table_minimum"=>"1000", "arrival_time(1i)"=>"2017", "arrival_time(2i)"=>"6", "arrival_time(3i)"=>"7", "arrival_time(4i)"=>"14", "arrival_time(5i)"=>"35", "table_locations"=>["1"], "comments"=>""}, "commit"=>"Submit"}
   (0.1ms)  BEGIN
  SQL (0.4ms)  INSERT INTO "requests" ("concierge_name", "concierge_number", "concierge_email", "client_name", "client_number", "client_email", "arriving_with_client", "people", "females", "table_minimum", "arrival_time", "comments", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14) RETURNING "id"  [["concierge_name", "Alex"], ["concierge_number", "954-123-4567"], ["concierge_email", "alex@email.com"], ["client_name", "Adam"], ["client_number", "954-765-4321"], ["client_email", "adam@email.com"], ["arriving_with_client", "t"], ["people", 1], ["females", 1], ["table_minimum", 1000], ["arrival_time", "2017-06-07 14:35:00"], ["comments", ""], ["created_at", "2017-06-07 14:35:26.658718"], ["updated_at", "2017-06-07 14:35:26.658718"]]
   (0.3ms)  COMMIT
Redirected to http://localhost:3000/thanks
Completed 302 Found in 8ms (ActiveRecord: 0.8ms)

app/models/request.rb

class Request < ApplicationRecord
    has_many :request_locations
    has_many :table_locations, through: :request_locations
end

app/models/table_locations.rb

class TableLocation < ApplicationRecord
    has_many :request_locations
    has_many :requests, through: :request_locations
end

app/models/request_location.rb

class RequestLocation < ApplicationRecord
    belongs_to :request
    belongs_to :table_location
end

app/controllers/requests_controller.rb

class RequestsController < ApplicationController
  before_action :set_request, only: [:show,
                                     :edit,
                                     :update,
                                     :destroy]

  before_action :authenticate_admin!, except: [:index,
                                               :new,
                                               :create]

  def index
    redirect_to root_path unless admin_signed_in?
    @requests = Request.search(params[:term], params[:filter], params[:page])
  end

  def show
  end

  def new
    @request = Request.new
  end

  def edit
  end

  def create
    @request = Request.new(request_params)
    @request.people = (@request.males || 0) + (@request.females || 0)

    respond_to do |format|
      if @request.save
        format.html { redirect_to thanks_path, notice: 'Request was successfully created.' }
        format.json { render :show, status: :created, location: @request }
      else
        format.html { render :new }
        format.json { render json: @request.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @request.update(request_params)
        format.html { redirect_to @request, notice: 'Request was successfully updated.' }
        format.json { render :show, status: :ok, location: @request }
      else
        format.html { render :edit }
        format.json { render json: @request.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @request.destroy
    respond_to do |format|
      format.html { redirect_to requests_url, notice: 'Request was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

    def set_request
      @request = Request.find(params[:id])
    end

    def request_params
      params.require(:request).permit(:concierge_name,
                                      :concierge_number,
                                      :concierge_email,
                                      :client_name,
                                      :client_number,
                                      :client_email,
                                      :hotel_employee,
                                      :concierge_service,
                                      :vip_promoter,
                                      :arriving_with_client,
                                      :client_alone,
                                      :people,
                                      :males,
                                      :females,
                                      :table_minimum,
                                      :arrival_time,
                                      :comments,
                                      table_locations: [:id]
      )
    end
end

app/views/requests/_form.html.erb

...
<% TableLocation.all.each do |t| %>
    <%= check_box_tag "request[table_locations][]", t.id, @request.table_locations.include?(t.id) %>
    <%= t.location %>

<% end %>
...

Body:
Explanations:

Your request_params permits table_locations: [:id], but this only permits the following format:

Parameters: {"utf8"=>"✓", ... "request"=>{"table_locations"=>{"id"=>"1"}, "comments"=>""}, "commit"=>"Submit"}

but yours is showing to be:

Parameters: {"utf8"=>"✓", ... "request"=>{"table_locations"=>["1"], "comments"=>""}, "commit"=>"Submit"}

therefore, try this: puts request_params inside the create method, and you'll notice that it doesn't have table_locations values (even though you thought it's there, but it's not), because it is not "properly" whitelisted in your strong params request_params.

To be able to associate multiple TableLocations objects to a newly built Request object, the format should be something like below

request = Request.new(table_location_ids: [1,2,3,4,5])

but from your implementation, you're doing it like this (which won't work):

request = Request.new(table_locations: [1,2,3,4,5])
# => this will raise an error:
# ActiveRecord::AssociationTypeMismatch: TableLocation expected, got Fixnum
# however yours didn't raise an error, because it was not whitelisted in the request_params in the first place

Solution:

requests_controller.rb

def request_params
  params.require(:request).permit(..., table_location_ids: [])
end

_form.html.erb

<% TableLocation.all.each do |t| %>
  <%= check_box_tag "request[table_location_ids][]", t.id %>
  <%= t.location %>
  <br />
<% end %>

Recommendation:

just in case you don't know yet that you can do the following in this way, I'll be refactoring your code to look something like this:

requests_controller.rb

def create
  @table_locations = TableLocation.all
end

_form.html.erb

<%= form_for @request do |f| %>
  <% @table_locations.each do |table_location| %>
    <%= f.check_box :table_location_ids, multiple: true, table_location.id %>
  <% end %>
<% end %>


问:
How to make an editable textView to enter in a cell but we can scroll a  datagridview?
I take a datagridveiw  ..in which I make a datagrid in that no one can edit a cells but they can scroll a scrollbar.

I can not used ENABLE property..b'cs in it I can not scroll ....

I used v s 2008

答:
It sounds like you want to build a DataGridView which can be scrolled but not editted.  If so then use the ReadOnly property

```<code>myDataGridView.ReadOnly = True
</code>```

Documentation:

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.readonly.aspx

Body:
It sounds like you want to build a DataGridView which can be scrolled but not editted.  If so then use the ReadOnly property

myDataGridView.ReadOnly = True

Documentation:

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.readonly.aspx


问:
How to optimize and faster for loop when handling large dataset in R?
Currently, I'm working on the data transformation. The data is not super large, about 190k rows.

I wrote a for loop like this:

```<code>for (i in 1:nrow(df2)){
#a
record.a <- df[which(df$first_lat==df2[i,"third_lat"]
            & df$first_lon==df2[i,"third_lon"]
            & df$sixth_lat==df2[i,"fourth_lat"]
            & df$sixth_lon==df2[i,"fourth_lon"]
            & df[,4]==df2[i,4]
            & df[,3]==df2[i,5]),]
df2[i,18] <- ifelse(nrow(record.a) != 0,record.a$order_cnt,NA)

#b
record.b <- df[which(df$fifth_lat==df2[i,"third_lat"]
            & df$fifth_lon==df2[i,"third_lon"]
            & df$sixth_lat==df2[i,"second_lat"]
            & df$sixth_lon==df2[i,"second_lon"]
            & df[,4]==df2[i,4]
            & df[,3]==df2[i,5]),]
df2[i,19] <- ifelse(nrow(record.b) != 0,record.b$order_cnt,NA)

#c
record.c <- df[which(df$fifth_lat==df2[i,"first_lat"]
            & df$fifth_lon==df2[i,"first_lon"]
            & df$fourth_lat==df2[i,"second_lat"]
            & df$fourth_lon==df2[i,"second_lon"]
            & df[,4]==df2[i,4]
            & df[,3]==df2[i,5]),]
df2[i,20] <- ifelse(nrow(record.c) != 0,record.c$order_cnt,NA)

#d
record.d <- df[which(df$third_lat==df2[i,"first_lat"]
            & df$third_lon==df2[i,"first_lon"]
            & df$fourth_lat==df2[i,"sixth_lat"]
            & df$fourth_lon==df2[i,"sixth_lon"]
            & df[,4]==df2[i,4]
            & df[,3]==df2[i,5]),]
df2[i,21] <- ifelse(nrow(record.d) != 0,record.d$order_cnt,NA)

#e
record.e <- df[which(df$third_lat==df2[i,"fifth_lat"]
            & df$third_lon==df2[i,"fifth_lon"]
            & df$second_lat==df2[i,"sixth_lat"]
            & df$second_lon==df2[i,"sixth_lon"]
            & df[,4]==df2[i,4]
            & df[,3]==df2[i,5]),]
df2[i,22] <- ifelse(nrow(record.e) != 0,record.e$order_cnt,NA)

#f
record.f <- df[which(df$first_lat==df2[i,"fifth_lat"]
            & df$first_lon==df2[i,"fifth_lon"]
            & df$second_lat==df2[i,"fourth_lat"]
            & df$second_lon==df2[i,"fourth_lon"]
            & df[,4]==df2[i,4]
            & df[,3]==df2[i,5]),]
df2[i,23] <- ifelse(nrow(record.f) != 0,record.f$order_cnt,NA)
}
</code>```

So, basically, I need to fill out 6 columns of df2 respectively from df with 6 criteria. In the for loop, nrow(df2) is about 190k. It runs super slow. But I used view(df2) to check it and it runs fine. So is there any method I could make it faster? I may apply the same data transformation to a much larger dataset in the future.

df:
df

df2:
df2

The data is about grids on a map. df2 is basically a subset of df but add 6 additional columns. Both df and df2 has the same lon and lat information.

Each grid_id stands for a hexagon area in a map. Each hexagon is connected to other six hexagons by two pairs of lon and lat. What I want to do is that find a particular values from the six surrounding hexagons (in df) to fill into columns (a, b, c, d, e, f) in df2. Also, I need two other conditions, which is hours, ten_mins_interval. (df[,4]==df2[i,4] & df[,3]==df2[i,5]))

So I think the logic is:

For each grid_id, hours, ten_mins_interval (1 row) in df2

find the corresponding 6 grid_ids (6 rows) with same hours, ten_mins_interval in df

fill order_cnt from those 6 rows into a,b,c,d,e,f columns in df2

答:
If you start with your current df2[,1:17] you can add df[,18] with the merge command:

```<code>df2 <- merge(df[,c("first_lat","first_lon","sixth_lat","sixth_lon","col4name","col5name","order_cn")],
      df2,
      by.x=c("first_lat","first_lon","sixth_lat","sixth_lon","col4name","col5name"),
      by.y=c("third_lat","third_lon","fourth_lat","fourth_lon","col4name","col3name"),
      all.y=TRUE)
</code>```

You'll need to replace col4name with the name of the fourth column and so on - I can't see from the screenshot what that might be. Five more versions of this command can be easily generated to add the other five columns. As the operation works on whole vectors at time, it's likely to be faster than looping. As data wasn't provided in a suitable format this isn't tested.

Body:
Currently, I'm working on the data transformation. The data is not super large, about 190k rows.

I wrote a for loop like this:

for (i in 1:nrow(df2)){
#a
record.a <- df[which(df$first_lat==df2[i,"third_lat"]
            & df$first_lon==df2[i,"third_lon"]
            & df$sixth_lat==df2[i,"fourth_lat"]
            & df$sixth_lon==df2[i,"fourth_lon"]
            & df[,4]==df2[i,4]
            & df[,3]==df2[i,5]),]
df2[i,18] <- ifelse(nrow(record.a) != 0,record.a$order_cnt,NA)

#b
record.b <- df[which(df$fifth_lat==df2[i,"third_lat"]
            & df$fifth_lon==df2[i,"third_lon"]
            & df$sixth_lat==df2[i,"second_lat"]
            & df$sixth_lon==df2[i,"second_lon"]
            & df[,4]==df2[i,4]
            & df[,3]==df2[i,5]),]
df2[i,19] <- ifelse(nrow(record.b) != 0,record.b$order_cnt,NA)

#c
record.c <- df[which(df$fifth_lat==df2[i,"first_lat"]
            & df$fifth_lon==df2[i,"first_lon"]
            & df$fourth_lat==df2[i,"second_lat"]
            & df$fourth_lon==df2[i,"second_lon"]
            & df[,4]==df2[i,4]
            & df[,3]==df2[i,5]),]
df2[i,20] <- ifelse(nrow(record.c) != 0,record.c$order_cnt,NA)

#d
record.d <- df[which(df$third_lat==df2[i,"first_lat"]
            & df$third_lon==df2[i,"first_lon"]
            & df$fourth_lat==df2[i,"sixth_lat"]
            & df$fourth_lon==df2[i,"sixth_lon"]
            & df[,4]==df2[i,4]
            & df[,3]==df2[i,5]),]
df2[i,21] <- ifelse(nrow(record.d) != 0,record.d$order_cnt,NA)

#e
record.e <- df[which(df$third_lat==df2[i,"fifth_lat"]
            & df$third_lon==df2[i,"fifth_lon"]
            & df$second_lat==df2[i,"sixth_lat"]
            & df$second_lon==df2[i,"sixth_lon"]
            & df[,4]==df2[i,4]
            & df[,3]==df2[i,5]),]
df2[i,22] <- ifelse(nrow(record.e) != 0,record.e$order_cnt,NA)

#f
record.f <- df[which(df$first_lat==df2[i,"fifth_lat"]
            & df$first_lon==df2[i,"fifth_lon"]
            & df$second_lat==df2[i,"fourth_lat"]
            & df$second_lon==df2[i,"fourth_lon"]
            & df[,4]==df2[i,4]
            & df[,3]==df2[i,5]),]
df2[i,23] <- ifelse(nrow(record.f) != 0,record.f$order_cnt,NA)
}

So, basically, I need to fill out 6 columns of df2 respectively from df with 6 criteria. In the for loop, nrow(df2) is about 190k. It runs super slow. But I used view(df2) to check it and it runs fine. So is there any method I could make it faster? I may apply the same data transformation to a much larger dataset in the future.

df:
df

df2:
df2

The data is about grids on a map. df2 is basically a subset of df but add 6 additional columns. Both df and df2 has the same lon and lat information.

Each grid_id stands for a hexagon area in a map. Each hexagon is connected to other six hexagons by two pairs of lon and lat. What I want to do is that find a particular values from the six surrounding hexagons (in df) to fill into columns (a, b, c, d, e, f) in df2. Also, I need two other conditions, which is hours, ten_mins_interval. (df[,4]==df2[i,4] & df[,3]==df2[i,5]))

So I think the logic is:

For each grid_id, hours, ten_mins_interval (1 row) in df2

find the corresponding 6 grid_ids (6 rows) with same hours, ten_mins_interval in df

fill order_cnt from those 6 rows into a,b,c,d,e,f columns in df2

Body:
If you start with your current df2[,1:17] you can add df[,18] with the merge command:

df2 <- merge(df[,c("first_lat","first_lon","sixth_lat","sixth_lon","col4name","col5name","order_cn")],
      df2,
      by.x=c("first_lat","first_lon","sixth_lat","sixth_lon","col4name","col5name"),
      by.y=c("third_lat","third_lon","fourth_lat","fourth_lon","col4name","col3name"),
      all.y=TRUE)

You'll need to replace col4name with the name of the fourth column and so on - I can't see from the screenshot what that might be. Five more versions of this command can be easily generated to add the other five columns. As the operation works on whole vectors at time, it's likely to be faster than looping. As data wasn't provided in a suitable format this isn't tested.


问:
Pointers and Address in C
I write a C program. I have 2 pointers *a and *b. Now, I impose *a = 20 and *b = 10. After that I impose a = b in subroutine but the value seem doesn't change. I expect that *a = 10 and *b = 10. Please help me find a solution for this. Thank you.

```<code>#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void Copy(int *a1, int *a2)
{
    a1 = a2;
}

void Test()
{
    // a = 20
    int *a = (int *)malloc(sizeof(int));
    *a = 20;

    // b = 10
    int *b = (int *)malloc(sizeof(int));
    *b = 10;

    Copy(a, b); // a = b
    printf("\na = %d", *a);
    printf("\nb = %d", *b);
}

int main(int argc, char *argv[]){
    Test();
    fflush(stdin);
    printf("\nPress any key to continue");
    getchar();
    return 0;
}
</code>```

答:
If you want to assign the values, such that after the call of Copy *a == *b holds, then you'd have to change your function as follows:

```<code>void Copy(int *a1, int *a2)
{
    *a1 = *a2;
}
</code>```

If you want to assign the pointers, such that after the call of Copy a==b holds, then you have to pass a pointer to the pointers:

```<code>void Copy(int **a1, int **a2)
{
    *a1 = *a2;
}

void Test() {
    ...
    Copy (&a, &b);
    ...
}
</code>```

Note that a==b also implies that *a == *b.

Title: Pointers and Address in C

Body:
I write a C program. I have 2 pointers *a and *b. Now, I impose *a = 20 and *b = 10. After that I impose a = b in subroutine but the value seem doesn't change. I expect that *a = 10 and *b = 10. Please help me find a solution for this. Thank you.

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void Copy(int *a1, int *a2)
{
    a1 = a2;
}

void Test()
{
    // a = 20
    int *a = (int *)malloc(sizeof(int));
    *a = 20;

    // b = 10
    int *b = (int *)malloc(sizeof(int));
    *b = 10;

    Copy(a, b); // a = b
    printf("\na = %d", *a);
    printf("\nb = %d", *b);
}

int main(int argc, char *argv[]){
    Test();
    fflush(stdin);
    printf("\nPress any key to continue");
    getchar();
    return 0;
}

Body:
If you want to assign the values, such that after the call of Copy *a == *b holds, then you'd have to change your function as follows:

void Copy(int *a1, int *a2)
{
    *a1 = *a2;
}

If you want to assign the pointers, such that after the call of Copy a==b holds, then you have to pass a pointer to the pointers:

void Copy(int **a1, int **a2)
{
    *a1 = *a2;
}

void Test() {
    ...
    Copy (&a, &b);
    ...
}

Note that a==b also implies that *a == *b.


问:
How to operate on part of line only
How do I make sed operate on specific parts of a line only? And, on the contrary, how do I make sed not work on specific parts of a line?

Examples:

```<code>"A a A a ( A a ) A ( a A ) a"
</code>```

How do I, for instance, replace all the As with Ts only between the ( and ) to obtain:

```<code>"A a A a ( T a ) A ( a T ) a"
</code>```

And given next example input:

```<code>"F f F f ( F f ) F ( f F ) f"
</code>```

How do I, for instance, replace all the Fs with Xs but not between the ( and ) to
obtain:

"X f X f ( F f ) X ( f F ) f"

I searched Google but found nothing usable. I guess it's a general question about sed. The problem is reducible to general sed "templates", I hope.

having FROM and TO then operate between them only (on all occurrences on given line)

having FROM and TO operate anywhere else than between them...

special case when FROM and TO are the same (between " and " or "FOO" and "FOO" etc.)
for both 1. and 2.

It should work with any operation, not just substitution, but also with printing etc., like printing everything between strings "FOO" and "BAR" in string.

```<code>"1 2 3 BAR a b c FOO d e f BAR g a h FOO i j k BAR l m n FOO o p q"
</code>```

The result will be

```<code>" d e f  i j k "
</code>```

So, general examples on how to do it would be highly appreciated. It also seems that this question is quite common, but no good howto is found on the Google yet. I also guess this
would be quite challenging to answer. Please, also do no give any hints on how to do it
using Perl, AWK or whatever else than sed. This question is really a sed-only question.

答:
Divide and conquer.

Insert newlines to separate the segments then use the newlines, line beginning (^), line ending ($) and delimiter characters (parentheses in this case) as anchors and loop. The added newlines are removed at the end.

```<code>$ echo "A a A a ( A a ) A ( a A ) a" |
    sed 's/([^)]*)/\n&/g;
         :a;
           s/\(\n([^)]*\)A\([^)]*)\)/\1T\2/;
         ta;
         s/\n//g'
A a A a ( T a ) A ( a T ) a
$ echo "F f F f ( F f ) F ( f F ) f" |
    sed 's/(/\n(/g;
         s/)/)\n/g;
         :a;
           s/\([^(]*\)F\([^)]*\(\n\|$\)\)/\1X\2/g;
         ta;
         s/\n//g'
X f X f ( F f ) X ( f F ) f
$ echo "1 2 3 BAR a b c FOO d e f BAR g a h FOO i j k BAR l m n FOO o p q" |
    sed 's/^/BAR/;
         s/$/FOO/;
         s/FOO/&\n/g;
         s/BAR/\n&/g;
         s/BAR[^\n]*\n//g;
         s/[^\n]*FOO\n//g;
         s/\n//g'
 d e f  i j k
</code>```

Title: How to operate on part of line only

Body:
How do I make sed operate on specific parts of a line only? And, on the contrary, how do I make sed not work on specific parts of a line?

Examples:

"A a A a ( A a ) A ( a A ) a"

How do I, for instance, replace all the As with Ts only between the ( and ) to obtain:

"A a A a ( T a ) A ( a T ) a"

And given next example input:

"F f F f ( F f ) F ( f F ) f"

How do I, for instance, replace all the Fs with Xs but not between the ( and ) to
obtain:

"X f X f ( F f ) X ( f F ) f"

I searched Google but found nothing usable. I guess it's a general question about sed. The problem is reducible to general sed "templates", I hope.

having FROM and TO then operate between them only (on all occurrences on given line)

having FROM and TO operate anywhere else than between them...

special case when FROM and TO are the same (between " and " or "FOO" and "FOO" etc.)
for both 1. and 2.

It should work with any operation, not just substitution, but also with printing etc., like printing everything between strings "FOO" and "BAR" in string.

"1 2 3 BAR a b c FOO d e f BAR g a h FOO i j k BAR l m n FOO o p q"

The result will be

" d e f  i j k "

So, general examples on how to do it would be highly appreciated. It also seems that this question is quite common, but no good howto is found on the Google yet. I also guess this
would be quite challenging to answer. Please, also do no give any hints on how to do it
using Perl, AWK or whatever else than sed. This question is really a sed-only question.

Body:
Divide and conquer.

Insert newlines to separate the segments then use the newlines, line beginning (^), line ending ($) and delimiter characters (parentheses in this case) as anchors and loop. The added newlines are removed at the end.

$ echo "A a A a ( A a ) A ( a A ) a" |
    sed 's/([^)]*)/\n&/g;
         :a;
           s/\(\n([^)]*\)A\([^)]*)\)/\1T\2/;
         ta;
         s/\n//g'
A a A a ( T a ) A ( a T ) a
$ echo "F f F f ( F f ) F ( f F ) f" |
    sed 's/(/\n(/g;
         s/)/)\n/g;
         :a;
           s/\([^(]*\)F\([^)]*\(\n\|$\)\)/\1X\2/g;
         ta;
         s/\n//g'
X f X f ( F f ) X ( f F ) f
$ echo "1 2 3 BAR a b c FOO d e f BAR g a h FOO i j k BAR l m n FOO o p q" |
    sed 's/^/BAR/;
         s/$/FOO/;
         s/FOO/&\n/g;
         s/BAR/\n&/g;
         s/BAR[^\n]*\n//g;
         s/[^\n]*FOO\n//g;
         s/\n//g'
 d e f  i j k


问:
Response for preflight is invalid (redirect) with AngularJS and ElasticSearch
I'm working on an Angular 1.6.3 app which uses the elasticsearch.js library to query an ElasticSearch 5.4 instance running on a remote server. Recently, our app started having problems where it receives several Response for preflight is invalid (redirect) errors when it initially reaches out to ElasticSearch for data. Currently this problem only happens in Chrome:

Screenshot of request in Developer Tools:

This error seems to happen randomly, and it doesn't occur when a user accesses the app in Chrome's Incognito Mode or another browser like Firefox.

After doing some research, I found out that this OPTIONS request is a preflight request the browser sends out to ask the server if it's okay to send the actual POST containing what I want to query ElasticSearch for. The reason a preflight is occurring is because I am trying to do a POST with application/json as the Content-Type header, which isn't one of the "standard" values for the Content-Type header.

My question is - how do I resolve this? I've changed the CORS settings in elasticsearch.yml to no avail:

```<code>http.cors.enabled: true
http.cors.allow-origin: "*"
http.cors.allow-methods: OPTIONS, HEAD, GET, POST, PUT, DELETE
http.cors.allow-headers: "X-Requested-With, X-Auth-Token, Content-Type, Content-Length, Authorization"
</code>```

I've also tried changing the elasticsearch.js Content-Type headers for each ElasticSearch request but each request continues to send application/json, like the settings don't listen to what I enter:

```<code>var client = elasticsearch.Client({
  hosts: [{
    host: 'es-proxy.company.net',
    port: 80,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  }]
});
</code>```

A screenshot of the OPTION request that fails from Chrome DevTool net-internals event page:

Any help would be appreciated. Thank you.

答: The cause of problem can be seen in the Chrome DevTool net-internals event page near the bottom of the OPTION request, where it says CHROME_EXTENSION_REDIRECTED_REQUEST. A Chrome extension was randomly redirecting my requests to ElasticSearch, effectively cancelling them. Since it is a Chrome extension that was installed by my company (through an enterprise policy) and thus unremovable, I was able to get the ElasticSearch host added to the extension's whitelist.

Body:
I'm working on an Angular 1.6.3 app which uses the elasticsearch.js library to query an ElasticSearch 5.4 instance running on a remote server. Recently, our app started having problems where it receives several Response for preflight is invalid (redirect) errors when it initially reaches out to ElasticSearch for data. Currently this problem only happens in Chrome:

Screenshot of request in Developer Tools:

This error seems to happen randomly, and it doesn't occur when a user accesses the app in Chrome's Incognito Mode or another browser like Firefox.

After doing some research, I found out that this OPTIONS request is a preflight request the browser sends out to ask the server if it's okay to send the actual POST containing what I want to query ElasticSearch for. The reason a preflight is occurring is because I am trying to do a POST with application/json as the Content-Type header, which isn't one of the "standard" values for the Content-Type header.

My question is - how do I resolve this? I've changed the CORS settings in elasticsearch.yml to no avail:

http.cors.enabled: true
http.cors.allow-origin: "*"
http.cors.allow-methods: OPTIONS, HEAD, GET, POST, PUT, DELETE
http.cors.allow-headers: "X-Requested-With, X-Auth-Token, Content-Type, Content-Length, Authorization"

I've also tried changing the elasticsearch.js Content-Type headers for each ElasticSearch request but each request continues to send application/json, like the settings don't listen to what I enter:

var client = elasticsearch.Client({
  hosts: [{
    host: 'es-proxy.company.net',
    port: 80,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  }]
});

A screenshot of the OPTION request that fails from Chrome DevTool net-internals event page:

Any help would be appreciated. Thank you.


问:
How to apply functional programming to remove two nested for i in?
originally I had this awful piece of code with two for i in. To sum up, the idea is to get a list of AMI's ID of some AMIS with a particular tag. To do so, I iterate over list (wrong!) and I get a list of IDS.

```<code>def aws_get_images_exceptions(connection, exceptions):
 list_exceptions = []
    for ex in exceptions:
        images = connection.get_all_images(filters={ "tag-key":"Name","tag-value":ex})
        for ami in images:
            list_exceptions.append(ami.id)
    return list_exceptions
</code>```

Over each iteration I get the complete list of "exceptions" based on the fixed tag Role that I provide to function and then I append the right AMIS.

Ok, I was able to remove the second for i in with the next code:

```<code>def aws_get_images_exceptions(connection, exceptions):
for ex in exceptions:
        images = connection.get_all_images(filters={ "tag-key":"Name","tag-value":ex})
       list_exceptions = list(map(lambda x: x.id, images)) + list_exceptions
return list_exceptions
</code>```

I've checked and I get the same amount of AMIS, same IDS, etc. But I don't get the way to do it in a functional way removing the very first for. As you notice I do a manual call to get_all_images because I iterate over a list of "exceptions" which I give to the function.

Do you know how I can remove this first for i in?

Thanks to all!

答:
Functional style doesn't necessarily mean writing a one-line list comprehension to do everything. The essence of what you want is to iterate over a bunch of streams; you have a list of exceptions, each of which produces a list of images to iterate over. You can use natural Python syntax handle this just as cleanly.

```<code>def aws_get_images_exceptions(connection, exceptions):
    for ex in exceptions:
        filters = {"tag-key": "Name", "tag-value": ex}
        for ami in connection.get_all_images(filters=filters):
            yield ami.id
</code>```

Don't worry about defining the variable filters; temporary variables are often used (via let expressions) even in pure functional languages. Otherwise, you don't have any real side effects (other than the unavoidable database query).

Notice the only significant change I've made to your code is to yield each id, rather than append it to a list that gets returned. The caller can decide whether to create a list from the resulting generator.

```<code>ids = list(aws_get_images_exceptions(connection, exceptions))
</code>```

Body:
originally I had this awful piece of code with two for i in. To sum up, the idea is to get a list of AMI's ID of some AMIS with a particular tag. To do so, I iterate over list (wrong!) and I get a list of IDS.

def aws_get_images_exceptions(connection, exceptions):
 list_exceptions = []
    for ex in exceptions:
        images = connection.get_all_images(filters={ "tag-key":"Name","tag-value":ex})
        for ami in images:
            list_exceptions.append(ami.id)
    return list_exceptions

Over each iteration I get the complete list of "exceptions" based on the fixed tag Role that I provide to function and then I append the right AMIS.

Ok, I was able to remove the second for i in with the next code:

def aws_get_images_exceptions(connection, exceptions):
for ex in exceptions:
        images = connection.get_all_images(filters={ "tag-key":"Name","tag-value":ex})
       list_exceptions = list(map(lambda x: x.id, images)) + list_exceptions
return list_exceptions

I've checked and I get the same amount of AMIS, same IDS, etc. But I don't get the way to do it in a functional way removing the very first for. As you notice I do a manual call to get_all_images because I iterate over a list of "exceptions" which I give to the function.

Do you know how I can remove this first for i in?

Thanks to all!

Body:
Functional style doesn't necessarily mean writing a one-line list comprehension to do everything. The essence of what you want is to iterate over a bunch of streams; you have a list of exceptions, each of which produces a list of images to iterate over. You can use natural Python syntax handle this just as cleanly.

def aws_get_images_exceptions(connection, exceptions):
    for ex in exceptions:
        filters = {"tag-key": "Name", "tag-value": ex}
        for ami in connection.get_all_images(filters=filters):
            yield ami.id

Don't worry about defining the variable filters; temporary variables are often used (via let expressions) even in pure functional languages. Otherwise, you don't have any real side effects (other than the unavoidable database query).

Notice the only significant change I've made to your code is to yield each id, rather than append it to a list that gets returned. The caller can decide whether to create a list from the resulting generator.

ids = list(aws_get_images_exceptions(connection, exceptions))


问:
when I add elements to the vector<int *>, I meet some problems
here is my coding:

```<code>std::vector<int *>a;
for(i=0;i<3;i++)
{
  int j=i+1;
  int *p=&j;
  a.push_back(p);
}
for(auto &c:a)
{
  std::cout<<*c<<std::endl;
}
</code>```

I want to make the output be 1,2,3 ,but the output is 3,3,3.it seems that I have added  same pointer to a,but I want to add  different pointers to a by circulation,what should I do and how does the mistake above happen?

答:
```<code>std::vector<int *>a;
for(i=0;i<3;i++)
{
  int j=i+1;
  int *p=&j;
  a.push_back(p);
}
</code>```

p is an address in the stack. Moreover, j and p are valid only in the respective iteration of the loop, they are not significant anymore (j is destructed) as soon as the loop goes to the next iteration or ends.

If you really want a vector of pointers, the pointers need to be valid. One option is that pointers point to objects in heap. Another option is that pointers point to objects in stack which never go out of scope, i.e. never destructed.

Another, perhaps better, option is to have a vector of the objects itself, for e.g. vector<int>.

Body:
here is my coding:

std::vector<int *>a;
for(i=0;i<3;i++)
{
  int j=i+1;
  int *p=&j;
  a.push_back(p);
}
for(auto &c:a)
{
  std::cout<<*c<<std::endl;
}

I want to make the output be 1,2,3 ,but the output is 3,3,3.it seems that I have added  same pointer to a,but I want to add  different pointers to a by circulation,what should I do and how does the mistake above happen?

Body:
std::vector<int *>a;
for(i=0;i<3;i++)
{
  int j=i+1;
  int *p=&j;
  a.push_back(p);
}

p is an address in the stack. Moreover, j and p are valid only in the respective iteration of the loop, they are not significant anymore (j is destructed) as soon as the loop goes to the next iteration or ends.

If you really want a vector of pointers, the pointers need to be valid. One option is that pointers point to objects in heap. Another option is that pointers point to objects in stack which never go out of scope, i.e. never destructed.

Another, perhaps better, option is to have a vector of the objects itself, for e.g. vector<int>.


问:
Custom error function for neural network in R
I use R-packages (nnet, amore, neuralnet) for designing a neural network. The problem is that I want to use a custom error function. Based on the output from the neural network I have a custom calculation...

It seems not possible to do this is in a package in R? Is there anybody who knows what I can do?

Other possibility is that I use a genetic algorithm to optimize my weights of my neural network, but I don't get the desired optimization here. My network 28 inputs & 9 hidden neurons is too big to use a genetic algorithm to optimize, I get stuck in local optima...
(Maybe the genetic algorithm approach is an option but it would be time consuming to try to achieve a decent solution with it.)

答: With the neuralnet package you can pass custom activation and error functions which are automatically differentiated (assuming the function can be with the internal R functions).  See this question here regarding how to implemented ReLU for the activation function.  The same thing should be possible by passing your custom error function to the err.fct argument.


问:
ruby-on-rails - Problem with Nested Resources
I have a Problem with Nested Resources.

2 Models

```<code>User => has_many :stuffs

Stuff => belongs_to :user
</code>```

routes.rb

```<code>map.resources :stuffs

map.resources :users, :has_many => [:stuffs]
</code>```

When i call /users/1/stuffs it presents me the Stuff for the corresponding User. but i got this also when i call /users/2/stuffs. It should return 0 "Stuffs" but it dont work.

```<code>MySQL Query from Server
SELECT * FROM `stuffs`
</code>```

rake routes

```<code>stuffs GET    /stuffs(.:format)                         {:action=>"index", :controller=>"stuffs"}
                POST   /stuffs(.:format)                         {:action=>"create", :controller=>"stuffs"}
      new_stuff GET    /stuffs/new(.:format)                     {:action=>"new", :controller=>"stuffs"}
     edit_stuff GET    /stuffs/:id/edit(.:format)                {:action=>"edit", :controller=>"stuffs"}
          stuff GET    /stuffs/:id(.:format)                     {:action=>"show", :controller=>"stuffs"}
                PUT    /stuffs/:id(.:format)                     {:action=>"update", :controller=>"stuffs"}
                DELETE /stuffs/:id(.:format)                     {:action=>"destroy", :controller=>"stuffs"}
    user_stuffs GET    /users/:user_id/stuffs(.:format)          {:action=>"index", :controller=>"stuffs"}
                POST   /users/:user_id/stuffs(.:format)          {:action=>"create", :controller=>"stuffs"}
 new_user_stuff GET    /users/:user_id/stuffs/new(.:format)      {:action=>"new", :controller=>"stuffs"}
edit_user_stuff GET    /users/:user_id/stuffs/:id/edit(.:format) {:action=>"edit", :controller=>"stuffs"}
     user_stuff GET    /users/:user_id/stuffs/:id(.:format)      {:action=>"show", :controller=>"stuffs"}
                PUT    /users/:user_id/stuffs/:id(.:format)      {:action=>"update", :controller=>"stuffs"}
                DELETE /users/:user_id/stuffs/:id(.:format)      {:action=>"destroy", :controller=>"stuffs"}
          users GET    /users(.:format)                          {:action=>"index", :controller=>"users"}
                POST   /users(.:format)                          {:action=>"create", :controller=>"users"}
       new_user GET    /users/new(.:format)                      {:action=>"new", :controller=>"users"}
      edit_user GET    /users/:id/edit(.:format)                 {:action=>"edit", :controller=>"users"}
           user GET    /users/:id(.:format)                      {:action=>"show", :controller=>"users"}
                PUT    /users/:id(.:format)                      {:action=>"update", :controller=>"users"}
                DELETE /users/:id(.:format)                      {:action=>"destroy", :controller=>"users"}
           root        /                                         {:action=>"index", :controller=>"users"}
</code>```

gem list

```<code>actionmailer (2.3.8)
actionpack (2.3.8)
activerecord (2.3.8)
activeresource (2.3.8)
activesupport (2.3.8)
arel (2.0.6)
authlogic (2.1.6)
builder (2.1.2)
cgi_multipart_eof_fix (2.5.0)
gem_plugin (0.2.3)
i18n (0.5.0)
mongrel (1.1.5 x86-mingw32)
mysql (2.8.1 x86-mingw32)
paperclip (2.3.7)
rack (1.1.0)
rails (2.3.8)
rake (0.8.7)
tzinfo (0.3.23)
</code>```

There is no where clause for the corresponding user_id. But how to fix it?

Rails Version 2.3.8

Should work like this => http://guides.rubyonrails.org/routing.html 2.7 Nested Resources

Hope somebody can help

答:
Try this </p>

```<code>map.resources :users do |users|
  users.resources :stuffs
end
</code>```

Body:
I have a Problem with Nested Resources.

2 Models

User => has_many :stuffs

Stuff => belongs_to :user

routes.rb

map.resources :stuffs

map.resources :users, :has_many => [:stuffs]

When i call /users/1/stuffs it presents me the Stuff for the corresponding User. but i got this also when i call /users/2/stuffs. It should return 0 "Stuffs" but it dont work.

MySQL Query from Server
SELECT * FROM `stuffs`

rake routes

stuffs GET    /stuffs(.:format)                         {:action=>"index", :controller=>"stuffs"}
                POST   /stuffs(.:format)                         {:action=>"create", :controller=>"stuffs"}
      new_stuff GET    /stuffs/new(.:format)                     {:action=>"new", :controller=>"stuffs"}
     edit_stuff GET    /stuffs/:id/edit(.:format)                {:action=>"edit", :controller=>"stuffs"}
          stuff GET    /stuffs/:id(.:format)                     {:action=>"show", :controller=>"stuffs"}
                PUT    /stuffs/:id(.:format)                     {:action=>"update", :controller=>"stuffs"}
                DELETE /stuffs/:id(.:format)                     {:action=>"destroy", :controller=>"stuffs"}
    user_stuffs GET    /users/:user_id/stuffs(.:format)          {:action=>"index", :controller=>"stuffs"}
                POST   /users/:user_id/stuffs(.:format)          {:action=>"create", :controller=>"stuffs"}
 new_user_stuff GET    /users/:user_id/stuffs/new(.:format)      {:action=>"new", :controller=>"stuffs"}
edit_user_stuff GET    /users/:user_id/stuffs/:id/edit(.:format) {:action=>"edit", :controller=>"stuffs"}
     user_stuff GET    /users/:user_id/stuffs/:id(.:format)      {:action=>"show", :controller=>"stuffs"}
                PUT    /users/:user_id/stuffs/:id(.:format)      {:action=>"update", :controller=>"stuffs"}
                DELETE /users/:user_id/stuffs/:id(.:format)      {:action=>"destroy", :controller=>"stuffs"}
          users GET    /users(.:format)                          {:action=>"index", :controller=>"users"}
                POST   /users(.:format)                          {:action=>"create", :controller=>"users"}
       new_user GET    /users/new(.:format)                      {:action=>"new", :controller=>"users"}
      edit_user GET    /users/:id/edit(.:format)                 {:action=>"edit", :controller=>"users"}
           user GET    /users/:id(.:format)                      {:action=>"show", :controller=>"users"}
                PUT    /users/:id(.:format)                      {:action=>"update", :controller=>"users"}
                DELETE /users/:id(.:format)                      {:action=>"destroy", :controller=>"users"}
           root        /                                         {:action=>"index", :controller=>"users"}

gem list

actionmailer (2.3.8)
actionpack (2.3.8)
activerecord (2.3.8)
activeresource (2.3.8)
activesupport (2.3.8)
arel (2.0.6)
authlogic (2.1.6)
builder (2.1.2)
cgi_multipart_eof_fix (2.5.0)
gem_plugin (0.2.3)
i18n (0.5.0)
mongrel (1.1.5 x86-mingw32)
mysql (2.8.1 x86-mingw32)
paperclip (2.3.7)
rack (1.1.0)
rails (2.3.8)
rake (0.8.7)
tzinfo (0.3.23)

There is no where clause for the corresponding user_id. But how to fix it?

Rails Version 2.3.8

Should work like this => http://guides.rubyonrails.org/routing.html 2.7 Nested Resources

Hope somebody can help

Body:
Try this

map.resources :users do |users|
  users.resources :stuffs
end


问:
Prediction returns NaN?
I'm not sure what data to provide here and cannot provide a means to replicate the issue without sharing my full data. I can only provide the code and error message and hope that someone recognises this.

I have a model that uses ranger random forrest with a log transformed target variable "mod.rangerRF.logknn". My newdata has tens of thousands of records, however when I predict on it a small handful (5 to be exact) return NaN.

This only happens with the log version of the model.

Example with predicting on a single observation:

```<code>predict(mod.rangerRF.logknn, newdata = filter(p.test.knn, id == 31874))
[1] 15.40513
</code>```

A number is returned which I can then back transform. This is the case for all but the 5 problem records which are returning NaN.

```<code>> predict(mod.rangerRF.logknn, newdata = filter(p.test.knn, id == 31873))
[1] NaN
</code>```

A NaN which I cannot back transform.

Tens of thousands of rows, hundreds of features. Only 5 instances of NaN returned when running predict.

I'm not sure where to start in debugging this.

During preprocessing I ensured full data with no missing values. All data are numeric thanks to making use of dummy variables.

Does anyone recognise this problem? Any pointers on where I can look?

Per the comments here is the output of the model

```<code>> print(mod.rangerRF.logknn)
Random Forest

30471 samples
  193 predictor

No pre-processing
Resampling: Cross-Validated (5 fold)
Summary of sample sizes: 24376, 24376, 24378, 24377, 24377
Resampling results across tuning parameters:

  mtry  RMSE       Rsquared
   2    0.5125155  0.2832599
   5    0.4936741  0.3343648
  10    0.4845437  0.3592030
  20    0.4797720  0.3732469
  40    0.4778534  0.3790508

RMSE was used to select the optimal model using  the smallest value.
The final value used for the model was mtry = 40.
</code>```

答:
This issue was just opened on Ranger's github: https://github.com/imbs-hl/ranger/issues/201

Hope that helps.

Title: Prediction returns NaN?

Body:
I'm not sure what data to provide here and cannot provide a means to replicate the issue without sharing my full data. I can only provide the code and error message and hope that someone recognises this.

I have a model that uses ranger random forrest with a log transformed target variable "mod.rangerRF.logknn". My newdata has tens of thousands of records, however when I predict on it a small handful (5 to be exact) return NaN.

This only happens with the log version of the model.

Example with predicting on a single observation:

predict(mod.rangerRF.logknn, newdata = filter(p.test.knn, id == 31874))
[1] 15.40513

A number is returned which I can then back transform. This is the case for all but the 5 problem records which are returning NaN.

> predict(mod.rangerRF.logknn, newdata = filter(p.test.knn, id == 31873))
[1] NaN

A NaN which I cannot back transform.

Tens of thousands of rows, hundreds of features. Only 5 instances of NaN returned when running predict.

I'm not sure where to start in debugging this.

During preprocessing I ensured full data with no missing values. All data are numeric thanks to making use of dummy variables.

Does anyone recognise this problem? Any pointers on where I can look?

Per the comments here is the output of the model

> print(mod.rangerRF.logknn)
Random Forest

30471 samples
  193 predictor

No pre-processing
Resampling: Cross-Validated (5 fold)
Summary of sample sizes: 24376, 24376, 24378, 24377, 24377
Resampling results across tuning parameters:

  mtry  RMSE       Rsquared
   2    0.5125155  0.2832599
   5    0.4936741  0.3343648
  10    0.4845437  0.3592030
  20    0.4797720  0.3732469
  40    0.4778534  0.3790508

RMSE was used to select the optimal model using  the smallest value.
The final value used for the model was mtry = 40.


问:
Kafka Error reading field 'correlation_id': java.nio.BufferUnderflowException
Getting this kafka exception on consumer :

```<code>org.apache.kafka.common.protocol.types.SchemaException: Error reading field 'correlation_id': java.nio.BufferUnderflowException
at org.apache.kafka.common.protocol.types.Schema.read(Schema.java:71)
at org.apache.kafka.common.requests.ResponseHeader.parse(ResponseHeader.java:53)
at org.apache.kafka.clients.NetworkClient.handleCompletedReceives(NetworkClient.java:435)
at org.apache.kafka.clients.NetworkClient.poll(NetworkClient.java:265)
at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.clientPoll(ConsumerNetworkClient.java:320)
at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.poll(ConsumerNetworkClient.java:213)
at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.poll(ConsumerNetworkClient.java:193)
at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.awaitMetadataUpdate(ConsumerNetworkClient.java:134)
at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.ensureCoordinatorKnown(AbstractCoordinator.java:184)
at org.apache.kafka.clients.consumer.KafkaConsumer.pollOnce(KafkaConsumer.java:886)
at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:853)
</code>```

No client-server version mismatch.

答:
Be sure your client connect to a real Kafka port !

this specific error happens while parsing (one of?) the first header field of the expected kafka message, as shown by the invocation of ResponseHeader.java in stack-trace.

So this can occurs if you target a listening port that has nothing to do with kafka server.

just a 1 minute check !

Otherwise, you should check for a client-server version mismatch.

Body:
Getting this kafka exception on consumer :

org.apache.kafka.common.protocol.types.SchemaException: Error reading field 'correlation_id': java.nio.BufferUnderflowException
at org.apache.kafka.common.protocol.types.Schema.read(Schema.java:71)
at org.apache.kafka.common.requests.ResponseHeader.parse(ResponseHeader.java:53)
at org.apache.kafka.clients.NetworkClient.handleCompletedReceives(NetworkClient.java:435)
at org.apache.kafka.clients.NetworkClient.poll(NetworkClient.java:265)
at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.clientPoll(ConsumerNetworkClient.java:320)
at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.poll(ConsumerNetworkClient.java:213)
at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.poll(ConsumerNetworkClient.java:193)
at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.awaitMetadataUpdate(ConsumerNetworkClient.java:134)
at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.ensureCoordinatorKnown(AbstractCoordinator.java:184)
at org.apache.kafka.clients.consumer.KafkaConsumer.pollOnce(KafkaConsumer.java:886)
at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:853)

No client-server version mismatch.


问:
sc is not defined in pyspark
SparkContext function is returning error in pyspark in cmd and Jupyter

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sc' is not defined
</code>```

I have tried:

```<code>>>> from pyspark import SparkContext
>>> sc = SparkContext()
</code>```

But still showing the error:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\spark\python\pyspark\context.py", line 115, in __init__
    SparkContext._ensure_initialized(self, gateway=gateway, conf=conf)
  File "c:\spark\python\pyspark\context.py", line 275, in _ensure_initialized
    callsite.function, callsite.file, callsite.linenum))
**ValueError: Cannot run multiple SparkContexts at once; existing SparkContext(app
=PySparkShell, master=local[*]) created by getOrCreate at c:\spark\bin\..\python
\pyspark\shell.py:43**strong text****
</code>```

How to solve the problem?

答:
It's possible that you had another notebook executing pySpark, you could use  SparkContext.getOrCreate().

Regards.

Title: sc is not defined in pyspark

Body:
SparkContext function is returning error in pyspark in cmd and Jupyter

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sc' is not defined

I have tried:

>>> from pyspark import SparkContext
>>> sc = SparkContext()

But still showing the error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\spark\python\pyspark\context.py", line 115, in __init__
    SparkContext._ensure_initialized(self, gateway=gateway, conf=conf)
  File "c:\spark\python\pyspark\context.py", line 275, in _ensure_initialized
    callsite.function, callsite.file, callsite.linenum))
**ValueError: Cannot run multiple SparkContexts at once; existing SparkContext(app
=PySparkShell, master=local[*]) created by getOrCreate at c:\spark\bin\..\python
\pyspark\shell.py:43**strong text****

How to solve the problem?


问:
Filtering specific lines in csv keeping track of last value
I've got a .csv file with different data formats and I'm trying to operate with the values on the same column.

my csv file is something like this:

```<code>"int","float","stirng", more data
</code>```

Example:

```<code>"2","1.378","Johnny"
"1","1.379","Walker"
"5","1.380","Jack"
"8","1.700","Daniels"
"8","1.710","Baileys"
"8","1.381","Monkey"
"8","1.711","Shoulder"
"8","1.383","Captain"
"8","1.385","Morgan"
"8","1.392","Drinks"
More rows
</code>```

I would like to subtract values in the second column if their difference is >x.
 (only those, I don't care about the others).

My code so far:

```<code>with open ('input.csv', 'r') as file, open ('output.csv', 'w') as f_out:
    readCSV = csv.reader(file)
    writeCSV = csv.writer(f_out, lineterminator='\n')
    last = None

    for row in readCSV:
        datalat = float(row[1])

        if last is not None:
            #print("difference -> %f" %(datalat-last))
            outp = (datalat-last)
            if outp <= 0.02:
                writeCSV.writerow(row)
            last = datalat
</code>```

The output looks like:

```<code>5,1.380,Jack
8,1.710,Baileys
8,1.381,Monkey
8,1.383,Captain
8,1.385,Morgan
8,1.392,Drinks
</code>```

But I would like it to be:

```<code>"2","1.378","Johnny"
"1","1.379","Walker"
"5","1.380","Jack"
"8","1.381","Monkey"
"8","1.383","Captain"
"8","1.385","Morgan"
"8","1.392","Drinks"
</code>```

So what it should do is only write rows that have less than 0.02 difference, IF there is a row with a bigger difference discard it, then compare the next row to the last written row, as opposed to the last discarded row.

答:
Two things:

You should take the absolute value (using abs) of the difference as you don't know apriori which of the two is greater.

Only update last if the condition is fulfilled, so last is never a discarded value.

```<code>last = float(next(readCSV)[1])  # assign first reference value
f_out.seek(0)                   # return to start of file
for row in readCSV:
    datalat = float(row[1])
    diff = abs(datalat-last)
    if diff <= 0.02:
        writeCSV.writerow(row)
        last = datalat
</code>```

Body:
I've got a .csv file with different data formats and I'm trying to operate with the values on the same column.

my csv file is something like this:

"int","float","stirng", more data

Example:

"2","1.378","Johnny"
"1","1.379","Walker"
"5","1.380","Jack"
"8","1.700","Daniels"
"8","1.710","Baileys"
"8","1.381","Monkey"
"8","1.711","Shoulder"
"8","1.383","Captain"
"8","1.385","Morgan"
"8","1.392","Drinks"
More rows

I would like to subtract values in the second column if their difference is >x.
 (only those, I don't care about the others).

My code so far:

with open ('input.csv', 'r') as file, open ('output.csv', 'w') as f_out:
    readCSV = csv.reader(file)
    writeCSV = csv.writer(f_out, lineterminator='\n')
    last = None

    for row in readCSV:
        datalat = float(row[1])

        if last is not None:
            #print("difference -> %f" %(datalat-last))
            outp = (datalat-last)
            if outp <= 0.02:
                writeCSV.writerow(row)
            last = datalat

The output looks like:

5,1.380,Jack
8,1.710,Baileys
8,1.381,Monkey
8,1.383,Captain
8,1.385,Morgan
8,1.392,Drinks

But I would like it to be:

"2","1.378","Johnny"
"1","1.379","Walker"
"5","1.380","Jack"
"8","1.381","Monkey"
"8","1.383","Captain"
"8","1.385","Morgan"
"8","1.392","Drinks"

So what it should do is only write rows that have less than 0.02 difference, IF there is a row with a bigger difference discard it, then compare the next row to the last written row, as opposed to the last discarded row.

Body:
Two things:

You should take the absolute value (using abs) of the difference as you don't know apriori which of the two is greater.

Only update last if the condition is fulfilled, so last is never a discarded value.

last = float(next(readCSV)[1])  # assign first reference value
f_out.seek(0)                   # return to start of file
for row in readCSV:
    datalat = float(row[1])
    diff = abs(datalat-last)
    if diff <= 0.02:
        writeCSV.writerow(row)
        last = datalat