问:
Higher-order function composition notation
I'm working with this higher-order compose function:

```<code>fun <T, U, V> higherCompose(): ((U) -> V) -> ((T) -> U) -> (T) -> V =
    { f ->
        { g ->
            { x -> f(g(x)) }
        }
    }
</code>```

And the application:

```<code> val cos = higherCompose<Double, Double, Double>()()
{ x: Double -> Math.sin(x)}() { x : Double -> Math.PI/2  - x }
</code>```

I do understand what we're trying to achieve here mathematically. But what I'm struggling with is notation and the programming meaning:

What exactly is

```<code>higherCompose<Double>()
</code>```

And why do we apply so strangely values to it:

```<code>1. () ()
2. { function1} { function 1}
</code>```

答:
Another way to handle function composition in Kotlin is to use an extension function on the function type.  Try something like this:

```<code>infix fun <P1, R1, R2> ((P1) -> R1).then(f: ((R1)-> R2)) : (P1) -> R2 {
    return { p1 : P1 -> f(this(p1)) }
}
</code>```

This allows you to use a simpler construct in your code:

```<code>function1 then function1
</code>```

Using your example above you can do:

```<code>infix fun <P1, R1, R2> ((P1) -> R1).then(f: ((R1)-> R2)) : (P1) -> R2 {
    return { p1 : P1 -> f(this(p1)) }
}

fun main() {
    val c = { x: Double -> Math.sin(x)} then { x : Double -> Math.PI/2  - x }
    println(c(2.4))
}
</code>```

which prints 0.8953331462437456.

Check out my Functional FizzBuzz post which uses this approach.

Body:
I'm working with this higher-order compose function:

fun <T, U, V> higherCompose(): ((U) -> V) -> ((T) -> U) -> (T) -> V =
    { f ->
        { g ->
            { x -> f(g(x)) }
        }
    }

And the application:

 val cos = higherCompose<Double, Double, Double>()()
{ x: Double -> Math.sin(x)}() { x : Double -> Math.PI/2  - x }

I do understand what we're trying to achieve here mathematically. But what I'm struggling with is notation and the programming meaning:

What exactly is

higherCompose<Double>()

And why do we apply so strangely values to it:

1. () ()
2. { function1} { function 1}

Body:
Another way to handle function composition in Kotlin is to use an extension function on the function type.  Try something like this:

infix fun <P1, R1, R2> ((P1) -> R1).then(f: ((R1)-> R2)) : (P1) -> R2 {
    return { p1 : P1 -> f(this(p1)) }
}

This allows you to use a simpler construct in your code:

function1 then function1

Using your example above you can do:

infix fun <P1, R1, R2> ((P1) -> R1).then(f: ((R1)-> R2)) : (P1) -> R2 {
    return { p1 : P1 -> f(this(p1)) }
}

fun main() {
    val c = { x: Double -> Math.sin(x)} then { x : Double -> Math.PI/2  - x }
    println(c(2.4))
}

which prints 0.8953331462437456.

Check out my Functional FizzBuzz post which uses this approach.


来源: stackexchange

问:
Angular Subdomain
I am trying to create a subdomain in angular 6 using the below method.

For example:

localhost:4200

client1.localhost:4200

client2.localhost:4200

```<code>  getSubdomain() {
    const domain = window.location.hostname;
    if (domain.indexOf('.') < 0
       || domain.split('.')[0] === 'example'
       || domain.split('.')[0] === 'lvh'
       || domain.split('.')[0] === 'www') {
       this.subdomain = '';
    } else {
       this.subdomain = domain.split('.')[0];
    }
    console.log('subdomain', this.subdomain);
  }
</code>```

When running the command 'ng serve --disable-host-check' it's working fine. But this is not secure way.

'Invalid Host Header' error message is displayed, when the command 'ng serve' is ran.

Kindly suggest me any other option to create a subdomain in angular 6.

答:
For development purpose you can add sub domain in etc/host file (C:\Windows\System32\drivers\etc\hosts) like below.

```<code>127.0.0.1       client1
::1         client1
127.0.0.1       client2
::1         client2
</code>```

Serve application by using command:-

```<code>ng serve --host client1 --port 4300 --open
ng serve --host client2 --port 4400 --open
</code>```

ContentLicense: CC BY-SA 4.0

Title: Angular Subdomain

Body:
I am trying to create a subdomain in angular 6 using the below method.

For example:

localhost:4200

client1.localhost:4200

client2.localhost:4200

  getSubdomain() {
    const domain = window.location.hostname;
    if (domain.indexOf('.') < 0
       || domain.split('.')[0] === 'example'
       || domain.split('.')[0] === 'lvh'
       || domain.split('.')[0] === 'www') {
       this.subdomain = '';
    } else {
       this.subdomain = domain.split('.')[0];
    }
    console.log('subdomain', this.subdomain);
  }

When running the command 'ng serve --disable-host-check' it's working fine. But this is not secure way.

'Invalid Host Header' error message is displayed, when the command 'ng serve' is ran.

Kindly suggest me any other option to create a subdomain in angular 6.

Body:
For development purpose you can add sub domain in etc/host file (C:\Windows\System32\drivers\etc\hosts) like below.

127.0.0.1       client1
::1         client1
127.0.0.1       client2
::1         client2

Serve application by using command:-

ng serve --host client1 --port 4300 --open
ng serve --host client2 --port 4400 --open


问:
Bottomsheet with moving Floating action buttons
I want to use Bottom-sheet from support library and two floating action buttons (FABS) as shows the pictures. The point is that I also want both FABS moving together with the bottom-sheet like the picture 1 and 2.
What is the basic layout that I have to use and how to make the FABS to be sticky on bottom-sheet?

UPDATE

```<code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical"
tools:context=".MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay"/>

</android.support.design.widget.AppBarLayout>

<android.support.design.widget.CoordinatorLayout
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

      <!-- my context here -->

    </LinearLayout>

      <!-- bottomsheet -->
    <FrameLayout
        android:id="@+id/bottom_sheet"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ff0000"
        app:behavior_hideable="true"
        app:layout_behavior="android.support.design.widget.BottomSheetBehavior">

        <include layout="@layout/navigation_info" />

    </FrameLayout>

    <!-- FABS -->

    <!-- wrap to primary fab to extend the height -->

    <LinearLayout
        android:id="@+id/primary_wrap"
        android:layout_width="wrap_content"
        android:layout_height="88dp"
        app:layout_anchor="@id/bottom_sheet"
        app:layout_anchorGravity="top|end">

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/primary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:layout_margin="@dimen/fab_margin"
            android:src="@android:drawable/ic_delete"/>
    </LinearLayout>

    <!-- Pin secondary fab in the top of the extended primary -->
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/secondary"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top|end"
        android:layout_margin="16dp"
        android:src="@android:drawable/ic_dialog_email"
        app:layout_anchor="@+id/primary_wrap"
        app:layout_anchorGravity="top|end"/>

</android.support.design.widget.CoordinatorLayout>
</code>```

Based on Ruan_Lopes answer.

With this layout my FABS works as I want but I still think that I am not doing it very clear.

I am wondering if its possible to do this with more official way.

答:
This code worked for me

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.androidsample.BottomSheetActivity">

    <!-- include app bar -->
    <include layout="@layout/app_bar" />

    <!-- include main content -->
    <include layout="@layout/activity_bottom_sheet_content" />

    <!-- include bottom sheet -->
    <include layout="@layout/bottom_sheet" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/b2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/activity_vertical_margin"
        android:src="@drawable/ic_share_black_24dp"
        app:backgroundTint="#3F51B5"
        app:layout_anchor="@+id/text"
        app:layout_anchorGravity="top|end" />

    <TextView
        android:id="@+id/text"
        android:layout_width="50dp"
        android:layout_height="70dp"
        app:layout_anchor="@+id/b1"
        app:layout_anchorGravity="top|end" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/b1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/activity_vertical_margin"
        android:src="@drawable/ic_share_black_24dp"
        app:backgroundTint="#3F51B5"
        app:layout_anchor="@+id/bottom_sheet_mapviewfinal"
        app:layout_anchorGravity="top|end" />

