问:
How to disable Tomcat JARScanner
How: To disable Tomcat JARScanner?

Why: To stop Tomcat scan every .jar in my LIB folder.

According to documentation it says that it is possible to disable it within context.xml. But it seems to not be working. (May be I am missing something)
I made an exhaustive search in forums and could not find the solution.

This is in context.xml (not working yet):

```<code><JarScanner scanClassPath="false" scanAllFiles="false" scanAllDirectories="false"></JarScanner>
</code>```

Thanks in advance.

答:
you can disable the JarScanner globally for user-definted patterns by opeining the file at

```<code>%TOMCAT_HOME%/conf/catalina.properties
</code>```

and add a filename pattern to tomcat.util.scan.StandardJarScanFilter.jarsToSkip list.
For example, if you want to disable jar scanning completely you could add:

```<code>tomcat.util.scan.StandardJarScanFilter.jarsToSkip=\
*.jar,\
</code>```

NOTE: this may of course lead to issues if you're employing JSTL, as templates won't be found by the scanner

Title: How to disable Tomcat JARScanner

Body:
How: To disable Tomcat JARScanner?

Why: To stop Tomcat scan every .jar in my LIB folder.

According to documentation it says that it is possible to disable it within context.xml. But it seems to not be working. (May be I am missing something)
I made an exhaustive search in forums and could not find the solution.

This is in context.xml (not working yet):

<JarScanner scanClassPath="false" scanAllFiles="false" scanAllDirectories="false"></JarScanner>

Thanks in advance.

Body:
you can disable the JarScanner globally for user-definted patterns by opeining the file at

%TOMCAT_HOME%/conf/catalina.properties

and add a filename pattern to tomcat.util.scan.StandardJarScanFilter.jarsToSkip list.
For example, if you want to disable jar scanning completely you could add:

tomcat.util.scan.StandardJarScanFilter.jarsToSkip=\
*.jar,\

NOTE: this may of course lead to issues if you're employing JSTL, as templates won't be found by the scanner


来源: stackexchange

问:
How to transfer call log data?

My end goal is to design an app that upon installation automatically retrieves all call history data and pushes it to the database, preferably in csv format. There will be a data science model performed on the data, and the results will be sent back to the app for display.

I wanted to ask if this is even possible for an app to do? If so, what is the like basic algorithm I should go for?
P.s.:I am a data science student, and I am looking at android code for the first time.

答:
Yes you can read the call logs, heres something to start with

First enable the permission in your manifest

<uses-permission android:name="android.permission.READ_CALL_LOG" />

You also need to request the permission from the permission manager

```<code>ActivityCompat.checkSelfPermission(context,Manifest.permission.READ_CALL_LOG) == PackageManager.PERMISSION_GRANTED {
  // Get data from database
}
else {
  // Request permission from user
}
</code>```

Get data from database

```<code>val projection = arrayOf(
            CallLog.Calls.CACHED_NAME,
            CallLog.Calls.NUMBER,
            CallLog.Calls.TYPE,
            CallLog.Calls.DATE)

val cursor = getContentResolver().query(CallLog.Calls.CONTENT_URI, projection, null, null, null)
        if(cursor != null) {
            while (cursor.moveToNext()) {
                // Data for your database
                val name: String = cursor.getString(0)
                val number: String = cursor.getString(1)
                val type: String = cursor.getString(2)
                val time: String = cursor.getString(3)
            }
            cursor.close()
        }
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to transfer call log data?

Body:
Yes you can read the call logs, heres something to start with

First enable the permission in your manifest

<uses-permission android:name="android.permission.READ_CALL_LOG" />

You also need to request the permission from the permission manager

ActivityCompat.checkSelfPermission(context,Manifest.permission.READ_CALL_LOG) == PackageManager.PERMISSION_GRANTED {
  // Get data from database
}
else {
  // Request permission from user
}

Get data from database

val projection = arrayOf(
            CallLog.Calls.CACHED_NAME,
            CallLog.Calls.NUMBER,
            CallLog.Calls.TYPE,
            CallLog.Calls.DATE)

val cursor = getContentResolver().query(CallLog.Calls.CONTENT_URI, projection, null, null, null)
        if(cursor != null) {
            while (cursor.moveToNext()) {
                // Data for your database
                val name: String = cursor.getString(0)
                val number: String = cursor.getString(1)
                val type: String = cursor.getString(2)
                val time: String = cursor.getString(3)
            }
            cursor.close()
        }


问:
function for showing unique cells
VBA function which deletes duplicates and writes with comma

I need a formula (function) which will have two arguments:
1.range (will be selected)
2.separator character between duplicates.
Example I have in a range some codes of products 0001, 0015, 0015, 0015, 0015, 0015, 0015, 0015, 0015, 0020 in different cells. I want to get 0001, 0015, 0020 using formula.

What I have written:

```<code>Function UNIQUE_NUMBER(RangeD As Range, SepCharacter As String)
Dim UNIQUE As String
On Error GoTo msg
For Each cell In RangeD
If Not IsEmpty(cell) Then
    If Cells(cell.Row, cell.Column) = "" Then Resume Next
    r = cell.Row
    C = cell.Column
    a_length = Len(a)
    a = a & SepCharacter & Cells(r, C)

        If WorksheetFunction.Search(Cells(r, C) & SepCharacter, a, a_length + 1) > 1 And Cells(r, C) <> "" Then
        a = WorksheetFunction.Substitute(a, Cells(r, C) & SepCharacter, "", 1)

        End If
End If

Next cell
SepCharacter2 = SepCharacter & SepCharacter
UNIQUE = Mid(a, Len(SepCharacter) + 1, Len(a))
UNIQUE_NUMBER = Replace(Replace(Replace(Replace(Replace(Replace(Replace(UNIQUE, SepCharacter2, ""), SepCharacter2, ""), SepCharacter2, ""), SepCharacter2, ""), SepCharacter2, ""), SepCharacter2, ""), SepCharacter2, "")
Exit Function
msg:
Resume Next
End Function
</code>```

And it sometimes work correctly (somehow), but sometimes doesn’t
What do you offer?

答:
If I understand you correctly,

your product codes are in a range of cells, with one code per cell

your output should be in a single cell, as a sepChar separated cell.

Since you show your output with comma-space as the separator, I put that as the default separator in the code.

If you have Excel O365, you can do this with a worksheet formula:

```<code>=TEXTJOIN(", ",TRUE,UNIQUE(myRange))
</code>```

If not, a VBA routine is probably easiest:

To extract unique values from a list, I would suggest using a Dictionary or Collection object, although there are other, efficient methods.

In the code below, I demonstrate the Collection object, as it is also present in Excel for MAC.

```<code>Option Explicit
Function vbaUNIQUE(rg As Range, Optional sep As String = ", ") As String
    Dim col As Collection
    Dim c As Range
    Dim i As Long, s As String

Set col = New Collection

'Collection object will return an error if we try
' to add a duplicate key.  Therefore the `OnError`
' statement will skip over any duplicates
On Error Resume Next
For Each c In rg
    If Not c.Value = "" Then col.Add Item:=c.Value, Key:=CStr(c.Value)
Next c
On Error GoTo 0

'create output string
For i = 1 To col.Count
    s = s & sep & col(i)
Next i

vbaUNIQUE = Mid(s, Len(sep) + 1)

End Function

</code>```

Title: function for showing unique cells

Body:
VBA function which deletes duplicates and writes with comma

I need a formula (function) which will have two arguments:
1.range (will be selected)
2.separator character between duplicates.
Example I have in a range some codes of products 0001, 0015, 0015, 0015, 0015, 0015, 0015, 0015, 0015, 0020 in different cells. I want to get 0001, 0015, 0020 using formula.

What I have written:

Function UNIQUE_NUMBER(RangeD As Range, SepCharacter As String)
Dim UNIQUE As String
On Error GoTo msg
For Each cell In RangeD
If Not IsEmpty(cell) Then
    If Cells(cell.Row, cell.Column) = "" Then Resume Next
    r = cell.Row
    C = cell.Column
    a_length = Len(a)
    a = a & SepCharacter & Cells(r, C)

        If WorksheetFunction.Search(Cells(r, C) & SepCharacter, a, a_length + 1) > 1 And Cells(r, C) <> "" Then
        a = WorksheetFunction.Substitute(a, Cells(r, C) & SepCharacter, "", 1)

        End If
End If

Next cell
SepCharacter2 = SepCharacter & SepCharacter
UNIQUE = Mid(a, Len(SepCharacter) + 1, Len(a))
UNIQUE_NUMBER = Replace(Replace(Replace(Replace(Replace(Replace(Replace(UNIQUE, SepCharacter2, ""), SepCharacter2, ""), SepCharacter2, ""), SepCharacter2, ""), SepCharacter2, ""), SepCharacter2, ""), SepCharacter2, "")
Exit Function
msg:
Resume Next
End Function

And it sometimes work correctly (somehow), but sometimes doesn’t
What do you offer?

Body:
If I understand you correctly,

your product codes are in a range of cells, with one code per cell

your output should be in a single cell, as a sepChar separated cell.

Since you show your output with comma-space as the separator, I put that as the default separator in the code.

If you have Excel O365, you can do this with a worksheet formula:

=TEXTJOIN(", ",TRUE,UNIQUE(myRange))

If not, a VBA routine is probably easiest:

To extract unique values from a list, I would suggest using a Dictionary or Collection object, although there are other, efficient methods.

In the code below, I demonstrate the Collection object, as it is also present in Excel for MAC.

Option Explicit
Function vbaUNIQUE(rg As Range, Optional sep As String = ", ") As String
    Dim col As Collection
    Dim c As Range
    Dim i As Long, s As String

Set col = New Collection

'Collection object will return an error if we try
' to add a duplicate key.  Therefore the `OnError`
' statement will skip over any duplicates
On Error Resume Next
For Each c In rg
    If Not c.Value = "" Then col.Add Item:=c.Value, Key:=CStr(c.Value)
Next c
On Error GoTo 0

'create output string
For i = 1 To col.Count
    s = s & sep & col(i)
Next i

vbaUNIQUE = Mid(s, Len(sep) + 1)

End Function


问:
SpringBook + VueJS + SpringSecurity Cookie is not passed
I'm creating a project using SpringBoot2 and VueJS. I'm using a custom JWT token for authorisation. When the user logs in I set a cookie in the response "AUTH_TOKEN=tokenValue". I expected that every call from VueJS (using fetch) would pass that cookie to SpringBoot, but not all endpoints get the cookie.

When I test SpringBoot with RestTemplate and with Postman the cookie is passed just fine and the endpoint works. When I use the VueJS website, the cookie is only passed to endpoints that have "permitAll" in my SecurityConfig.

I have also verified that my VueJS is always sending the cookie (I used a php endpoint to test this and the cookie is always there). So something happens when I use the browser and not all endpoints have the cookie. Here is my Config and how I use it:

Security Config:

```<code>@Configuration
open class SecurityConfig(private val jwtTokenProvider :JwtTokenProvider) : WebSecurityConfigurerAdapter() {

    @Bean
    override fun authenticationManagerBean(): AuthenticationManager {
        return super.authenticationManagerBean()
    }

    @Throws(Exception::class)
    override fun configure(http: HttpSecurity) {
        //@formatter:off
        http
                .httpBasic().disable()
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/thisEndpointDoesGetTheCookie").permitAll()
                .anyRequest().authenticated() //Anything else does not
                .and()
                .apply(JwtConfigurer(jwtTokenProvider))
        //@formatter:on
    }

}
</code>```

When I set another endpoint with permitAll then that endpoint starts getting the token too (in my jwtConfigurer/provider)

The call is done using fetch and VueJS

Here is my logout example (same as any other endpoint)

```<code>    logout() {
      fetch('http://localhost:8100/auth/logout', {
            method: "post",
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            }
            ,credentials: 'include', //Yes I'm including the credentials
            body: ""
          }).then(res => {
            console.log("Logout was successful");
          }).catch(error => {
              console.log(error.message);
              console.log("Logout failed");
          });
    },
