问:
react Error in ./src/App.js 'store' is not defined
attempting to follow this tutorial
https://thinkster.io/tutorials/setting-up-react-redux/introducing-react-redux

App.js file-

```<code>import React from 'react';
import { connect } from 'react-redux';

const mapStateToProps = state => ({
  appName: state.appName
});

class App extends React.Component {
  render() {
    const onClick = () => store.dispatch({ type: 'TOGGLE' });
    return (
      <div>
        { this.props.appName }
      </div>
    );
  }
}

export default connect(mapStateToProps, () => ({}))(App);
</code>```

according to the video, by importing the connect function and defining mapStateToProps we will get access to store. it does not work.

also, the code in the video is different from the code in the guide.
so at this point i'm not sure if i'm doing something incorrectly, or if this guide is just bad. can anyone suggest a better guide for learning react?

full error message-

Failed to compile.

Error in ./src/App.js

c:\Sites\react_frontend\django-frontend\src\App.js

14:11  warning  'onClick' is assigned a value but never used  no-unused-vars

14:27  error    'store' is not defined                        no-undef

✖ 2 problems (1 error, 1 warning)

答:
I am also using Thinkster and the line below worked for me. I found that there is no need to provide the empty object at all.

```<code>export default connect(mapStateToProps)(App);
</code>```

I agree with you that the react redux tutorial is quite poorly done. I found that the Backend Tutorials(Express and mongo) was a lot more cohesive than the front end. The tutorials linked together well and each one started where the other left off.

Body:
attempting to follow this tutorial
https://thinkster.io/tutorials/setting-up-react-redux/introducing-react-redux

App.js file-

import React from 'react';
import { connect } from 'react-redux';

const mapStateToProps = state => ({
  appName: state.appName
});

class App extends React.Component {
  render() {
    const onClick = () => store.dispatch({ type: 'TOGGLE' });
    return (

        { this.props.appName }

    );
  }
}

export default connect(mapStateToProps, () => ({}))(App);

according to the video, by importing the connect function and defining mapStateToProps we will get access to store. it does not work.

also, the code in the video is different from the code in the guide.
so at this point i'm not sure if i'm doing something incorrectly, or if this guide is just bad. can anyone suggest a better guide for learning react?

full error message-

Failed to compile.

Error in ./src/App.js

c:\Sites\react_frontend\django-frontend\src\App.js

14:11  warning  'onClick' is assigned a value but never used  no-unused-vars

14:27  error    'store' is not defined                        no-undef

✖ 2 problems (1 error, 1 warning)

Body:
I am also using Thinkster and the line below worked for me. I found that there is no need to provide the empty object at all.

export default connect(mapStateToProps)(App);

I agree with you that the react redux tutorial is quite poorly done. I found that the Backend Tutorials(Express and mongo) was a lot more cohesive than the front end. The tutorials linked together well and each one started where the other left off.


来源: stackexchange

问:
Import Error : Calling python script from shell
I want to run my python script from a shell.

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

import subprocess
import time

from path.to.my.function1 import function1
from path.to.my.function2 import function2

  #some code here

if __name__ == "__main__":
</code>```

From my shell command, I want to run it like this:

```<code>./myPythonScript.py
</code>```

The result is :

```<code>ImportError: No module named path.to.my.function1
</code>```

When I run it from Eclipse for example, I don't have any errors. I have some empty _ init _.py files in my directories.

I don't want to add

```<code>sys.path.append(0, /path/to/my/function1)
</code>```

because it needs to be easily exportable. Also I don't want to add my file path to the source folder of PYTHONPATH. It needs to be plug and play.

I don't know if i have a different compiler or I should modify my #! /usr/bin/python. Or could it be my PYTHONPATH ?

答:
You can make your code a python package and then you will be able to do so.
Simply add __init__.py script to the directory and add a __main__.py script to your directory. In the __main__.py
 add the code you do after if __name__ == '__main__'.
For import add the following line:
    from .path.to.my.script import foo

Finally, run python -m < directory name >. Outside your package directory.

ContentLicense: CC BY-SA 3.0

Body:
I want to run my python script from a shell.

#! /usr/bin/python

import subprocess
import time

from path.to.my.function1 import function1
from path.to.my.function2 import function2

  #some code here

if __name__ == "__main__":

From my shell command, I want to run it like this:

./myPythonScript.py

The result is :

ImportError: No module named path.to.my.function1

When I run it from Eclipse for example, I don't have any errors. I have some empty _ init _.py files in my directories.

I don't want to add

sys.path.append(0, /path/to/my/function1)

because it needs to be easily exportable. Also I don't want to add my file path to the source folder of PYTHONPATH. It needs to be plug and play.

I don't know if i have a different compiler or I should modify my #! /usr/bin/python. Or could it be my PYTHONPATH ?


问:
Using an array as a property in Access VBA
Folks,

I am trying to write a class module in VBA that reads some file names from an Access database so that they can be imported into the same database. I have written several class modules for this database already and they seem to work. However, this module has an array of type clsImportFile that I am trying to use as a property. The actual error that exists is

Run-Time error '438': Object doesn't support this property or method

Here is the clsFileProcessor definition:

```<code>Option Compare Database
Option Explicit

Private pFiles As Variant
Private pIndex As Long
Private pSize As Long

Property Get Files() As Variant
    Files = pFiles
End Property

Property Let Files(f As Variant)
    pFiles = f
End Property

Property Get Index() As Long
    Index = pIndex
End Property

Property Let Index(i As Long)
    pIndex = i
End Property

Property Get Size() As Long
    Size = pSize
End Property

Property Let Size(s As Long)
    pSize = s
End Property

Public Sub Initialize()
    Dim FileArray() As Variant
    ReDim FileArray(Size) As Variant
    Files = FileArray()
End Sub

Public Sub IncrementIndex()
    pIndex = pIndex + 1
End Sub

Public Sub IncrementSize()
    Dim newSize As Integer
    newSize = pSize + 10
    Dim newFiles() As Variant
    ReDim newFiles(newSize) As Variant
    Dim i As Integer
    For i = 0 To Index
        newFiles(i) = pFiles(i)
    Next i
    Files = newFiles()
End Sub

Public Sub AddImportHistory(ih As clsImportHistory)
    If Index + 1 = Size Then
        IncrementSize
    Else
        Files(Index) = ih
        IncrementIndex
    End If
End Sub
</code>```

Here is the Create sub from my factory:

```<code>Public Function CreateFileProcessor() As clsFileProcessor
    Set CreateFileProcessor = New clsFileProcessor
    CreateFileProcessor.Index = 0
    CreateFileProcessor.Size = 10
    CreateFileProcessor.Initialize
End Function
</code>```

Finally, here is the test sub:

```<code>Public Sub TestFileProcessor()
    Dim fp1 As clsFileProcessor
    Set fp1 = CreateFileProcessor()
    Debug.Assert fp1.Index = 0
    Debug.Assert fp1.Size = 10
    Dim ih1 As clsImportHistory
    Set ih1 = CreateImportHistory(i:=3425)
    Dim ih2 As clsImportHistory
    Set ih2 = CreateImportHistory(i:=3426)
    fp1.AddImportHistory (ih1)
    Debug.Assert False