</android.support.design.widget.CoordinatorLayout>
</code>```

with layout_anchor id you are referring to the id of the bottom_sheet.

reference:
Medium Reference

Hope it helps.

ContentLicense: CC BY-SA 3.0

Body:
I want to use Bottom-sheet from support library and two floating action buttons (FABS) as shows the pictures. The point is that I also want both FABS moving together with the bottom-sheet like the picture 1 and 2.
What is the basic layout that I have to use and how to make the FABS to be sticky on bottom-sheet?

UPDATE

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical"
tools:context=".MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay"/>

</android.support.design.widget.AppBarLayout>

<android.support.design.widget.CoordinatorLayout
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </LinearLayout>

    <FrameLayout
        android:id="@+id/bottom_sheet"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ff0000"
        app:behavior_hideable="true"
        app:layout_behavior="android.support.design.widget.BottomSheetBehavior">

        <include layout="@layout/navigation_info" />

    </FrameLayout>

    <LinearLayout
        android:id="@+id/primary_wrap"
        android:layout_width="wrap_content"
        android:layout_height="88dp"
        app:layout_anchor="@id/bottom_sheet"
        app:layout_anchorGravity="top|end">

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/primary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:layout_margin="@dimen/fab_margin"
            android:src="@android:drawable/ic_delete"/>
    </LinearLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/secondary"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top|end"
        android:layout_margin="16dp"
        android:src="@android:drawable/ic_dialog_email"
        app:layout_anchor="@+id/primary_wrap"
        app:layout_anchorGravity="top|end"/>

</android.support.design.widget.CoordinatorLayout>

Based on Ruan_Lopes answer.

With this layout my FABS works as I want but I still think that I am not doing it very clear.

I am wondering if its possible to do this with more official way.

Body:
This code worked for me

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.androidsample.BottomSheetActivity">

    <!-- include app bar -->
    <include layout="@layout/app_bar" />

    <!-- include main content -->
    <include layout="@layout/activity_bottom_sheet_content" />

    <!-- include bottom sheet -->
    <include layout="@layout/bottom_sheet" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/b2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/activity_vertical_margin"
        android:src="@drawable/ic_share_black_24dp"
        app:backgroundTint="#3F51B5"
        app:layout_anchor="@+id/text"
        app:layout_anchorGravity="top|end" />

    <TextView
        android:id="@+id/text"
        android:layout_width="50dp"
        android:layout_height="70dp"
        app:layout_anchor="@+id/b1"
        app:layout_anchorGravity="top|end" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/b1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/activity_vertical_margin"
        android:src="@drawable/ic_share_black_24dp"
        app:backgroundTint="#3F51B5"
        app:layout_anchor="@+id/bottom_sheet_mapviewfinal"
        app:layout_anchorGravity="top|end" />

</android.support.design.widget.CoordinatorLayout>

with layout_anchor id you are referring to the id of the bottom_sheet.

reference:
Medium Reference

Hope it helps.


问:
Mozilla Add-on allow Ace Editor code validation
Ace Editor uses this thing called 'blob' to create the Worker (which finds errors in code) and I want to use it in my Firefox extension. The console log showed errors like:

Content Security Policy: The page's settings blocked the loading of a
  resource at blob:moz-extension://{extension-private-uuid}

I am able to fix this using

```<code>"content_security_policy": "script-src 'self' blob:; object-src 'self'",
</code>```

but I read that Add-ons that use the blob: keyword will get rejected from AMO because of major security risks. Is that likely still the case considering that it's a library? If so, then is there any other way of getting the worker to work without blob and without editing any files?

答:
Ok I found the solution.

There is an Ace Editor setting

```<code>ace.config.set('loadWorkerFromBlob', false);
</code>```

which disables the loading of the worker file via blob. Yayyy!

Body:
Ace Editor uses this thing called 'blob' to create the Worker (which finds errors in code) and I want to use it in my Firefox extension. The console log showed errors like:

Content Security Policy: The page's settings blocked the loading of a
  resource at blob:moz-extension://{extension-private-uuid}

I am able to fix this using

"content_security_policy": "script-src 'self' blob:; object-src 'self'",

but I read that Add-ons that use the blob: keyword will get rejected from AMO because of major security risks. Is that likely still the case considering that it's a library? If so, then is there any other way of getting the worker to work without blob and without editing any files?

Body:
Ok I found the solution.

There is an Ace Editor setting

ace.config.set('loadWorkerFromBlob', false);

which disables the loading of the worker file via blob. Yayyy!


问:
twilio Handle a SMS StatusCallback and get all values from request in flask / python
i need to retrive twilio SMS StatusCallback json, but i have problem to take all values in a single json from twilio.

i follow this example https://www.twilio.com/docs/sms/tutorials/how-to-confirm-delivery-python?code-sample=code-handle-a-sms-statuscallback-1&code-language=Python&code-sdk-version=6.x

i try to improve with request.get_json() but i recive None values. it's work if i specify with value with requests.values.get

```<code>@app.route("/MessageStatus", methods=['POST'])
def incoming_sms():

    message_sid = request.values.get('MessageSid', None)
    message_status = request.values.get('MessageStatus', None)
    logging.info('SID: {}, Status: {}'.format(message_sid, message_status))
    print(request.get_json())

    return ('', 204)
</code>```

thank you a lot!

Body:
i need to retrive twilio SMS StatusCallback json, but i have problem to take all values in a single json from twilio.

i follow this example https://www.twilio.com/docs/sms/tutorials/how-to-confirm-delivery-python?code-sample=code-handle-a-sms-statuscallback-1&code-language=Python&code-sdk-version=6.x

i try to improve with request.get_json() but i recive None values. it's work if i specify with value with requests.values.get

@app.route("/MessageStatus", methods=['POST'])
def incoming_sms():

    message_sid = request.values.get('MessageSid', None)
    message_status = request.values.get('MessageStatus', None)
    logging.info('SID: {}, Status: {}'.format(message_sid, message_status))
    print(request.get_json())

    return ('', 204)

thank you a lot!

Body: print(json.dumps(request.values.to_dict()))


问:
dplyr: keep empty levels of factor but not empty levels of a combination of factors that don't appear in data
When grouping and summarising with dplyr, what is the correct way to keep empty levels of each grouping factor but not keep empty combinations from multiple grouping factors?

As an example, consider data recorded at different times at multiple sites. I might filter and then calculate something for each year in each site. I'd like to have the default value of the summary on an empty vector if the filter removes a year completely. So site "a" has 10 years and site "b" has 1 year so I'd always like 11 rows in the summary.

If I use .drop = TRUE in group_by I lose years:

library(dplyr)
library(zoo)
library(lubridate)

set.seed(1)

df <- data.frame(site = factor(c(rep("a", 120), rep("b", 12))),
                 date = c(seq.Date(as.Date("2000/1/1"), by = "month", length.out = 120), seq.Date(as.Date("2000/1/1"), by = "month", length.out = 12)),
                 value = rnorm(132, 50, 10))
df$year <- factor(lubridate::year(df$date))

df %>%
  filter(value > 65) %>%
  group_by(site, year, .drop = TRUE) %>%
  summarise(f = first(date))
#> # A tibble: 6 x 3
#> # Groups:   site [1]
#>   site  year  f
#>   <fct> <fct> <date>
#> 1 a     2000  2000-04-01
#> 2 a     2004  2004-08-01
#> 3 a     2005  2005-01-01
#> 4 a     2007  2007-11-01
#> 5 a     2008  2008-10-01
#> 6 a     2009  2009-02-01
```

<p>and with <code>.drop = FALSE</code> I gain all the extra years for site "b" which were not in the original data:</p>

<pre class="lang-r prettyprint-override"><code>df %>%
  filter(value > 65) %>%
  group_by(site, year, .drop = FALSE) %>%
  summarise(f = first(date))
#> # A tibble: 20 x 3
#> # Groups:   site [2]
#>    site  year  f
#>    <fct> <fct> <date>
#>  1 a     2000  2000-04-01
#>  2 a     2001  NA
#>  3 a     2002  NA
#>  4 a     2003  NA
#>  5 a     2004  2004-08-01
#>  6 a     2005  2005-01-01
#>  7 a     2006  NA
#>  8 a     2007  2007-11-01
#>  9 a     2008  2008-10-01
#> 10 a     2009  2009-02-01
#> 11 b     2000  NA
#> 12 b     2001  NA
#> 13 b     2002  NA
#> 14 b     2003  NA
#> 15 b     2004  NA
#> 16 b     2005  NA
#> 17 b     2006  NA
#> 18 b     2007  NA
#> 19 b     2008  NA
#> 20 b     2009  NA
</code>```

The best way I could think of was to calculate counts, then merge then filter then drop the count variable, but that's pretty messy.
I know the .drop was only recently added to dplyr, which is very useful for one factor, but is there yet a clean way to do this for multiple factors?

df %>%
  filter(value > 65) %>%
  group_by(site, year, .drop = FALSE) %>%
  summarise(f = first(date)) %>%
  left_join(df %>% count(site, year, .drop = FALSE), by = c("site", "year")) %>%
  filter(n > 0) %>%
  select(-n)
#> # A tibble: 11 x 3
#> # Groups:   site [2]
#>    site  year  f
#>    <fct> <fct> <date>
#>  1 a     2000  2000-04-01
#>  2 a     2001  NA
#>  3 a     2002  NA
#>  4 a     2003  NA
#>  5 a     2004  2004-08-01
#>  6 a     2005  2005-01-01
#>  7 a     2006  NA
#>  8 a     2007  2007-11-01
#>  9 a     2008  2008-10-01
#> 10 a     2009  2009-02-01
#> 11 b     2000  NA
```

答:
Not sure if this is what you like.

If you replace dates with value < 65 with NA instead of filtering them out you can proceed as usual.

```<code>

df %>%
  mutate(date = replace(date, value < 65, NA)) %>%
  group_by(site, year) %>%
  summarise(f = first(date[!is.na(date)]))

# A tibble: 11 x 3
# Groups:   site [2]
   site  year  f
   <fct> <fct> <date>
 1 a     2000  NA
 2 a     2001  NA
 3 a     2002  2002-03-01
 4 a     2003  NA
 5 a     2004  NA
 6 a     2005  NA
 7 a     2006  2006-02-01
 8 a     2007  NA
 9 a     2008  2008-07-01
10 a     2009  2009-02-01
11 b     2000  2000-08-01

</code>```

Body:
When grouping and summarising with dplyr, what is the correct way to keep empty levels of each grouping factor but not keep empty combinations from multiple grouping factors?

As an example, consider data recorded at different times at multiple sites. I might filter and then calculate something for each year in each site. I'd like to have the default value of the summary on an empty vector if the filter removes a year completely. So site "a" has 10 years and site "b" has 1 year so I'd always like 11 rows in the summary.

If I use .drop = TRUE in group_by I lose years:

library(dplyr)
library(zoo)
library(lubridate)

set.seed(1)

df <- data.frame(site = factor(c(rep("a", 120), rep("b", 12))),
                 date = c(seq.Date(as.Date("2000/1/1"), by = "month", length.out = 120), seq.Date(as.Date("2000/1/1"), by = "month", length.out = 12)),
                 value = rnorm(132, 50, 10))
df$year <- factor(lubridate::year(df$date))

df %>%
  filter(value > 65) %>%
  group_by(site, year, .drop = TRUE) %>%
  summarise(f = first(date))
#> # A tibble: 6 x 3
#> # Groups:   site [1]
#>   site  year  f
#>   <fct> <fct> <date>
#> 1 a     2000  2000-04-01
#> 2 a     2004  2004-08-01
#> 3 a     2005  2005-01-01
#> 4 a     2007  2007-11-01
#> 5 a     2008  2008-10-01
#> 6 a     2009  2009-02-01

and with .drop = FALSE I gain all the extra years for site "b" which were not in the original data:

df %>%
  filter(value > 65) %>%
  group_by(site, year, .drop = FALSE) %>%
  summarise(f = first(date))