</code>```

This is how I set the cookie when the user logs in. I can see it in the browser

```<code>    // create a cookie
    val cookie = Cookie("AUTH_TOKEN", signedInUser.token)

    // expires in 30 days
    cookie.maxAge = 30 * 24 * 60 * 60
    // optional properties
    cookie.secure = authTokenCookieSecure //false for localhost
    cookie.isHttpOnly = true
    cookie.path = "/"
    // add cookie to response
    response.addCookie(cookie)
</code>```

When I make the call using TestRestTemplate (from my tests) or when I'm using
postman the endpoints behave as expected.

```<code>val headers = HttpHeaders()
headers["Cookie"] = "AUTH_TOKEN=$jwtToken"
</code>```

What I'm I missing?

答:
Problem occurs because you have to configure CORS in Spring Security.
For custom headers you have to set your header name in Access-Control-Expose-Headers.

Example solution code:

```<code>@Bean
fun corsConfigurationSource(): CorsConfigurationSource {
    val configuration = CorsConfiguration().applyPermitDefaultValues()
    configuration.allowedOrigins = listOf("*")
    configuration.allowedMethods = HttpMethod.values().map { it.name }
    configuration.allowedHeaders = listOf("*")
    configuration.exposedHeaders = listOf("AUTH_TOKEN")
    val source = UrlBasedCorsConfigurationSource()
    source.registerCorsConfiguration("/**", configuration)
    return source
}
</code>```

This CORS configuration allows any domain to access your header. It's good solution for DEV environment. For PROD you should specify origin instead of providing *.

Links: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers

Body:
I'm creating a project using SpringBoot2 and VueJS. I'm using a custom JWT token for authorisation. When the user logs in I set a cookie in the response "AUTH_TOKEN=tokenValue". I expected that every call from VueJS (using fetch) would pass that cookie to SpringBoot, but not all endpoints get the cookie.

When I test SpringBoot with RestTemplate and with Postman the cookie is passed just fine and the endpoint works. When I use the VueJS website, the cookie is only passed to endpoints that have "permitAll" in my SecurityConfig.

I have also verified that my VueJS is always sending the cookie (I used a php endpoint to test this and the cookie is always there). So something happens when I use the browser and not all endpoints have the cookie. Here is my Config and how I use it:

Security Config:

@Configuration
open class SecurityConfig(private val jwtTokenProvider :JwtTokenProvider) : WebSecurityConfigurerAdapter() {

    @Bean
    override fun authenticationManagerBean(): AuthenticationManager {
        return super.authenticationManagerBean()
    }

    @Throws(Exception::class)
    override fun configure(http: HttpSecurity) {
        //@formatter:off
        http
                .httpBasic().disable()
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/thisEndpointDoesGetTheCookie").permitAll()
                .anyRequest().authenticated() //Anything else does not
                .and()
                .apply(JwtConfigurer(jwtTokenProvider))
        //@formatter:on
    }

}

When I set another endpoint with permitAll then that endpoint starts getting the token too (in my jwtConfigurer/provider)

The call is done using fetch and VueJS

Here is my logout example (same as any other endpoint)

    logout() {
      fetch('http://localhost:8100/auth/logout', {
            method: "post",
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            }
            ,credentials: 'include', //Yes I'm including the credentials
            body: ""
          }).then(res => {
            console.log("Logout was successful");
          }).catch(error => {
              console.log(error.message);
              console.log("Logout failed");
          });
    },

This is how I set the cookie when the user logs in. I can see it in the browser

    // create a cookie
    val cookie = Cookie("AUTH_TOKEN", signedInUser.token)

    // expires in 30 days
    cookie.maxAge = 30 * 24 * 60 * 60
    // optional properties
    cookie.secure = authTokenCookieSecure //false for localhost
    cookie.isHttpOnly = true
    cookie.path = "/"
    // add cookie to response
    response.addCookie(cookie)

When I make the call using TestRestTemplate (from my tests) or when I'm using
postman the endpoints behave as expected.

val headers = HttpHeaders()
headers["Cookie"] = "AUTH_TOKEN=$jwtToken"

What I'm I missing?

Body:
Problem occurs because you have to configure CORS in Spring Security.
For custom headers you have to set your header name in Access-Control-Expose-Headers.

Example solution code:

@Bean
fun corsConfigurationSource(): CorsConfigurationSource {
    val configuration = CorsConfiguration().applyPermitDefaultValues()
    configuration.allowedOrigins = listOf("*")
    configuration.allowedMethods = HttpMethod.values().map { it.name }
    configuration.allowedHeaders = listOf("*")
    configuration.exposedHeaders = listOf("AUTH_TOKEN")
    val source = UrlBasedCorsConfigurationSource()
    source.registerCorsConfiguration("/**", configuration)
    return source
}

This CORS configuration allows any domain to access your header. It's good solution for DEV environment. For PROD you should specify origin instead of providing *.

Links: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers


问:
Cannot resolve symbol 'NavigationView'
I made a NavigationView inside a DrawerLayout in an XML file - but when I try to initialize it in Java I get this error.

```<code>// DrawerLayout initialises fine
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.nav_drawer);
// Cannot resolve symbol 'NavigationView'
NavigationView navView = (NavigationView) findViewById(R.id.navigation_view);
</code>```

I tried adding the import line

```<code>import  android.support.design.widget.NavigationView
</code>```

but this is also giving me errors. Any ideas? Haven't been able to find a solution online.

Edit:
After adding dependency given in Tanis' answer, I get these errors

```<code>Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugCompile'.
   > Could not find com.android.support:design:22.2.1.
     Searched in the following locations:
         https://jcenter.bintray.com/com/android/support/design/22.2.1/design-22.2.1.pom
         https://jcenter.bintray.com/com/android/support/design/22.2.1/design-22.2.1.jar
         https://repo1.maven.org/maven2/com/android/support/design/22.2.1/design-22.2.1.pom
         https://repo1.maven.org/maven2/com/android/support/design/22.2.1/design-22.2.1.jar
         file:/C:/Users/SV_Laptop03/AppData/Local/Android/sdk/extras/android/m2repository/com/android/support/design/22.2.1/design-22.2.1.pom
         file:/C:/Users/SV_Laptop03/AppData/Local/Android/sdk/extras/android/m2repository/com/android/support/design/22.2.1/design-22.2.1.jar
         file:/C:/Users/SV_Laptop03/AppData/Local/Android/sdk/extras/google/m2repository/com/android/support/design/22.2.1/design-22.2.1.pom
         file:/C:/Users/SV_Laptop03/AppData/Local/Android/sdk/extras/google/m2repository/com/android/support/design/22.2.1/design-22.2.1.jar
     Required by:
         MyApp:app:unspecified
</code>```

答:
Search for NavigationView in the Android Studio pallet, and click on the Download arrow next to it. It will add the following to your code:

```<code>import com.google.android.material.navigation.NavigationView;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Cannot resolve symbol 'NavigationView'

Body:
I made a NavigationView inside a DrawerLayout in an XML file - but when I try to initialize it in Java I get this error.

// DrawerLayout initialises fine
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.nav_drawer);
// Cannot resolve symbol 'NavigationView'
NavigationView navView = (NavigationView) findViewById(R.id.navigation_view);

I tried adding the import line

import  android.support.design.widget.NavigationView

but this is also giving me errors. Any ideas? Haven't been able to find a solution online.

Edit:
After adding dependency given in Tanis' answer, I get these errors

Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugCompile'.
   > Could not find com.android.support:design:22.2.1.
     Searched in the following locations:
         https://jcenter.bintray.com/com/android/support/design/22.2.1/design-22.2.1.pom
         https://jcenter.bintray.com/com/android/support/design/22.2.1/design-22.2.1.jar
         https://repo1.maven.org/maven2/com/android/support/design/22.2.1/design-22.2.1.pom
         https://repo1.maven.org/maven2/com/android/support/design/22.2.1/design-22.2.1.jar
         file:/C:/Users/SV_Laptop03/AppData/Local/Android/sdk/extras/android/m2repository/com/android/support/design/22.2.1/design-22.2.1.pom
         file:/C:/Users/SV_Laptop03/AppData/Local/Android/sdk/extras/android/m2repository/com/android/support/design/22.2.1/design-22.2.1.jar
         file:/C:/Users/SV_Laptop03/AppData/Local/Android/sdk/extras/google/m2repository/com/android/support/design/22.2.1/design-22.2.1.pom
         file:/C:/Users/SV_Laptop03/AppData/Local/Android/sdk/extras/google/m2repository/com/android/support/design/22.2.1/design-22.2.1.jar
     Required by:
         MyApp:app:unspecified

Body:
Search for NavigationView in the Android Studio pallet, and click on the Download arrow next to it. It will add the following to your code:

import com.google.android.material.navigation.NavigationView;


问:
find out object item names in as3
let's say you're passing an object to a function

```<code>{title:"my title", data:"corresponding data"}
</code>```

how can I get the function to know what the names of the items/sub-objects are (title and data) without specifying them?

答:
You can use a for(String in Object) loop like so:

```<code>var i:String;
for(i in object)
{
    var key:String = i;
    var value:Object = object[i];

    // do stuff with key/value
}
</code>```

PS it would make more sense obviously to use key in the loop, my example is done for the sake of demonstration.

Why was this downvoted.. Because I didn't do a function?

```<code>function findKeys(obj:Object):Array
{
    var ar:Array = [];

    var i:String;
    for(i in obj)
    {
        ar.push(i);
    }

    return ar;
}

var ob:Object = {things:"value", other:5};

trace(findKeys(ob)); // other,things
</code>```

Title: find out object item names in as3

Body:
let's say you're passing an object to a function

{title:"my title", data:"corresponding data"}

how can I get the function to know what the names of the items/sub-objects are (title and data) without specifying them?

Body:
You can use a for(String in Object) loop like so:

var i:String;
for(i in object)
{
    var key:String = i;
    var value:Object = object[i];

    // do stuff with key/value
}

PS it would make more sense obviously to use key in the loop, my example is done for the sake of demonstration.

Why was this downvoted.. Because I didn't do a function?

function findKeys(obj:Object):Array
{
    var ar:Array = [];

    var i:String;
    for(i in obj)
    {
        ar.push(i);
    }

    return ar;
}

var ob:Object = {things:"value", other:5};

trace(findKeys(ob)); // other,things


问:
How to crop the largest circle out of an image (shooting target) using OpenCV
as the title states, I'm trying to crop the largest circle out of an image. I'm using OpenCV in python. To be exact, it's a shooting target, which always has the same format, but the picture of it can be taken with any mobile device and in different lighting conditions (I will include some examples lower).

I'm completely new to image recognition, so I have been trying out many different ways of doing this, but couldn't figure out a universal solution, that would work on all of my target images.

Why I'm trying to do this:

My assignment is to calculate score of one or multiple shots on the given target image. I have tried color segmentation to find the shots, but since the shots can be on different backgrounds, this wouldn't work properly. So now I'm trying to see the difference between the empty shooting target image and the already shot on target image. Also, I need to be able to tell, which target it was shot on (there are two target types). So I'm trying to crop out only the target from image to get rid of the background interference and then continue with the shot identifications.

What I have tried so far:

1) Finding the largest circle with HoughCircles. My next step would be to somehow remove the outer part of that found circle. I have played with the configuration of HoughCircles method for quite some time, but always one of the example images wasn't highlighting the most outer circle correctly or wasn't highlighting any of the circles :/.

My final configuration looked something like this:

```<code>img = cv2.GaussianBlur(img, (3, 3), 0)
cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 2, 10000, param1=50, param2=100, minRadius=200, maxRadius=0)
</code>```

It seemed like using HoughCircles wouldn't be the right way to do this, so I moved on to another possible solution I found on the internet.

2) Finding all the countours by filtering the 'black' color range in which the circles seem to be on the pictures and than finding the largest one. The problem with this solution seemed to be that sometimes the pictures had a shadow that destroyed the outer circle and therefore it seemed impossible to crop by it.

My code looked like this:

```<code># black color boundaries [B, G, R]
lower = [0, 0, 0]
upper = [150, 150, 150]

# create NumPy arrays from the boundaries
lower = np.array(lower, dtype="uint8")
upper = np.array(upper, dtype="uint8")

# find the colors within the specified boundaries and apply the mask
mask = cv2.inRange(img, lower, upper)
output = cv2.bitwise_and(img, img, mask=mask)

ret, thresh = cv2.threshold(mask, 40, 255, 0)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

if len(contours) != 0:
    # draw in blue the contours that were founded
    cv2.drawContours(output, contours, -1, 255, 3)

    # find the biggest countour (c) by the area
    c = max(contours, key=cv2.contourArea)
    x, y, w, h = cv2.boundingRect(c)
</code>```

After that, I would try to draw a circle by the largest found contour (c) and crop by it. But I have already seen that the drawn circles weren't complete (probably due to some shadow on the picture) and therefore this wouldn't work anyway.

After those failures, I have tried so many solutions from other questions on here, but none would work for my problem.

Example images:

Target example 1

Target example 2

Target to calc score 1

Target to calc score 2

To be completely honest with you, I'm really lost on how to go about this. I would appreciate any help, advice, anything.

答:
There are two different types of target in your samples. You may want to process them separately or ask the user for the input, what kind of target it is. Basically, you want to know how large the black part of the target, does it cover 7-10 or 4-10.

Binarize your image. Build a histogram along X and Y -- you'll find the position of the black part of your target as (x_left, x_right, y_top, y_bottom). Once you know that, you can calculate the center ((top+bottom)/2, (left+right)/2). After that you can easily calculate the score for every pixel of the image, since you know the center, the black spot size and the number of different score areas within.

Body:
as the title states, I'm trying to crop the largest circle out of an image. I'm using OpenCV in python. To be exact, it's a shooting target, which always has the same format, but the picture of it can be taken with any mobile device and in different lighting conditions (I will include some examples lower).

I'm completely new to image recognition, so I have been trying out many different ways of doing this, but couldn't figure out a universal solution, that would work on all of my target images.

Why I'm trying to do this:

My assignment is to calculate score of one or multiple shots on the given target image. I have tried color segmentation to find the shots, but since the shots can be on different backgrounds, this wouldn't work properly. So now I'm trying to see the difference between the empty shooting target image and the already shot on target image. Also, I need to be able to tell, which target it was shot on (there are two target types). So I'm trying to crop out only the target from image to get rid of the background interference and then continue with the shot identifications.

What I have tried so far:

1) Finding the largest circle with HoughCircles. My next step would be to somehow remove the outer part of that found circle. I have played with the configuration of HoughCircles method for quite some time, but always one of the example images wasn't highlighting the most outer circle correctly or wasn't highlighting any of the circles :/.

My final configuration looked something like this:

img = cv2.GaussianBlur(img, (3, 3), 0)
cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 2, 10000, param1=50, param2=100, minRadius=200, maxRadius=0)

It seemed like using HoughCircles wouldn't be the right way to do this, so I moved on to another possible solution I found on the internet.

2) Finding all the countours by filtering the 'black' color range in which the circles seem to be on the pictures and than finding the largest one. The problem with this solution seemed to be that sometimes the pictures had a shadow that destroyed the outer circle and therefore it seemed impossible to crop by it.

My code looked like this:

# black color boundaries [B, G, R]
lower = [0, 0, 0]
upper = [150, 150, 150]

# create NumPy arrays from the boundaries
lower = np.array(lower, dtype="uint8")
upper = np.array(upper, dtype="uint8")

# find the colors within the specified boundaries and apply the mask
mask = cv2.inRange(img, lower, upper)
output = cv2.bitwise_and(img, img, mask=mask)

ret, thresh = cv2.threshold(mask, 40, 255, 0)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

if len(contours) != 0:
    # draw in blue the contours that were founded
    cv2.drawContours(output, contours, -1, 255, 3)

    # find the biggest countour (c) by the area
    c = max(contours, key=cv2.contourArea)
    x, y, w, h = cv2.boundingRect(c)

After that, I would try to draw a circle by the largest found contour (c) and crop by it. But I have already seen that the drawn circles weren't complete (probably due to some shadow on the picture) and therefore this wouldn't work anyway.

After those failures, I have tried so many solutions from other questions on here, but none would work for my problem.

Example images:

Target example 1

Target example 2

Target to calc score 1

Target to calc score 2

To be completely honest with you, I'm really lost on how to go about this. I would appreciate any help, advice, anything.


问:
SQL query to find minimum difference between row values of a column
I am trying to find the minimum difference between years for each ID. For example,

I have this data:

```<code>ID     year
1      2001
1      2001
2      2003
2      2004
2      2010
3      2000
</code>```

and I want this output:

```<code>ID    year
1      0
2      1
3      0
</code>```

答:
You can use lag():

```<code>select id, coalesce(min(year - prev_year), 0)
from (select t.*, lag(year) over (partition by id order by year) as prev_year
      from t
     ) t
group by id;
</code>```

Here is a db<>fiddle.

Body:
I am trying to find the minimum difference between years for each ID. For example,

I have this data:

ID     year
1      2001
1      2001
2      2003
2      2004
2      2010
3      2000

and I want this output:

ID    year
1      0
2      1
3      0

Body:
You can use lag():

select id, coalesce(min(year - prev_year), 0)
from (select t.*, lag(year) over (partition by id order by year) as prev_year
      from t
     ) t
group by id;

Here is a db<>fiddle.


问:
multiple form dont update mysql
I have this function an first query working fine
but second is multiple form like input name="id[]" ,urunad="id[]",birim="id[]"...
I take $_POST to function</p>

```<code>$id2 = $gid;
$sid2 = $sid;
$urunad2 = $urunad;
$birim2 = $birim;
$adet2 = $adet;
$fiyat2 = $fiyat;
$kdvsiztoplam2 = $kdvsiztoplam;
whats the problem please help me

     public function updateData($kasano,$gid,$sturu,$firmaid,$firmaadi,$vergid,$vergin,$adres,$telefon,$email,$sid,$urunad,$birim,$adet,$fiyat,$kdvsiztoplam,$kdv,$aratoplam,$geneltoplam,$kdvtutar,$kdvdahil,$tarih)
            {
                    $query = $this->db->prepare("update siparis set kasano = ? ,sturu = ? ,firmaid = ? ,firmaadi = ? ,vergid = ? ,vergin = ? ,adres = ? ,telefon = ? ,email = ? ,kdv = ? ,aratoplam = ? ,geneltoplam = ? ,kdvtutar = ? ,kdvdahil = ? ,tarih = ?");
                    $update = $query->execute(array($kasano,$sturu,$firmaid,$firmaadi,$vergid,$vergin,$adres,$telefon,$email,$kdv,$aratoplam,$geneltoplam,$kdvtutar,$kdvdahil,$tarih));
                    return $update;

                    $id2 = $gid;
                    $sid2 = $sid;
                    $urunad2 = $urunad;
                    $birim2 = $birim;
                    $adet2 = $adet;
                    $fiyat2 = $fiyat;
                    $kdvsiztoplam2 = $kdvsiztoplam;

                for($i=0;$i<count($id2);$i++)
                {
                    $query = $this->db->prepare("update surunler set id = ? ,sid = ?,urunad = ? ,birim = ? ,adet = ? ,fiyat = ? ,kdvsiztoplam = ? ");
                    $update = $query->execute(array($id2[$i],$sid2[$i],$urunad2[$i],$birim2[$i],$adet2[$i],$fiyat2[$i],$kdvsiztoplam2[$i]));
                    return $update;
                }

            }
</code>```

答:
When you type "return" in PHP the entire function is aborted at that point and control returned to the calling function.

This means nothing below the first query will run.

Secondly, a return in a for loop does not apply to the for loop as it does in some languages, it still will abort the entire function and return control to the calling function.

Title: multiple form dont update mysql

Body:
I have this function an first query working fine
but second is multiple form like input name="id[]" ,urunad="id[]",birim="id[]"...
I take $_POST to function

$id2 = $gid;
$sid2 = $sid;
$urunad2 = $urunad;
$birim2 = $birim;
$adet2 = $adet;
$fiyat2 = $fiyat;
$kdvsiztoplam2 = $kdvsiztoplam;
whats the problem please help me

     public function updateData($kasano,$gid,$sturu,$firmaid,$firmaadi,$vergid,$vergin,$adres,$telefon,$email,$sid,$urunad,$birim,$adet,$fiyat,$kdvsiztoplam,$kdv,$aratoplam,$geneltoplam,$kdvtutar,$kdvdahil,$tarih)
            {
                    $query = $this->db->prepare("update siparis set kasano = ? ,sturu = ? ,firmaid = ? ,firmaadi = ? ,vergid = ? ,vergin = ? ,adres = ? ,telefon = ? ,email = ? ,kdv = ? ,aratoplam = ? ,geneltoplam = ? ,kdvtutar = ? ,kdvdahil = ? ,tarih = ?");
                    $update = $query->execute(array($kasano,$sturu,$firmaid,$firmaadi,$vergid,$vergin,$adres,$telefon,$email,$kdv,$aratoplam,$geneltoplam,$kdvtutar,$kdvdahil,$tarih));
                    return $update;

                    $id2 = $gid;
                    $sid2 = $sid;
                    $urunad2 = $urunad;
                    $birim2 = $birim;
                    $adet2 = $adet;
                    $fiyat2 = $fiyat;
                    $kdvsiztoplam2 = $kdvsiztoplam;

                for($i=0;$i<count($id2);$i++)
                {
                    $query = $this->db->prepare("update surunler set id = ? ,sid = ?,urunad = ? ,birim = ? ,adet = ? ,fiyat = ? ,kdvsiztoplam = ? ");
                    $update = $query->execute(array($id2[$i],$sid2[$i],$urunad2[$i],$birim2[$i],$adet2[$i],$fiyat2[$i],$kdvsiztoplam2[$i]));
                    return $update;
                }

            }


问:
Gunicorn Flask Restful API and Flask-Socketio crashes when I bind a host and port to Gunicorn
This is a bit odd as I have been deploying my Flask apps for over a 2 years now using the same way with minor differences depending on the tech stack.
When I run my Flask app without specifying a host:port for gunicorn as the following:

```<code>web: gunicorn --worker-class eventlet -w 1 wsgi:app
</code>```

as mentioned int the documenets here, it works fine, but my sockets don't, as the Gunicorn server starts at almost a different port everytime, which makes it not possible to specify a fixed port in the frontend. That is why I specify the host and port as the following:

```<code>web: gunicorn --bind 127.0.0.1:8000 --worker-class eventlet -w 1 wsgi:app
</code>```

I should note that I have also tried other alternatives as:

```<code>web: gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker --bind 127.0.0.1:8000 -w 1 wsgi:app
</code>```

What happens here is the app is deployed successfully also when I bind a host and address, but crushes with no logs or errors when  which is really frustrating. What is more frustrating is that it works with no issues on the local host whether I specify an address not. Here is my Heroku logs:

```<code>2020-05-30T10:32:09.146144+00:00 app[api]: Deploy 37f7668f by user use@email.com
2020-05-30T10:32:09.146144+00:00 app[api]: Release v39 created by user user@emai.com
2020-05-30T10:32:20.484467+00:00 app[web.1]: [2020-05-30 10:32:20 +0000] [4] [INFO] Starting gunicorn 20.0.4
2020-05-30T10:32:20.485325+00:00 app[web.1]: [2020-05-30 10:32:20 +0000] [4] [INFO] Listening at: http://127.0.0.1:8000 (4)
2020-05-30T10:32:20.485476+00:00 app[web.1]: [2020-05-30 10:32:20 +0000] [4] [INFO] Using worker: eventlet
2020-05-30T10:32:20.490925+00:00 app[web.1]: [2020-05-30 10:32:20 +0000] [9] [INFO] Booting worker with pid: 9
2020-05-30T10:32:22.886718+00:00 app[web.1]: Server initialized for eventlet.
2020-05-30T10:32:26.000000+00:00 app[api]: Build succeeded
2020-05-30T10:33:17.674322+00:00 heroku[web.1]: State changed from starting to crashed
2020-05-30T10:33:18.184411+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=langcodex.herokuapp.com request_id=d0742a73-96a0-490e-860b-e0ccda544e0b fwd="41.92.113.84" dyno= connect= service= status=503 bytes= protocol=https
2020-05-30T10:33:19.352104+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=langcodex.herokuapp.com request_id=8f202689-ee4c-4871-bfe3-ef8f9c34b397 fwd="41.92.113.84" dyno= connect= service= status=503 bytes= protocol=https
</code>```