End Sub
</code>```

The line fp1.AddImportHistory (ih1) is what is pointed to on the error but I suspect that it has to do with the array.

EDIT:
I found by commenting out everything in clsFileProcessor.AddImportHistory then systematically un-commenting lines that the issue is with the assignment to the Files property. I am Dimming the Files property as a Variant. Is that my issue? I am using the Variant type because I am not sure how to define a property that returns or sets an array.

答:
I got side tracked for a few days but when I came back to this I figured out that I needed to change

```<code>fp1.AddImportHistory (ih1)
</code>```

to

```<code>Call fp1.AddImportHistory (ih1)
</code>```

The trouble is I knew that and just glossed over it.

Body:
Folks,

I am trying to write a class module in VBA that reads some file names from an Access database so that they can be imported into the same database. I have written several class modules for this database already and they seem to work. However, this module has an array of type clsImportFile that I am trying to use as a property. The actual error that exists is

Run-Time error '438': Object doesn't support this property or method

Here is the clsFileProcessor definition:

Option Compare Database
Option Explicit

Private pFiles As Variant
Private pIndex As Long
Private pSize As Long

Property Get Files() As Variant
    Files = pFiles
End Property

Property Let Files(f As Variant)
    pFiles = f
End Property

Property Get Index() As Long
    Index = pIndex
End Property

Property Let Index(i As Long)
    pIndex = i
End Property

Property Get Size() As Long
    Size = pSize
End Property

Property Let Size(s As Long)
    pSize = s
End Property

Public Sub Initialize()
    Dim FileArray() As Variant
    ReDim FileArray(Size) As Variant
    Files = FileArray()
End Sub

Public Sub IncrementIndex()
    pIndex = pIndex + 1
End Sub

Public Sub IncrementSize()
    Dim newSize As Integer
    newSize = pSize + 10
    Dim newFiles() As Variant
    ReDim newFiles(newSize) As Variant
    Dim i As Integer
    For i = 0 To Index
        newFiles(i) = pFiles(i)
    Next i
    Files = newFiles()
End Sub

Public Sub AddImportHistory(ih As clsImportHistory)
    If Index + 1 = Size Then
        IncrementSize
    Else
        Files(Index) = ih
        IncrementIndex
    End If
End Sub

Here is the Create sub from my factory:

Public Function CreateFileProcessor() As clsFileProcessor
    Set CreateFileProcessor = New clsFileProcessor
    CreateFileProcessor.Index = 0
    CreateFileProcessor.Size = 10
    CreateFileProcessor.Initialize
End Function

Finally, here is the test sub:

Public Sub TestFileProcessor()
    Dim fp1 As clsFileProcessor
    Set fp1 = CreateFileProcessor()
    Debug.Assert fp1.Index = 0
    Debug.Assert fp1.Size = 10
    Dim ih1 As clsImportHistory
    Set ih1 = CreateImportHistory(i:=3425)
    Dim ih2 As clsImportHistory
    Set ih2 = CreateImportHistory(i:=3426)
    fp1.AddImportHistory (ih1)
    Debug.Assert False
End Sub

The line fp1.AddImportHistory (ih1) is what is pointed to on the error but I suspect that it has to do with the array.

EDIT:
I found by commenting out everything in clsFileProcessor.AddImportHistory then systematically un-commenting lines that the issue is with the assignment to the Files property. I am Dimming the Files property as a Variant. Is that my issue? I am using the Variant type because I am not sure how to define a property that returns or sets an array.

Body:
I got side tracked for a few days but when I came back to this I figured out that I needed to change

fp1.AddImportHistory (ih1)

to

Call fp1.AddImportHistory (ih1)

The trouble is I knew that and just glossed over it.


问:
HTML display image on top-left of page
I want to display an image on the top-left corner of my page. There should be a space of 10 pixels to the top and a space of 10 pixels to the left. I searched the web and found two possible answers. The first one uses the margin property while the second top and left with position: absolute;:

```<code><body>
<img src="x.jpg" style="margin-top: 10px; margin-left: 10px;">
</body>
</code>```

and

```<code><body>
<img src="x.jpg" style="top: 10px; left: 10px; position: absolute;">
</body>
</code>```

Both seem to work but is there any difference between them? Which one should I use?

答:
I would recommend the first option because you won't have to worry about it's absolute position in the future.
As an example, if you go for the 2nd option, other ellements will go in it and you will have to give them margins.
I hope this helped you !</p>

Title: HTML display image on top-left of page

Body:
I want to display an image on the top-left corner of my page. There should be a space of 10 pixels to the top and a space of 10 pixels to the left. I searched the web and found two possible answers. The first one uses the margin property while the second top and left with position: absolute;:

and

Both seem to work but is there any difference between them? Which one should I use?


问:
Create a development environment for Laravel in Docker
I have a custom Laravel installation on my Ubuntu machine. As per Laravel's instructions however, I didn't use Homestead to spin up my app. Instead I installed the app using composer on my machine and then installed the dependencies and libraries as per the requirement.

Now I want to use another machine for development. How's it possible using Docker to package a replica of my machine's environment to create a container to be used on the other machine. I am new to Docker and haven't used it before for whatsoever reasons.

答:
I created a barebones Docker Compose repo  that can be used for Laravel or as a LAMP Server and it comes with:

Apache

PHP

MySQL

Composer

PHPMyAdmin

Most of the ones I came across are pretty bloated with stuff that I didn't need.


问:
Cast from List to List when B extends A
I have two clases:

```<code>public class A {
   //attibutes and methods
}

public class B extends A {
   //atributes and methods
}
</code>```

Now I have a service that returns a List with elements of type A. Lets call it generateAElements();

I want to call that method, filter the List obtained to only keep the elements of type B, which also are of type A.

```<code>List<A> listA = generateAElements();
List<A> listAA = listA.filter( p -> p instanceof B).collect(Collectors.toList());
List<B> listB = new ArrayList<>();
// need to create a new list, iterate overListA and add elements of type B?
for (A itemA : listA) {
    listB.add((B) itemA);
}
</code>```

Is there an efficient way to do this?

Important: The list may contain a large number of elements.

答:
Assuming you're using Java 8+, you could use streams:

```<code>List<B> listB = listA
    .stream()
    .filter(B.class::isInstance)
    .map(B.class::cast)
    .collect(Collectors.toList());
</code>```

Of course, this is doable in earlier Java versions, it's just likely to be more verbose.

A note on terminology: This is not "casting from List to List" - the only things being cast here are individual entries.

Title: Cast from List<A> to List<B> when B extends A

Body:
I have two clases:

public class A {
   //attibutes and methods
}

public class B extends A {
   //atributes and methods
}

Now I have a service that returns a List with elements of type A. Lets call it generateAElements();

I want to call that method, filter the List obtained to only keep the elements of type B, which also are of type A.

List listA = generateAElements();
List listAA = listA.filter( p -> p instanceof B).collect(Collectors.toList());
List listB = new ArrayList<>();
// need to create a new list, iterate overListA and add elements of type B?
for (A itemA : listA) {
    listB.add((B) itemA);
}

Is there an efficient way to do this?

Important: The list may contain a large number of elements.

Body:
Assuming you're using Java 8+, you could use streams:

List<B> listB = listA
    .stream()
    .filter(B.class::isInstance)
    .map(B.class::cast)
    .collect(Collectors.toList());

Of course, this is doable in earlier Java versions, it's just likely to be more verbose.

A note on terminology: This is not "casting from List<A> to List<B>" - the only things being cast here are individual entries.


问:
best way to sum up Matrix elements parallel in c#
What is the fastest most efficient way to sumUp all matrix elements parallel in .net 4.0 ?

using Parallel.For end in inner loop making lock(objectLock) { result += matrix[i, j] } is 2 times slowwer then sequential approach.

thanks for any hints,
bye

答: Use static variables for i,j and result without using lock</p>

ContentLicense: CC BY-SA 2.5


问:
Row wise operations in R
I have a dataframe with following layout:

```<code>id |diff
----
1 | 0
1 | 3
1 | 45
1 | 9
1 | 40
1 | 34
1 | 43
1 | 7
2 | 0
2 | 5
3 | 0
3 | 45
3 | 40
</code>```

I need to add a counter in a such a way that :

when the id changes the counter should reset to 1

when the id is same and the diff is less than 10 the counter shall give the preceding counter value.

when the id is same and the diff is greater than 10 the counter shall be incremented by +1.

The output I am looking for is :

```<code>id |diff | counter
-------------
1 | 0 | 1
1 | 3 | 1
1 | 45 | 2
1 | 9 |  2
1 | 40 | 3
1 | 34 | 4
1 | 43 | 5
1 | 7  | 5
2 | 0  | 1
2 | 5  | 1
3 | 0  | 1
3 | 45 | 2
3 | 40 | 3
</code>```

The for loop solution is :

```<code>for(i in 2:nrow(raw_data)){
  raw_data$counter[i]<- ifelse(raw_data$id[i]==raw_data$id[i-1],
        ifelse(raw_data$diff> 10,raw_data$counter[i-1] +1,raw_data$counter[i-1])
          ,1)}