#> # A tibble: 20 x 3
#> # Groups:   site [2]
#>    site  year  f
#>    <fct> <fct> <date>
#>  1 a     2000  2000-04-01
#>  2 a     2001  NA
#>  3 a     2002  NA
#>  4 a     2003  NA
#>  5 a     2004  2004-08-01
#>  6 a     2005  2005-01-01
#>  7 a     2006  NA
#>  8 a     2007  2007-11-01
#>  9 a     2008  2008-10-01
#> 10 a     2009  2009-02-01
#> 11 b     2000  NA
#> 12 b     2001  NA
#> 13 b     2002  NA
#> 14 b     2003  NA
#> 15 b     2004  NA
#> 16 b     2005  NA
#> 17 b     2006  NA
#> 18 b     2007  NA
#> 19 b     2008  NA
#> 20 b     2009  NA

The best way I could think of was to calculate counts, then merge then filter then drop the count variable, but that's pretty messy.
I know the .drop was only recently added to dplyr, which is very useful for one factor, but is there yet a clean way to do this for multiple factors?

df %>%
  filter(value > 65) %>%
  group_by(site, year, .drop = FALSE) %>%
  summarise(f = first(date)) %>%
  left_join(df %>% count(site, year, .drop = FALSE), by = c("site", "year")) %>%
  filter(n > 0) %>%
  select(-n)
#> # A tibble: 11 x 3
#> # Groups:   site [2]
#>    site  year  f
#>    <fct> <fct> <date>
#>  1 a     2000  2000-04-01
#>  2 a     2001  NA
#>  3 a     2002  NA
#>  4 a     2003  NA
#>  5 a     2004  2004-08-01
#>  6 a     2005  2005-01-01
#>  7 a     2006  NA
#>  8 a     2007  2007-11-01
#>  9 a     2008  2008-10-01
#> 10 a     2009  2009-02-01
#> 11 b     2000  NA

Body:
Not sure if this is what you like.

If you replace dates with value < 65 with NA instead of filtering them out you can proceed as usual.

df %>%
  mutate(date = replace(date, value < 65, NA)) %>%
  group_by(site, year) %>%
  summarise(f = first(date[!is.na(date)]))

# A tibble: 11 x 3
# Groups:   site [2]
   site  year  f
   <fct> <fct> <date>
 1 a     2000  NA
 2 a     2001  NA
 3 a     2002  2002-03-01
 4 a     2003  NA
 5 a     2004  NA
 6 a     2005  NA
 7 a     2006  2006-02-01
 8 a     2007  NA
 9 a     2008  2008-07-01
10 a     2009  2009-02-01
11 b     2000  2000-08-01


问:
How do I set/send geolocation parameters lat/long to an Android-x86 emulator
I downloaded an Android iso from the website Android x86 4.0 RC2 reconfigure keyboard.

Installed VirtualBox selecting a Linux distro ,256 MB RAM, 8 GB HDD.

I loaded the iso into the CD to finally install it on the virtual HDD, the emulator runs smoothly.

I allowedmock locations on the developer settings.

I can connect to internet trough the navigator using a NAT*** after executing the command on my host machine

```<code>VBoxManage modifyvm AndroidVM --natpf1 adb,tcp,*,5555,*,5555
</code>```

*If I select the bridge adapter I can not setup the ethernet, netcfg eth0 dhcp produces a timeout

I can connect adb from the host machine

```<code>adb connect localhost
</code>```

I checked that the device is connected:

```<code> C:\Android\android-sdk\platform-tools>adb devices
  List of devices attached
  localhost:5555  device
</code>```

But when I try to set/send geolocation to the emulator...

Via Eclipse-->The Emulator Controls -> Locations controls. It does not allow me to edit lat/long and send it.

If I try to connect using telnet localhost 5555, so I could use the geo command, a black screen appears and if I press any button the cursor moves but nothing appears.

Lastly, I tried to install the application Bluetooth GPS, but when Google Play appears to link an account for some reason network is not detected and I can not continue, even if I am previously registered on the google play website within the browser.

Thanks in advance.

答:
If you want to set the geolocation through some kind of pipeline, you may find this vbs script usable:</p>

```<code>Set client = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
auth_token_file = "C:\Users\" & CreateObject("WScript.Network").UserName & "\.emulator_console_auth_token"

WScript.Sleep 500
client.SendKeys"telnet localhost 5554"
client.SendKeys("{Enter}")
WScript.Sleep 1600
client.SendKeys"auth "
client.SendKeys fso.OpenTextFile(auth_token_file, 1).readAll
client.SendKeys("{Enter}")
WScript.Sleep 1600
client.SendKeys"geo fix 15.9666 45.8154"
WScript.Sleep 1600
client.SendKeys("{Enter}")
WScript.Sleep 1600
client.SendKeys"exit"
client.SendKeys("{Enter}")
client.SendKeys("{Enter}")
</code>```

Body:
I downloaded an Android iso from the website Android x86 4.0 RC2 reconfigure keyboard.

Installed VirtualBox selecting a Linux distro ,256 MB RAM, 8 GB HDD.

I loaded the iso into the CD to finally install it on the virtual HDD, the emulator runs smoothly.

I allowedmock locations on the developer settings.

I can connect to internet trough the navigator using a NAT*** after executing the command on my host machine

VBoxManage modifyvm AndroidVM --natpf1 adb,tcp,*,5555,*,5555

*If I select the bridge adapter I can not setup the ethernet, netcfg eth0 dhcp produces a timeout

I can connect adb from the host machine

adb connect localhost

I checked that the device is connected:

 C:\Android\android-sdk\platform-tools>adb devices
  List of devices attached
  localhost:5555  device

But when I try to set/send geolocation to the emulator...

Via Eclipse-->The Emulator Controls -> Locations controls. It does not allow me to edit lat/long and send it.

If I try to connect using telnet localhost 5555, so I could use the geo command, a black screen appears and if I press any button the cursor moves but nothing appears.

Lastly, I tried to install the application Bluetooth GPS, but when Google Play appears to link an account for some reason network is not detected and I can not continue, even if I am previously registered on the google play website within the browser.

Thanks in advance.

Body:
If you want to set the geolocation through some kind of pipeline, you may find this vbs script usable:

Set client = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
auth_token_file = "C:\Users\" & CreateObject("WScript.Network").UserName & "\.emulator_console_auth_token"

WScript.Sleep 500
client.SendKeys"telnet localhost 5554"
client.SendKeys("{Enter}")
WScript.Sleep 1600
client.SendKeys"auth "
client.SendKeys fso.OpenTextFile(auth_token_file, 1).readAll
client.SendKeys("{Enter}")
WScript.Sleep 1600
client.SendKeys"geo fix 15.9666 45.8154"
WScript.Sleep 1600
client.SendKeys("{Enter}")
WScript.Sleep 1600
client.SendKeys"exit"
client.SendKeys("{Enter}")
client.SendKeys("{Enter}")


问:
How do I sort a 2 dimensional array columns in Swift based on the values in a row?
How can I sort a two dimensional array based on values in one of the rows?

```<code>let array = [["X", "Y",   1,  2,  3,  4,  5],
             ["V", "W", "A","B","C","D","E"]
]

let sorted = [["X", "Y",   5,  4,  3,  2,  1],
              ["V", "W", "E","D","C","B","A"]
    ]
</code>```

The Swift Array.sort({e1, e2 in e1 < e2}) passes in row elements, not column elements.

To make matters worse the first two column in the row must not be sorted.

Bear in mind row 2 must be rearranged according to the row 1 order.  So assuming we are sorting by row 0 and ignoring 1st 2 columns

```<code>[["X", "Y",   1,  2,  3,  4,  5],
 ["V", "W", "E","B","A","D","F"]]
</code>```

should become

```<code>[["X", "Y",   5,  4,  3,  2,  1],
 ["V", "W", "F","D","A","B","E"]]
</code>```

答:
Here is the solution I came up with - very ugly !!</p>