Here is my app/init.py file:

```<code>import logging, os
from logging.handlers import SMTPHandler, RotatingFileHandler
from flask import Flask
from flask_socketio import SocketIO
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_mail import Mail
from flask_migrate import Migrate
from flask_seasurf import SeaSurf
from flask_cors import CORS
from config import Config, Development

db = SQLAlchemy()
login_manager = LoginManager()
migrate = Migrate()
mail = Mail()
seasurf = SeaSurf()
socket = SocketIO()
cors = CORS()

def create_app(config_class=Config):
    """Construct the core application."""
    app = Flask(__name__, static_folder='frontend/build/static',
        instance_relative_config=True)
    # Application Configuration
    app.config.from_object(config_class)
    with app.app_context():
        # Initialize Plugins
        login_manager.init_app(app)
        db.init_app(app)
        mail.init_app(app)
        migrate.init_app(app, db)
        seasurf.init_app(app)
        cors.init_app(app, resources={r'/api/*': {'origins': '*'}})
        socket.init_app(app, cors_allowed_origins="*",
            async_mode='eventlet',
            engineio_logger=True,
            logger=True)
        # Initialize Global db
        db.create_all()
        from app.serve_frontend_bp import serve_frontend_bp as serve_frontend_blueprint
        app.register_blueprint(serve_frontend_blueprint)
        from app.socket_bp import socket_bp as socket_blueprint
        app.register_blueprint(socket_blueprint)
        from app.nlp_bp import nlp_bp as nlp_blueprint
        app.register_blueprint(nlp_blueprint, url_prefix='/api/nlp')
        from app.main_bp import main_bp as main_blueprint
        app.register_blueprint(main_blueprint, url_prefix='/api')
        from app.errors_bp import errors_bp as errors_blueprint
        app.register_blueprint(errors_blueprint)
        # Configute Debugging
        if app.debug or app.testing:

            if app.config['LOG_TO_STDOUT']:
                stream_handler = logging.StreamHandler()
                stream_handler.setLevel(logging.INFO)
                app.logger.addHandler(stream_handler)
            else:
                if not os.path.exists('logs'):
                    os.mkdir('logs')
                file_handler = RotatingFileHandler('logs/langandcode.log',
                                                   maxBytes=20480, backupCount=20)
                file_handler.setFormatter(logging.Formatter(
                    '%(asctime)s %(levelname)s: %(message)s '
                    '[in %(pathname)s:%(lineno)d]'))
                file_handler.setLevel(logging.INFO)
                app.logger.addHandler(file_handler)
            app.logger.setLevel(logging.INFO)
            app.logger.info('LanguageandCode startup')
        return app
</code>```

Here is my app structure:

```<code>.
├── app
│   ├── auth_bp
│   ├── core
│   ├── decorators.py
│   ├── email.py
│   ├── errors_bp
│   ├── exceptions.py
│   ├── factory.py
│   ├── forms.py
│   ├── frontend
│   ├── functions.py
│   ├── __init__.py
│   ├── logs
│   ├── main
│   ├── main_bp
│   ├── models.py
│   ├── nlp_bp
│   ├── __pycache__
│   ├── serve_frontend_bp
│   ├── socket_bp
│   └── templates
├── config.py
├── latest.dump
├── logs
│   └── langandcode.log
├── migrations
│   ├── alembic.ini
│   ├── env.py
│   ├── __pycache__
│   ├── README
│   ├── script.py.mako
│   └── versions
├── Procfile
├── requirements.txt
├── runtime.txt
└── wsgi.py
</code>```

I hope I really find an answer for this as it doesn't make much sense to me, especially with no logs or errors. I hope there's a work to make the port fixed so as to my sockets work. Thank you very much for your time and help.

答:
Alright so what I added to make this work is essentially using:

```<code>web: gunicorn --worker-class eventlet -w 1 wsgi:app
</code>```

or

```<code>web: gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker -w 1 wsgi:app
</code>```

interchangeably in the procfile, with one minor modification in my app/init.py, in the initialization of the socketio:

```<code>        socket.init_app(app, cors_allowed_origins="*",
        async_mode='gevent',
        engineio_logger=True,
        logger=True,
        port=8000)
</code>```

I basically added a port of 8000 for the sockets to proxy requests to instead of the Gunicorn port that's unknown to the frontend until the server starts,if that's the case. I still don't know why the server crushes when I specify the host and name, and I hope I find an answer, but I'm glad my app and sockets are working correctly now.

Body:
This is a bit odd as I have been deploying my Flask apps for over a 2 years now using the same way with minor differences depending on the tech stack.
When I run my Flask app without specifying a host:port for gunicorn as the following:

web: gunicorn --worker-class eventlet -w 1 wsgi:app

as mentioned int the documenets here, it works fine, but my sockets don't, as the Gunicorn server starts at almost a different port everytime, which makes it not possible to specify a fixed port in the frontend. That is why I specify the host and port as the following:

web: gunicorn --bind 127.0.0.1:8000 --worker-class eventlet -w 1 wsgi:app

I should note that I have also tried other alternatives as:

web: gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker --bind 127.0.0.1:8000 -w 1 wsgi:app

What happens here is the app is deployed successfully also when I bind a host and address, but crushes with no logs or errors when  which is really frustrating. What is more frustrating is that it works with no issues on the local host whether I specify an address not. Here is my Heroku logs:

2020-05-30T10:32:09.146144+00:00 app[api]: Deploy 37f7668f by user use@email.com
2020-05-30T10:32:09.146144+00:00 app[api]: Release v39 created by user user@emai.com
2020-05-30T10:32:20.484467+00:00 app[web.1]: [2020-05-30 10:32:20 +0000] [4] [INFO] Starting gunicorn 20.0.4
2020-05-30T10:32:20.485325+00:00 app[web.1]: [2020-05-30 10:32:20 +0000] [4] [INFO] Listening at: http://127.0.0.1:8000 (4)
2020-05-30T10:32:20.485476+00:00 app[web.1]: [2020-05-30 10:32:20 +0000] [4] [INFO] Using worker: eventlet
2020-05-30T10:32:20.490925+00:00 app[web.1]: [2020-05-30 10:32:20 +0000] [9] [INFO] Booting worker with pid: 9
2020-05-30T10:32:22.886718+00:00 app[web.1]: Server initialized for eventlet.
2020-05-30T10:32:26.000000+00:00 app[api]: Build succeeded
2020-05-30T10:33:17.674322+00:00 heroku[web.1]: State changed from starting to crashed
2020-05-30T10:33:18.184411+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=langcodex.herokuapp.com request_id=d0742a73-96a0-490e-860b-e0ccda544e0b fwd="41.92.113.84" dyno= connect= service= status=503 bytes= protocol=https
2020-05-30T10:33:19.352104+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=langcodex.herokuapp.com request_id=8f202689-ee4c-4871-bfe3-ef8f9c34b397 fwd="41.92.113.84" dyno= connect= service= status=503 bytes= protocol=https

Here is my app/init.py file:

import logging, os
from logging.handlers import SMTPHandler, RotatingFileHandler
from flask import Flask
from flask_socketio import SocketIO
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_mail import Mail
from flask_migrate import Migrate
from flask_seasurf import SeaSurf
from flask_cors import CORS
from config import Config, Development

db = SQLAlchemy()
login_manager = LoginManager()
migrate = Migrate()
mail = Mail()
seasurf = SeaSurf()
socket = SocketIO()
cors = CORS()

def create_app(config_class=Config):
    """Construct the core application."""
    app = Flask(__name__, static_folder='frontend/build/static',
        instance_relative_config=True)
    # Application Configuration
    app.config.from_object(config_class)
    with app.app_context():
        # Initialize Plugins
        login_manager.init_app(app)
        db.init_app(app)
        mail.init_app(app)
        migrate.init_app(app, db)
        seasurf.init_app(app)
        cors.init_app(app, resources={r'/api/*': {'origins': '*'}})
        socket.init_app(app, cors_allowed_origins="*",
            async_mode='eventlet',
            engineio_logger=True,
            logger=True)
        # Initialize Global db
        db.create_all()
        from app.serve_frontend_bp import serve_frontend_bp as serve_frontend_blueprint
        app.register_blueprint(serve_frontend_blueprint)
        from app.socket_bp import socket_bp as socket_blueprint
        app.register_blueprint(socket_blueprint)
        from app.nlp_bp import nlp_bp as nlp_blueprint
        app.register_blueprint(nlp_blueprint, url_prefix='/api/nlp')
        from app.main_bp import main_bp as main_blueprint
        app.register_blueprint(main_blueprint, url_prefix='/api')
        from app.errors_bp import errors_bp as errors_blueprint
        app.register_blueprint(errors_blueprint)
        # Configute Debugging
        if app.debug or app.testing:

            if app.config['LOG_TO_STDOUT']:
                stream_handler = logging.StreamHandler()
                stream_handler.setLevel(logging.INFO)
                app.logger.addHandler(stream_handler)
            else:
                if not os.path.exists('logs'):
                    os.mkdir('logs')
                file_handler = RotatingFileHandler('logs/langandcode.log',
                                                   maxBytes=20480, backupCount=20)
                file_handler.setFormatter(logging.Formatter(
                    '%(asctime)s %(levelname)s: %(message)s '
                    '[in %(pathname)s:%(lineno)d]'))
                file_handler.setLevel(logging.INFO)
                app.logger.addHandler(file_handler)
            app.logger.setLevel(logging.INFO)
            app.logger.info('LanguageandCode startup')
        return app

Here is my app structure:

.
├── app
│   ├── auth_bp
│   ├── core
│   ├── decorators.py
│   ├── email.py
│   ├── errors_bp
│   ├── exceptions.py
│   ├── factory.py
│   ├── forms.py
│   ├── frontend
│   ├── functions.py
│   ├── __init__.py
│   ├── logs
│   ├── main
│   ├── main_bp
│   ├── models.py
│   ├── nlp_bp
│   ├── __pycache__
│   ├── serve_frontend_bp
│   ├── socket_bp
│   └── templates
├── config.py
├── latest.dump
├── logs
│   └── langandcode.log
├── migrations
│   ├── alembic.ini
│   ├── env.py
│   ├── __pycache__
│   ├── README
│   ├── script.py.mako
│   └── versions
├── Procfile
├── requirements.txt
├── runtime.txt
└── wsgi.py

I hope I really find an answer for this as it doesn't make much sense to me, especially with no logs or errors. I hope there's a work to make the port fixed so as to my sockets work. Thank you very much for your time and help.

Body:
Alright so what I added to make this work is essentially using:

web: gunicorn --worker-class eventlet -w 1 wsgi:app

or

web: gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker -w 1 wsgi:app

interchangeably in the procfile, with one minor modification in my app/init.py, in the initialization of the socketio:

        socket.init_app(app, cors_allowed_origins="*",
        async_mode='gevent',
        engineio_logger=True,
        logger=True,
        port=8000)

I basically added a port of 8000 for the sockets to proxy requests to instead of the Gunicorn port that's unknown to the frontend until the server starts,if that's the case. I still don't know why the server crushes when I specify the host and name, and I hope I find an answer, but I'm glad my app and sockets are working correctly now.


问:
Removing numbers from a given string
I am trying to get rid of any numbers in a string.

However, when I run my program the number is removed, but other parts of the string are removed as well.

```<code>string = 'My name is Anish, & I am 22 years old! The wall is blue, and the floor is orange. The weather is great, but it is raining?'

def num_remover(words):
    t = words.split()
    d = [e for e in t if e.isalpha()]
    a = " ".join(d)
    return a

print(bluh_remover(string))
</code>```