</code>```

I am aware of the increase in time due to 'for' loop. Looking for a faster way.

答:
As the OP is looking for a faster way, here is a benchmark comparison of P Lapointe's dplyr solution and a data.table version.

The data.table version is a re-write of P Lapointe's approach in data.table syntax:

```<code>library(data.table)   # CRAN version 1.10.4 used
DT <- fread(
"id |diff
1 | 0
1 | 3
1 | 45
1 | 9
1 | 40
1 | 34
1 | 43
1 | 7
2 | 0
2 | 5
3 | 0
3 | 45
3 | 40"
, sep = "|")

DT[, counter := cumsum(diff > 10L) + 1L, id]

DT
#    id diff counter
# 1:  1    0       1
# 2:  1    3       1
# 3:  1   45       2
# 4:  1    9       2
# 5:  1   40       3
# 6:  1   34       4
# 7:  1   43       5
# 8:  1    7       5
# 9:  2    0       1
#10:  2    5       1
#11:  3    0       1
#12:  3   45       2
#13:  3   40       3
</code>```

Benchmark

For benchmarking, a larger data set of 130'000 rows is created:

```<code># copy original data set 10000 times
DTlarge <- rbindlist(lapply(seq_len(10000L), function(x) DT))
# make id column unique again
DTlarge[, id := rleid(id)]
dim(DTlarge)
#[1] 130000      2
</code>```

Timing is done by the mircobenchmark package:

```<code>df1 <- as.data.frame(DTlarge)
dt1 <- copy(DTlarge)
library(dplyr)
microbenchmark::microbenchmark(
  dplyr = {
    df1%>%
      group_by(id)%>%
      mutate(counter=cumsum(diff>10)+1)
  },
  dt = {
    dt1[, counter := cumsum(diff > 10L) + 1L, id]
  },
  times = 10L
)
</code>```

The results show that the data.table version is about 20 times faster for this problem size:

```<code>Unit: milliseconds
  expr       min        lq      mean    median        uq      max neval
 dplyr 500.51729 505.50173 512.25642 509.64096 517.31095 535.2736    10
    dt  23.06037  23.99073  25.30913  24.71059  25.98322  30.7868    10
</code>```

Title: Row wise operations in R

Body:
I have a dataframe with following layout:

id |diff
----
1 | 0
1 | 3
1 | 45
1 | 9
1 | 40
1 | 34
1 | 43
1 | 7
2 | 0
2 | 5
3 | 0
3 | 45
3 | 40

I need to add a counter in a such a way that :

when the id changes the counter should reset to 1

when the id is same and the diff is less than 10 the counter shall give the preceding counter value.

when the id is same and the diff is greater than 10 the counter shall be incremented by +1.

The output I am looking for is :

id |diff | counter
-------------
1 | 0 | 1
1 | 3 | 1
1 | 45 | 2
1 | 9 |  2
1 | 40 | 3
1 | 34 | 4
1 | 43 | 5
1 | 7  | 5
2 | 0  | 1
2 | 5  | 1
3 | 0  | 1
3 | 45 | 2
3 | 40 | 3

The for loop solution is :

for(i in 2:nrow(raw_data)){
  raw_data$counter[i]<- ifelse(raw_data$id[i]==raw_data$id[i-1],
        ifelse(raw_data$diff> 10,raw_data$counter[i-1] +1,raw_data$counter[i-1])
          ,1)}

I am aware of the increase in time due to 'for' loop. Looking for a faster way.

Body:
As the OP is looking for a faster way, here is a benchmark comparison of P Lapointe's dplyr solution and a data.table version.

The data.table version is a re-write of P Lapointe's approach in data.table syntax:

library(data.table)   # CRAN version 1.10.4 used
DT <- fread(
"id |diff
1 | 0
1 | 3
1 | 45
1 | 9
1 | 40
1 | 34
1 | 43
1 | 7
2 | 0
2 | 5
3 | 0
3 | 45
3 | 40"
, sep = "|")

DT[, counter := cumsum(diff > 10L) + 1L, id]

DT
#    id diff counter
# 1:  1    0       1
# 2:  1    3       1
# 3:  1   45       2
# 4:  1    9       2
# 5:  1   40       3
# 6:  1   34       4
# 7:  1   43       5
# 8:  1    7       5
# 9:  2    0       1
#10:  2    5       1
#11:  3    0       1
#12:  3   45       2
#13:  3   40       3

Benchmark

For benchmarking, a larger data set of 130'000 rows is created:

# copy original data set 10000 times
DTlarge <- rbindlist(lapply(seq_len(10000L), function(x) DT))
# make id column unique again
DTlarge[, id := rleid(id)]
dim(DTlarge)
#[1] 130000      2

Timing is done by the mircobenchmark package:

df1 <- as.data.frame(DTlarge)
dt1 <- copy(DTlarge)
library(dplyr)
microbenchmark::microbenchmark(
  dplyr = {
    df1%>%
      group_by(id)%>%
      mutate(counter=cumsum(diff>10)+1)
  },
  dt = {
    dt1[, counter := cumsum(diff > 10L) + 1L, id]
  },
  times = 10L
)

The results show that the data.table version is about 20 times faster for this problem size:

Unit: milliseconds
  expr       min        lq      mean    median        uq      max neval
 dplyr 500.51729 505.50173 512.25642 509.64096 517.31095 535.2736    10
    dt  23.06037  23.99073  25.30913  24.71059  25.98322  30.7868    10


问:
mysqlclient pip failure on Linux
I'm working on a Python3.4/Django project (on CentOS 6.8x64) and am trying to install the mysqlclient driver. Despite hours of googling I can't figure out how to sort out what looks like a compile error during install.

As far as I can tell I have all the necessary library packages installed but so far no luck. Here's the output (sorry for the verbosity):

```<code>$ sudo pip3 install mysqlclient
Collecting mysqlclient
  Using cached mysqlclient-1.3.10.tar.gz