```<code>extension Array where Element == Array<String> {
    /// Creates a totals row at the bottom
    /// ignore - number of columns to ignore at the start
    mutating func addTotalsRow(ignore: Int){
        // Create a totals row (top row)
        var totals = [String]()
        // Add columns if required
        if ignore > 0 {
            totals.append("Total")
            totals.append(contentsOf: repeatElement("", count: ignore - 1))

        }

        for row in self {
            for i in ignore..<row.count {

                let value = row[i].toDouble ?? 0.0
                if (i+1) > totals.count {
                    totals.append("0.0")
                }
                totals[i] = ((totals[i].toDouble ?? 0.0) + value).formatted4
            }
        }

        self.append(totals)

        return
    }

    /// Sort columnwise using values in 'row', ignoring first 'ignore' columns
    /// Also sorts the optional header row
    /// Returns (sortedRows, sortedHeaderRow)
    func columnSorted(_ sortRow: Int, ignoreColumnCount: Int, order: SortOrder = .ascending, headerRow: [String]?)->([[String]], [String]?) {

        // Now calculate a totals row
        var newHeader: [String]?

        // Create an array of objects holding the total and the column index
        var indexes = [IX]()

        let totals = self[sortRow]

        // Ignore the text columns
        for i in ignoreColumnCount..<totals.count {
            indexes.append(IX(total: totals[i], index: i))
        }
        // Sort IX by the totals
        indexes.sort(by: {ix1, ix2 in
            return order == .descending ? ix1.intTotal > ix2.intTotal : ix1.intTotal < ix2.intTotal})

        // Create the Totals data row
        var totalsRow = [String]()
        totalsRow.append(contentsOf: totals[0..<ignoreColumnCount])
        totalsRow.append(contentsOf: indexes.map({$0.total}))

        if let header = headerRow {
            newHeader = [String]()
            newHeader!.append(contentsOf: header[0..<ignoreColumnCount])
            for i in 0..<indexes.count {
                let ix = indexes[i].index
                if ((i+ignoreColumnCount)+1) > newHeader!.count {
                    newHeader!.append("")
                }
                newHeader![i+ignoreColumnCount] = header[ix]
            }
        }

        var newData = [[String]]()
        // newData.append(totalsRow)
        // Now do the same for all the rows in data
        for row in self {
            var newRow = [String]()
            newRow.append(contentsOf: row[0..<ignoreColumnCount])

            for i in 0..<indexes.count {
                let ix = indexes[i].index
                if ((i+ignoreColumnCount)+1) > newRow.count {
                    newRow.append("0.0")
                }
                newRow[i+ignoreColumnCount] = row[ix]
            }
            newData.append(newRow)
        }

        // Sort by count
        return (newData, newHeader)
    }
    /// Sort by column index 0...
    mutating func sort(by column: Int, order: SortOrder = .ascending) {

        guard column > 0 else {
            return
        }
        let index = column - 1

        self.sort(by: {r1, r2 in
            let count1 = (r1[index].toDouble ?? 0.0)
            let count2 = (r2[index].toDouble ?? 0.0)
            if let val = r1[index].toDouble {
                return order == .descending ? (r1[index].toDouble ?? 0.0) > (r2[index].toDouble ?? 0.0) : (r1[index].toDouble ?? 0.0) < (r2[index].toDouble ?? 0.0)
            } else {
                return order == .descending ? r1[index] > r2[index] : r1[index] > r2[index]
            }
        })
    }

    func sorted(by column: Int, order: SortOrder = .ascending, ignoreFirstRow: Bool = false)->[[String]] {

        guard column > 0 else {
            return self
        }
        let index = column - 1

        var resultSet = [[String]]()

        if ignoreFirstRow {
            // Save the first row
            let firstRow = self[0]

            let dataRows = self[1..<count].sorted(by: {r1, r2 in

                if let val = r1[index].toDouble {
                    return order == .descending ? (r1[index].toDouble ?? 0.0) > (r2[index].toDouble ?? 0.0) : (r1[index].toDouble ?? 0.0) < (r2[index].toDouble ?? 0.0)
                } else {
                    return order == .descending ? r1[index] > r2[index] : r1[index] < r2[index]
                }

            })
            resultSet.append(firstRow)
            resultSet.append(contentsOf: dataRows)
        } else {

            let dataRows = self[0..<count].sorted(by: {r1, r2 in

                if let val = r1[index].toDouble {
                    return order == .descending ? (r1[index].toDouble ?? 0.0) > (r2[index].toDouble ?? 0.0) : (r1[index].toDouble ?? 0.0) < (r2[index].toDouble ?? 0.0)
                } else {
                    return order == .descending ? r1[index] > r2[index] : r1[index] < r2[index]
                }

            })
            resultSet.append(contentsOf: dataRows)
        }

        return resultSet
    }
    func printArray(){
        for row in self {
            print("\(row)")
        }
    }
}
</code>```

Body:
How can I sort a two dimensional array based on values in one of the rows?

let array = [["X", "Y",   1,  2,  3,  4,  5],
             ["V", "W", "A","B","C","D","E"]
]

let sorted = [["X", "Y",   5,  4,  3,  2,  1],
              ["V", "W", "E","D","C","B","A"]
    ]

The Swift Array.sort({e1, e2 in e1 < e2}) passes in row elements, not column elements.

To make matters worse the first two column in the row must not be sorted.

Bear in mind row 2 must be rearranged according to the row 1 order.  So assuming we are sorting by row 0 and ignoring 1st 2 columns

[["X", "Y",   1,  2,  3,  4,  5],
 ["V", "W", "E","B","A","D","F"]]

should become

[["X", "Y",   5,  4,  3,  2,  1],
 ["V", "W", "F","D","A","B","E"]]

Body:
Here is the solution I came up with - very ugly !!

extension Array where Element == Array<String> {
    /// Creates a totals row at the bottom
    /// ignore - number of columns to ignore at the start
    mutating func addTotalsRow(ignore: Int){
        // Create a totals row (top row)
        var totals = [String]()
        // Add columns if required
        if ignore > 0 {
            totals.append("Total")
            totals.append(contentsOf: repeatElement("", count: ignore - 1))

        }

        for row in self {
            for i in ignore..<row.count {

                let value = row[i].toDouble ?? 0.0
                if (i+1) > totals.count {
                    totals.append("0.0")
                }
                totals[i] = ((totals[i].toDouble ?? 0.0) + value).formatted4
            }
        }

        self.append(totals)

        return
    }

    /// Sort columnwise using values in 'row', ignoring first 'ignore' columns
    /// Also sorts the optional header row
    /// Returns (sortedRows, sortedHeaderRow)
    func columnSorted(_ sortRow: Int, ignoreColumnCount: Int, order: SortOrder = .ascending, headerRow: [String]?)->([[String]], [String]?) {

        // Now calculate a totals row
        var newHeader: [String]?

        // Create an array of objects holding the total and the column index
        var indexes = [IX]()

        let totals = self[sortRow]

        // Ignore the text columns
        for i in ignoreColumnCount..<totals.count {
            indexes.append(IX(total: totals[i], index: i))
        }
        // Sort IX by the totals
        indexes.sort(by: {ix1, ix2 in
            return order == .descending ? ix1.intTotal > ix2.intTotal : ix1.intTotal < ix2.intTotal})

        // Create the Totals data row
        var totalsRow = [String]()
        totalsRow.append(contentsOf: totals[0..<ignoreColumnCount])
        totalsRow.append(contentsOf: indexes.map({$0.total}))

        if let header = headerRow {
            newHeader = [String]()
            newHeader!.append(contentsOf: header[0..<ignoreColumnCount])
            for i in 0..<indexes.count {
                let ix = indexes[i].index
                if ((i+ignoreColumnCount)+1) > newHeader!.count {
                    newHeader!.append("")
                }
                newHeader![i+ignoreColumnCount] = header[ix]
            }
        }

        var newData = [[String]]()
        // newData.append(totalsRow)
        // Now do the same for all the rows in data
        for row in self {
            var newRow = [String]()
            newRow.append(contentsOf: row[0..<ignoreColumnCount])

            for i in 0..<indexes.count {
                let ix = indexes[i].index
                if ((i+ignoreColumnCount)+1) > newRow.count {
                    newRow.append("0.0")
                }
                newRow[i+ignoreColumnCount] = row[ix]
            }
            newData.append(newRow)
        }

        // Sort by count
        return (newData, newHeader)
    }
    /// Sort by column index 0...
    mutating func sort(by column: Int, order: SortOrder = .ascending) {

        guard column > 0 else {
            return
        }
        let index = column - 1

        self.sort(by: {r1, r2 in
            let count1 = (r1[index].toDouble ?? 0.0)
            let count2 = (r2[index].toDouble ?? 0.0)
            if let val = r1[index].toDouble {
                return order == .descending ? (r1[index].toDouble ?? 0.0) > (r2[index].toDouble ?? 0.0) : (r1[index].toDouble ?? 0.0) < (r2[index].toDouble ?? 0.0)
            } else {
                return order == .descending ? r1[index] > r2[index] : r1[index] > r2[index]
            }
        })
    }

    func sorted(by column: Int, order: SortOrder = .ascending, ignoreFirstRow: Bool = false)->[[String]] {

        guard column > 0 else {
            return self
        }
        let index = column - 1

        var resultSet = [[String]]()

        if ignoreFirstRow {
            // Save the first row
            let firstRow = self[0]

            let dataRows = self[1..<count].sorted(by: {r1, r2 in

                if let val = r1[index].toDouble {
                    return order == .descending ? (r1[index].toDouble ?? 0.0) > (r2[index].toDouble ?? 0.0) : (r1[index].toDouble ?? 0.0) < (r2[index].toDouble ?? 0.0)
                } else {
                    return order == .descending ? r1[index] > r2[index] : r1[index] < r2[index]
                }

            })
            resultSet.append(firstRow)
            resultSet.append(contentsOf: dataRows)
        } else {

            let dataRows = self[0..<count].sorted(by: {r1, r2 in

                if let val = r1[index].toDouble {
                    return order == .descending ? (r1[index].toDouble ?? 0.0) > (r2[index].toDouble ?? 0.0) : (r1[index].toDouble ?? 0.0) < (r2[index].toDouble ?? 0.0)
                } else {
                    return order == .descending ? r1[index] > r2[index] : r1[index] < r2[index]
                }

            })
            resultSet.append(contentsOf: dataRows)
        }

        return resultSet
    }
    func printArray(){
        for row in self {
            print("\(row)")
        }
    }
}


问:
How to implement google maps with laravel and vue js to observe the distance in real time that the user walks?
I am building a web application with Laravel and Vue JS. The idea of this application is that the user who uses the application must perform challenges and training exercises. I need to create a section where the user can see the distance he walks in real time.

I am using vue2-google-maps and I currently have the following code.

<template>

Search and add a pin

        <gmap-autocomplete
          @place_changed="setPlace">
        </gmap-autocomplete>
        <button @click="addMarker">Add</button>

    <gmap-map
      :center="center"
      :zoom="12"
      style="width:100%;  height: 400px;"
    >
      <gmap-marker
        :key="index"
        v-for="(m, index) in markers"
        :position="m.position"
        @click="center=m.position"
      ></gmap-marker>
    </gmap-map>

</template>

```

But I'm not sure if with vue2-google-maps I can achieve what I'm trying to do. I need help and suggestions, please.

答: it's definitely doable, you just need to set an interval to geolocate your position every N seconds and then push points and draw the polyline that marks your path. Then you probably have to save all the points server side to keep an history of your trainings and you can also use sockets to send updates to all clients connected if you want to show them your position in realtime</p>

Body:
I am building a web application with Laravel and Vue JS. The idea of this application is that the user who uses the application must perform challenges and training exercises. I need to create a section where the user can see the distance he walks in real time.

I am using vue2-google-maps and I currently have the following code.

<template>

Search and add a pin

        <gmap-autocomplete
          @place_changed="setPlace">
        </gmap-autocomplete>
        <button @click="addMarker">Add</button>

    <gmap-map
      :center="center"
      :zoom="12"
      style="width:100%;  height: 400px;"
    >
      <gmap-marker
        :key="index"
        v-for="(m, index) in markers"
        :position="m.position"
        @click="center=m.position"
      ></gmap-marker>
    </gmap-map>

</template>

But I'm not sure if with vue2-google-maps I can achieve what I'm trying to do. I need help and suggestions, please.


问:
Vertical alignment in a position-fixed div
I have a div, inside a bootstrap column, that has class position-fixed so that the contents inside are fixed relative to the viewport. I am able to horizontally align these contents but I am having trouble vertically aligning it.

I know there are many methods out there in bootstrap 4, but it all seems to break due to the position-fixed class. Either the contents disappear somewhere outside the page, or nothing happens.

```<code><div class="container-fluid">
<div class="row">