output:

My name is I am 22 years The wall is and the floor is The weather is but it is

答:
For any string longer than 10 words, a simple Replace loop would be faster. In VBA, for example:</p>

```<code>Dim StrTxt As String, i As Long
StrTxt = "My name is Anish, & I am 22 years old! The wall is blue, and the floor is orange. The weather is great, but it is raining?"
For i = 0 To 9
  StrTxt = Replace(StrTxt, i, "")
Next
MsgBox StrTxt
</code>```

Title: Removing numbers from a given string

Body:
I am trying to get rid of any numbers in a string.

However, when I run my program the number is removed, but other parts of the string are removed as well.

string = 'My name is Anish, & I am 22 years old! The wall is blue, and the floor is orange. The weather is great, but it is raining?'

def num_remover(words):
    t = words.split()
    d = [e for e in t if e.isalpha()]
    a = " ".join(d)
    return a

print(bluh_remover(string))

output:

My name is I am 22 years The wall is and the floor is The weather is but it is

Body:
For any string longer than 10 words, a simple Replace loop would be faster. In VBA, for example:

Dim StrTxt As String, i As Long
StrTxt = "My name is Anish, & I am 22 years old! The wall is blue, and the floor is orange. The weather is great, but it is raining?"
For i = 0 To 9
  StrTxt = Replace(StrTxt, i, "")
Next
MsgBox StrTxt


问:
How can my Cocoa app be notified when the user empties the trash?
My app puts some files in the trash, but also implements undo to pull them back out again. I need to know if the user empties the trash so I can empty my undo stack.

Do I need to monitor file system events to achieve this, or is there an easier way?

答:
You can use UKKQueue to watch file change (empty thrash) notifications:

http://www.cocoadev.com/index.pl?UKKQueue

ContentLicense: CC BY-SA 2.5


问:
oracle sql procedure with in and multi out params error
I created a procedure to get multiple out params. But compilation error came. I couldn't find the issue. please, I need some support to find the issue.............

my code is,

Basic database customer, reservation and service tables are below,

```<code>CREATE TABLE CUSTOMER
       (CUSTOMER_ID NUMBER(4) NOT NULL,
        CUSTOMER_NAME VARCHAR2(10),
        GENDER VARCHAR(10),
        ADDRESS VARCHAR(50),
        EMAIL VARCHAR(50),
        DISCOUNT FLOAT(10),
        PRIMARY KEY(CUSTOMER_ID)
        );

CREATE TABLE SERVICE
        (SERVICE_ID NUMBER(4) NOT NULL,
        SERVICE_NAME VARCHAR(100),
        CHARGE FLOAT(10),
        PRIMARY KEY(SERVICE_ID)
        );

CREATE TABLE RESERVATION
        (RESERVATION_ID NUMBER(4) NOT NULL,
        RESERVATION_DATE DATE,
        CUSTOMER_ID NUMBER(4),
        SERVICE_ID NUMBER(4),
        EMPLOYEE_ID NUMBER(4),
        PRIMARY KEY(RESERVATION_ID),
        FOREIGN KEY (CUSTOMER_ID) REFERENCES CUSTOMER(CUSTOMER_ID),
        FOREIGN KEY (SERVICE_ID) REFERENCES SERVICE(SERVICE_ID),
        FOREIGN KEY (EMPLOYEE_ID) REFERENCES EMPLOYEE(EMPLOYEE_ID)
        );
</code>```

I need to get some vales from the reservation table, service table and customer table. my procedure is below,

```<code>SET SERVEROUTPUT ON
CREATE OR REPLACE PROCEDURE GET_RECEIPT(
    RES_ID IN RESERVATION.RESERVATION_ID%TYPE,
    C_NAME OUT CUSTOMER.CUSTOMER_NAME%TYPE,
    S_NAME OUT SERVICE.SERVICE_NAME%TYPE,
    CHARGE_VAL OUT FLOAT(10),
    DISCOUNT_VAL OUT FLOAT(10),
    TOTAL_VAL OUT FLOAT(10)
    )
AS
BEGIN
    SELECT
        c.CUSTOMER_NAME AS CUS_NAME INTO C_NAME,
        s.SERVICE_NAME AS SER_NAME INTO S_NAME,
        s.CHARGE AS CHAR_VAL INTO CHARGE_VAL,
        c.DISCOUNT INTO DISCOUNT_VAL,
        (s.CHARGE-c.DISCOUNT)AS TOTAL INTO TOTAL_VAL
    FROM RESERVATION r LEFT OUTER JOIN CUSTOMER c ON r.CUSTOMER_ID=c.CUSTOMER_ID LEFT OUTER JOIN SERVICE s ON r.SERVICE_ID=s.SERVICE_ID
    WHERE r.RESERVATION_ID=RES_ID;
END;
/
</code>```

But this procedure couldn't compile. it says compilation fails. how can I fix this?

答:
Fixed, it looks like this:

```<code>SQL> create or replace procedure get_receipt(
  2      res_id in reservation.reservation_id%type,
  3      c_name out customer.customer_name%type,
  4      s_name out service.service_name%type,
  5      charge_val out float,
  6      discount_val out float,
  7      total_val out float
  8      )
  9  as
 10  begin
 11      select c.customer_name, s.service_name, s.charge, c.discount, s.charge - c.discount
 12      into c_name, s_name, charge_val, discount_val, total_val
 13      from reservation r left outer join customer c on r.customer_id=c.customer_id
 14      left outer join service s on r.service_id=s.service_id
 15      where r.reservation_id=res_id;
 16  end;
 17  /

Procedure created.

SQL>
</code>```

What did you do wrong?

parameters don't have size (it is not float(10) but just float)

in PL/SQL, select has to have into clause - which is what you did, but in a wrong manner. Should be as in my example.

Body:
I created a procedure to get multiple out params. But compilation error came. I couldn't find the issue. please, I need some support to find the issue.............

my code is,

Basic database customer, reservation and service tables are below,

CREATE TABLE CUSTOMER
       (CUSTOMER_ID NUMBER(4) NOT NULL,
        CUSTOMER_NAME VARCHAR2(10),
        GENDER VARCHAR(10),
        ADDRESS VARCHAR(50),
        EMAIL VARCHAR(50),
        DISCOUNT FLOAT(10),
        PRIMARY KEY(CUSTOMER_ID)
        );

CREATE TABLE SERVICE
        (SERVICE_ID NUMBER(4) NOT NULL,
        SERVICE_NAME VARCHAR(100),
        CHARGE FLOAT(10),
        PRIMARY KEY(SERVICE_ID)
        );

CREATE TABLE RESERVATION
        (RESERVATION_ID NUMBER(4) NOT NULL,
        RESERVATION_DATE DATE,
        CUSTOMER_ID NUMBER(4),
        SERVICE_ID NUMBER(4),
        EMPLOYEE_ID NUMBER(4),
        PRIMARY KEY(RESERVATION_ID),
        FOREIGN KEY (CUSTOMER_ID) REFERENCES CUSTOMER(CUSTOMER_ID),
        FOREIGN KEY (SERVICE_ID) REFERENCES SERVICE(SERVICE_ID),
        FOREIGN KEY (EMPLOYEE_ID) REFERENCES EMPLOYEE(EMPLOYEE_ID)
        );

I need to get some vales from the reservation table, service table and customer table. my procedure is below,

SET SERVEROUTPUT ON
CREATE OR REPLACE PROCEDURE GET_RECEIPT(
    RES_ID IN RESERVATION.RESERVATION_ID%TYPE,
    C_NAME OUT CUSTOMER.CUSTOMER_NAME%TYPE,
    S_NAME OUT SERVICE.SERVICE_NAME%TYPE,
    CHARGE_VAL OUT FLOAT(10),
    DISCOUNT_VAL OUT FLOAT(10),
    TOTAL_VAL OUT FLOAT(10)
    )
AS
BEGIN
    SELECT
        c.CUSTOMER_NAME AS CUS_NAME INTO C_NAME,
        s.SERVICE_NAME AS SER_NAME INTO S_NAME,
        s.CHARGE AS CHAR_VAL INTO CHARGE_VAL,
        c.DISCOUNT INTO DISCOUNT_VAL,
        (s.CHARGE-c.DISCOUNT)AS TOTAL INTO TOTAL_VAL
    FROM RESERVATION r LEFT OUTER JOIN CUSTOMER c ON r.CUSTOMER_ID=c.CUSTOMER_ID LEFT OUTER JOIN SERVICE s ON r.SERVICE_ID=s.SERVICE_ID
    WHERE r.RESERVATION_ID=RES_ID;
END;
/

But this procedure couldn't compile. it says compilation fails. how can I fix this?

Body:
Fixed, it looks like this:

SQL> create or replace procedure get_receipt(
  2      res_id in reservation.reservation_id%type,
  3      c_name out customer.customer_name%type,
  4      s_name out service.service_name%type,
  5      charge_val out float,
  6      discount_val out float,
  7      total_val out float
  8      )
  9  as
 10  begin
 11      select c.customer_name, s.service_name, s.charge, c.discount, s.charge - c.discount
 12      into c_name, s_name, charge_val, discount_val, total_val
 13      from reservation r left outer join customer c on r.customer_id=c.customer_id
 14      left outer join service s on r.service_id=s.service_id
 15      where r.reservation_id=res_id;
 16  end;
 17  /

Procedure created.

SQL>

What did you do wrong?

parameters don't have size (it is not float(10) but just float)

in PL/SQL, select has to have into clause - which is what you did, but in a wrong manner. Should be as in my example.


问:
Get distinct values of two columns and merge into rows
I have a table named dbo.WebsiteIP having two columns IPAddress, SiteName, and I am doing a bulk insert the values to the this table which look like below

```<code>IPAddress       SiteName
192.168.30.6    website1.domain.com
192.168.30.6    website2.domain.com
192.168.30.7    website3.domain.com
192.168.30.7    website4.domain.com
192.168.30.7    website5.domain.com
192.168.30.7    website6.domain.com
192.168.30.7    website7.domain.com
192.168.30.8    website8.domain.com
192.168.30.8    website9.domain.com
192.168.30.8    website10.domain.com
192.168.30.8    website11.domain.com
192.168.30.9    website12.domain.com
192.168.30.8    website13.domain.com
192.168.30.8    website14.domain.com
192.168.30.24   website15.domain.com
192.168.30.8    website16.domain.com
192.168.30.8    website17.domain.com
</code>```

I want to do a distinct query for the IP Address and combine the SiteName like below

```<code>IPAddress       WebsiteName
192.168.30.6    website1, website2,
192.168.30.7    website3, website4, website5, website6, website7
192.168.30.8    website8, website9, website10, website11, website13, website14
192.168.30.9    website12
192.168.30.24   website15
</code>```

I can able to combine the IPAddress using the below query but how to combine the appropriate Sitename to the IP Address.

```<code>Update Table1
Set IP= (Select IPAddress + ',' + ' '
From dbo.WebsiteIP
GROUP BY IPAddress FOR XML PATH(''))
GO
</code>```

答:
You can achieve this by using STUFF

```<code>DECLARE @T Table(
IP VARCHAR(MAX),
WEBSITE VARCHAR(MAX))

INSERT INTO @T VALUES('192.168.30.6','website1.domain.com')
INSERT INTO @T VALUES('192.168.30.6','website2.domain.com')
INSERT INTO @T VALUES('192.168.30.7','website3.domain.com')
INSERT INTO @T VALUES('192.168.30.7','website4.domain.com')
INSERT INTO @T VALUES('192.168.30.7','website5.domain.com')
INSERT INTO @T VALUES('192.168.30.7','website6.domain.com')
INSERT INTO @T VALUES('192.168.30.7','website7.domain.com')
INSERT INTO @T VALUES('192.168.30.8','website8.domain.com')
INSERT INTO @T VALUES('192.168.30.8','website9.domain.com')
INSERT INTO @T VALUES('192.168.30.8','website10.domain.com')
INSERT INTO @T VALUES('192.168.30.8','website11.domain.com')
INSERT INTO @T VALUES('192.168.30.9','website12.domain.com')
INSERT INTO @T VALUES('192.168.30.8','website13.domain.com')
INSERT INTO @T VALUES('192.168.30.8','website14.domain.com')
INSERT INTO @T VALUES('192.168.30.24','website15.domain.com')
INSERT INTO @T VALUES('192.168.30.8',' website16.domain.com')
INSERT INTO @T VALUES('192.168.30.8',' website17.domain.com')
</code>```