Installing collected packages: mysqlclient
  Running setup.py install for mysqlclient ... error
    Complete output from command /usr/bin/python3.4 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-qqqgbh_2/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-cwqrqsw1-record/install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_py
    creating build
    creating build/lib.linux-x86_64-3.4
    copying _mysql_exceptions.py -> build/lib.linux-x86_64-3.4
    creating build/lib.linux-x86_64-3.4/MySQLdb
    copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.4/MySQLdb
    copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.4/MySQLdb
    copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.4/MySQLdb
    copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.4/MySQLdb
    copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.4/MySQLdb
    copying MySQLdb/release.py -> build/lib.linux-x86_64-3.4/MySQLdb
    copying MySQLdb/times.py -> build/lib.linux-x86_64-3.4/MySQLdb
    creating build/lib.linux-x86_64-3.4/MySQLdb/constants
    copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.4/MySQLdb/constants
    copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.4/MySQLdb/constants
    copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.4/MySQLdb/constants
    copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.4/MySQLdb/constants
    copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.4/MySQLdb/constants
    copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.4/MySQLdb/constants
    copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-3.4/MySQLdb/constants
    running build_ext
    building '_mysql' extension
    creating build/temp.linux-x86_64-3.4
    gcc -pthread -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -Dversion_info=(1,3,10,'final',0) -D__version__=1.3.10 -I/usr/include/mysql -I/usr/include/python3.4m -c _mysql.c -o build/temp.linux-x86_64-3.4/_mysql.o
    _mysql.c: In function ‘_mysql_ConnectionObject_ping’:
    _mysql.c:1911: error: ‘MYSQL’ has no member named ‘reconnect’
    error: command 'gcc' failed with exit status 1

    ----------------------------------------
Command "/usr/bin/python3.4 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-qqqgbh_2/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-cwqrqsw1-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-qqqgbh_2/mysqlclient/
</code>```

答:
i guess you need to install mysql-devel or mariadb-devel (if that is already available on centos 6) in order to compile.</p>

```<code>yum install mysql-devel
</code>```

Title: mysqlclient pip failure on Linux

Body:
I'm working on a Python3.4/Django project (on CentOS 6.8x64) and am trying to install the mysqlclient driver. Despite hours of googling I can't figure out how to sort out what looks like a compile error during install.

As far as I can tell I have all the necessary library packages installed but so far no luck. Here's the output (sorry for the verbosity):

$ sudo pip3 install mysqlclient
Collecting mysqlclient
  Using cached mysqlclient-1.3.10.tar.gz
Installing collected packages: mysqlclient
  Running setup.py install for mysqlclient ... error
    Complete output from command /usr/bin/python3.4 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-qqqgbh_2/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-cwqrqsw1-record/install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_py
    creating build
    creating build/lib.linux-x86_64-3.4
    copying _mysql_exceptions.py -> build/lib.linux-x86_64-3.4
    creating build/lib.linux-x86_64-3.4/MySQLdb
    copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.4/MySQLdb
    copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.4/MySQLdb
    copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.4/MySQLdb
    copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.4/MySQLdb
    copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.4/MySQLdb
    copying MySQLdb/release.py -> build/lib.linux-x86_64-3.4/MySQLdb
    copying MySQLdb/times.py -> build/lib.linux-x86_64-3.4/MySQLdb
    creating build/lib.linux-x86_64-3.4/MySQLdb/constants
    copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.4/MySQLdb/constants
    copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.4/MySQLdb/constants
    copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.4/MySQLdb/constants
    copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.4/MySQLdb/constants
    copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.4/MySQLdb/constants
    copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.4/MySQLdb/constants
    copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-3.4/MySQLdb/constants
    running build_ext
    building '_mysql' extension
    creating build/temp.linux-x86_64-3.4
    gcc -pthread -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -Dversion_info=(1,3,10,'final',0) -D__version__=1.3.10 -I/usr/include/mysql -I/usr/include/python3.4m -c _mysql.c -o build/temp.linux-x86_64-3.4/_mysql.o
    _mysql.c: In function ‘_mysql_ConnectionObject_ping’:
    _mysql.c:1911: error: ‘MYSQL’ has no member named ‘reconnect’
    error: command 'gcc' failed with exit status 1

    ----------------------------------------
Command "/usr/bin/python3.4 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-qqqgbh_2/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-cwqrqsw1-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-qqqgbh_2/mysqlclient/

Body:
i guess you need to install mysql-devel or mariadb-devel (if that is already available on centos 6) in order to compile.

yum install mysql-devel


问:
Is there an equivalent of SQL NULLIF function in c#?
Is there an equivalent of SQL NULLIF function built-in within c#?

Example of what it could look like :

```<code>double? result
double denominator = 0;
double Numerator = 100;
result = Numerator / NullIf(denominator, 0);
result = Numerator / denominator.NullIf(0);
result = Numerator / Object.NullIf(denominator, 0);
</code>```

答:
Why do we assume this extension method is able to know what is null in our context.

Its the responsibility of the context that calls it.
Therefore is a mistake of saying only one value will be considered null as all the response in this thread impliy.

```<code>public static T? NullIf<T>(this T value, Func<T,bool> isConsideredNull)
{
        if(value == null)
        {
           return null;
        }
        return isConsideredNull(value) ? (T?)null : value;
}
</code>```

We would use it the following way

```<code>string test = "NULL";