<div class="col-md">
    <div class="container">
        <div class="row justify-content-md-center">

            <div class="position-fixed h-100 col-md-auto">
                <div class="text-center vertical-center">
                    <h2>Title</h2>
                    <p>Subtext</p>
                    <a data-toggle="modal" data-target="#Modal" href="#">Click me</a>
                </div>
            </div>

        </div>
    </div>
  </div>

</div>
</div
</code>```

答:
```<code>#OuterDiv {
    position: fixed;
    width: 100%;
    height: 50px;
}

#InnerDiv {
    display: inline-block;
    top: 50%;
    transform: translateY(-50%);
    position: relative;
}
</code>```

Body:
I have a div, inside a bootstrap column, that has class position-fixed so that the contents inside are fixed relative to the viewport. I am able to horizontally align these contents but I am having trouble vertically aligning it.

I know there are many methods out there in bootstrap 4, but it all seems to break due to the position-fixed class. Either the contents disappear somewhere outside the page, or nothing happens.

Title

Subtext

                    Click me

</div


问:
How to hold collection of files throughout application?
In my mobile application I need to hold a collection of File objects (pictures, documents) that can be accessed throughout the whole application and users can make various operations over the collection:

view all/individual files

upload subsets of the collection to a server

share individual files

...

The collection is initialized only once.

I was wondering if it is a good idea to use a singleton pattern as an object that holds the collection so I do not have to initialize the collection every time user opens a particular screen?

答: If you are using Java ME try RecordStore. You can access it from anywhere in the application. </p>


问:
Ansible - appending file content by cat command
I am downloading a file with some text and I want to attach this text to another file.

After download inet_licence_5 file on localhost. stage file is on localhost too.

This work fine:

```<code>cat ./inet_licence_5 >> ./stage
</code>```

Unfortunately, in ansible, it does not work.

```<code>- name: Append to ./stage
  command: cat ./inet_licence_5 >> ./stage
  delegate_to: 127.0.0.1