Main Query

```<code>SELECT M.IP,STUFF (( Select ','+WEBSITE
From @T S WHERE S.IP=M.IP
FOR XML PATH('')),1,1,'')
FROM @T M GROUP BY M.IP
</code>```

For Update Query

```<code> update Table1 T1 set IP = T2.SiteName
 from(SELECT M.IP,STUFF (( Select ','+WEBSITE
 From @T S WHERE S.IP=M.IP
 FOR XML PATH('')),1,1,'')  AS Site
 FROM @T M GROUP BY M.IP
 ) S ON S.IP=T1.IP
</code>```

Body:
I have a table named dbo.WebsiteIP having two columns IPAddress, SiteName, and I am doing a bulk insert the values to the this table which look like below

IPAddress       SiteName
192.168.30.6    website1.domain.com
192.168.30.6    website2.domain.com
192.168.30.7    website3.domain.com
192.168.30.7    website4.domain.com
192.168.30.7    website5.domain.com
192.168.30.7    website6.domain.com
192.168.30.7    website7.domain.com
192.168.30.8    website8.domain.com
192.168.30.8    website9.domain.com
192.168.30.8    website10.domain.com
192.168.30.8    website11.domain.com
192.168.30.9    website12.domain.com
192.168.30.8    website13.domain.com
192.168.30.8    website14.domain.com
192.168.30.24   website15.domain.com
192.168.30.8    website16.domain.com
192.168.30.8    website17.domain.com

I want to do a distinct query for the IP Address and combine the SiteName like below

IPAddress       WebsiteName
192.168.30.6    website1, website2,
192.168.30.7    website3, website4, website5, website6, website7
192.168.30.8    website8, website9, website10, website11, website13, website14
192.168.30.9    website12
192.168.30.24   website15

I can able to combine the IPAddress using the below query but how to combine the appropriate Sitename to the IP Address.

Update Table1
Set IP= (Select IPAddress + ',' + ' '
From dbo.WebsiteIP
GROUP BY IPAddress FOR XML PATH(''))
GO

Body:
You can achieve this by using STUFF

DECLARE @T Table(
IP VARCHAR(MAX),
WEBSITE VARCHAR(MAX))

INSERT INTO @T VALUES('192.168.30.6','website1.domain.com')
INSERT INTO @T VALUES('192.168.30.6','website2.domain.com')
INSERT INTO @T VALUES('192.168.30.7','website3.domain.com')
INSERT INTO @T VALUES('192.168.30.7','website4.domain.com')
INSERT INTO @T VALUES('192.168.30.7','website5.domain.com')
INSERT INTO @T VALUES('192.168.30.7','website6.domain.com')
INSERT INTO @T VALUES('192.168.30.7','website7.domain.com')
INSERT INTO @T VALUES('192.168.30.8','website8.domain.com')
INSERT INTO @T VALUES('192.168.30.8','website9.domain.com')
INSERT INTO @T VALUES('192.168.30.8','website10.domain.com')
INSERT INTO @T VALUES('192.168.30.8','website11.domain.com')
INSERT INTO @T VALUES('192.168.30.9','website12.domain.com')
INSERT INTO @T VALUES('192.168.30.8','website13.domain.com')
INSERT INTO @T VALUES('192.168.30.8','website14.domain.com')
INSERT INTO @T VALUES('192.168.30.24','website15.domain.com')
INSERT INTO @T VALUES('192.168.30.8',' website16.domain.com')
INSERT INTO @T VALUES('192.168.30.8',' website17.domain.com')

Main Query

SELECT M.IP,STUFF (( Select ','+WEBSITE
From @T S WHERE S.IP=M.IP
FOR XML PATH('')),1,1,'')
FROM @T M GROUP BY M.IP

For Update Query

 update Table1 T1 set IP = T2.SiteName
 from(SELECT M.IP,STUFF (( Select ','+WEBSITE
 From @T S WHERE S.IP=M.IP
 FOR XML PATH('')),1,1,'')  AS Site
 FROM @T M GROUP BY M.IP
 ) S ON S.IP=T1.IP


问:
The parameters of the objects in my list change even if I clone the list
Good morning,

I make a software that creates steps from the above and adds them to a common list.

Here's my code:

```<code>        List<List<Crêpe>> Solutions = new List<List<Crêpe>>();
        Solutions.Add(new List<Crêpe>(Ordre)); // 1.

        for (int i = NombreMax; i > 0; i--)
        {
            Ordre.Reverse(0, positionDuNombreAChercher); // 2.

            for (int n = 0; n < positionDuNombreAChercher; n++)
            {
                Ordre[n].FaceCraméBienPlacé = !Ordre[n].FaceCraméBienPlacé; // 3.
            }

            Solutions.Add(new List<Crêpe>(Ordre));

        }
</code>```

I've put some markers to explain my problem to you:

In 1, I clone my list and add it in "Solution".

In 2, I reverse the "Ordre" list, which no longer has a link with the list I cloned because it is a clone and therefore the changes are not made in "Solution".

In 3, you can see I'm changing the parameters of the object in "Ordre". That's where the error happens!
So I change my parameters in the object and my list that I clone is not supposed to change it's parameter's object because it was cloned but the problem is that the list that I cloned at the beginning to also change these object parameters.

to note:
She changed her settings but not her order, as step 3 does with this list.

I'm really sorry if that wasn't clear, if you want a better explanation tell me.

Thank you for helping me :)

EDIT :
Here is the object :

```<code>internal class Crêpe
{
    internal int Nombre { get; set; }
    internal bool FaceCraméBienPlacé { get; set; }

    public Crêpe(int position, bool faceCraméBienPlacé)
    {
        Nombre = position;
        FaceCraméBienPlacé = faceCraméBienPlacé;
    }
}
</code>```

答:
You copied the list, but you didn't copy the crêpes!

To copy the crêpes, you can write a GetCopy method in the Crêpe class:

```<code>public Crêpe GetCopy() => new Crêpe(Nombre, FaceCraméBienPlacé);
</code>```

And then use Select to create a copy of each Crêpe, then use ToList to create a new list:

```<code>Solutions.Add(Ordre.Select(x => x.GetCopy()).ToList()); // 1.
</code>```

You should also change the last line in the outer loop.

Body:
Good morning,

I make a software that creates steps from the above and adds them to a common list.

Here's my code:

        List<List<Crêpe>> Solutions = new List<List<Crêpe>>();
        Solutions.Add(new List<Crêpe>(Ordre)); // 1.

        for (int i = NombreMax; i > 0; i--)
        {
            Ordre.Reverse(0, positionDuNombreAChercher); // 2.

            for (int n = 0; n < positionDuNombreAChercher; n++)
            {
                Ordre[n].FaceCraméBienPlacé = !Ordre[n].FaceCraméBienPlacé; // 3.
            }

            Solutions.Add(new List<Crêpe>(Ordre));

        }

I've put some markers to explain my problem to you:

In 1, I clone my list and add it in "Solution".

In 2, I reverse the "Ordre" list, which no longer has a link with the list I cloned because it is a clone and therefore the changes are not made in "Solution".

In 3, you can see I'm changing the parameters of the object in "Ordre". That's where the error happens!
So I change my parameters in the object and my list that I clone is not supposed to change it's parameter's object because it was cloned but the problem is that the list that I cloned at the beginning to also change these object parameters.

to note:
She changed her settings but not her order, as step 3 does with this list.

I'm really sorry if that wasn't clear, if you want a better explanation tell me.

Thank you for helping me :)

EDIT :
Here is the object :

internal class Crêpe
{
    internal int Nombre { get; set; }
    internal bool FaceCraméBienPlacé { get; set; }

    public Crêpe(int position, bool faceCraméBienPlacé)
    {
        Nombre = position;
        FaceCraméBienPlacé = faceCraméBienPlacé;
    }
}

Body:
You copied the list, but you didn't copy the crêpes!

To copy the crêpes, you can write a GetCopy method in the Crêpe class:

public Crêpe GetCopy() => new Crêpe(Nombre, FaceCraméBienPlacé);

And then use Select to create a copy of each Crêpe, then use ToList to create a new list:

Solutions.Add(Ordre.Select(x => x.GetCopy()).ToList()); // 1.

You should also change the last line in the outer loop.


问:
replace ALL pixels if Red Channel NOT found in the list
I have a colored image and a mask in a numPy value as defined below:

```<code>img = cv2.imread(path)
mask = [13 16 17 23 24 25 29 30 31 100]
</code>```

Now, I want to change ALL pixels to 0 or Black if my colored image the Red channel value IS NOT in my mask.  I can do this by doing a loop, but I want to do this in a numPyish way.  Is this possible?

答:
You can use np.isin to check.

```<code>img = cv2.imread(path)
mask = np.array([13, 16, 17, 23, 24, 25, 29, 30, 31, 100])
reds = np.isin(img[:,:,2],mask)
</code>```

OpenCV loads images in the bgr format, meaning that red is the last channel. np.isin returns you a boolean array of shape (HxW), telling you which red pixels are in the mask and which ones aren't. You can then do a simple check if all pixels are True or not.

```<code>if np.prod(reds):
    img[:]=0
</code>```

Body:
I have a colored image and a mask in a numPy value as defined below:

img = cv2.imread(path)
mask = [13 16 17 23 24 25 29 30 31 100]

Now, I want to change ALL pixels to 0 or Black if my colored image the Red channel value IS NOT in my mask.  I can do this by doing a loop, but I want to do this in a numPyish way.  Is this possible?

Body:
You can use np.isin to check.

img = cv2.imread(path)
mask = np.array([13, 16, 17, 23, 24, 25, 29, 30, 31, 100])
reds = np.isin(img[:,:,2],mask)

OpenCV loads images in the bgr format, meaning that red is the last channel. np.isin returns you a boolean array of shape (HxW), telling you which red pixels are in the mask and which ones aren't. You can then do a simple check if all pixels are True or not.

if np.prod(reds):
    img[:]=0


问:
Google Apps Script V8 assignment to null cancels debugging
A variable assignment to null causes debugging to cancel execution at that line.
Here is a test script that reproduces the problem:

```<code>function myFunction() {
  var a = "Hallo";
  Logger.log("a=" + a);
  var b = null;
  Logger.log("b=" + b);
}
</code>```

When debugging this script execution is cancelled on line "var b = null;".  Log output is:

```<code>Mar 11, 2020, 8:52:49 PM    Info    a=Hallo
Mar 11, 2020, 8:52:54 PM    Info    Execution cancelled.
</code>```