test.NullIf((x)=> x.Equals("NULL"));
test.NullIf((x)=> x == "NULL");
test.NullIf((x)=> x.Equals("NULL",StringComparison.InvariantCultureIgnoreCase));
</code>```

Body:
Is there an equivalent of SQL NULLIF function built-in within c#?

Example of what it could look like :

double? result
double denominator = 0;
double Numerator = 100;
result = Numerator / NullIf(denominator, 0);
result = Numerator / denominator.NullIf(0);
result = Numerator / Object.NullIf(denominator, 0);

Body:
Why do we assume this extension method is able to know what is null in our context.

Its the responsibility of the context that calls it.
Therefore is a mistake of saying only one value will be considered null as all the response in this thread impliy.

public static T? NullIf<T>(this T value, Func<T,bool> isConsideredNull)
{
        if(value == null)
        {
           return null;
        }
        return isConsideredNull(value) ? (T?)null : value;
}

We would use it the following way

string test = "NULL";

test.NullIf((x)=> x.Equals("NULL"));
test.NullIf((x)=> x == "NULL");
test.NullIf((x)=> x.Equals("NULL",StringComparison.InvariantCultureIgnoreCase));


问:
How to create multiple nodes with cypher in neo4j
I would like to create multiple disconnected nodes using a single cypher query

The documentation says:

Create multiple nodes with a parameter for their properties. By providing Cypher an array of maps, it will create a node for each map.

```<code>CREATE (n { props })
RETURN n
</code>```

In the neo4j rest web console I tried (amongst many other things)

```<code>CREATE (n [{a:1,b:2}, {a:1,b:2}]) RETURN n
</code>```

But receive this error

Invalid input '[': expected whitespace, comment, node labels, MapLiteral, a parameter, ')' or a relationship pattern (line 1, column 11)
  "CREATE (n [{a:1,b:2}, {a:1,b:2}]) RETURN n"

Is it possible to do what I am trying and if so how?

答:
I tried the answer from Michael Hunger, but it didnt work. Older version perhaps? I'm using 3.1.3

Here's what worked for me

```<code>UNWIND {props} AS map
CREATE (n)
SET n = map
</code>```

where you need to pass {props} as the parameter to the java api

Here's a quick example in Groovy:

```<code>List<Map<String, String>> props = list.collect{ C c -> ["name": c.name] }
neo4jOperations.query("unwind {props} as map create (c) set c = map", ["props": props])
</code>```

Body:
I would like to create multiple disconnected nodes using a single cypher query

The documentation says:

Create multiple nodes with a parameter for their properties. By providing Cypher an array of maps, it will create a node for each map.

CREATE (n { props })
RETURN n

In the neo4j rest web console I tried (amongst many other things)

CREATE (n [{a:1,b:2}, {a:1,b:2}]) RETURN n

But receive this error

Invalid input '[': expected whitespace, comment, node labels, MapLiteral, a parameter, ')' or a relationship pattern (line 1, column 11)
  "CREATE (n [{a:1,b:2}, {a:1,b:2}]) RETURN n"

Is it possible to do what I am trying and if so how?

Body:
I tried the answer from Michael Hunger, but it didnt work. Older version perhaps? I'm using 3.1.3

Here's what worked for me

UNWIND {props} AS map
CREATE (n)
SET n = map

where you need to pass {props} as the parameter to the java api

Here's a quick example in Groovy:

List<Map<String, String>> props = list.collect{ C c -> ["name": c.name] }
neo4jOperations.query("unwind {props} as map create (c) set c = map", ["props": props])


问:
react native bind this undefined function
I am trying to set state after socket on function but

```<code>componentWillMount() {
socket.on('foo', function(msg){
//alert(JSON.stringify(msg));
//this.setState({user:msg});
this.setState({veri:msg});
this.setState({initial:msg});

});
</code>```

undefined is not a function (evaluating 'this.setState({ veri: msg
  })')
      index.android.js:95:14 emit
      index.js:133:25 onevent
      socket.js:270:15 onpacket
      socket.js:228:19
      index.js:21:20 emit
      index.js:133:25 ondecoded
      manager.js:345:12
      index.js:21:20 emit
      index.js:133:25 add
      index.js:241:16 ondata
      manager.js:335:19
      index.js:21:20 emit
      index.js:133:25 onPacket
      socket.js:457:18
      socket.js:274:18 emit
      index.js:133:25 onPacket
      transport.js:145:12 onData
      transport.js:137:16 onmessage
      websocket.js:147:16 dispatchEvent
      event-target.js:172:43
      WebSocket.js:148:27 emit
      EventEmitter.js:182:12
  __callFunction
      MessageQueue.js:250:47
      MessageQueue.js:101:26
  __guard
      MessageQueue.js:218:6 callFunctionReturnFlushedQueue
      MessageQueue.js:100:17

答:
While it's not possible to tell conclusively from the small chunk of code you provided, it's likely that this inside of socket.on is referring to the socket, not React.

You could either try using an arrow function:

```<code>socket.on('foo', msg => {
    this.setState({veri:msg});
    this.setState({initial:msg});
});
</code>```

You could also set this to something (like self) before calling socket, then use self instead of this inside:

```<code>const self = this;
socket.on('foo', function(msg){
    this.setState({veri:msg});
    this.setState({initial:msg});
});
</code>```

You could also define the function outside the handler, and bind it to this:

```<code>const handleFoo = (function(msg){
    this.setState({veri:msg});
    this.setState({initial:msg});
}).bind(this);

socket.on('foo', handleFoo);
</code>```

All three of those are ways to keep this what you expect and not let it change inside of another context.

Body:
I am trying to set state after socket on function but

componentWillMount() {
socket.on('foo', function(msg){
//alert(JSON.stringify(msg));
//this.setState({user:msg});
this.setState({veri:msg});
this.setState({initial:msg});

});

undefined is not a function (evaluating 'this.setState({ veri: msg
  })')
      index.android.js:95:14 emit
      index.js:133:25 onevent
      socket.js:270:15 onpacket
      socket.js:228:19
      index.js:21:20 emit
      index.js:133:25 ondecoded
      manager.js:345:12
      index.js:21:20 emit
      index.js:133:25 add
      index.js:241:16 ondata
      manager.js:335:19
      index.js:21:20 emit
      index.js:133:25 onPacket
      socket.js:457:18
      socket.js:274:18 emit
      index.js:133:25 onPacket
      transport.js:145:12 onData
      transport.js:137:16 onmessage
      websocket.js:147:16 dispatchEvent
      event-target.js:172:43
      WebSocket.js:148:27 emit
      EventEmitter.js:182:12
  __callFunction
      MessageQueue.js:250:47
      MessageQueue.js:101:26
  __guard
      MessageQueue.js:218:6 callFunctionReturnFlushedQueue
      MessageQueue.js:100:17

Body:
While it's not possible to tell conclusively from the small chunk of code you provided, it's likely that this inside of socket.on is referring to the socket, not React.

You could either try using an arrow function:

socket.on('foo', msg => {
    this.setState({veri:msg});
    this.setState({initial:msg});
});

You could also set this to something (like self) before calling socket, then use self instead of this inside:

const self = this;
socket.on('foo', function(msg){
    this.setState({veri:msg});
    this.setState({initial:msg});
});

You could also define the function outside the handler, and bind it to this:

const handleFoo = (function(msg){
    this.setState({veri:msg});
    this.setState({initial:msg});
}).bind(this);

socket.on('foo', handleFoo);

All three of those are ways to keep this what you expect and not let it change inside of another context.


问:
How to clear input field whitespace in live ajax search after I click on a result
I have a simple ajax live search script using PHP jQuery and ajax. It all works great but the input box does not clear completely so the results box doesn't disappear unless I manually clear it..

JS -

```<code><script type="text/javascript">
        $(document).ready(function(){
            $('.search-box input[type="text"]').on("keyup input", function(){
                /* Get input value on change */
                var inputVal = $(this).val();
                var resultDropdown = $(this).siblings(".result");
                if(inputVal.length){
                    $.get("backend-search.php", {term: inputVal}).done(function(data){
                        // Display the returned data in browser
                        resultDropdown.html(data);
                    });

                } else{
                    resultDropdown.empty();
                }
            });

            // Set search input value on click of result item
            $(document).on("click", ".result", function(){
                $(this).parents(".search-box").find('input[type="text"]').val($(this).text());
                $(this).parent(".result").empty();

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

PHP -

```<code>$user = $_GET['user'];

$term = mysqli_real_escape_string($conn, $_REQUEST['term']);
if(isset($term)){
// Attempt select query execution
$sql = "SELECT * FROM prospects WHERE dealer_name LIKE '" . $term . "%'";
if($result = mysqli_query($conn, $sql)){
    if(mysqli_num_rows($result) > 0){
        while($row = mysqli_fetch_array($result)){
            $dealer_name = $row['dealer_name'];
            echo "<form method='post' class='editForm'>
             <input type='hidden' name='dealer' value='$dealer_name'/>
                        <input type='submit' id='subDealer' value='$dealer_name'/>
                    </form>";
        }
        // Close result set
    } else{
        echo "<p>No matches found</p>";
    }
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
}
</code>```

HTML -

```<code> <div class="search-box">
     <input type="text" id="searchBox" autocomplete="off" placeholder="Search dealer..." />
     <div class="result"></div>
 </div>
</code>```

Like it said it all works but there is blank whitespace in the input field (#searchBox) which will not allow the .result to clear..

Thanks!

答:
Try the below snippet</p>

```<code>// Set search input value on click of result item
$(document).on("click", ".result", function(){
    $(this).parents(".search-box").find('input[type="text"]').val($(this).text().trim());
});

$(document).on('click', 'input[type=submit]', function() {
   // This is NOT the best practice. But it works. Try to change your implementation to a better one!
   setTimeout(function() {
       $('.result').empty();
   }, 1000);
   return true;
}
</code>```

Body:
I have a simple ajax live search script using PHP jQuery and ajax. It all works great but the input box does not clear completely so the results box doesn't disappear unless I manually clear it..

JS -

PHP -

$user = $_GET['user'];

$term = mysqli_real_escape_string($conn, $_REQUEST['term']);
if(isset($term)){
// Attempt select query execution
$sql = "SELECT * FROM prospects WHERE dealer_name LIKE '" . $term . "%'";
if($result = mysqli_query($conn, $sql)){
    if(mysqli_num_rows($result) > 0){
        while($row = mysqli_fetch_array($result)){
            $dealer_name = $row['dealer_name'];
            echo "<form method='post' class='editForm'>
             <input type='hidden' name='dealer' value='$dealer_name'/>
                        <input type='submit' id='subDealer' value='$dealer_name'/>
                    </form>";
        }
        // Close result set
    } else{
        echo "
No matches found
";
    }
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
}

HTML -

     <input type="text" id="searchBox" autocomplete="off" placeholder="Search dealer..." />

Like it said it all works but there is blank whitespace in the input field (#searchBox) which will not allow the .result to clear..

Thanks!

Body:
Try the below snippet

// Set search input value on click of result item
$(document).on("click", ".result", function(){
    $(this).parents(".search-box").find('input[type="text"]').val($(this).text().trim());
});

$(document).on('click', 'input[type=submit]', function() {
   // This is NOT the best practice. But it works. Try to change your implementation to a better one!
   setTimeout(function() {
       $('.result').empty();
   }, 1000);
   return true;
}


问:
Enable form button when radio button is checked
I am using this line to (try) to enable a disabled submit button by removing a class. There is no result or error shown. Is this the way to go or do I need to write an separate script for this?</p>

```<code><label><input type="checkbox" value="ja" echo onclick=\"document.getElementById(\'submit_delete\').removeClass(\'disabled\')\">Ja ik wil deze toolbox verwijderen</label>';

<button type="button" id="submit_delete" class="btn btn-primary disabled">Opslaan</button>
</code>```

答:
Just by removing class, the button cannot be enabled. First you should have disabled attribute on the button. Then remove that attribute on check of the checkbox.

```<code><label><input type="checkbox" value="ja" onchange="enableDisableBtn">Ja ik wil deze toolbox verwijderen</label>;

<button type="button" id="submit_delete" class="btn btn-primary disabled" disabled>Opslaan</button>
<style type="text/css">
    .btn.disabled{
      opacity:.5;
    }
</style>
<script>
    function enableDisableBtn(e){
        var chk = e.target;
        var btn = document.getElementById('submit_delete');
        if(chk.checked){
            btn.disabled = false;
            btn.className = "btn btn-primary";
        }else{
            btn.disabled = true;
            btn.className = "btn btn-primary disabled";
        }

    }
</script>
</code>```

You can see I have added disabled attribute to button and removed it on the change of the checkbox, where I have checked the state of the checkbox

Body:
I am using this line to (try) to enable a disabled submit button by removing a class. There is no result or error shown. Is this the way to go or do I need to write an separate script for this?

<input type="checkbox" value="ja" echo onclick=\"document.getElementById(\'submit_delete\').removeClass(\'disabled\')\">Ja ik wil deze toolbox verwijderen';

<button type="button" id="submit_delete" class="btn btn-primary disabled">Opslaan</button>

Body:
Just by removing class, the button cannot be enabled. First you should have disabled attribute on the button. Then remove that attribute on check of the checkbox.

<label><input type="checkbox" value="ja" onchange="enableDisableBtn">Ja ik wil deze toolbox verwijderen</label>;

<button type="button" id="submit_delete" class="btn btn-primary disabled" disabled>Opslaan</button>
<style type="text/css">
    .btn.disabled{
      opacity:.5;
    }
</style>
<script>
    function enableDisableBtn(e){
        var chk = e.target;
        var btn = document.getElementById('submit_delete');
        if(chk.checked){
            btn.disabled = false;
            btn.className = "btn btn-primary";
        }else{
            btn.disabled = true;
            btn.className = "btn btn-primary disabled";
        }

    }
</script>

You can see I have added disabled attribute to button and removed it on the change of the checkbox, where I have checked the state of the checkbox


答:
It depends on the situation. If you use margin, then the rest of the page will notice that the image exists, and move (if they overlap). If you use position: absolute; then the rest of the page won't notice that it exists, and will ignore it, and, if it collides with the image, then it will go under.

Example using absolute positioning:

.absolute {
  position: absolute;
  top: 10px;
  left: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="http://www.jamfoo.com/chat/smiley.png" class="absolute">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sit amet nisi nec est tristique efficitur. Fusce ut dapibus lorem. Mauris semper orci non magna malesuada tristique. In hac habitasse platea dictumst. In posuere arcu a turpis aliquam, vel ultrices ligula egestas. Quisque congue eu sem et porta. Pellentesque velit enim, tristique in felis nec, ornare pretium urna. Etiam ipsum turpis, commodo non augue ac, bibendum condimentum ipsum. Etiam tristique neque volutpat, luctus purus nec, tempus elit. Vestibulum rhoncus bibendum erat, sed malesuada quam convallis vel. Ut bibendum scelerisque ex, a fringilla magna euismod non. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec euismod consequat turpis, eu tincidunt lacus fermentum eu. Nam egestas nibh quis sapien posuere egestas. </p></code>```

Example using margin:

.margin {
  margin-top: 10px;
  margin-left: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="http://www.jamfoo.com/chat/smiley.png" class="margin">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sit amet nisi nec est tristique efficitur. Fusce ut dapibus lorem. Mauris semper orci non magna malesuada tristique. In hac habitasse platea dictumst. In posuere arcu a turpis aliquam, vel ultrices ligula egestas. Quisque congue eu sem et porta. Pellentesque velit enim, tristique in felis nec, ornare pretium urna. Etiam ipsum turpis, commodo non augue ac, bibendum condimentum ipsum. Etiam tristique neque volutpat, luctus purus nec, tempus elit. Vestibulum rhoncus bibendum erat, sed malesuada quam convallis vel. Ut bibendum scelerisque ex, a fringilla magna euismod non. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec euismod consequat turpis, eu tincidunt lacus fermentum eu. Nam egestas nibh quis sapien posuere egestas. </p></code>```

Also note that if you use position: absolute; then the img will be 10px down and 10px left from the top/left of the page, but if you use margin, then it will be 10px down and 10px left from the top/left of its parent. For example;

.blue {
  background-color: blue;
  margin-top: 150px;
}
.margin {
  margin-top: 10px;
  margin-left: 10px;
  background-color: red;
}
.no-margin {
  background-color: red;
}
.absolute {
  background-color: red;
  position: absolute;
  top: 10px;
  left: 10px;
}

/* this style can be ignored */
span.absolute {
  left: 110px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="blue">
  <img src="http://www.jamfoo.com/chat/smiley.png" class="margin">
  <span class="margin">This example uses margin</span>
</div>
<div class="blue">
  <img src="http://www.jamfoo.com/chat/smiley.png" class="no-margin">
  <span class="no-margin">This example uses no margin</span>
</div>
<div class="blue">
  <img src="http://www.jamfoo.com/chat/smiley.png" class="absolute">
  <span class="absolute">This example uses absolute positioning, and is at the top of the page, even though it is after the other two divs.</span>
</div></code>```

Title: HTML display image on top-left of page

Body:
I want to display an image on the top-left corner of my page. There should be a space of 10 pixels to the top and a space of 10 pixels to the left. I searched the web and found two possible answers. The first one uses the margin property while the second top and left with position: absolute;:

and

Both seem to work but is there any difference between them? Which one should I use?

Body:
It depends on the situation. If you use margin, then the rest of the page will notice that the image exists, and move (if they overlap). If you use position: absolute; then the rest of the page won't notice that it exists, and will ignore it, and, if it collides with the image, then it will go under.

Example using absolute positioning:

.absolute {
  position: absolute;
  top: 10px;
  left: 10px;
}

<img src="http://www.jamfoo.com/chat/smiley.png" class="absolute">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sit amet nisi nec est tristique efficitur. Fusce ut dapibus lorem. Mauris semper orci non magna malesuada tristique. In hac habitasse platea dictumst. In posuere arcu a turpis aliquam, vel ultrices ligula egestas. Quisque congue eu sem et porta. Pellentesque velit enim, tristique in felis nec, ornare pretium urna. Etiam ipsum turpis, commodo non augue ac, bibendum condimentum ipsum. Etiam tristique neque volutpat, luctus purus nec, tempus elit. Vestibulum rhoncus bibendum erat, sed malesuada quam convallis vel. Ut bibendum scelerisque ex, a fringilla magna euismod non. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec euismod consequat turpis, eu tincidunt lacus fermentum eu. Nam egestas nibh quis sapien posuere egestas. </p>

Example using margin:

.margin {
  margin-top: 10px;
  margin-left: 10px;
}

<img src="http://www.jamfoo.com/chat/smiley.png" class="margin">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sit amet nisi nec est tristique efficitur. Fusce ut dapibus lorem. Mauris semper orci non magna malesuada tristique. In hac habitasse platea dictumst. In posuere arcu a turpis aliquam, vel ultrices ligula egestas. Quisque congue eu sem et porta. Pellentesque velit enim, tristique in felis nec, ornare pretium urna. Etiam ipsum turpis, commodo non augue ac, bibendum condimentum ipsum. Etiam tristique neque volutpat, luctus purus nec, tempus elit. Vestibulum rhoncus bibendum erat, sed malesuada quam convallis vel. Ut bibendum scelerisque ex, a fringilla magna euismod non. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec euismod consequat turpis, eu tincidunt lacus fermentum eu. Nam egestas nibh quis sapien posuere egestas. </p>

Also note that if you use position: absolute; then the img will be 10px down and 10px left from the top/left of the page, but if you use margin, then it will be 10px down and 10px left from the top/left of its parent. For example;

.blue {
  background-color: blue;
  margin-top: 150px;
}
.margin {
  margin-top: 10px;
  margin-left: 10px;
  background-color: red;
}
.no-margin {
  background-color: red;
}
.absolute {
  background-color: red;
  position: absolute;
  top: 10px;
  left: 10px;
}

/* this style can be ignored */
span.absolute {
  left: 110px;
}

<div class="blue">
  <img src="http://www.jamfoo.com/chat/smiley.png" class="margin">
  <span class="margin">This example uses margin</span>
</div>
<div class="blue">
  <img src="http://www.jamfoo.com/chat/smiley.png" class="no-margin">
  <span class="no-margin">This example uses no margin</span>
</div>
<div class="blue">
  <img src="http://www.jamfoo.com/chat/smiley.png" class="absolute">
  <span class="absolute">This example uses absolute positioning, and is at the top of the page, even though it is after the other two divs.</span>
</div>


问:
Apply function across rows
Is there a more efficient way to do this?

I have a df with 4 rows and 25 columns, and I want to make a calculation across all rows with the following formula:

```<code>(df['next column'] - df['current column'])/df['current column']
</code>```

答:
We can do

```<code>(df[-1] - df[-ncol(df)])/df[-ncol(df)]
</code>```

data

```<code>set.seed(24)
df <- as.data.frame(matrix(1:25, 5, 5))
</code>```

Title: Apply function across rows

Body:
Is there a more efficient way to do this?

I have a df with 4 rows and 25 columns, and I want to make a calculation across all rows with the following formula:

(df['next column'] - df['current column'])/df['current column']

Body:
We can do

(df[-1] - df[-ncol(df)])/df[-ncol(df)]

data

set.seed(24)
df <- as.data.frame(matrix(1:25, 5, 5))


答:
The following code could be a solution to your problem.

Hope it can help you.

```<code>pred.xgb <- prediction(xgboost_prediction[,2], test_set$y)
perf.xgb <- performance(pred.xgb, "fpr", "tpr")
tpr.xgb <- perf.xgb@x.values[[1]]
fpr.xgb <- perf.xgb@y.values[[1]]

pred.rf <- prediction(randomforest_prediction[,2], test_set$y)
perf.rf <- performance(pred.rf, "fpr", "tpr")
tpr.rf <- perf.rf@x.values[[1]]
fpr.rf <- perf.rf@y.values[[1]]

library(ggplot2)
df <- data.frame(tpr=c(tpr.xgb,tpr.rf), fpr=c(fpr.xgb, fpr.rf),
        Method=c(rep("XGB",each=length(tpr.xgb)),
                 rep("RF",each=length(tpr.rf))) )
ggplot(aes(x=fpr, y=tpr, color=Method), data=df) + geom_line()
</code>```

The AUC can be calculated using:

```<code>performance(pred.xgb, "auc")@y.values[[1]]
# 0.6766304

performance(pred.rf, "auc")@y.values[[1]]
# 0.6650815
</code>```

Title: accessing TPR and FPR for roc curve in ggplot in R

Body:
I am trying to plot roc curve in ggplot, I know ggplot needs "FPR" and "TPR" but I can get to this values from "performance" function or "prediction" function.

I need to combine two classifier's roc curve in one plot.

this is the code I want to use:

ggplot(df,aes(FPR,TPR,color=classifier))+geom_line(size = 2, alpha = 0.7)+
      labs(title= "ROC curve",
           x = "False Positive Rate (1-Specificity)",
           y = "True Positive Rate (Sensitivity)")

this is the data:

> dput(xgboost_prediction[1:100,])
structure(list(no = c(0.990442335605621, 0.534177422523499, 0.991996705532074,
0.84391313791275, 0.965542376041412, 0.691059589385986, 0.718063056468964,
0.995023250579834, 0.956590950489044, 0.94465434551239, 0.775800347328186,
0.725375294685364, 0.8955979347229, 0.519426822662354, 0.262101024389267,
0.920495390892029, 0.961367130279541, 0.529997289180756, 0.753180921077728,
0.374252378940582, 0.649519801139832, 0.873721957206726, 0.938673436641693,
0.98504501581192, 0.990583181381226, 0.991510570049286, 0.981655895709991,
0.903484642505646, 0.965107679367065, 0.953721821308136, 0.554582417011261,
0.919193744659424, 0.965399146080017, 0.574111104011536, 0.898433864116669,
0.901707828044891, 0.951646208763123, 0.637083053588867, 0.947289109230042,
0.920474767684937, 0.995938301086426, 0.973612129688263, 0.964727997779846,
0.884541928768158, 0.95257955789566, 0.412161201238632, 0.990020036697388,
0.976162195205688, 0.939770936965942, 0.968810081481934, 0.983040153980255,
0.89262580871582, 0.970016121864319, 0.923628032207489, 0.886549472808838,
0.522226393222809, 0.960890293121338, 0.975551664829254, 0.710578739643097,
0.973441541194916, 0.388043284416199, 0.944134533405304, 0.962944269180298,
0.958814978599548, 0.948761761188507, 0.973393976688385, 0.971923232078552,
0.883057355880737, 0.974324226379395, 0.886299729347229, 0.464900106191635,
0.746802806854248, 0.735462188720703, 0.663913428783417, 0.965535283088684,
0.990276217460632, 0.201064333319664, 0.98608660697937, 0.870771527290344,
0.99166601896286, 0.974869549274445, 0.990644574165344, 0.991726994514465,
0.827968239784241, 0.988746464252472, 0.783728361129761, 0.221792578697205,
0.98324054479599, 0.617589056491852, 0.986640393733978, 0.932099580764771,
0.967139899730682, 0.956782400608063, 0.90983521938324, 0.990782082080841,
0.995104193687439, 0.809846758842468, 0.698821008205414, 0.996101856231689,
0.528671264648438), yes = c(0.00955766439437866, 0.465822577476501,
0.00800329446792603, 0.15608686208725, 0.0344576239585876, 0.308940410614014,
0.281936943531036, 0.00497674942016602, 0.0434090495109558, 0.0553456544876099,
0.224199652671814, 0.274624705314636, 0.1044020652771, 0.480573177337646,
0.737898975610733, 0.0795046091079712, 0.038632869720459, 0.470002710819244,
0.246819078922272, 0.625747621059418, 0.350480198860168, 0.126278042793274,
0.0613265633583069, 0.0149549841880798, 0.00941681861877441,
0.00848942995071411, 0.0183441042900085, 0.0965153574943542,
0.0348923206329346, 0.046278178691864, 0.445417582988739, 0.0808062553405762,
0.0346008539199829, 0.425888895988464, 0.101566135883331, 0.0982921719551086,
0.0483537912368774, 0.362916946411133, 0.0527108907699585, 0.0795252323150635,
0.00406169891357422, 0.0263878703117371, 0.0352720022201538,
0.115458071231842, 0.0474204421043396, 0.587838798761368, 0.0099799633026123,
0.0238378047943115, 0.0602290630340576, 0.0311899185180664, 0.0169598460197449,
0.10737419128418, 0.0299838781356812, 0.076371967792511, 0.113450527191162,
0.477773606777191, 0.0391097068786621, 0.0244483351707458, 0.289421260356903,
0.0265584588050842, 0.611956715583801, 0.055865466594696, 0.0370557308197021,
0.0411850214004517, 0.0512382388114929, 0.026606023311615, 0.0280767679214478,
0.116942644119263, 0.0256757736206055, 0.113700270652771, 0.535099893808365,
0.253197193145752, 0.264537811279297, 0.336086571216583, 0.0344647169113159,
0.00972378253936768, 0.798935666680336, 0.0139133930206299, 0.129228472709656,
0.00833398103713989, 0.0251304507255554, 0.00935542583465576,
0.00827300548553467, 0.172031760215759, 0.0112535357475281, 0.216271638870239,
0.778207421302795, 0.01675945520401, 0.382410943508148, 0.0133596062660217,
0.0679004192352295, 0.0328601002693176, 0.0432175993919373, 0.0901647806167603,
0.00921791791915894, 0.00489580631256104, 0.190153241157532,
0.301178991794586, 0.00389814376831055, 0.471328735351562)), .Names = c("no",
"yes"), row.names = c(NA, 100L), class = "data.frame")

> dput(randomforest_prediction[1:100,])
structure(list(no = c(0.694, 0.606, 0.778, 0.498, 0.748, 0.604,
0.446, 0.586, 0.686, 0.748, 0.708, 0.574, 0.662, 0.614, 0.65,
0.616, 0.618, 0.664, 0.562, 0.496, 0.628, 0.77, 0.652, 0.738,
0.674, 0.73, 0.684, 0.7, 0.678, 0.672, 0.616, 0.71, 0.93, 0.774,
0.668, 0.682, 0.752, 0.926, 0.776, 0.796, 0.85, 0.728, 0.57,
0.648, 0.804, 0.64, 0.766, 0.722, 0.73, 0.706, 0.748, 0.608,
0.684, 0.708, 0.746, 0.554, 0.732, 0.816, 0.888, 0.656, 0.808,
0.908, 0.69, 0.722, 0.764, 0.746, 0.728, 0.57, 0.95, 0.656, 0.066,
0.692, 0.794, 0.638, 0.63, 0.8, 0.572, 0.776, 0.776, 0.702, 0.848,
0.77, 0.864, 0.682, 0.784, 0.582, 0.028, 0.694, 0.642, 0.428,
0.636, 0.654, 0.798, 0.576, 0.674, 0.756, 0.606, 0.648, 0.676,
0.498), yes = c(0.306, 0.394, 0.222, 0.502, 0.252, 0.396, 0.554,
0.414, 0.314, 0.252, 0.292, 0.426, 0.338, 0.386, 0.35, 0.384,
0.382, 0.336, 0.438, 0.504, 0.372, 0.23, 0.348, 0.262, 0.326,
0.27, 0.316, 0.3, 0.322, 0.328, 0.384, 0.29, 0.07, 0.226, 0.332,
0.318, 0.248, 0.074, 0.224, 0.204, 0.15, 0.272, 0.43, 0.352,
0.196, 0.36, 0.234, 0.278, 0.27, 0.294, 0.252, 0.392, 0.316,
0.292, 0.254, 0.446, 0.268, 0.184, 0.112, 0.344, 0.192, 0.092,
0.31, 0.278, 0.236, 0.254, 0.272, 0.43, 0.05, 0.344, 0.934, 0.308,
0.206, 0.362, 0.37, 0.2, 0.428, 0.224, 0.224, 0.298, 0.152, 0.23,
0.136, 0.318, 0.216, 0.418, 0.972, 0.306, 0.358, 0.572, 0.364,
0.346, 0.202, 0.424, 0.326, 0.244, 0.394, 0.352, 0.324, 0.502
)), .Names = c("no", "yes"), row.names = c("1", "2", "3", "4",
"7", "8", "9", "10", "13", "14", "15", "16", "18", "19", "22",
"23", "24", "27", "28", "29", "30", "31", "32", "33", "34", "35",
"36", "38", "39", "40", "41", "45", "46", "47", "48", "50", "51",
"55", "56", "57", "58", "60", "61", "62", "64", "65", "66", "68",
"70", "71", "73", "75", "76", "77", "78", "79", "80", "82", "83",
"84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "95",
"96", "99", "100", "101", "102", "103", "105", "106", "107",
"108", "109", "110", "112", "114", "115", "116", "118", "120",
"123", "124", "125", "126", "127", "128", "129", "130", "131",
"132", "133", "135"), class = "data.frame")

> dput(test_set$y[1:100])
structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L,
1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 1L, 1L, 1L, 1L, 1L), .Label = c("no", "yes"), class = "factor")

can someone please help? I have been trying for hours!

Body:
The following code could be a solution to your problem.

Hope it can help you.

pred.xgb <- prediction(xgboost_prediction[,2], test_set$y)
perf.xgb <- performance(pred.xgb, "fpr", "tpr")
tpr.xgb <- perf.xgb@x.values[[1]]
fpr.xgb <- perf.xgb@y.values[[1]]

pred.rf <- prediction(randomforest_prediction[,2], test_set$y)
perf.rf <- performance(pred.rf, "fpr", "tpr")
tpr.rf <- perf.rf@x.values[[1]]
fpr.rf <- perf.rf@y.values[[1]]

library(ggplot2)
df <- data.frame(tpr=c(tpr.xgb,tpr.rf), fpr=c(fpr.xgb, fpr.rf),
        Method=c(rep("XGB",each=length(tpr.xgb)),
                 rep("RF",each=length(tpr.rf))) )
ggplot(aes(x=fpr, y=tpr, color=Method), data=df) + geom_line()

The AUC can be calculated using:

performance(pred.xgb, "auc")@y.values[[1]]
# 0.6766304

performance(pred.rf, "auc")@y.values[[1]]
# 0.6650815