</code>```

Error:

```<code>TASK [Append to ./stage] *******************************
fatal: [my -> 127.0.0.1]: FAILED! => {"changed": true, "cmd":
["cat", "./inet_licence_5", ">>", "./stage"], "delta":
"0:00:00.001814", "end": "2019-05-28 11:55:22.766532", "failed":
true, "rc": 1, "start": "2019-05-28 11:55:22.764718", "stderr":
"cat: '>>': No such file or directory", "stderr_lines": ["cat: '>>':
No such file or directory"], "stdout": "asdasd", "stdout_lines":
["asdasd"]}
</code>```

Strange because I'm doing this job in the main location.

```<code>$ ls
base  inet_licence_5 playbook1.yml
$ ansible-playbook playbook1.yml
</code>```

答:
For odd reason you assume your working directory is the same when running Ansible as it you would be when trying from shell. This is not true (you can always verify by running i.e. pwd as command and check the output). So you need to either specify full paths in your command arguments or use chdir to ensure you are really in the right directory (docs: https://docs.ansible.com/ansible/2.5/modules/command_module.html)

EDIT

Seems I overlooked that part from linked docs:

The given command will be executed on all selected nodes. It will not be processed through the shell, so variables like $HOME and operations like "<", ">", "|", ";" and "&" will not work

so you need to go other way about that as ordinary redirection won't simply work in current approach. I'd use  shell module to run commands on guest, as this one seems to be less strict (and more raw).

Body:
I am downloading a file with some text and I want to attach this text to another file.

After download inet_licence_5 file on localhost. stage file is on localhost too.

This work fine:

cat ./inet_licence_5 >> ./stage

Unfortunately, in ansible, it does not work.

- name: Append to ./stage
  command: cat ./inet_licence_5 >> ./stage
  delegate_to: 127.0.0.1

Error:

TASK [Append to ./stage] *******************************
fatal: [my -> 127.0.0.1]: FAILED! => {"changed": true, "cmd":
["cat", "./inet_licence_5", ">>", "./stage"], "delta":
"0:00:00.001814", "end": "2019-05-28 11:55:22.766532", "failed":
true, "rc": 1, "start": "2019-05-28 11:55:22.764718", "stderr":
"cat: '>>': No such file or directory", "stderr_lines": ["cat: '>>':
No such file or directory"], "stdout": "asdasd", "stdout_lines":
["asdasd"]}

Strange because I'm doing this job in the main location.

$ ls
base  inet_licence_5 playbook1.yml
$ ansible-playbook playbook1.yml


问:
How to avoid repeating dependency versions in a multi-module Gradle project?
There's a sample Spring Boot project here that contains two modules.

The build.gradle for one of the modules looks like this:

```<code>buildscript {
    ext { springBootVersion = '2.1.4.RELEASE' }
    repositories { mavenCentral() }
    dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") }
}

plugins {
    id "io.spring.dependency-management" version "1.0.5.RELEASE"
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

bootJar {
    baseName = 'gs-multi-module-application'
    version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8

repositories { mavenCentral() }

dependencies {
    compile('org.springframework.boot:spring-boot-starter-actuator')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile project(':library')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}
</code>```

The other module's build.gradle looks like this:

```<code>buildscript {
    repositories { mavenCentral() }
}

plugins { id "io.spring.dependency-management" version "1.0.5.RELEASE" }

ext { springBootVersion = '2.1.4.RELEASE' }

apply plugin: 'java'
apply plugin: 'eclipse'

jar {
    baseName = 'gs-multi-module-library'
    version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8

repositories { mavenCentral() }

dependencies {
    compile('org.springframework.boot:spring-boot-starter')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

dependencyManagement {
    imports { mavenBom("org.springframework.boot:spring-boot-dependencies:${springBootVersion}") }
}
</code>```

The springBootVersion = '2.1.4.RELEASE' is declared in both modules. For a 2 module project that might not be a problem, but if my project had 10 modules and I wanted to make sure that all modules always depend on the same version of Spring Boot, it would be inconvenient and error-prone to repeat this version in every module.

Similarly, I might want to add a dependency on commons-io to both of these modules, and ensure they both always depend on the same version of commons-io.

How can I avoid repeating the version numbers in each and every build.gradle file?

答:
You can move the ext{} block to a new file and reference it in your project's build.gradle file via the apply from: statement.

```<code>// project/versions.gradle
ext {
    springBootVersion = '2.1.4.RELEASE'
}

// project/build.gradle
buildscript {
    apply from: 'versions.gradle'
}

// module/build.gradle
dependencies {
    implementation "some.dependency:dependency:$springBootVersion"
}
</code>```

Now you only have to define your dependency versions in one place.

Typically, a project will have a project-level build.gradle file in addition to module-specific build.gradle files. However, the repo you shared is missing the project-level build script. This is why the ext{} block is defined in each module's build script. This is likely not optimal, and I recommend looking at other repos to see how different developers tackled this issue.

Body:
There's a sample Spring Boot project here that contains two modules.

The build.gradle for one of the modules looks like this:

buildscript {
    ext { springBootVersion = '2.1.4.RELEASE' }
    repositories { mavenCentral() }
    dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") }
}

plugins {
    id "io.spring.dependency-management" version "1.0.5.RELEASE"
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

bootJar {
    baseName = 'gs-multi-module-application'
    version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8

repositories { mavenCentral() }

dependencies {
    compile('org.springframework.boot:spring-boot-starter-actuator')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile project(':library')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

The other module's build.gradle looks like this:

buildscript {
    repositories { mavenCentral() }
}

plugins { id "io.spring.dependency-management" version "1.0.5.RELEASE" }

ext { springBootVersion = '2.1.4.RELEASE' }

apply plugin: 'java'
apply plugin: 'eclipse'

jar {
    baseName = 'gs-multi-module-library'
    version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8

repositories { mavenCentral() }

dependencies {
    compile('org.springframework.boot:spring-boot-starter')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

dependencyManagement {
    imports { mavenBom("org.springframework.boot:spring-boot-dependencies:${springBootVersion}") }
}

The springBootVersion = '2.1.4.RELEASE' is declared in both modules. For a 2 module project that might not be a problem, but if my project had 10 modules and I wanted to make sure that all modules always depend on the same version of Spring Boot, it would be inconvenient and error-prone to repeat this version in every module.

Similarly, I might want to add a dependency on commons-io to both of these modules, and ensure they both always depend on the same version of commons-io.

How can I avoid repeating the version numbers in each and every build.gradle file?

Body:
You can move the ext{} block to a new file and reference it in your project's build.gradle file via the apply from: statement.

// project/versions.gradle
ext {
    springBootVersion = '2.1.4.RELEASE'
}

// project/build.gradle
buildscript {
    apply from: 'versions.gradle'
}

// module/build.gradle
dependencies {
    implementation "some.dependency:dependency:$springBootVersion"
}

Now you only have to define your dependency versions in one place.

Typically, a project will have a project-level build.gradle file in addition to module-specific build.gradle files. However, the repo you shared is missing the project-level build script. This is why the ext{} block is defined in each module's build script. This is likely not optimal, and I recommend looking at other repos to see how different developers tackled this issue.


问:
find-bug error String can't cast to Util.Map
find-bug shows String can't cast to util.Map

When run through the application getting correct result.
siteList looks [{site_id=47, site_code=a}, {site_id=48, site_code=ABC}, {site_id=49, site_code=ABCD}, {site_id=54, site_code=ABCE}, {site_id=1, site_code=FXGL}]

```<code>public static List<SitesDto> transformSites(List<String> siteList) {
                List<SitesDto> sitList = new ArrayList<>();
                for (Object object : siteList) {
                    Map row = (Map) object;----->showing error
                    final SitesDto site = new SitesDto();
                    String code = (String) row.get(SITE_CODE);
                    Object id = row.get(SITE_ID);
                    site.setSiteId(((Number) id).longValue());
                    site.setSiteCode(code);
                    sitList.add(site);
                }
                return sitList;
            }
</code>```

find-bug shows String can't cast to util.Map

答:
The java.util.Map interface represents a mapping between a key and a value.
Where as, siteList is a collection of Strings (they are not key and value pairs which Map is expecting), so is the error String can't cast to util.Map.

The List passed in parameter should be of  List<Map<String,Object>>

Hope it helps.

Body:
find-bug shows String can't cast to util.Map

When run through the application getting correct result.
siteList looks [{site_id=47, site_code=a}, {site_id=48, site_code=ABC}, {site_id=49, site_code=ABCD}, {site_id=54, site_code=ABCE}, {site_id=1, site_code=FXGL}]

public static List<SitesDto> transformSites(List<String> siteList) {
                List<SitesDto> sitList = new ArrayList<>();
                for (Object object : siteList) {
                    Map row = (Map) object;----->showing error
                    final SitesDto site = new SitesDto();
                    String code = (String) row.get(SITE_CODE);
                    Object id = row.get(SITE_ID);
                    site.setSiteId(((Number) id).longValue());
                    site.setSiteCode(code);
                    sitList.add(site);
                }
                return sitList;
            }

find-bug shows String can't cast to util.Map


问:
Is sed auto in-place substitution?
I have this code, which I do want for replacement of a specific pattern, but not multi in-place replacement.

```<code> echo "ss qq" | sed  "s/ss/qq/g; s/qq/dd/g;"
</code>```

The result is

```<code>dd dd
</code>```

and wish it would be

```<code>qq dd
</code>```

Also via "looping" we get the same result.

```<code>echo "ss qq" | sed  ":loop; s/ss/qq/g; s/qq/dd/g; t loop;"
</code>```

its petty, very disappointing bug !!

Any suggestion why it's happening?

答:
This might work for you (GNU sed):

```<code>sed  's/ss\|qq/\n&/;:a;s/\nss/qq\n/;s/\nqq/dd\n/;s/\n\(.\)/\1\n/;ta;s/\n//' file
</code>```

This introduces a marker in the form of a newline, as to where the last substitution occurred. At the end of the line the marker is removed.

The reason for the marker is because each invocation of a substitution command starts afresh from the beginning of the line, not from where the last substitution finished. The g flag may confuse the issue but only belongs the current invocation of the substitution.

As already mentioned, a better way is to is to use an alternative for the first substitution and replace this globally as the last command.

```<code>sed 's/ss/\n/g;s/qq/dd/g;s/\n/qq/g' file
</code>```

Title: Is sed auto in-place substitution?

Body:
I have this code, which I do want for replacement of a specific pattern, but not multi in-place replacement.

 echo "ss qq" | sed  "s/ss/qq/g; s/qq/dd/g;"

The result is

dd dd

and wish it would be

qq dd

Also via "looping" we get the same result.

echo "ss qq" | sed  ":loop; s/ss/qq/g; s/qq/dd/g; t loop;"

its petty, very disappointing bug !!

Any suggestion why it's happening?

Body:
This might work for you (GNU sed):

sed  's/ss\|qq/\n&/;:a;s/\nss/qq\n/;s/\nqq/dd\n/;s/\n\(.\)/\1\n/;ta;s/\n//' file

This introduces a marker in the form of a newline, as to where the last substitution occurred. At the end of the line the marker is removed.

The reason for the marker is because each invocation of a substitution command starts afresh from the beginning of the line, not from where the last substitution finished. The g flag may confuse the issue but only belongs the current invocation of the substitution.

As already mentioned, a better way is to is to use an alternative for the first substitution and replace this globally as the last command.

sed 's/ss/\n/g;s/qq/dd/g;s/\n/qq/g' file


问:
ERROR TypeError: fs.createWriteStream is not a function Angular 6 GIF export
I have created the following function to  create  GIF and I want to export it to a .gif image.

```<code>import * as gifEncoder from 'gif-encoder';

animate() {
    var canvas: HTMLCanvasElement = this.canvas.nativeElement;
    var context = canvas.getContext('2d');
    var gif = gifEncoder;
    gif = new gifEncoder(10, 10);

    if (this.numberOfFrames < this.points.length - 1) {
        requestAnimationFrame(() => this.animate());
    }
    else {
        console.log("Program End Reached...");
        gif.finish();
        this.gif = gif;
    }

    context.beginPath();
    var fromX = this.points[this.numberOfFrames - 1].x;
    var fromY = this.points[this.numberOfFrames - 1].y;
    var toX = this.points[this.numberOfFrames].x;
    var toY = this.points[this.numberOfFrames].y;
    context.lineWidth = 5;
    context.strokeStyle = "red";
    context.moveTo(fromX, fromY);
    context.lineTo(toX, toY);
    context.stroke();
    gif.writeHeader();
    gif.addFrame(context);

    this.numberOfFrames++;
}
</code>```

Then I have a button to export this canvas content to a GIF file.

```<code>downloadAsGIF() {
    let fs = require('fs');
    var file = fs.createWriteStream('img.gif');
    this.gif.pipe(file);
}
</code>```

Error:

```<code>ERROR TypeError: fs.createWriteStream is not a function
</code>```

Where am I  going wrong? Any help would be apppreciated. I am using this tutorial

答:
Actually that will run on server side. Browser don't have fs. So you gotta use some other library which is supported by browser.

That said, here's a client side JS answer.

Using

Using BrowserFS.configure(), you can easily configure BrowserFS to use
  a variety of file system types.

Here's a simple usage example using the LocalStorage-backed file
  system:

```<code><script type="text/javascript" src="browserfs.min.js"></script>
<script type="text/javascript">
  // Installs globals onto window:
  // * Buffer
  // * require (monkey-patches if already defined)
  // * process
  // You can pass in an arbitrary object if you do not wish to pollute
  // the global namespace.
  BrowserFS.install(window);
  // Configures BrowserFS to use the LocalStorage file system.
  BrowserFS.configure({
    fs: "LocalStorage"
  }, function(e) {
    if (e) {
      // An error happened!
      throw e;
    }
    // Otherwise, BrowserFS is ready-to-use!
  });
</script>
</code>```

Can easily use like this:

```<code>var fs = require('fs');
fs.writeFile('/test.txt', 'Cool, I can do this in the browser!', function(err) {
  fs.readFile('/test.txt', function(err, contents) {
    console.log(contents.toString());
  });
});
</code>```

Body:
I have created the following function to  create  GIF and I want to export it to a .gif image.

import * as gifEncoder from 'gif-encoder';

animate() {
    var canvas: HTMLCanvasElement = this.canvas.nativeElement;
    var context = canvas.getContext('2d');
    var gif = gifEncoder;
    gif = new gifEncoder(10, 10);

    if (this.numberOfFrames < this.points.length - 1) {
        requestAnimationFrame(() => this.animate());
    }
    else {
        console.log("Program End Reached...");
        gif.finish();
        this.gif = gif;
    }

    context.beginPath();
    var fromX = this.points[this.numberOfFrames - 1].x;
    var fromY = this.points[this.numberOfFrames - 1].y;
    var toX = this.points[this.numberOfFrames].x;
    var toY = this.points[this.numberOfFrames].y;
    context.lineWidth = 5;
    context.strokeStyle = "red";
    context.moveTo(fromX, fromY);
    context.lineTo(toX, toY);
    context.stroke();
    gif.writeHeader();
    gif.addFrame(context);

    this.numberOfFrames++;
}

Then I have a button to export this canvas content to a GIF file.

downloadAsGIF() {
    let fs = require('fs');
    var file = fs.createWriteStream('img.gif');
    this.gif.pipe(file);
}

Error:

ERROR TypeError: fs.createWriteStream is not a function

Where am I  going wrong? Any help would be apppreciated. I am using this tutorial

Body:
Actually that will run on server side. Browser don't have fs. So you gotta use some other library which is supported by browser.

That said, here's a client side JS answer.

Using

Using BrowserFS.configure(), you can easily configure BrowserFS to use
  a variety of file system types.

Here's a simple usage example using the LocalStorage-backed file
  system:

<script type="text/javascript" src="browserfs.min.js"></script>
<script type="text/javascript">
  // Installs globals onto window:
  // * Buffer
  // * require (monkey-patches if already defined)
  // * process
  // You can pass in an arbitrary object if you do not wish to pollute
  // the global namespace.
  BrowserFS.install(window);
  // Configures BrowserFS to use the LocalStorage file system.
  BrowserFS.configure({
    fs: "LocalStorage"
  }, function(e) {
    if (e) {
      // An error happened!
      throw e;
    }
    // Otherwise, BrowserFS is ready-to-use!
  });
</script>

Can easily use like this:

var fs = require('fs');
fs.writeFile('/test.txt', 'Cool, I can do this in the browser!', function(err) {
  fs.readFile('/test.txt', function(err, contents) {
    console.log(contents.toString());
  });
});


问:
Python - Average of three values in a while true loop
I'm developing a python script on a raspberry pi with a distance sensor.
My code is working and i can reach the distance but I want to avoid some false positive/negative so I would like to get the average of the last three data.

Here is my code:

while True:
        distance= misura() # GETTING THE REAL DISTANCE IN CM
        print "Distanza : %.2f" % distanza

        avg_distance = <something> # <- HERE I NEED SOMETHING ELEGANT

        if (avg_distance > 30):
            print "NOT PRESENT"
        else:
            print "PRESENT"

        time.sleep(1.5)
```

I would like some function (maybe based on a list?) that returns the average of the last three (or n) distances

IMPORTANT:
I don't want to store ALL the values because this script will run for days and days

答:
First create a list (outside the loop):

```<code>distances = [misura(),misura(),misura()]
</code>```

Then your loop should be like this:

```<code>while True:
    distances.append(misura())
    print "Distanza : %.2f" % distances[-1]

    distances = distances[1:] # this way you keep only the last 3 values
    avg_distance = sum(distances) / len(distances)

    if (avg_distance > 30):
        print "NOT PRESENT"
    else:
        print "PRESENT"

    time.sleep(1.5)
</code>```

Body:
I'm developing a python script on a raspberry pi with a distance sensor.
My code is working and i can reach the distance but I want to avoid some false positive/negative so I would like to get the average of the last three data.

Here is my code:

while True:
        distance= misura() # GETTING THE REAL DISTANCE IN CM
        print "Distanza : %.2f" % distanza

        avg_distance = <something> # <- HERE I NEED SOMETHING ELEGANT

        if (avg_distance > 30):
            print "NOT PRESENT"
        else:
            print "PRESENT"

        time.sleep(1.5)

I would like some function (maybe based on a list?) that returns the average of the last three (or n) distances

IMPORTANT:
I don't want to store ALL the values because this script will run for days and days

Body:
First create a list (outside the loop):

distances = [misura(),misura(),misura()]

Then your loop should be like this:

while True:
    distances.append(misura())
    print "Distanza : %.2f" % distances[-1]

    distances = distances[1:] # this way you keep only the last 3 values
    avg_distance = sum(distances) / len(distances)

    if (avg_distance > 30):
        print "NOT PRESENT"
    else:
        print "PRESENT"

    time.sleep(1.5)


问:
Selenium extent reports framework not generating failed status
Currently, I am using Selenium TestNG and Extent Reports framework for reporting. I am facing a problem where all are my test cases are showing Pass and not showing Fail.

```<code>@BeforeTest
public void setUp()
{
    //where we need to generate the report
    htmlReporter = new ExtentHtmlReporter(System.getProperty("user.dir")+"/test-output/MyReport.html");
    extent = new ExtentReports();
    extent.attachReporter(htmlReporter);

    // Set our document title, theme etc..
    htmlReporter.config().setDocumentTitle("My Test Report");
    htmlReporter.config().setReportName("Test Report");
    htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
    htmlReporter.config().setTheme(Theme.DARK);
}

@Test
public void On_Page_IM() throws InterruptedException {
    test = extent.createTest("On_Page_IM");
    wd.manage().window().maximize();
    Thread.sleep(10000);
    test.log(Status.INFO,"On page intent media: Show");
}

@AfterSuite
public void tearDown()
{
    extent.flush();
    wd.quit();
}
</code>```

答:
Just add below code at end of ur tests</p>

```<code>@AfterMethod
public void AfterMethod(ITestResult result) {

    if (result.getStatus() == ITestResult.FAILURE) {
        test.log(Status.FAIL,
                MarkupHelper.createLabel(result.getName()
                        + " Test case FAILED due to below issues:",
                        ExtentColor.RED));
        test.fail(result.getThrowable());
    } else if (result.getStatus() == ITestResult.SUCCESS) {
        test.log(
                Status.PASS,
                MarkupHelper.createLabel(result.getName()
                        + " Test Case PASSED", ExtentColor.GREEN));
    } else {
        test.log(
                Status.SKIP,
                MarkupHelper.createLabel(result.getName()
                        + " Test Case SKIPPED", ExtentColor.ORANGE));
        test.skip(result.getThrowable());
    }
}

@AfterTest
public void AfterTest() {

    extent.flush();

}
</code>```

Body:
Currently, I am using Selenium TestNG and Extent Reports framework for reporting. I am facing a problem where all are my test cases are showing Pass and not showing Fail.

@BeforeTest
public void setUp()
{
    //where we need to generate the report
    htmlReporter = new ExtentHtmlReporter(System.getProperty("user.dir")+"/test-output/MyReport.html");
    extent = new ExtentReports();
    extent.attachReporter(htmlReporter);

    // Set our document title, theme etc..
    htmlReporter.config().setDocumentTitle("My Test Report");
    htmlReporter.config().setReportName("Test Report");
    htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
    htmlReporter.config().setTheme(Theme.DARK);
}

@Test
public void On_Page_IM() throws InterruptedException {
    test = extent.createTest("On_Page_IM");
    wd.manage().window().maximize();
    Thread.sleep(10000);
    test.log(Status.INFO,"On page intent media: Show");
}

@AfterSuite
public void tearDown()
{
    extent.flush();
    wd.quit();
}

Body:
Just add below code at end of ur tests

@AfterMethod
public void AfterMethod(ITestResult result) {

    if (result.getStatus() == ITestResult.FAILURE) {
        test.log(Status.FAIL,
                MarkupHelper.createLabel(result.getName()
                        + " Test case FAILED due to below issues:",
                        ExtentColor.RED));
        test.fail(result.getThrowable());
    } else if (result.getStatus() == ITestResult.SUCCESS) {
        test.log(
                Status.PASS,
                MarkupHelper.createLabel(result.getName()
                        + " Test Case PASSED", ExtentColor.GREEN));
    } else {
        test.log(
                Status.SKIP,
                MarkupHelper.createLabel(result.getName()
                        + " Test Case SKIPPED", ExtentColor.ORANGE));
        test.skip(result.getThrowable());
    }
}

@AfterTest
public void AfterTest() {

    extent.flush();

}


问:
Get transaction details using transaction id
How to get transaction details using transaction id ?

I tried generate access token and then tried to get transaction details.But its showing me INVALID_RESOURCE_ID

To generate access token :

```<code>curl -v https://api.sandbox.paypal.com/v1/oauth2/token \
   -H "Accept: application/json" \
   -H "Accept-Language: en_US" \
   -u "EOJ2S-Z60oN_le_KS1d75wsZ6y0SFdVsY9183IvxFyZp:EC1usMEUk8e9ihI7ZdXLF5cz6y0SFdVsY9183IvxFyZp"
   -d "grant_type=client_credentials"
</code>```

To get transaction details :

```<code>$access_token = '<ACCESS_TOKEN>';
$curl = curl_init("https://api.sandbox.paypal.com/v1/checkout/orders/<TXN_ID>");
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Authorization: Bearer ' .$access_token,
    'Accept: application/json',
    'Content-Type: application/json'
));
$response = curl_exec($curl);
$result = json_decode($response);
print_r($result);exit;
</code>```

Response :

```<code>stdClass Object ( [name] => VALIDATION_ERROR [details] => Array ( [0] => stdClass Object ( [field] => #/id [location] => body [issue] => INVALID_RESOURCE_ID ) ) [message] => Invalid request - see details [information_link] => https://developer.paypal.com/docs/api/orders/v1/#error-VALIDATION_ERROR [debug_id] => 447f920460e84 )
</code>```

I would like to know how can i get transaction details using transaction id in sandbox mode  ?

答:
It seems that you provide a invalid resource id in your request.

I recommend to use the official PayPal PHP SDK. You can download it here:
PayPal-PHP-SDK Github and there is a good example for getting a transaction here

Body:
How to get transaction details using transaction id ?

I tried generate access token and then tried to get transaction details.But its showing me INVALID_RESOURCE_ID

To generate access token :

curl -v https://api.sandbox.paypal.com/v1/oauth2/token \
   -H "Accept: application/json" \
   -H "Accept-Language: en_US" \
   -u "EOJ2S-Z60oN_le_KS1d75wsZ6y0SFdVsY9183IvxFyZp:EC1usMEUk8e9ihI7ZdXLF5cz6y0SFdVsY9183IvxFyZp"
   -d "grant_type=client_credentials"

To get transaction details :

$access_token = '<ACCESS_TOKEN>';
$curl = curl_init("https://api.sandbox.paypal.com/v1/checkout/orders/<TXN_ID>");
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Authorization: Bearer ' .$access_token,
    'Accept: application/json',
    'Content-Type: application/json'
));
$response = curl_exec($curl);
$result = json_decode($response);
print_r($result);exit;

Response :

stdClass Object ( [name] => VALIDATION_ERROR [details] => Array ( [0] => stdClass Object ( [field] => #/id [location] => body [issue] => INVALID_RESOURCE_ID ) ) [message] => Invalid request - see details [information_link] => https://developer.paypal.com/docs/api/orders/v1/#error-VALIDATION_ERROR [debug_id] => 447f920460e84 )

I would like to know how can i get transaction details using transaction id in sandbox mode  ?


问:
How to close the browser window in pug/Jade
we are implementing OAUTH authenticataion for login. After click on the link from my application it is redirecting to the browser where the login page is opening. The page is configured using Jade/pug and implemented using form validation and routing mechanism using express js.

But while trying to close the browser window with the close button, getting the below error saying:

Scripts may close only the windows that were opened by it

login.jade

```<code> form(name="myForm", action="/login",method="POST",novalidate)
                        divForm
                            divw1
                                .group
                                    input(type='number', required='', name="userid",autocomplete="off", data-required-msg='Username is required')
                                    label Enter User ID
                            divw1
                                .group
                                    input(type='password', required='', name="password")
                                    label Enter Password
                        divButtons
                             input(type="button",value="CANCEL",onClick='onBtnClk()',ID="cancel")
     input(type="submit",value="LOGIN",ID="login")
</code>```

login.js

```<code>   var express = require('express');
   var router = express.Router();

    router.post('/', '', function(req, res, next) {
        if (req.body.userid === '' && req.body.password === '') {
            // Looks like the user not provided credentials, let's show the ui again...

            res.render('login', {
              error: 'User ID and Password are mandatory'
            });
            return;
          }

    });
</code>```

layout.jade

```<code>function onBtnClk(){
  window.top.close(); //window not closing(Scripts may close only the windows that were opened by it)
}
</code>```

答:
This problem is not about Pug,
it's about the JavaScript API.
The API only allows your script to close windows that were opened by a script,
see here.

So as long as your window is not opened by a script you will not be able to close it, meaning you should rather tell the user that the login was successful and they can close the window

Body:
we are implementing OAUTH authenticataion for login. After click on the link from my application it is redirecting to the browser where the login page is opening. The page is configured using Jade/pug and implemented using form validation and routing mechanism using express js.

But while trying to close the browser window with the close button, getting the below error saying:

Scripts may close only the windows that were opened by it

login.jade

 form(name="myForm", action="/login",method="POST",novalidate)
                        divForm
                            divw1
                                .group
                                    input(type='number', required='', name="userid",autocomplete="off", data-required-msg='Username is required')
                                    label Enter User ID
                            divw1
                                .group
                                    input(type='password', required='', name="password")
                                    label Enter Password
                        divButtons
                             input(type="button",value="CANCEL",onClick='onBtnClk()',ID="cancel")
     input(type="submit",value="LOGIN",ID="login")

login.js

   var express = require('express');
   var router = express.Router();

    router.post('/', '', function(req, res, next) {
        if (req.body.userid === '' && req.body.password === '') {
            // Looks like the user not provided credentials, let's show the ui again...

            res.render('login', {
              error: 'User ID and Password are mandatory'
            });
            return;
          }

    });

layout.jade

function onBtnClk(){
  window.top.close(); //window not closing(Scripts may close only the windows that were opened by it)
}


问:
How to create a script that deletes certain files in only the same folder the script is saved
I'm really new to this. But I was wondering how to create a .vbs script that, when ran, will delete 3 files out of whatever folder the script is saved in. The folder location will change constantly so I need it to look only wherever the script is saved. It would also be nice if after it deleted the files, a dialog box would pop up stating that the task is finished.</p>

答:
```<code>'Very simple code where both the vbs file
'and the files to be deleted are in the same directory.

Set WshShell = WScript.CreateObject("WScript.Shell")

Set fso = CreateObject("Scripting.FileSystemObject")

Route=(fso.GetParentFolderName(WScript.ScriptFullName))&"\"

' Route =Directory where these files and the vbs file are located

file1 = Route&"Example.txt":ctrol1=" Doesn't exist" ' Example 1

file2 = Route&"Example.pdf":ctrol2=" Doesn't exist" ' Example 2

file3 = Route&"Example.jpg":ctrol3=" Doesn't exist" ' Example 3

' ctrol1, ctrol2. ctrrol3 are variables of control for each file,
' of entry they leave with that the file to erase does not exist.
' It changes its value when the file exists and has been deleted.

If fso.FileExists(file1) Then fso.DeleteFile(file1) :ctrol1=" deleted"
' if file 1 exists then delete it

If fso.FileExists(file2) Then fso.DeleteFile(file2) :ctrol2=" deleted"
' if file 2 exists then delete it

If fso.FileExists(file3) Then fso.DeleteFile(file3) :ctrol3=" deleted"
' if file 2 exists then delete it

' result of the process. chr(13) is a line break.

Msgbox "The Files: "&chr(13)&chr(13)&file1&ctrol1&chr(13)_
&file2&ctrol2&chr(13)&file3&ctrol3,4096
</code>```


问:
Null or false value in grails
I have a domain class in which one of its fields is of type Boolean. When I retrieve it, how can I differentiate whether it's set to false or it's null ?

Thanks

答: if(field == null) will work as expected.

Title: Null or false value in grails


问:
InflateException: Binary XML file line #8: Error inflating class ImageView
I know there are other questions on SO asking the same thing. I have already looked at most of them.

Most answers call about memory errors. I can't see how an ImageView which loads just a small icon (24x24 pixels) can make something like this.

But I'd like to post the stacktrace here maybe someone else can identify something I can't and help me.

```<code>06-03 22:14:17.367 28590-28590/css.mvp.example.debug W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41e4ad40)
06-03 22:14:17.409 28590-28590/css.mvp.example.debug E/AndroidRuntime: FATAL EXCEPTION: main
Process: css.mvp.example.debug, PID: 28590  android.view.InflateException: Binary XML file line #8: Error inflating class ImageView
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
    at css.mvp.example.main.projects.fragments.adapters.PollAnswersAdapter.getView(PollAnswersAdapter.java:38)
    at android.widget.AbsListView.obtainView(AbsListView.java:2255)
    at android.widget.ListView.measureHeightOfChildren(ListView.java:1263)
    at android.widget.ListView.onMeasure(ListView.java:1175)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
    at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:668)
    at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:735)
    at android.view.View.measure(View.java:16540)
    at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1075)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:16540)
    at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1942)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1132)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1321)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1019)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5725)
</code>```

Layout file

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout   xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal"
android:weightSum="11"
android:paddingTop="16dp" android:paddingBottom="16dp"
android:gravity="center_horizontal"
android:layout_width="match_parent" android:layout_height="wrap_content">

<ImageView
    android:id="@+id/iv_answer_circle"
    android:src="@drawable/ic_dot"
    android:layout_gravity="center" android:layout_weight="2"
    android:layout_marginLeft="16dp" android:layout_marginRight="16dp"
    android:layout_width="0dp" android:layout_height="wrap_content" />

<TextView android:id="@+id/tv_poll_answer"
    android:layout_weight="6"
    android:layout_width="0dp" android:layout_height="wrap_content" />

<TextView android:id="@+id/tv_poll_answer_num"
    android:layout_weight="1"
    android:layout_marginLeft="16dp" android:layout_marginRight="8dp"
    android:layout_width="0dp" android:layout_height="wrap_content" />

<TextView android:id="@+id/tv_poll_answer_percent"
    android:layout_weight="2"
    android:layout_marginRight="16dp"
    android:layout_width="0dp" android:layout_height="wrap_content" />

</LinearLayout>
</code>```

EDIT 2 : the code of my Adapter class.

```<code>public class PollAnswersAdapter extends ArrayAdapter<PollAnswerItem> {

    private Context context;
    private ArrayList<PollAnswerItem> data;

    public PollAnswersAdapter(Context context, ArrayList<PollAnswerItem> data) {
        super(context, -1, data);
        this.context = context;
        this.data = data;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View rowView = inflater.inflate(R.layout.row_answer, parent, false);

        ImageView ivCircle = (ImageView) rowView.findViewById(R.id.iv_answer_circle);
        TextView tvAnswer = (TextView) rowView.findViewById(R.id.tv_poll_answer);
        TextView tvNums = (TextView) rowView.findViewById(R.id.tv_poll_answer_num);
        TextView tvPercent = (TextView) rowView.findViewById(R.id.tv_poll_answer_percent);

        tvAnswer.setText(data.get(position).getAnswer());
        tvNums.setText(data.get(position).getNum());
        tvPercent.setText(data.get(position).getPercent() + "%");
        tvPercent.setTextColor(ColorTemplate.PREDEFINED_COLORS[position]);

        return rowView;
    }

}
</code>```

答: Don't paste your image into drawable in Android studio, paste it into the drawable folder and clean the project and then run it will work.</p>

Body:
I know there are other questions on SO asking the same thing. I have already looked at most of them.

Most answers call about memory errors. I can't see how an ImageView which loads just a small icon (24x24 pixels) can make something like this.

But I'd like to post the stacktrace here maybe someone else can identify something I can't and help me.

06-03 22:14:17.367 28590-28590/css.mvp.example.debug W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41e4ad40)
06-03 22:14:17.409 28590-28590/css.mvp.example.debug E/AndroidRuntime: FATAL EXCEPTION: main
Process: css.mvp.example.debug, PID: 28590  android.view.InflateException: Binary XML file line #8: Error inflating class ImageView
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
    at css.mvp.example.main.projects.fragments.adapters.PollAnswersAdapter.getView(PollAnswersAdapter.java:38)
    at android.widget.AbsListView.obtainView(AbsListView.java:2255)
    at android.widget.ListView.measureHeightOfChildren(ListView.java:1263)
    at android.widget.ListView.onMeasure(ListView.java:1175)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
    at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:668)
    at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:735)
    at android.view.View.measure(View.java:16540)
    at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1075)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:16540)
    at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5137)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
    at android.view.View.measure(View.java:16540)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1942)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1132)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1321)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1019)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5725)

Layout file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout   xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal"
android:weightSum="11"
android:paddingTop="16dp" android:paddingBottom="16dp"
android:gravity="center_horizontal"
android:layout_width="match_parent" android:layout_height="wrap_content">

<ImageView
    android:id="@+id/iv_answer_circle"
    android:src="@drawable/ic_dot"
    android:layout_gravity="center" android:layout_weight="2"
    android:layout_marginLeft="16dp" android:layout_marginRight="16dp"
    android:layout_width="0dp" android:layout_height="wrap_content" />

<TextView android:id="@+id/tv_poll_answer"
    android:layout_weight="6"
    android:layout_width="0dp" android:layout_height="wrap_content" />

<TextView android:id="@+id/tv_poll_answer_num"
    android:layout_weight="1"
    android:layout_marginLeft="16dp" android:layout_marginRight="8dp"
    android:layout_width="0dp" android:layout_height="wrap_content" />

<TextView android:id="@+id/tv_poll_answer_percent"
    android:layout_weight="2"
    android:layout_marginRight="16dp"
    android:layout_width="0dp" android:layout_height="wrap_content" />

</LinearLayout>

EDIT 2 : the code of my Adapter class.

public class PollAnswersAdapter extends ArrayAdapter<PollAnswerItem> {

    private Context context;
    private ArrayList<PollAnswerItem> data;

    public PollAnswersAdapter(Context context, ArrayList<PollAnswerItem> data) {
        super(context, -1, data);
        this.context = context;
        this.data = data;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View rowView = inflater.inflate(R.layout.row_answer, parent, false);

        ImageView ivCircle = (ImageView) rowView.findViewById(R.id.iv_answer_circle);
        TextView tvAnswer = (TextView) rowView.findViewById(R.id.tv_poll_answer);
        TextView tvNums = (TextView) rowView.findViewById(R.id.tv_poll_answer_num);
        TextView tvPercent = (TextView) rowView.findViewById(R.id.tv_poll_answer_percent);

        tvAnswer.setText(data.get(position).getAnswer());
        tvNums.setText(data.get(position).getNum());
        tvPercent.setText(data.get(position).getPercent() + "%");
        tvPercent.setTextColor(ColorTemplate.PREDEFINED_COLORS[position]);

        return rowView;
    }

}