The result is the same when stepping over the line and running past the line in debug mode. However, in the latter case a red error message flashes for a moment at the top of the screen that says: "We're sorry, a server error occurred. Please wait a bit and try again."... waiting and retrying makes no difference.
[Tried it again today after Jeff's comment below and was only able to recreate it by stepping over the assignment line in debug mode]

When running the script normally (not in debug) it completes successfully.

答:
I found temporary workaround:

Temporally (just for debugging) remove var for variable that takes null value.

Be careful: variable without var becomes global - so you can accidentally change value of the global variable with the same name.

But without the var you will not be able to see your variable in the debugger. So another workaround is to test your variable using if statement to see the value in the debugger:

change:

```<code>  var b = null;
</code>```

temporally (just for debugging) to:

```<code>  b = null;
  if (b==null){
    var b0='null';
  } else {
    var b0=b;
  }
</code>```

and observe b0 variable in the debugger

Body:
A variable assignment to null causes debugging to cancel execution at that line.
Here is a test script that reproduces the problem:

function myFunction() {
  var a = "Hallo";
  Logger.log("a=" + a);
  var b = null;
  Logger.log("b=" + b);
}

When debugging this script execution is cancelled on line "var b = null;".  Log output is:

Mar 11, 2020, 8:52:49 PM    Info    a=Hallo
Mar 11, 2020, 8:52:54 PM    Info    Execution cancelled.

The result is the same when stepping over the line and running past the line in debug mode. However, in the latter case a red error message flashes for a moment at the top of the screen that says: "We're sorry, a server error occurred. Please wait a bit and try again."... waiting and retrying makes no difference.
[Tried it again today after Jeff's comment below and was only able to recreate it by stepping over the assignment line in debug mode]

When running the script normally (not in debug) it completes successfully.

Body:
I found temporary workaround:

Temporally (just for debugging) remove var for variable that takes null value.

Be careful: variable without var becomes global - so you can accidentally change value of the global variable with the same name.

But without the var you will not be able to see your variable in the debugger. So another workaround is to test your variable using if statement to see the value in the debugger:

change:

  var b = null;

temporally (just for debugging) to:

  b = null;
  if (b==null){
    var b0='null';
  } else {
    var b0=b;
  }

and observe b0 variable in the debugger


问:
Finding combinations of elements in a list based on routing
I'm not sure how to verbally express what I want to achieve, and formulating a proper question for this, so here's an example:

If I have a comprehensive list with elements like this:

```<code>list = ['A to B', 'B to C', 'C to D', 'D to E', 'A to C', 'A to D', 'A to E',
 'B to A', 'B to C', 'B to D', 'B to E', 'C to A', 'E to B', 'E to C', 'E to A']
</code>```

I would like to find all unique combinations of exactly 3 elements expressing a routing, and subsequently, store those combinations in separate lists like so:

```<code>['A to B', 'B to C', 'C to A'],

['B to C', 'C to A', 'A to B'],

etc.
</code>```

So, in the first example output, A reverts back to A, and in the second output, B reverts back to B. I would like to see anything reverting back to itself in this fashion.

I'm new to Python and trying to think of ways to do this, but I get stuck.

How would I achieve this?

答:
I would suggest putting all steps into a dictionary of key -> list of keys  it leads to.

You can query this to get all the triplets:

```<code>data = ['A to B', 'B to C', 'C to D', 'D to E', 'A to C', 'A to D', 'A to E',
 'B to A', 'B to C', 'B to D', 'B to E', 'C to A', 'E to B', 'E to C', 'E to A']

from collections import defaultdict
routes = defaultdict(list)

for d in data:
    frm, to = d.split(" to ")
    routes[frm].append(to)

print (routes)

plets = set()

for frm, to in routes.items():
    for target in to:
        for target2 in routes[target]:
            if frm in routes[target2]:
                plets.add( (frm, target, target2, frm) )

for t in sorted(plets):
    print(*t, sep= " -> ")
</code>```

Output:

```<code>defaultdict(<class 'list'>, {'A': ['B', 'C', 'D', 'E'],
                             'B': ['C', 'A', 'C', 'D', 'E'],
                             'C': ['D', 'A'],
                             'D': ['E'],
                             'E': ['B', 'C', 'A']})

A -> B -> C -> A
A -> B -> E -> A
A -> D -> E -> A
A -> E -> B -> A
A -> E -> C -> A
B -> A -> E -> B
B -> C -> A -> B
B -> D -> E -> B
B -> E -> A -> B
C -> A -> B -> C
C -> A -> E -> C
C -> D -> E -> C
D -> E -> A -> D
D -> E -> B -> D
D -> E -> C -> D
E -> A -> B -> E
E -> A -> D -> E
E -> B -> A -> E
E -> B -> D -> E
E -> C -> A -> E
E -> C -> D -> E
</code>```

Using a set to store your possible routes avoids getting same ones multiple times.

Edit for outputting issue:

```<code>def formIt(a,b,c,d):
    return f"{a} to {b}",f"{b} to {c}",f"{c} to {d}"

for frm, to in routes.items():
    for target in to:
        for target2 in routes[target]:
            if frm in routes[target2]:
                plets.add( formIt(frm, target, target2, frm) )

for t in sorted(plets):
    print(*t, sep = ", ")
</code>```

to get

```<code>A to B, B to C, C to A
A to B, B to E, E to A
A to D, D to E, E to A
 ... snipp...
E to C, C to A, A to E
E to C, C to D, D to E
</code>```

Body:
I'm not sure how to verbally express what I want to achieve, and formulating a proper question for this, so here's an example:

If I have a comprehensive list with elements like this:

list = ['A to B', 'B to C', 'C to D', 'D to E', 'A to C', 'A to D', 'A to E',
 'B to A', 'B to C', 'B to D', 'B to E', 'C to A', 'E to B', 'E to C', 'E to A']

I would like to find all unique combinations of exactly 3 elements expressing a routing, and subsequently, store those combinations in separate lists like so:

['A to B', 'B to C', 'C to A'],

['B to C', 'C to A', 'A to B'],

etc.

So, in the first example output, A reverts back to A, and in the second output, B reverts back to B. I would like to see anything reverting back to itself in this fashion.

I'm new to Python and trying to think of ways to do this, but I get stuck.

How would I achieve this?

Body:
I would suggest putting all steps into a dictionary of key -> list of keys  it leads to.

You can query this to get all the triplets:

data = ['A to B', 'B to C', 'C to D', 'D to E', 'A to C', 'A to D', 'A to E',
 'B to A', 'B to C', 'B to D', 'B to E', 'C to A', 'E to B', 'E to C', 'E to A']

from collections import defaultdict
routes = defaultdict(list)

for d in data:
    frm, to = d.split(" to ")
    routes[frm].append(to)

print (routes)

plets = set()

for frm, to in routes.items():
    for target in to:
        for target2 in routes[target]:
            if frm in routes[target2]:
                plets.add( (frm, target, target2, frm) )

for t in sorted(plets):
    print(*t, sep= " -> ")

Output:

defaultdict(<class 'list'>, {'A': ['B', 'C', 'D', 'E'],
                             'B': ['C', 'A', 'C', 'D', 'E'],
                             'C': ['D', 'A'],
                             'D': ['E'],
                             'E': ['B', 'C', 'A']})

A -> B -> C -> A
A -> B -> E -> A
A -> D -> E -> A
A -> E -> B -> A
A -> E -> C -> A
B -> A -> E -> B
B -> C -> A -> B
B -> D -> E -> B
B -> E -> A -> B
C -> A -> B -> C
C -> A -> E -> C
C -> D -> E -> C
D -> E -> A -> D
D -> E -> B -> D
D -> E -> C -> D
E -> A -> B -> E
E -> A -> D -> E
E -> B -> A -> E
E -> B -> D -> E
E -> C -> A -> E
E -> C -> D -> E

Using a set to store your possible routes avoids getting same ones multiple times.

Edit for outputting issue:

def formIt(a,b,c,d):
    return f"{a} to {b}",f"{b} to {c}",f"{c} to {d}"

for frm, to in routes.items():
    for target in to:
        for target2 in routes[target]:
            if frm in routes[target2]:
                plets.add( formIt(frm, target, target2, frm) )

for t in sorted(plets):
    print(*t, sep = ", ")

to get

A to B, B to C, C to A
A to B, B to E, E to A
A to D, D to E, E to A
 ... snipp...
E to C, C to A, A to E
E to C, C to D, D to E


问:
Html.TextBoxFor formatting or Html.EditorFor htmlAttributes?
I am kind of stumped because, I want to format the value and add a html attribute for css class.

If I use @Html.TextBoxFor(m => m.DateModified)
- I can add html attribute but formatting does not work via DisplayFormat attribute on the member.

If I use  @Html.EditorFor(m => m.DateModified)
- Formatting works but I cannot add html attribute

If I use @Html.TextBox("DateModified", Model.DateModified, ...)
- I get null reference exception when Model is null when the form is in add mode

What is the best way to achieve this?

答:
I ended up solving this by creating a custom editor template for my date picker as so:

Shared/EditorTemplates/DateTime.cshtml

```<code> @model System.DateTime?
 @Html.TextBox("", Model.HasValue ? Model.Value.ToString("dd/MM/yyyy") : string.Empty, new { @class = "date-picker" })
</code>```

Then in my original page continue to use

```<code>@Html.EditorFor(m => m.DateModified)
</code>```

Body:
I ended up solving this by creating a custom editor template for my date picker as so:

Shared/EditorTemplates/DateTime.cshtml

 @model System.DateTime?
 @Html.TextBox("", Model.HasValue ? Model.Value.ToString("dd/MM/yyyy") : string.Empty, new { @class = "date-picker" })

Then in my original page continue to use

@Html.EditorFor(m => m.DateModified)


问:
Set a String to TextView and wait for a while and set another String to same TextView
I want to set "First" word to TextView (textTT) and wait for a while set to "Second" to same TextView
but result is directly set "second" to TextView
but I need firstly set "First". How can I overcome this?
<></p>

```<code>private void applicationTest()  {
    textTT.setText("First");
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    textTT.setText("Second");
}
</code>```

答:
Using thred.sleep is a very bad practice since you freeze the whole app! So you basically say: set text first but do nothing, then set second. So you see second.
Instead you should use Handler. In that case you say: set first then create a parallel task that waits for 1sec before it executes. After 1 sec it sets second.

That is the code for this:

```<code>private void applicationTest()  {
    textTT.setText("First");
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
       @Override
       public void run() {
          textTT.setText("Second");
       }
   }, 1000);
}
</code>```

Body:
I want to set "First" word to TextView (textTT) and wait for a while set to "Second" to same TextView
but result is directly set "second" to TextView
but I need firstly set "First". How can I overcome this?
<>

private void applicationTest()  {
    textTT.setText("First");
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    textTT.setText("Second");
}

Body:
Using thred.sleep is a very bad practice since you freeze the whole app! So you basically say: set text first but do nothing, then set second. So you see second.
Instead you should use Handler. In that case you say: set first then create a parallel task that waits for 1sec before it executes. After 1 sec it sets second.

That is the code for this:

private void applicationTest()  {
    textTT.setText("First");
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
       @Override
       public void run() {
          textTT.setText("Second");
       }
   }, 1000);
}


问:
Append pandas dataframe with dictionary using for loop
I have the following dictionary and I want to add these in to a pandas dataframe:

```<code>crimes1 = {'SOUTHERN': 28445,
 'NORTHERN': 20100,
 'MISSION': 19503}
</code>```

I create the blank dataframe with the column names I want:

```<code>column_names = ['Neighborhood', 'Count']
crimes2 = pd.DataFrame(columns=column_names)
</code>```

Next I want to append the dataframe with my dictionary containing the keys and values above using a for loop:

```<code>for i, x in crimes1:
    crimes2 = crimes2.append({'Neighborhood': i}, {'Count': x}, ignore_index=True)
</code>```

The error I get is ValueError: too many values to unpack (expected 2)

I can populate only one column when I do it separately but can't seem to get both in to the one dataframe. Any ideas on how to get this to work using the for loop above?

答:
You can use the map function

```<code>crimes2 = pd.DataFrame(map(list, crimes1.items()))

crimes2.columns = ['Neighborhood', 'Count']
</code>```

Body:
I have the following dictionary and I want to add these in to a pandas dataframe:

crimes1 = {'SOUTHERN': 28445,
 'NORTHERN': 20100,
 'MISSION': 19503}

I create the blank dataframe with the column names I want:

column_names = ['Neighborhood', 'Count']
crimes2 = pd.DataFrame(columns=column_names)

Next I want to append the dataframe with my dictionary containing the keys and values above using a for loop:

for i, x in crimes1:
    crimes2 = crimes2.append({'Neighborhood': i}, {'Count': x}, ignore_index=True)

The error I get is ValueError: too many values to unpack (expected 2)

I can populate only one column when I do it separately but can't seem to get both in to the one dataframe. Any ideas on how to get this to work using the for loop above?

Body:
You can use the map function

crimes2 = pd.DataFrame(map(list, crimes1.items()))

crimes2.columns = ['Neighborhood', 'Count']


问:
Pyspark Dataframe: can't resolve calculating mean/avg/agg of Column(inclusive of empty values)
I am running a Glue Job, and my Dataset contains column with few empty values.As of running crawler on the Dataset, datatype identified as 'double' for the column.

While replacing empty values with mean of the Column, I am not able to calculate mean as it says mean/avg/agg can only be applied on the numeric column.

And while doing Typecast to IntegerType or DecimalType

```<code>dataframe_temp = dataframe.withColumn("col_1",dataframe["col_1"].cast(IntegerType()))
</code>```

getting error as :AnalysisException: "cannot resolve 'CAST(`col_1` AS INT)' due to data type mismatch: cannot cast struct<double:double,string:string> to int;

However, on manual removal of empty values, mean is working fine.

Could anyone please suggest me, how to replace empty values in the column with the mean of the column.

答:
Use Imputer estimator to impute missing values. You can use sample code as following-

val df = spark.createDataFrame(Seq(
      (1.0, 0),
      (2.0, 0),
      (0, 3.0),
      (4.0, 4.0),
      (5.0, 5.0)
    )).toDF("_c1", "_c2")

val imputer = new Imputer()
    .setStrategy("mean") // supported mode "mean"/"median"
    .setMissingValue(0)
    .setInputCols(Array("_c1","_c2"))
    .setOutputCols(Array("_c1_out","_c2_out"));

val transformedData = imputer.fit(df).transform(df)
```

Please note that- the input columns should be of DoubleType or FloatType.

Body:
I am running a Glue Job, and my Dataset contains column with few empty values.As of running crawler on the Dataset, datatype identified as 'double' for the column.

While replacing empty values with mean of the Column, I am not able to calculate mean as it says mean/avg/agg can only be applied on the numeric column.

And while doing Typecast to IntegerType or DecimalType

dataframe_temp = dataframe.withColumn("col_1",dataframe["col_1"].cast(IntegerType()))

getting error as :AnalysisException: "cannot resolve 'CAST(`col_1` AS INT)' due to data type mismatch: cannot cast struct<double:double,string:string> to int;

However, on manual removal of empty values, mean is working fine.

Could anyone please suggest me, how to replace empty values in the column with the mean of the column.

Body:
Use Imputer estimator to impute missing values. You can use sample code as following-

val df = spark.createDataFrame(Seq(
      (1.0, 0),
      (2.0, 0),
      (0, 3.0),
      (4.0, 4.0),
      (5.0, 5.0)
    )).toDF("_c1", "_c2")

val imputer = new Imputer()
    .setStrategy("mean") // supported mode "mean"/"median"
    .setMissingValue(0)
    .setInputCols(Array("_c1","_c2"))
    .setOutputCols(Array("_c1_out","_c2_out"));

val transformedData = imputer.fit(df).transform(df)

Please note that- the input columns should be of DoubleType or FloatType.


问:
How to make 15px of free space under the picture?
Here is the code:
https://jsfiddle.net/Krzysiek_35/Ljybwz97/44/

body
{
    left: 8%;
  top: 10%;
  position: absolute;
  background-color: #6699cc;
}

.box3
{
    background-color: #191919;
    position: absolute;
    padding: 15px 40px 0px;
    font-size: 12px;
    color: #DDDDDD;
    font-family: Verdana;
    font-size: 12px;
    width: 400px;
}

.box3 > li
{
    display: flex;
    align-items: center;
}

.box3 > li span
{
    margin: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

    <div class="box3">

        <li>
            <img src="pictures/contact/skype.png" width="34px" height="34px" />
            <span>Skype name</span>
        </li>

        <li>
            <img src="pictures/contact/gadu-gadu.png" width="34px" height="34px" />
            <span>Gadu-Gadu number</span>
        </li>

        <li>
            <img src="pictures/contact/email.png" width="34px" height="34px" />
            <span>Email address</span>
        </li>

    </div>

</body></code>```

Unfortunately, these 2 variants are wrong!

Variant number 1:

.box3 > li img
{
    margin-bottom: 15px;
}```
</div>
</div>
</p>
<p>Variant number 2:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box3 > li img
{
    padding: 0px 0px 15px;
}</code>```

padding -> 15px (as the upper space), 40px (as the left space) and 0px (as the bottom space)

How to make 15px of free space under the picture?

I will be very grateful for effective help.

答:
just add margin bottom to LI

body
{
 left: 8%;
  top: 10%;
  position: absolute;
  background-color: #6699cc;
}

.box3
{
 background-color: #191919;
 position: absolute;
 padding: 15px 40px 0px;
 font-size: 12px;
 color: #DDDDDD;
 font-family: Verdana;
 font-size: 12px;
 width: 400px;
}

.box3 > li
{
 display: flex;
 align-items: center;
margin-bottom: 15px;
}

.box3 > li span
{
 margin: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="box3">

  <li>
   <img src="pictures/contact/skype.png" width="34px" height="34px" />
   <span>Skype name</span>
  </li>

  <li>
   <img src="pictures/contact/gadu-gadu.png" width="34px" height="34px" />
   <span>Gadu-Gadu number</span>
  </li>

  <li>
   <img src="pictures/contact/email.png" width="34px" height="34px" />
   <span>Email address</span>
  </li>

 </div></code>```

Body:
Here is the code:
https://jsfiddle.net/Krzysiek_35/Ljybwz97/44/

body
{
    left: 8%;
  top: 10%;
  position: absolute;
  background-color: #6699cc;
}

.box3
{
    background-color: #191919;
    position: absolute;
    padding: 15px 40px 0px;
    font-size: 12px;
    color: #DDDDDD;
    font-family: Verdana;
    font-size: 12px;
    width: 400px;
}

.box3 > li
{
    display: flex;
    align-items: center;
}

.box3 > li span
{
    margin: 5px;
}

            Skype name

            Gadu-Gadu number

            Email address

Unfortunately, these 2 variants are wrong!

Variant number 1:

.box3 > li img
{
    margin-bottom: 15px;
}

Variant number 2:

.box3 > li img
{
    padding: 0px 0px 15px;
}

padding -> 15px (as the upper space), 40px (as the left space) and 0px (as the bottom space)

How to make 15px of free space under the picture?

I will be very grateful for effective help.

Body:
just add margin bottom to LI

body
{
 left: 8%;
  top: 10%;
  position: absolute;
  background-color: #6699cc;
}

.box3
{
 background-color: #191919;
 position: absolute;
 padding: 15px 40px 0px;
 font-size: 12px;
 color: #DDDDDD;
 font-family: Verdana;
 font-size: 12px;
 width: 400px;
}

.box3 > li
{
 display: flex;
 align-items: center;
margin-bottom: 15px;
}

.box3 > li span
{
 margin: 5px;
}

 <div class="box3">

  <li>
   <img src="pictures/contact/skype.png" width="34px" height="34px" />
   <span>Skype name</span>
  </li>

  <li>
   <img src="pictures/contact/gadu-gadu.png" width="34px" height="34px" />
   <span>Gadu-Gadu number</span>
  </li>

  <li>
   <img src="pictures/contact/email.png" width="34px" height="34px" />
   <span>Email address</span>
  </li>

 </div>


问:
How to create dotted path from a text in html5 canvas (currently using phaser.io)
I want to create a dotted letter to represent a path on an html canvas, for example

```<code>function convertToDotttedPath(text, font) {

   return [{x: x0, y: y0}, {x: x1, y: y1}...] //to represent a path of text on a 2D canvas

}
</code>```

Is there a library I can use? I would want to do this in code rather than manually using Adobe flash, like in the video below.

I'm trying to do this similar thing here but in canvas: https://www.youtube.com/watch?v=Xi25vodMYg0

答:
How about using setLineDash it would draw a dotted letter or word...

Code is simple, something like this:

<canvas id="c" width=600 height=160></canvas>

```
</div>
</div>
</p>

<hr>

<p>You can play with the font, lineWidth and LineDash values to get different results</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="c" width=600 height=160></canvas>

<script>
  var ctx = document.getElementById("c").getContext("2d");
  ctx.font = "50px Arial";
  ctx.lineWidth = 0.5;
  ctx.setLineDash([1, 4]);
  ctx.strokeText("HELLO", 10, 45);

  ctx.setLineDash([3, 6]);
  ctx.strokeText("WORLD", 10, 90);
</script></code>```

You can apply it to lines as well

<canvas id="c" width=160 height=160></canvas>

```

And using that same setLineDash you can do some fancy animations:

https://raw.githack.com/heldersepu/hs-scripts/master/HTML/canvas_text_anim.html

https://raw.githack.com/heldersepu/hs-scripts/master/HTML/canvas_text_flicker.html

Body:
I want to create a dotted letter to represent a path on an html canvas, for example

function convertToDotttedPath(text, font) {

   return [{x: x0, y: y0}, {x: x1, y: y1}...] //to represent a path of text on a 2D canvas

}

Is there a library I can use? I would want to do this in code rather than manually using Adobe flash, like in the video below.

I'm trying to do this similar thing here but in canvas: https://www.youtube.com/watch?v=Xi25vodMYg0

Body:
How about using setLineDash it would draw a dotted letter or word...

Code is simple, something like this:

<canvas id="c" width=600 height=160></canvas>

<script>
  var ctx = document.getElementById("c").getContext("2d");
  ctx.font = "150px Arial";
  ctx.lineWidth = 2;
  ctx.setLineDash([3, 13]);
  ctx.strokeText("HELLO", 10, 120);
</script>

You can play with the font, lineWidth and LineDash values to get different results

<canvas id="c" width=600 height=160></canvas>

<script>
  var ctx = document.getElementById("c").getContext("2d");
  ctx.font = "50px Arial";
  ctx.lineWidth = 0.5;
  ctx.setLineDash([1, 4]);
  ctx.strokeText("HELLO", 10, 45);

  ctx.setLineDash([3, 6]);
  ctx.strokeText("WORLD", 10, 90);
</script>

You can apply it to lines as well

<canvas id="c" width=160 height=160></canvas>

<script>
  var ctx = document.getElementById("c").getContext("2d");
  ctx.translate(80, 80);
  ctx.lineWidth = 0.5;

  function drawTriangle(size, angle) {
    ctx.beginPath();
    size = size * 12
    for (j = 0; j < 4; j++) {
      a = angle * Math.PI / 180
      x = size * Math.sin(a)
      y = size * Math.cos(a)
      ctx.lineTo(x, y);
      angle += 120
    }
    ctx.stroke();
  }

  for (i = 20; i > 0; i--) {
    ctx.setLineDash([i, i/2]);
    drawTriangle(i, i*2 - Math.sin(i / 50))
  }
</script>

And using that same setLineDash you can do some fancy animations:

https://raw.githack.com/heldersepu/hs-scripts/master/HTML/canvas_text_anim.html

https://raw.githack.com/heldersepu/hs-scripts/master/HTML/canvas_text_flicker.html


问:
How can I get an XML attribute by name instead of iterating over all the attributes?
I'm using vb script and MSXML2.DOMDocument  to parse a xml document.

Is it possible get a particular attribute by name instead of iterating over all the attributes?

Today I am doing this

```<code>For x = 0 To (curNode.Attributes.length - 1)
    sAttrName = curNode.Attributes.Item(x).nodeName
     if sAttrName = 'customer' then
        avalue=curNode.Attributes.Item(x).nodeValue
</code>```

but I want do something like this

```<code> avalue=curNode.Attributes.Item("customer").nodeValue
</code>```

答:
Try getAttribute(), as in curNode.getAttribute("customer").

I'm assuming that curNode is an oXMLDOMElement, though you didn't show its type.

Body:
I'm using vb script and MSXML2.DOMDocument  to parse a xml document.

Is it possible get a particular attribute by name instead of iterating over all the attributes?

Today I am doing this

For x = 0 To (curNode.Attributes.length - 1)
    sAttrName = curNode.Attributes.Item(x).nodeName
     if sAttrName = 'customer' then
        avalue=curNode.Attributes.Item(x).nodeValue

but I want do something like this

 avalue=curNode.Attributes.Item("customer").nodeValue