问:
How to replace all the same text inside a blocked text in vim?
How to change this code:

```<code>    dayHour: {
        sunday: {
          openHour: null,
          closeHour: null,
        },
        monday: {
          openHour: null,
          closeHour: null,
        },
        tuesday: {
          openHour: null,
          closeHour: null,
        },
        wednesday: {
          openHour: null,
          closeHour: null,
        },
        thursday: {
          openHour: null,
          closeHour: null,
        },
        ...
     }
</code>```

to this code :

```<code>dayHour: {
    sunday: {
      openHour: null,
      closeHour: null,
      openMenu: null,
      closeMenu: null
    },
    monday: {
      openHour: null,
      closeHour: null,
      openMenu: null,
      closeMenu: null
    },
    tuesday: {
      openHour: null,
      closeHour: null,
      openMenu: null,
      closeMenu: null
    },
    wednesday: {
      openHour: null,
      closeHour: null,
      openMenu: null,
      closeMenu: null
    },
    thursday: {
      openHour: null,
      closeHour: null,
      openMenu: null,
      closeMenu: null
    },
    ...
  }
</code>```

This is what I've tried, I block the text :

```<code>openHour: null,
closeHour: null
</code>```

and I have no idea what to do next to find and replace the text I've blocked.
I have search several questions on google but I found nothing, and don't even know what keyword to search. Thanks

答:
This is a very common technique: use :global to match the lines you want. Then editing commands can be entered, for example, with :normal

```<code>g/closeHour/normal! oopenMenu: null,^McloseMenu: null
</code>```

Here ^M must be input as ^V<Enter>

If your replacement text is already yanked into a register, you can put it as well:

```<code>g/closeHour/normal! ]p
</code>```

(note: changing normal! ]p into put is possible but may require additional indentation fix, e.g. ='[).

Body:
How to change this code:

    dayHour: {
        sunday: {
          openHour: null,
          closeHour: null,
        },
        monday: {
          openHour: null,
          closeHour: null,
        },
        tuesday: {
          openHour: null,
          closeHour: null,
        },
        wednesday: {
          openHour: null,
          closeHour: null,
        },
        thursday: {
          openHour: null,
          closeHour: null,
        },
        ...
     }

to this code :

dayHour: {
    sunday: {
      openHour: null,
      closeHour: null,
      openMenu: null,
      closeMenu: null
    },
    monday: {
      openHour: null,
      closeHour: null,
      openMenu: null,
      closeMenu: null
    },
    tuesday: {
      openHour: null,
      closeHour: null,
      openMenu: null,
      closeMenu: null
    },
    wednesday: {
      openHour: null,
      closeHour: null,
      openMenu: null,
      closeMenu: null
    },
    thursday: {
      openHour: null,
      closeHour: null,
      openMenu: null,
      closeMenu: null
    },
    ...
  }

This is what I've tried, I block the text :

openHour: null,
closeHour: null

and I have no idea what to do next to find and replace the text I've blocked.
I have search several questions on google but I found nothing, and don't even know what keyword to search. Thanks

Body:
This is a very common technique: use :global to match the lines you want. Then editing commands can be entered, for example, with :normal

g/closeHour/normal! oopenMenu: null,^McloseMenu: null

Here ^M must be input as ^V<Enter>

If your replacement text is already yanked into a register, you can put it as well:

g/closeHour/normal! ]p

(note: changing normal! ]p into put is possible but may require additional indentation fix, e.g. ='[).


来源: stackexchange

问:
Parsing URL with port and without scheme
I am trying to parse a URL in Go and get host and scheme from the URL. But while parsing the URL with port and without scheme I am getting unexpected result.

```<code>u, err := url.ParseRequestURI("hello.com:81")
fmt.Println("host :",u.Host)
fmt.Println("scheme :",u.Scheme)

</code>```

I am getting unexpected result

```<code>host :
scheme: hello.com
</code>```

I wanted this instead

```<code>host : hello.com:80
scheme:
</code>```

答:
According to go doc, The general url form represented is:

```<code>[scheme:][//[userinfo@]host][/]path[?query][#fragment]
</code>```

URLs that do not start with a slash after the scheme are interpreted as:

```<code>scheme:opaque[?query][#fragment]
</code>```

Your URL is parsed as the second format.

You can use this method to get the result expected as yours. In the function, if there is no scheme in URL we add it then again parse it to get the expected result.

```<code>func parseRawURL(rawurl string) (domain string, scheme string, err error) {
    u, err := url.ParseRequestURI(rawurl)
    if err != nil || u.Host == "" {
        u, repErr := url.ParseRequestURI("https://" + rawurl)
        if repErr != nil {
            fmt.Printf("Could not parse raw url: %s, error: %v", rawurl, err)
            return
        }
        domain = u.Host
        err = nil
        return
    }

    domain = u.Host
    scheme = u.Scheme
    return
}
</code>```

You can try it out in go playground

ContentLicense: CC BY-SA 4.0

Body:
I am trying to parse a URL in Go and get host and scheme from the URL. But while parsing the URL with port and without scheme I am getting unexpected result.

u, err := url.ParseRequestURI("hello.com:81")
fmt.Println("host :",u.Host)
fmt.Println("scheme :",u.Scheme)

I am getting unexpected result

host :
scheme: hello.com

I wanted this instead

host : hello.com:80
scheme:

Body:
According to go doc, The general url form represented is:

[scheme:][//[userinfo@]host][/]path[?query][#fragment]

URLs that do not start with a slash after the scheme are interpreted as:

scheme:opaque[?query][#fragment]

Your URL is parsed as the second format.

You can use this method to get the result expected as yours. In the function, if there is no scheme in URL we add it then again parse it to get the expected result.

func parseRawURL(rawurl string) (domain string, scheme string, err error) {
    u, err := url.ParseRequestURI(rawurl)
    if err != nil || u.Host == "" {
        u, repErr := url.ParseRequestURI("https://" + rawurl)
        if repErr != nil {
            fmt.Printf("Could not parse raw url: %s, error: %v", rawurl, err)
            return
        }
        domain = u.Host
        err = nil
        return
    }

    domain = u.Host
    scheme = u.Scheme
    return
}

You can try it out in go playground


问:
Entity Framework calling MAX on null on Records
When calling Max() on an IQueryable and there are zero records I get the following exception.

The cast to value type 'Int32' failed because the materialized value is null.
Either the result type's generic parameter or the query must use a nullable type.

```<code>var version = ctx.Entries
    .Where(e => e.Competition.CompetitionId == storeCompetition.CompetitionId)
    .Max(e => e.Version);
</code>```

Now I understand why this happens my question is how is the best way to do this if the table can be empty. The code below works and solves this problem, but its very ugly is there no MaxOrDefault() concept?

```<code>int? version = ctx.Entries
    .Where(e => e.Competition.CompetitionId == storeCompetition.CompetitionId)
    .Select(e => (int?)e.Version)
    .Max();
</code>```

答:
I want to suggest a merge from the existing answers:

@divega answer works great and the sql output is fine but because of 'don't repeat yourself'
an extension will be a better way like
@Code Uniquely showed. But this solution can output more complex sql as you needed.
But you can use the following extension to bring both together:

```<code> public static int MaxOrZero<TSource>(this IQueryable<TSource> source,
 Expression<Func<TSource, int>> selector)
        {
            var converted = Expression.Convert(selector.Body, typeof(int?));
            var typed = Expression.Lambda<Func<TSource, int?>>(converted, selector.Parameters);

            return source.Max(typed) ?? 0;
        }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
When calling Max() on an IQueryable and there are zero records I get the following exception.

The cast to value type 'Int32' failed because the materialized value is null.
Either the result type's generic parameter or the query must use a nullable type.

var version = ctx.Entries
    .Where(e => e.Competition.CompetitionId == storeCompetition.CompetitionId)
    .Max(e => e.Version);

Now I understand why this happens my question is how is the best way to do this if the table can be empty. The code below works and solves this problem, but its very ugly is there no MaxOrDefault() concept?

int? version = ctx.Entries
    .Where(e => e.Competition.CompetitionId == storeCompetition.CompetitionId)
    .Select(e => (int?)e.Version)
    .Max();

Body:
I want to suggest a merge from the existing answers:

@divega answer works great and the sql output is fine but because of 'don't repeat yourself'
an extension will be a better way like
@Code Uniquely showed. But this solution can output more complex sql as you needed.
But you can use the following extension to bring both together:

 public static int MaxOrZero<TSource>(this IQueryable<TSource> source,
 Expression<Func<TSource, int>> selector)
        {
            var converted = Expression.Convert(selector.Body, typeof(int?));
            var typed = Expression.Lambda<Func<TSource, int?>>(converted, selector.Parameters);

            return source.Max(typed) ?? 0;
        }


问:
Python Output Snowflake Connector To CSV
I currently am trying to print the output of a snowflake connector query and write it to csv, but I'm having issues doing this. Currently, my code example looks like:

```<code>query = '''SELECT TOP 10 * FROM TABLE;'''

conn = snowflake.connector.connect(user='XXXX',
                                   password='XXXX',
                                   account='XXXX')

query_output = conn.cursor().execute(query)
</code>```

Is there a way for me to print the output of the query, like maybe print(query_output) and then also write it to csv like query_output.to_csv(path)?

答:
I highly recommend using Pandas' DataFrames API. Amongst several other data transformation and analysis capabilities, it has an excellent CSV reader and writer implementation that is very flexible.

Snowflake's Python Connector also natively supports transforming results as Pandas DataFrame objects.

A very simple, adapted example is provided below (1 added line):

query = '''SELECT TOP 10 * FROM TABLE;'''

conn = snowflake.connector.connect(user='XXXX',
                                   password='XXXX',
                                   account='XXXX')

query_output = conn.cursor().execute(query)

## You may have to run: pip3 install --user pandas ##

query_output.fetch_pandas_all().to_csv("/path/to/write/table.csv")
```

The default CSV formatting uses , as the separator, OS-specific newlines (\n except on Windows, which uses \r\n), and minimal quoting (auto-quotes VARCHAR columns that carry delimiter characters within them).

Body:
I currently am trying to print the output of a snowflake connector query and write it to csv, but I'm having issues doing this. Currently, my code example looks like:

query = '''SELECT TOP 10 * FROM TABLE;'''

conn = snowflake.connector.connect(user='XXXX',
                                   password='XXXX',
                                   account='XXXX')

query_output = conn.cursor().execute(query)

Is there a way for me to print the output of the query, like maybe print(query_output) and then also write it to csv like query_output.to_csv(path)?

Body:
I highly recommend using Pandas' DataFrames API. Amongst several other data transformation and analysis capabilities, it has an excellent CSV reader and writer implementation that is very flexible.

Snowflake's Python Connector also natively supports transforming results as Pandas DataFrame objects.

A very simple, adapted example is provided below (1 added line):

query = '''SELECT TOP 10 * FROM TABLE;'''

conn = snowflake.connector.connect(user='XXXX',
                                   password='XXXX',
                                   account='XXXX')

query_output = conn.cursor().execute(query)

## You may have to run: pip3 install --user pandas ##

query_output.fetch_pandas_all().to_csv("/path/to/write/table.csv")

The default CSV formatting uses , as the separator, OS-specific newlines (\n except on Windows, which uses \r\n), and minimal quoting (auto-quotes VARCHAR columns that carry delimiter characters within them).


问:
Android - Paytm payment gateway integration Issue : Type com.paytm.pg.AppTest is defined multiple times
I'm trying to integrate Paytm in my android application,

When I try to Initiate Transaction API as per documnetation in https://developer.paytm.com/docs/initiate-transaction-api/ I get this error:

Type com.paytm.pg.AppTest is defined multiple times: /home/gowthamn/.gradle/caches/transforms-2/files-2.1/80727521e63bd8147327c9aae576f6b7/jetified-PaytmChecksum.jar:com/paytm/pg/AppTest.class, /home/gowthamn/.gradle/caches/transforms-2/files-2.1/80727521e63bd8147327c9aae576f6b7/jetified-PaytmChecksum.jar:target/test-classes/com/paytm/pg/AppTest.class.

Changes I did in Code are mentioned below:

I added implementation 'com.paytm.appinvokesdk:appinvokesdk:1.2' in app level build.gradle.

I added maven {
            url "https://artifactory.paytm.in/libs-release-local"
        } in project level build.gradle

Also paytmchecksum.jar file from https://github.com/Paytm-Payments/Paytm_Web_Sample_Kit_Java/tree/master/Java%20Kit%201.8

I have searched in google about this error. Some suggested to remove the paytmchecksum.jar file.

But if I remove the jar file, I don't find CheckSumServiceHelper.java in code which is used to genrate checksum.

答: We do not recommend to generate checksum at App side, Checksum should be generate at server side. </p>


问:
Large performance difference: Using sysdate vs using pre-formatted date
Why is there such a huge performance difference between these two queries?

```<code>-- (89 seconds)
SELECT max(mydate) FROM mytable WHERE eqpid = 'ABCDEFG'
AND mydate < sysdate - 5
</code>```

vs.

```<code>-- (0.6 seconds)
SELECT max(mydate) FROM mytable WHERE eqpid = 'ABCDEFG'
AND mydate < TO_DATE('05/27/2011 03:13:00', 'MM/DD/YYYY HH24:MI:SS') -- 5 days ago
</code>```

Regardless of indexes, it seems that both to_date and sysdate just return "some date value".

Notes: A composite index exists on this table including eqpid and 2 other columns.
An index also exists for mydate. Both are b-tree. There are about 29 million rows.

Why would the optimizer choose such an obviously different (and in one case, awful) plan for these?

答: Jonathan Lewis has written about issues with sysdate in 9i; have a look at the 'surprising sysdate' section here, for example. Essentially the arithmetic on sysdate seems to confuse the optimizer, so in this case it thinks the index on mydate is more selective. This seems like quite an extreme example though. (Originally pointed in this direction from a not-really-related Ask Tom post).

ContentLicense: CC BY-SA 3.0

Body:
Why is there such a huge performance difference between these two queries?

-- (89 seconds)
SELECT max(mydate) FROM mytable WHERE eqpid = 'ABCDEFG'
AND mydate < sysdate - 5

vs.

-- (0.6 seconds)
SELECT max(mydate) FROM mytable WHERE eqpid = 'ABCDEFG'
AND mydate < TO_DATE('05/27/2011 03:13:00', 'MM/DD/YYYY HH24:MI:SS') -- 5 days ago

Regardless of indexes, it seems that both to_date and sysdate just return "some date value".

Notes: A composite index exists on this table including eqpid and 2 other columns.
An index also exists for mydate. Both are b-tree. There are about 29 million rows.

Why would the optimizer choose such an obviously different (and in one case, awful) plan for these?


问:
angular-material change checkbox color
I'm using checkbox of angular-material2. Currently the default color of checkbox is coming as purple color.

Looks like they have changed default color of checkbox from "primary" to accent.

Is there a way to get "primary"(green) color instead of purple without overriding css.

I tried giving color="primary" to  but that didn't worked.

Code : <md-checkbox></md-checkbox>

Import statement:

```<code>import {MdCheckbox} from '@angular2-material/checkbox';
</code>```

Plunker http://plnkr.co/edit/sFC0kfdzj7fxtUC3GXdr?p=preview

答:
For me what has worked is the following:

```<code><mat-checkbox class="tn-checkbox">Check me!</mat-checkbox>
</code>```

In the css (or in my case sass):

```<code>.#{$wf__ns}checkbox {
  .mat-checkbox-ripple {
    .mat-ripple-element {
      background: $cool-blue !important;
    }
  }

  &.mat-checkbox-checked {
    .mat-checkbox-background {
      background: $cool-blue;
    }
    .mat-checkbox-ripple {
      .mat-ripple-element {
        background: $cool-blue !important;
      }
    }
  }
}
</code>```

Explanation:

The checked background color is changed to mat-checkbox-background within mat-checkbox-checked. IF you want to modify the background color when it is not checked just copy that part and copy it outside of mat-checkbox-checked.

As for the ripple classes, it turns out that the material has an animation when you press the button. That class controls the color of the animation, if you don't change it it will remain the same (pink).

If you do not change it by pressing the checkbox you will see a strange pink effect.

The other answers do not work for me although I rely on the first to develop it.

It may be from my version of angular that I leave below:

```<code>Angular CLI: 8.3.25
Node: 13.3.0
Angular: 8.2.14
</code>```

Title: angular-material change checkbox color

Body:
I'm using checkbox of angular-material2. Currently the default color of checkbox is coming as purple color.

Looks like they have changed default color of checkbox from "primary" to accent.

Is there a way to get "primary"(green) color instead of purple without overriding css.

I tried giving color="primary" to  but that didn't worked.

Code : <md-checkbox></md-checkbox>

Import statement:

import {MdCheckbox} from '@angular2-material/checkbox';

Plunker http://plnkr.co/edit/sFC0kfdzj7fxtUC3GXdr?p=preview

Body:
For me what has worked is the following:

<mat-checkbox class="tn-checkbox">Check me!</mat-checkbox>

In the css (or in my case sass):

.#{$wf__ns}checkbox {
  .mat-checkbox-ripple {
    .mat-ripple-element {
      background: $cool-blue !important;
    }
  }

  &.mat-checkbox-checked {
    .mat-checkbox-background {
      background: $cool-blue;
    }
    .mat-checkbox-ripple {
      .mat-ripple-element {
        background: $cool-blue !important;
      }
    }
  }
}

Explanation:

The checked background color is changed to mat-checkbox-background within mat-checkbox-checked. IF you want to modify the background color when it is not checked just copy that part and copy it outside of mat-checkbox-checked.

As for the ripple classes, it turns out that the material has an animation when you press the button. That class controls the color of the animation, if you don't change it it will remain the same (pink).

If you do not change it by pressing the checkbox you will see a strange pink effect.

The other answers do not work for me although I rely on the first to develop it.

It may be from my version of angular that I leave below:

Angular CLI: 8.3.25
Node: 13.3.0
Angular: 8.2.14


问:
How to get user details from keycloak (not logged in user but any user by his id)
In my Java web application with Spring Boot I have Keycloak authentication done but now I need to get user details of some user by id (not user that is logged in). Is it possible ? I want to get his roles, groups and data from Java code.</p>

答:
You can use the REST API by getting an access token from:

@POST ${yourHost}/auth/realms/${yourRealm}/protocol/openid-connect/token

with @RequestBody

```<code>{
  "client_id": "admin-cli",
  "username": "admin",
  "password": "secret",
  "grant_type": "password"
}
</code>```

Then, call ${_HOST}/auth/admin/realms/${_REALM}/users

using that token as a Header's parameter "Authorization: bearer " + ${_TOKEN}

Do the same to get userByID, but by calling: ${_HOST}/auth/admin/realms/${_REALM}/users/${_USER_ID}

Body:
You can use the REST API by getting an access token from:

@POST ${yourHost}/auth/realms/${yourRealm}/protocol/openid-connect/token

with @RequestBody

{
  "client_id": "admin-cli",
  "username": "admin",
  "password": "secret",
  "grant_type": "password"
}

Then, call ${_HOST}/auth/admin/realms/${_REALM}/users

using that token as a Header's parameter "Authorization: bearer " + ${_TOKEN}

Do the same to get userByID, but by calling: ${_HOST}/auth/admin/realms/${_REALM}/users/${_USER_ID}


问:
Vuejs : Open a collapse menu when a particular tab is active and close it when it is not active
I have two methods forceOpenSettings() and forceCloseSettings(). I need these for opening and closing of a collapsable section. the methods are working fine as I tested it separately. But I need to do this based on a condition, I have b-tab with 4 tabs. Out of which when i click on a tab the collpase should open, and whenever the tab becomes inactive , the collapse must close

```<code><b-tabs content-class="mt-3">
  <b-tab title="First" active><p>I'm the first tab</p></b-tab>
  <b-tab title="Second"><p>I'm the second tab</p></b-tab>
</b-tabs>
</code>```

The same thing I'am achieving in a b-collapse using @show and @hide and it working fine,

```<code><b-collapse role="tabpanel" @show="forceOpenSettings" @hide="forceCloseSettings">......</b-collapse>
</code>```

答:
Vue is data driven, you dont need functions to do this:

{
  ...,
  data(){
    return {
      ...,
      active: 'first',
      tabs: ["first", "second", "third"]
    }
  }
}
```

<pre class="lang-html prettyprint-override"><code><b-tabs content-class="mt-3">
  <b-tab
    v-for="tab in tabs"
    :key="tab"
    :title="tab"
    :active="active==tab"
    @click="active=tab"
    :style="`display:${active==tab? 'block':'none}`'"
  >
    <p>I'm the {{tab}} tab</p>
  </b-tab>

</b-tabs>
</code>```

Ok extending this for interaction with b-collapse component

{
  props: ["tab", "active"],
  computed(){
    collapse: {
      get: function(){
        return this.active == this.tab
      },
      set: function(value){
        this.$emit('update:active', this.tab)
      }
    }
  }
}
```

<pre class="lang-html prettyprint-override"><code><!-- wrap in component for prop management -> no collapse[tab] needed than -->
<template>
<b-collapse
  role="tabpanel"
  v-model="collapse"
 ><slot></slot></b-collapse>
 </template>

 <!-- then in scope of tabs -->
 <wrapped-collapse
    v-for="tab in tabs"
    :key="tab"
    :active.sync="active" :tab="tab"
  >...</wrapped-collapse>
</code>```

Body:
I have two methods forceOpenSettings() and forceCloseSettings(). I need these for opening and closing of a collapsable section. the methods are working fine as I tested it separately. But I need to do this based on a condition, I have b-tab with 4 tabs. Out of which when i click on a tab the collpase should open, and whenever the tab becomes inactive , the collapse must close

I'm the first tab

I'm the second tab

The same thing I'am achieving in a b-collapse using @show and @hide and it working fine,

......

Body:
Vue is data driven, you dont need functions to do this:

{
  ...,
  data(){
    return {
      ...,
      active: 'first',
      tabs: ["first", "second", "third"]
    }
  }
}

<b-tabs content-class="mt-3">
  <b-tab
    v-for="tab in tabs"
    :key="tab"
    :title="tab"
    :active="active==tab"
    @click="active=tab"
    :style="`display:${active==tab? 'block':'none}`'"
  >
    <p>I'm the {{tab}} tab</p>
  </b-tab>

</b-tabs>

Ok extending this for interaction with b-collapse component

{
  props: ["tab", "active"],
  computed(){
    collapse: {
      get: function(){
        return this.active == this.tab
      },
      set: function(value){
        this.$emit('update:active', this.tab)
      }
    }
  }
}

<!-- wrap in component for prop management -> no collapse[tab] needed than -->
<template>
<b-collapse
  role="tabpanel"
  v-model="collapse"
 ><slot></slot></b-collapse>
 </template>

 <!-- then in scope of tabs -->
 <wrapped-collapse
    v-for="tab in tabs"
    :key="tab"
    :active.sync="active" :tab="tab"
  >...</wrapped-collapse>


答:
You need to add scheme if you want to parse it with `ParseRequestURI``

acording docu :

ParseRequestURI parses rawurl into a URL structure. It assumes that rawurl was received in an HTTP request, so the rawurl is interpreted only as an absolute URI or an absolute path. The string rawurl is assumed not to have a #fragment suffix. (Web browsers strip #fragment before sending the URL to a web server.)

So hostname:81 is invalid url.

so try to do this :

```<code>u, err := url.ParseRequestURI("http://" + "hello.com:80")
fmt.Println("err:",err)
fmt.Println("host :",u.Host)
fmt.Println("scheme :",u.Scheme)
</code>```

or even in your case Parse is more correct:

```<code>u, err := url.Parse("http://" + "hello.com:80")
fmt.Println("err:",err)
fmt.Println("host :",u.Host)
fmt.Println("scheme :",u.Scheme)
</code>```

Title: Parsing URL with port and without scheme

Body:
You need to add scheme if you want to parse it with `ParseRequestURI``

acording docu :

ParseRequestURI parses rawurl into a URL structure. It assumes that rawurl was received in an HTTP request, so the rawurl is interpreted only as an absolute URI or an absolute path. The string rawurl is assumed not to have a #fragment suffix. (Web browsers strip #fragment before sending the URL to a web server.)

So hostname:81 is invalid url.

so try to do this :

u, err := url.ParseRequestURI("http://" + "hello.com:80")
fmt.Println("err:",err)
fmt.Println("host :",u.Host)
fmt.Println("scheme :",u.Scheme)

or even in your case Parse is more correct:

u, err := url.Parse("http://" + "hello.com:80")
fmt.Println("err:",err)
fmt.Println("host :",u.Host)
fmt.Println("scheme :",u.Scheme)


问:
Wget command not executed through Jenkins
So my problem is very weird, tried searching all around but not able to find the solution. My goal was to download something using wget using a Jenkins job. I confirmed wget works through command line, also placed wget in system32 folder, as to be invoked from anywhere. I put below command in a bat file and when I try to execute the bat file, like "E:\utilitydownload.bat" in Jenkins using Execute windows batch command, it returns 'wget' is not recognized as an internal or external command, operable program or batch file.

Content of utilitydownload.bat

```<code>E:
cd E:\wgetdownload
wget <some file on a server>
</code>```

答:
Little weird but i'm not sure why it didn't work from C:\Windows\System32. I also tried adding Path environment variable in Slave Configure section but to no avail.

However, if i keep the executable anywhere else, for example, C:\softwares\wget.exe, it works.

Output:

Body:
So my problem is very weird, tried searching all around but not able to find the solution. My goal was to download something using wget using a Jenkins job. I confirmed wget works through command line, also placed wget in system32 folder, as to be invoked from anywhere. I put below command in a bat file and when I try to execute the bat file, like "E:\utilitydownload.bat" in Jenkins using Execute windows batch command, it returns 'wget' is not recognized as an internal or external command, operable program or batch file.

Content of utilitydownload.bat

E:
cd E:\wgetdownload
wget <some file on a server>


问:
Append new data into another sheets
I am trying to append new range of data from CopySheet to Master5 by using the following code, it needs to be appended on the existing data in Master5. I tried using the getlastrow function, but it doesn't seems to work.

```<code>function copysheet() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('A4:R330').activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Master5'), true);
  spreadsheet.getRange('B2').activate();
  spreadsheet.getLastRow()+1.activate()
  spreadsheet.getRange('CopySheet!A4:R330').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('CopySheet'), true);
  spreadsheet.getRange('4:330').activate();
  spreadsheet.getActiveRangeList().clear({contentsOnly: true, commentsOnly: true, skipFilteredRows: true});
};
</code>```

答:
spreadsheet.getLastRow()+1.activate() is not a valid request

Only a range can be activated.

If you want to activate a cell under the last row,

first you need to chose not only a row, but also a column

second in a request of type x+y.activate() the method (in this case activate()) applies only to y. In order to apply a method to x and y, the correct syntax would be (x+y).activate().

Summary:

Change

spreadsheet.getLastRow()+1.activate()

to

```<code>var sheet = spreadsheet.getSheetByName("Chose the name of the sheet from which you want to retrieve the last row");
var lastRow = sheet.getLastRow();
sheet.getRange(lastRow+1,1).activate();
</code>```

Title: Append new data into another sheets

Body:
I am trying to append new range of data from CopySheet to Master5 by using the following code, it needs to be appended on the existing data in Master5. I tried using the getlastrow function, but it doesn't seems to work.

function copysheet() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('A4:R330').activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Master5'), true);
  spreadsheet.getRange('B2').activate();
  spreadsheet.getLastRow()+1.activate()
  spreadsheet.getRange('CopySheet!A4:R330').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('CopySheet'), true);
  spreadsheet.getRange('4:330').activate();
  spreadsheet.getActiveRangeList().clear({contentsOnly: true, commentsOnly: true, skipFilteredRows: true});
};

Body:
spreadsheet.getLastRow()+1.activate() is not a valid request

Only a range can be activated.

If you want to activate a cell under the last row,

first you need to chose not only a row, but also a column

second in a request of type x+y.activate() the method (in this case activate()) applies only to y. In order to apply a method to x and y, the correct syntax would be (x+y).activate().

Summary:

Change

spreadsheet.getLastRow()+1.activate()

to

var sheet = spreadsheet.getSheetByName("Chose the name of the sheet from which you want to retrieve the last row");
var lastRow = sheet.getLastRow();
sheet.getRange(lastRow+1,1).activate();


问:
How do I make a button event with innerhtml in ASP.NET
I tried a lot off things but the innerhtml just doesn't go to the onclick function. I use mysql database and put the innerhtml in a datareader which all work perfectly. The only problem is that i can't click on the html buttons and the asp:buttons arent showing up (also tried linkbuttons, onserverclick etc). I need the onclick function and not javascript because the sql doesn't work in javascript. Can anyone help me?

I tried to use it like this:

```<code>while(dr.read())
{
    ...
    WinkelmandBody.InnerHtml += "<td style='float:right'><button runat='server' onserverclick='btnTrash_Click'><i class='fa fa-trash'></i></button></td>";
</code>```

and tried:

```<code>    WinkelmandBody.InnerHtml += "<td style='float:right'><asp:LinkButton style='height:50px;width:50px' id='btnTrash' onClick='btnTrash_Click'><i class='fas fa-trash'></i></asp:LinkButton></td>";
}
</code>```

onclick thingy (I normally check this in debug mode):

```<code>protected void btnTrash_Click(object sender, EventArgs e)
        {
            Response.Write("<script>alert('test')</script>");
        }
</code>```

html:

```<code>    <tbody>
                            <div id="WinkelmandBody" runat="server">
                            </div>
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td>Sub-Totaal</td>
                                <td class="text-right" runat="server" id="SubTotaal"></td>
</tr>
    </tbody>
</code>```

These all worked, it's only the button that doesn't:

```<code>WinkelmandBody.InnerHtml += "<tr>";
                    WinkelmandBody.InnerHtml += $"<td><img src='imgs/{dr[2]}' style='height: 50px; width: 50px; '/> </td>";
                    WinkelmandBody.InnerHtml += $"<td>{dr[1]}</td>";
                    WinkelmandBody.InnerHtml += $"<td>{stock}</td>";
                    WinkelmandBody.InnerHtml += $"<td style='text-align:center; border:none'><input style='text-align:center' type='text' value='{dr[0]}' /></td>";
                    WinkelmandBody.InnerHtml += $"<td style='text-align:right'>{ Convert.ToInt32(dr[3]) * (Convert.ToInt32(dr[0])) }€</td>";
</code>```

答:
Just a little sidenote. A month after this post I didn't use innerhtml for showing my products but I used an asp:datalist. For the shopping basket I used asp:literal which worked way better than the innerhtml. This allowed me to use bootstrap 4 which I could use with the innerhtml control.

If you have anymore questions feel free to ask.

Body:
I tried a lot off things but the innerhtml just doesn't go to the onclick function. I use mysql database and put the innerhtml in a datareader which all work perfectly. The only problem is that i can't click on the html buttons and the asp:buttons arent showing up (also tried linkbuttons, onserverclick etc). I need the onclick function and not javascript because the sql doesn't work in javascript. Can anyone help me?

I tried to use it like this:

while(dr.read())
{
    ...
    WinkelmandBody.InnerHtml += "<button runat='server' onserverclick='btnTrash_Click'></button>	";

and tried:

    WinkelmandBody.InnerHtml += "<asp:LinkButton style='height:50px;width:50px' id='btnTrash' onClick='btnTrash_Click'></asp:LinkButton>	";
}

onclick thingy (I normally check this in debug mode):

protected void btnTrash_Click(object sender, EventArgs e)
        {
            Response.Write("");
        }

html:

                                Sub-Totaal

These all worked, it's only the button that doesn't:

WinkelmandBody.InnerHtml += "
";
                    WinkelmandBody.InnerHtml += $" 	";
                    WinkelmandBody.InnerHtml += $"{dr[1]}	";
                    WinkelmandBody.InnerHtml += $"{stock}	";
                    WinkelmandBody.InnerHtml += $"<input style='text-align:center' type='text' value='{dr[0]}' />	";
                    WinkelmandBody.InnerHtml += $"{ Convert.ToInt32(dr[3]) * (Convert.ToInt32(dr[0])) }€	";


问:
Oneliner to create a dictionary from two lists in Python
I want to create this dictionary, but using one liner.

```<code>{'apple_last_6kg':'buy','mango_last_6kg':'buy','banana_last_6kg':'buy',
 'apple_last_4kg':'buy','mango_last_4kg':'buy','banana_last_4kg':'buy',
 'apple_last_3kg':'buy','mango_last_3kg':'buy','banana_last_3kg':'buy',
 'apple_last_kg':'buy','mango_last_kg':'buy','banana_last_kg':'buy'}
</code>```

This is what I initially tried and got the error, though {**{'a':1},**{'b':2}} works perfectly and gives {'a':1,'b':2}, but using this formulation in dictionary comprehension gives error.:

```<code>dic2 = {**{i+'_last_'+time:'buy' for i in ['apple','mango','banana']} for time in ['kg','3kg','4kg','6kg']}
print(dic2)
File "<ipython-input-238-9332e6a46412>", line 29
    dic2 = {**{i+'_last_'+time:'buy' for i in ['apple','mango','banana']} for time in ['kg','3kg','4kg','6kg']}
          ^
SyntaxError: dict unpacking cannot be used in dict comprehension
</code>```

I solved this like below, but I would like to have a one liner dictionay-comprehension like solution. Any suggestions?

```<code># This solution is unelegant, so I don't want to use this.
dic2 = [{i+'_last_'+j:'buy' for i in ['apple','mango','banana']} for j in ['kg','3kg','4kg','6kg']]

new_dic = {}
for d in dic2:
    new_dic.update(d)
print(new_dic)
{'apple_last_3kg': 'buy','apple_last_4kg': 'buy','apple_last_6kg': 'buy',
 'apple_last_kg': 'buy','banana_last_3kg': 'buy','banana_last_4kg': 'buy',
 'banana_last_6kg': 'buy','banana_last_kg': 'buy','mango_last_3kg': 'buy',
 'mango_last_4kg': 'buy','mango_last_6kg': 'buy','mango_last_kg': 'buy'}
</code>```

答:
```<code>dict.fromkeys(
    (i+'_last_'+j for j in ['6kg','4kg','3kg','kg'] for i in ['apple','mango','banana']),
    "buy"
)
</code>```

See this classmethod here.

Body:
I want to create this dictionary, but using one liner.

{'apple_last_6kg':'buy','mango_last_6kg':'buy','banana_last_6kg':'buy',
 'apple_last_4kg':'buy','mango_last_4kg':'buy','banana_last_4kg':'buy',
 'apple_last_3kg':'buy','mango_last_3kg':'buy','banana_last_3kg':'buy',
 'apple_last_kg':'buy','mango_last_kg':'buy','banana_last_kg':'buy'}

This is what I initially tried and got the error, though {**{'a':1},**{'b':2}} works perfectly and gives {'a':1,'b':2}, but using this formulation in dictionary comprehension gives error.:

dic2 = {**{i+'_last_'+time:'buy' for i in ['apple','mango','banana']} for time in ['kg','3kg','4kg','6kg']}
print(dic2)
File "<ipython-input-238-9332e6a46412>", line 29
    dic2 = {**{i+'_last_'+time:'buy' for i in ['apple','mango','banana']} for time in ['kg','3kg','4kg','6kg']}
          ^
SyntaxError: dict unpacking cannot be used in dict comprehension

I solved this like below, but I would like to have a one liner dictionay-comprehension like solution. Any suggestions?

# This solution is unelegant, so I don't want to use this.
dic2 = [{i+'_last_'+j:'buy' for i in ['apple','mango','banana']} for j in ['kg','3kg','4kg','6kg']]

new_dic = {}
for d in dic2:
    new_dic.update(d)
print(new_dic)
{'apple_last_3kg': 'buy','apple_last_4kg': 'buy','apple_last_6kg': 'buy',
 'apple_last_kg': 'buy','banana_last_3kg': 'buy','banana_last_4kg': 'buy',
 'banana_last_6kg': 'buy','banana_last_kg': 'buy','mango_last_3kg': 'buy',
 'mango_last_4kg': 'buy','mango_last_6kg': 'buy','mango_last_kg': 'buy'}

Body:
dict.fromkeys(
    (i+'_last_'+j for j in ['6kg','4kg','3kg','kg'] for i in ['apple','mango','banana']),
    "buy"
)

See this classmethod here.


问:
Highcharts - dynamic data label positioning on multi series doughtnut charts
Background info:
I am trying to create a multi series doughnut chart with the data labels positioned in the center of each slice like this (see below) however I want the data labels to reposition itself if the div is resized:

Problem:
I am struggling to reposition the data labels accurately when the div is resized.

I need to get the current doughnut chart plot size in percentage with which I could calculate accurate distance from doughnut edges to place the data labels.

Example Fiddle

Here's a mockup in fiddle: http://jsfiddle.net/simkus/bo2eumkd/30/

```<code>$(function() {
  var container = $('#container')[0];
  $('#resizer').resizable({
    // On resize, set the chart size to that of the
    // resizer minus padding. If your chart has a lot of data or other
    // content, the redrawing might be slow. In that case, we recommend
    // that you use the 'stop' event instead of 'resize'.

   // TODO we need to calculate the distance of dataLabels from the edges of the
   // doughnut chart. The main thing is that the chart might be resized, to e.g. 200pxx200px
   // and then the labels now gets scatared by the current algorythm where we calculate `distance`
   // the `distance` should be calculated I think not in pixels by % of the current
   // chart placeholder size. The chart it self has a `size` of 80% for all series.
   // the inner size is also measured in %, so the distance somehow has to be done
   // similary, but at this point, the `distance` doesn't work with % as size and innerSize
    resize: function() {
      chart.setSize(
        this.offsetWidth - 20,
        this.offsetHeight - 20,
        false
      );
    }
  });

  let seriesData = [{
      "base": 1949,
      "data": [106, 105, 26, 43, 55, 136],
      "name": "Total",
    },
    {
      "base": 871,
      "data": [38, 44, 14, 20, 25, 75],
      "name": "Male",
    },
    {
      "base": 1063,
      "data": [65, 61, 12, 23, 31, 60],
      "name": "Female",
    }
  ]
  let categories = [
    "Don't know",
    "Australia",
    "India",
    "Japan",
    "Brazil",
    "I don’t know"
  ]

  let series = [];
  let plotArea = 350;
    let centerInnerSize = 40; // 40%

  for (let i = 0; i < seriesData.length; i++) {
      var showInLegend = false,
          data = [],
          innerSize = centerInnerSize + ((100 - centerInnerSize) / seriesData.length) * i,
          width = (plotArea / 2) * ((1 - centerInnerSize / 100) / seriesData.length),
          distance = (plotArea / 2) * (1 - innerSize / 100) - width / 2;

      if (i == 0) {
          showInLegend = true;
      }

      for (let j = 0; j < categories.length; j++) {
          data.push({
            'name': categories[j],
            'y': seriesData[i].data[j]
          })
      }

      series.push({
          name: seriesData[i].name,
          data: data,
          innerSize: innerSize + '%',
          size: "80%",
          showInLegend: true,
          dataLabels: {
              enabled: true,
              distance: -distance,
          }
      })
  }

  var chart = new Highcharts.Chart({
    chart: {
      renderTo: 'container',
      plotBackgroundColor: null,
      plotBorderWidth: 1,
      plotShadow: false,
      type: 'pie',
      events: {
        render() {
          let chart = this;

          chart.series.forEach(s => {
            s.points.forEach(p => {
              let label = p.dataLabel;

              p.dataLabel.translate(label.translateX, label.translateY)
            })
          })
        }
      }
    },
    subtitle: {
      text: 'Drag the handle in the lower right to resize'
    },
    tooltip: {
      pointFormat: '{series.name}: <b>{point.percentage:.2f}%</b>'
    },
    plotOptions: {
      pie: {
        allowPointSelect: false,
        cursor: 'pointer',
        minSize: 1,
        dataLabels: {
          enabled: true,
          color: '#000000',
          format: '{percentage:.2f} %',
        }
      }
    },
    series: series,
  });
});
</code>```

Any ideas how I can resolve this problem?

答:
Updated the distance calculation using percentage and now it works.

http://jsfiddle.net/4g1pxvqb/36/

```<code>  for (let i = 0; i < seriesData.length; i++) {
      var showInLegend = false,
          data = [],
          innerSize = centerInnerSize + ((100 - centerInnerSize) / seriesData.length) * i,
          width = (100 - centerInnerSize) / 3;

          distance = '-' + (10 + width * (2 - i)) + '%';
</code>```

Body:
Background info:
I am trying to create a multi series doughnut chart with the data labels positioned in the center of each slice like this (see below) however I want the data labels to reposition itself if the div is resized:

Problem:
I am struggling to reposition the data labels accurately when the div is resized.

I need to get the current doughnut chart plot size in percentage with which I could calculate accurate distance from doughnut edges to place the data labels.

Example Fiddle

Here's a mockup in fiddle: http://jsfiddle.net/simkus/bo2eumkd/30/

$(function() {
  var container = $('#container')[0];
  $('#resizer').resizable({
    // On resize, set the chart size to that of the
    // resizer minus padding. If your chart has a lot of data or other
    // content, the redrawing might be slow. In that case, we recommend
    // that you use the 'stop' event instead of 'resize'.

   // TODO we need to calculate the distance of dataLabels from the edges of the
   // doughnut chart. The main thing is that the chart might be resized, to e.g. 200pxx200px
   // and then the labels now gets scatared by the current algorythm where we calculate `distance`
   // the `distance` should be calculated I think not in pixels by % of the current
   // chart placeholder size. The chart it self has a `size` of 80% for all series.
   // the inner size is also measured in %, so the distance somehow has to be done
   // similary, but at this point, the `distance` doesn't work with % as size and innerSize
    resize: function() {
      chart.setSize(
        this.offsetWidth - 20,
        this.offsetHeight - 20,
        false
      );
    }
  });

  let seriesData = [{
      "base": 1949,
      "data": [106, 105, 26, 43, 55, 136],
      "name": "Total",
    },
    {
      "base": 871,
      "data": [38, 44, 14, 20, 25, 75],
      "name": "Male",
    },
    {
      "base": 1063,
      "data": [65, 61, 12, 23, 31, 60],
      "name": "Female",
    }
  ]
  let categories = [
    "Don't know",
    "Australia",
    "India",
    "Japan",
    "Brazil",
    "I don’t know"
  ]

  let series = [];
  let plotArea = 350;
    let centerInnerSize = 40; // 40%

  for (let i = 0; i < seriesData.length; i++) {
      var showInLegend = false,
          data = [],
          innerSize = centerInnerSize + ((100 - centerInnerSize) / seriesData.length) * i,
          width = (plotArea / 2) * ((1 - centerInnerSize / 100) / seriesData.length),
          distance = (plotArea / 2) * (1 - innerSize / 100) - width / 2;

      if (i == 0) {
          showInLegend = true;
      }

      for (let j = 0; j < categories.length; j++) {
          data.push({
            'name': categories[j],
            'y': seriesData[i].data[j]
          })
      }

      series.push({
          name: seriesData[i].name,
          data: data,
          innerSize: innerSize + '%',
          size: "80%",
          showInLegend: true,
          dataLabels: {
              enabled: true,
              distance: -distance,
          }
      })
  }

  var chart = new Highcharts.Chart({
    chart: {
      renderTo: 'container',
      plotBackgroundColor: null,
      plotBorderWidth: 1,
      plotShadow: false,
      type: 'pie',
      events: {
        render() {
          let chart = this;

          chart.series.forEach(s => {
            s.points.forEach(p => {
              let label = p.dataLabel;

              p.dataLabel.translate(label.translateX, label.translateY)
            })
          })
        }
      }
    },
    subtitle: {
      text: 'Drag the handle in the lower right to resize'
    },
    tooltip: {
      pointFormat: '{series.name}: {point.percentage:.2f}%'
    },
    plotOptions: {
      pie: {
        allowPointSelect: false,
        cursor: 'pointer',
        minSize: 1,
        dataLabels: {
          enabled: true,
          color: '#000000',
          format: '{percentage:.2f} %',
        }
      }
    },
    series: series,
  });
});

Any ideas how I can resolve this problem?

Body:
Updated the distance calculation using percentage and now it works.

http://jsfiddle.net/4g1pxvqb/36/

  for (let i = 0; i < seriesData.length; i++) {
      var showInLegend = false,
          data = [],
          innerSize = centerInnerSize + ((100 - centerInnerSize) / seriesData.length) * i,
          width = (100 - centerInnerSize) / 3;

          distance = '-' + (10 + width * (2 - i)) + '%';


问:
How to set the one value with where condition
I have dataframe(df) like this

```<code>   key            name value
0    0          master     0
1    1           basic     0
2    2           clear     0
3    3            debu     0
</code>```

What I want to do is like this below

```<code>items = [master,master,basic,clear]

for i in items:   # loop the items
    df[where('name==@i')].value += 1     # increment each item
</code>```

Final output should be

```<code>   key            name value
0    0          master     2
1    1           basic     1
2    2           clear     1
3    3            debu     0
</code>```

How can I fetch the one value and increment ???

答:
I prefer to use Series.map with Counter, then loop is not necessary:

```<code>from collections import Counter

items = ['master','master','basic','clear']

df['value'] = df['name'].map(Counter(items))
print (df)
   key    name  value
0    0  master      2
1    1   basic      1
2    2   clear      1
3    3    debu      0
</code>```

But it is possible like mentioned in comments filter by boolean indexing with DataFrame.loc, in my opinion assign with += is not problem in pandas, be free use it:

```<code>items = ['master','master','basic','clear']

for i in items:   # loop the items
    df.loc[df['name']==i, 'value'] += 1

print (df)
   key    name  value
0    0  master      2
1    1   basic      1
2    2   clear      1
3    3    debu      0
</code>```

Body:
I have dataframe(df) like this

   key            name value
0    0          master     0
1    1           basic     0
2    2           clear     0
3    3            debu     0

What I want to do is like this below

items = [master,master,basic,clear]

for i in items:   # loop the items
    df[where('name==@i')].value += 1     # increment each item

Final output should be

   key            name value
0    0          master     2
1    1           basic     1
2    2           clear     1
3    3            debu     0

How can I fetch the one value and increment ???

Body:
I prefer to use Series.map with Counter, then loop is not necessary:

from collections import Counter

items = ['master','master','basic','clear']

df['value'] = df['name'].map(Counter(items))
print (df)
   key    name  value
0    0  master      2
1    1   basic      1
2    2   clear      1
3    3    debu      0

But it is possible like mentioned in comments filter by boolean indexing with DataFrame.loc, in my opinion assign with += is not problem in pandas, be free use it:

items = ['master','master','basic','clear']

for i in items:   # loop the items
    df.loc[df['name']==i, 'value'] += 1

print (df)
   key    name  value
0    0  master      2
1    1   basic      1
2    2   clear      1
3    3    debu      0


答:
Trying to parse a hostname and path without a scheme is invalid but may not necessarily return an error, due to parsing ambiguities.

— documentation for net/url.Parse

What you have passed to ParseRequestURI isn't a URI, or at least not one that means what you think it means. If you had passed http://hello.com:81/ then the host would have been set as expected.

Body:
I am trying to parse a URL in Go and get host and scheme from the URL. But while parsing the URL with port and without scheme I am getting unexpected result.

u, err := url.ParseRequestURI("hello.com:81")
fmt.Println("host :",u.Host)
fmt.Println("scheme :",u.Scheme)

I am getting unexpected result

host :
scheme: hello.com

I wanted this instead

host : hello.com:80
scheme:


问:
Return non-nullable type
I'm sure, my code gets not null value for return:

    fun getBitmap(id: Int): Bitmap{
        if (!(id in bitmapStorage))
            bitmapStorage.put(id, BitmapFactory.decodeResource(resources, id))
        return bitmapStorage.get(id)
    }
```

What's the right way to return Bitmap type instead of Bitmap??

!!, as Bitmap or something else?

答:
As per your code, the method getBitmap() can never return null. In such cases, you'd return it as Bitmap (T - type of class).

But there could be cases, where a method can potentially return null at times, in such cases it is advised to return it as Bitmap? (T?)

And here is the beauty of Kotlin gets to shine, the caller of the method now has to handle the null explicitly. If the caller knows that it can never be null but still has annotated it as T? then, he/she can call it as getBitmap()!!.

More on it: https://kotlinlang.org/docs/reference/null-safety.html

Title: Return non-nullable type

Body:
I'm sure, my code gets not null value for return:

    fun getBitmap(id: Int): Bitmap{
        if (!(id in bitmapStorage))
            bitmapStorage.put(id, BitmapFactory.decodeResource(resources, id))
        return bitmapStorage.get(id)
    }

What's the right way to return Bitmap type instead of Bitmap??

!!, as Bitmap or something else?


问:
When gets this static variable initalised and when to use StringBuffer
I just saw this example

```<code>public class Runtime {
    //When is this private member initalised ??
    private static Runtime currentRuntime = new Runtime();

    public static Runtime getRuntime() {
        return currentRuntime;
    }
</code>```

Now when you call Runtime.getRuntime() currentRuntime is already initalised even an instance of this class was never created. How does it work ?

My second question is about StringBuffer ?

```<code>String var = "Hello World";
</code>```

Now if you do var = var + "!";

Whould it be better to use a StringBuffer. I mean StringBuffer reserves a lot of memory I think 1000Byte at least, so just for that simple example it would still be better no to use StringBuffer. Of course
now we have 2 Strings in memory "Hello World" and "Hello World!"  but still better than StringBuffer with 1000 Byte or more . Right ?

答:
I will answer this: "when gets this static variable initialized"

I've experienced that Java classes are loaded when they're needed. For example, if you never use it (for example, you never refer to a variable, or call a function/constructor) the JVM does not initialize the class.

So, when you call Runtime.getRuntime(), then the class is initialized and so are the static fields.

You can also test it using static blocks with this code

public class MainClass {
    public static void main(String[] args) {
        System.out.println("program starts");
        Runtime.getRuntime();
        System.out.println("programs end");
    }
}
```

<pre class="lang-java prettyprint-override"><code>public class Runtime {
    //When is this private member initalised ??
    private static Runtime currentRuntime = new Runtime();

    static {
        System.out.println("when this is called the class is beeing initialized");
        System.out.println("is currentRuntime null? -> " + (currentRuntime == null));
    }

    public static Runtime getRuntime() {
        System.out.println("getRuntime is executed");
        return currentRuntime;
    }
}
</code>```

This is what i get on the console

```<code>program starts
when this is called the class is beeing initialized
is currentRuntime null? -> false
getRuntime is called
programs end
</code>```

What does this mean? That the class Runtime (and its fields) are not initialized before main() starts, but it is initialized when Runtime is requested.

Also, the static block is called when currentRuntime is not null, so it's already initialized (remember that Java is top-down).

So, it's initialized when Runtime.getRuntime() is called, but before it's executed

Body:
I just saw this example

public class Runtime {
    //When is this private member initalised ??
    private static Runtime currentRuntime = new Runtime();

    public static Runtime getRuntime() {
        return currentRuntime;
    }

Now when you call Runtime.getRuntime() currentRuntime is already initalised even an instance of this class was never created. How does it work ?

My second question is about StringBuffer ?

String var = "Hello World";

Now if you do var = var + "!";

Whould it be better to use a StringBuffer. I mean StringBuffer reserves a lot of memory I think 1000Byte at least, so just for that simple example it would still be better no to use StringBuffer. Of course
now we have 2 Strings in memory "Hello World" and "Hello World!"  but still better than StringBuffer with 1000 Byte or more . Right ?

Body:
I will answer this: "when gets this static variable initialized"

I've experienced that Java classes are loaded when they're needed. For example, if you never use it (for example, you never refer to a variable, or call a function/constructor) the JVM does not initialize the class.

So, when you call Runtime.getRuntime(), then the class is initialized and so are the static fields.

You can also test it using static blocks with this code

public class MainClass {
    public static void main(String[] args) {
        System.out.println("program starts");
        Runtime.getRuntime();
        System.out.println("programs end");
    }
}

public class Runtime {
    //When is this private member initalised ??
    private static Runtime currentRuntime = new Runtime();

    static {
        System.out.println("when this is called the class is beeing initialized");
        System.out.println("is currentRuntime null? -> " + (currentRuntime == null));
    }

    public static Runtime getRuntime() {
        System.out.println("getRuntime is executed");
        return currentRuntime;
    }
}

This is what i get on the console

program starts
when this is called the class is beeing initialized
is currentRuntime null? -> false
getRuntime is called
programs end

What does this mean? That the class Runtime (and its fields) are not initialized before main() starts, but it is initialized when Runtime is requested.

Also, the static block is called when currentRuntime is not null, so it's already initialized (remember that Java is top-down).

So, it's initialized when Runtime.getRuntime() is called, but before it's executed


问:
MongoDB - MANY documents or MANY collections
I am currently working on a service that stores products owned by multiple stores, and I am trying to figure how is the best way of structuring the DB. The only problem is that products are from different domains, like, clothes, toys, electronics and sold by different sellers.

First idea that came to mind was having different collections for each seller, but I see this as a headache, having to manage different DB connections.

The idea of storing all products in the same document seems bad to me, because they are from different domains.

The only idea that I believe could work in this case is like this:
Let's say we have 3 stores: Store One, Store Two, Store Three. I would create a document for each store like this: products_storeone, products_storetwo, products_storethree and access them based on an identifier each store has. Now, each store will have multiple documents to store different things like products_identifier, users_identifier, orders_identifier.

Do you consider this is a good idea?
Please tell me your opinion on what could be the best way of achieving a structure for storing items for each store independently, without mixing them.

After some calculation, there will be maximum 50 documents for each store. I don't see this as a way to big number to handle like 1.000 stores. Do you think 50.000 documents are too much? Impacts performance?
Any tips in order to achieve high performance for queries are more than welcome.

Thanks!

答:
You can make an single db "products" and it will be an array of objects and each will be a single product. Each product will have "store" and "category" attribute by which we query efficiently.

Hope this can be of help.


问:
How do I extract data from a main table based on this specific scenario?
I am using SQL Server 2014. I have a table (T1) which contains the list of IDs of cancelled bookings and their equivalent re-bookings.

Extract of table T1:

```<code>CancelledID       Re-bookingID
  301                754
  387                801
  400                900
  ...
</code>```

Each CancelledID has a unique equivalent in the Re-bookingID column.

I have another table (T2) which contains the list of ALL BookingIDs with additional information related to each ID. An extract of this table is shown below:

```<code>BookingID     MonthOfStay      RoomNights
...
301             2019-03-01        10
387             2019-04-01         7
400             2019-03-01         5
754             2019-08-01        10
801             2019-09-01         3
900             2019-07-01         5
900             2019-08-01         4
...
</code>```

I need a  t-sql query which will me the following output:

```<code>  BookingID       Cancelled_MonthOfStay     Re-booking_MonthOfStay     RoomNights
    301                2019-03-01                                           10
    387                2019-04-01                                            7
    400                2019-03-01                                            5
    754                                           2019-08-01                10
    801                                           2019-09-01                 3
    900                                           2019-07-01                 5
    900                                           2019-08-01                 4
</code>```

As you can see, a re-booking can span over 2 months with additional room nights.

I am thinking about "Joins" between the 2 tables but I am stuck at the logic to be used for the "Joins" (if that is the right way of tackling the problem).

Note: The end in mind is to use this data to build a matrix with Cancelled_MonthOfStay as rows and Re-booking_MonthOfStay as columns. The value inside this matrix will be the total RoomNights.

Any help would be appreciated.

答:
Seems like the easiest method would be to unpivot your data in the "Cancellations" table, and then use a CASE expression to display the data in the appropriate column:

```<code>USE Sandbox;
GO

CREATE TABLE dbo.Cancellations (CancelledID int, RebookingID int)
INSERT INTO dbo.Cancellations
VALUES (301,754),
       (387,801),
       (400,900);

GO

CREATE TABLE dbo.Bookings (BookingID int, MonthOfStay date, RoomNights int)
INSERT INTO dbo.Bookings
VALUES (301,'20190301',10),
       (387,'20190401', 7),
       (400,'20190301', 5),
       (754,'20190801',10),
       (801,'20190901', 3),
       (900,'20190701', 5),
       (900,'20190801', 4);
GO

SELECT B.BookingID,
       CASE V.BookingType WHEN 'Cancellation' THEN B.MonthOfStay END AS CancelledMonthOfStay,
       CASE V.BookingType WHEN 'Rebooking' THEN B.MonthOfStay END AS RebookedMonthOfStay,
       B.RoomNights
FROM dbo.Cancellations C
     CROSS APPLY (VALUES(C.CancelledID, 'Cancellation'),(C.RebookingID, 'Rebooking')) V(BookingID,BookingType)
     JOIN dbo.Bookings B ON V.BookingID = B.BookingID
ORDER BY B.BookingID;

GO

DROP TABLE dbo.Cancellations;
DROP TABLE dbo.Bookings;
</code>```

Body:
I am using SQL Server 2014. I have a table (T1) which contains the list of IDs of cancelled bookings and their equivalent re-bookings.

Extract of table T1:

CancelledID       Re-bookingID
  301                754
  387                801
  400                900
  ...

Each CancelledID has a unique equivalent in the Re-bookingID column.

I have another table (T2) which contains the list of ALL BookingIDs with additional information related to each ID. An extract of this table is shown below:

BookingID     MonthOfStay      RoomNights
...
301             2019-03-01        10
387             2019-04-01         7
400             2019-03-01         5
754             2019-08-01        10
801             2019-09-01         3
900             2019-07-01         5
900             2019-08-01         4
...

I need a  t-sql query which will me the following output:

  BookingID       Cancelled_MonthOfStay     Re-booking_MonthOfStay     RoomNights
    301                2019-03-01                                           10
    387                2019-04-01                                            7
    400                2019-03-01                                            5
    754                                           2019-08-01                10
    801                                           2019-09-01                 3
    900                                           2019-07-01                 5
    900                                           2019-08-01                 4

As you can see, a re-booking can span over 2 months with additional room nights.

I am thinking about "Joins" between the 2 tables but I am stuck at the logic to be used for the "Joins" (if that is the right way of tackling the problem).

Note: The end in mind is to use this data to build a matrix with Cancelled_MonthOfStay as rows and Re-booking_MonthOfStay as columns. The value inside this matrix will be the total RoomNights.

Any help would be appreciated.

Body:
Seems like the easiest method would be to unpivot your data in the "Cancellations" table, and then use a CASE expression to display the data in the appropriate column:

USE Sandbox;
GO

CREATE TABLE dbo.Cancellations (CancelledID int, RebookingID int)
INSERT INTO dbo.Cancellations
VALUES (301,754),
       (387,801),
       (400,900);

GO

CREATE TABLE dbo.Bookings (BookingID int, MonthOfStay date, RoomNights int)
INSERT INTO dbo.Bookings
VALUES (301,'20190301',10),
       (387,'20190401', 7),
       (400,'20190301', 5),
       (754,'20190801',10),
       (801,'20190901', 3),
       (900,'20190701', 5),
       (900,'20190801', 4);
GO

SELECT B.BookingID,
       CASE V.BookingType WHEN 'Cancellation' THEN B.MonthOfStay END AS CancelledMonthOfStay,
       CASE V.BookingType WHEN 'Rebooking' THEN B.MonthOfStay END AS RebookedMonthOfStay,
       B.RoomNights
FROM dbo.Cancellations C
     CROSS APPLY (VALUES(C.CancelledID, 'Cancellation'),(C.RebookingID, 'Rebooking')) V(BookingID,BookingType)
     JOIN dbo.Bookings B ON V.BookingID = B.BookingID
ORDER BY B.BookingID;

GO

DROP TABLE dbo.Cancellations;
DROP TABLE dbo.Bookings;


问:
How can I import data from mssql to hbase with sqoop (use Azure HDInsight)?
I am trying to import data table from mssql to hbase with sqoop, I use C# language. I have followed this article

my code command to import data to hbase:

connectionstring:

```<code>connectionString = "jdbc:sqlserver://" + sqlDatabaseServerName + ";user=" + sqlDatabaseLogin + ";password=" + sqlDatabaseLoginPassword + ";database=" + sqlDatabaseDatabaseName;
</code>```

sqoop command:

```<code>"import --connect " + connectionString + " --table " + tableName + " -hbase-create-table –hbase-table TestTableHBase -column-family PostID -hbase-row-key PostID -m 1"
</code>```

I received a successful response but it didn't work.

答:
For MYSQL to HBASE:

You can use below command to import Mysql table to HBase table:

```<code>sqoop import --connect jdbc:mysql://localhost/emp --username root --password cloudera --table employee --hbase-table Academp --column-family emp_id --hbase-row-key id -m 1
</code>```

Reference: How to Import Table from MySQL to HBase

For SQL SERVER to HBASE

You can use below command to import SQL server table to HBase table:

```<code>sqoop import --connect "jdbc:sqlserver://hostname:1433;database=db_name;username=sqoop;password=???" --hbase-create-table --hbase-table table_name_in_hbase --column-family cf_name --hbase-row-key my_ID --table tablename_in_sql_server -m 1
</code>```

Reference: importing data from sql server to hbase

Body:
I am trying to import data table from mssql to hbase with sqoop, I use C# language. I have followed this article

my code command to import data to hbase:

connectionstring:

connectionString = "jdbc:sqlserver://" + sqlDatabaseServerName + ";user=" + sqlDatabaseLogin + ";password=" + sqlDatabaseLoginPassword + ";database=" + sqlDatabaseDatabaseName;

sqoop command:

"import --connect " + connectionString + " --table " + tableName + " -hbase-create-table –hbase-table TestTableHBase -column-family PostID -hbase-row-key PostID -m 1"

I received a successful response but it didn't work.

Body:
For MYSQL to HBASE:

You can use below command to import Mysql table to HBase table:

sqoop import --connect jdbc:mysql://localhost/emp --username root --password cloudera --table employee --hbase-table Academp --column-family emp_id --hbase-row-key id -m 1

Reference: How to Import Table from MySQL to HBase

For SQL SERVER to HBASE

You can use below command to import SQL server table to HBase table:

sqoop import --connect "jdbc:sqlserver://hostname:1433;database=db_name;username=sqoop;password=???" --hbase-create-table --hbase-table table_name_in_hbase --column-family cf_name --hbase-row-key my_ID --table tablename_in_sql_server -m 1

Reference: importing data from sql server to hbase


问:
Add DropDown without refreshing page
Good Evening, </p>

<p>Could one of you suggest a way to add a dropdown box dynamically without refreshing the page? The dropdown box must not be visible at first, it must then become visible later based on a choice made by the user.  However one constraint is it can only be Javascript, Php, and/or html  </p>

答: The easier way is to include the HTML but hidden, then display it via Javascript when appropiate. Need more deatails?</p>

Title: Add DropDown without refreshing page

Body:
Good Evening,

Could one of you suggest a way to add a dropdown box dynamically without refreshing the page? The dropdown box must not be visible at first, it must then become visible later based on a choice made by the user.  However one constraint is it can only be Javascript, Php, and/or html


问:
Sorting an array with child - parent dependencies
I am given the following array of objects:

```<code>let data = [{id: 3, name: ''}, {id: 4, name: ''}, {id: 5, name: '', parent: 3}, {id: 6, name: '', parent: 5},   {id: 7, name: '', parent: 4}, {id: 8, name: '', parent: 8}];
</code>```

How do I create a nested list, where an object with corresponding parent element is appended to a new
 element? So to make it clear it would look something like this:

```<code><li>
  object id:3 (parent)
    <li>object id:5</li>(child)
</li>`
</code>```

Any clues? :)

答:
You could do this with two functions one to create nested tree structure and another one to create a nested html structure based on previously create tree structure.

let data = [{id: 3, name: ''}, {id: 4, name: ''}, {id: 5, name: '', parent: 3}, {id: 6, name: '', parent: 5},   {id: 7, name: '', parent: 4}, {id: 8, name: '', parent: 8}];

const toTree = (data, pid = undefined) => {
  return data.reduce((r, e) => {
    if (pid == e.parent) {
      const obj = { ...e }
      const children = toTree(data, e.id);
      if (children) obj.children = children
      r.push(obj)
    }

    return r
  }, [])
}

const toHtml = (data) => {
  const ul = document.createElement('ul')

  data.forEach(e => {
    const li = document.createElement('li');
    const text = document.createElement('span')

    text.textContent = `object id: ${e.id}`;
    li.appendChild(text)

    const children = toHtml(e.children);
    if (children) li.appendChild(children)

    ul.appendChild(li)
  })

  return ul
}

const tree = toTree(data)
const html = toHtml(tree)

document.body.appendChild(html)```

Body:
I am given the following array of objects:

let data = [{id: 3, name: ''}, {id: 4, name: ''}, {id: 5, name: '', parent: 3}, {id: 6, name: '', parent: 5},   {id: 7, name: '', parent: 4}, {id: 8, name: '', parent: 8}];

How do I create a nested list, where an object with corresponding parent element is appended to a new
 element? So to make it clear it would look something like this:

  object id:3 (parent)

object id:5
(child)

`

Any clues? :)


问:
How to get rid of absolute paths from a file generated by docker-compose config?
I have a ton of docker-compose files. Some defining my microservices, some defining the infrastructural pieces, like db, message bus etc. I need to merge them all into one, big docker-compose.yml file, so that I can easily run it via my CI/CD pipeline. I wrote this shell script to do so, but it seems the docker-compose config command generates a file with absolute paths:

```<code>#!/bin/bash

ymls=`ls **/docker-compose.*.yml`
compose_string=""

for file in $ymls
do
    compose_string="${compose_string} -f ${file} --project-directory ."
done

echo $compose_string

docker-compose $compose_string config > docker-compose.merged.yml
</code>```

This gives me the below file contents (shortened for brevity):

```<code>services:
  curator-services:
    build:
      args:
        ELASTIC_PASSWORD: them-pass
      context: E:\repos\them-project\devops\curator
  manager-acl-app:
    build:
      context: E:\repos\them-project
      dockerfile: services/ThemProject.Services.ManagerAcl/Dockerfile
</code>```

Now, the easy solution would be to just run a regexp or something and substitute whatever is in the same line as the word context. The problem with that approach is that I keep my infrastructural definitions in another folder than my microservices Dockerfiles, so the context for the curator-services piece should be context: curator/ and for the manager-acl-app it should be context: ../. Is there a way around those absolute paths with docker-compose config?

答:
You can use --project-directory  option with docker-compose config.

Change your script to below

```<code>#!/bin/bash

ymls=`ls docker-compose.*.yml`
compose_string=""
DIR_PATH="." #Change it to Project Directory or current directory
for file in $ymls
do
    compose_string="${compose_string} -f ${file} --project-directory $DIR_PATH"
done

docker-compose ${compose_string} config > docker-compose.yml
</code>```

Ref:- https://docs.docker.com/compose/reference/overview/

Please check --project-directory in the above link

Body:
I have a ton of docker-compose files. Some defining my microservices, some defining the infrastructural pieces, like db, message bus etc. I need to merge them all into one, big docker-compose.yml file, so that I can easily run it via my CI/CD pipeline. I wrote this shell script to do so, but it seems the docker-compose config command generates a file with absolute paths:

#!/bin/bash

ymls=`ls **/docker-compose.*.yml`
compose_string=""

for file in $ymls
do
    compose_string="${compose_string} -f ${file} --project-directory ."
done

echo $compose_string

docker-compose $compose_string config > docker-compose.merged.yml

This gives me the below file contents (shortened for brevity):

services:
  curator-services:
    build:
      args:
        ELASTIC_PASSWORD: them-pass
      context: E:\repos\them-project\devops\curator
  manager-acl-app:
    build:
      context: E:\repos\them-project
      dockerfile: services/ThemProject.Services.ManagerAcl/Dockerfile

Now, the easy solution would be to just run a regexp or something and substitute whatever is in the same line as the word context. The problem with that approach is that I keep my infrastructural definitions in another folder than my microservices Dockerfiles, so the context for the curator-services piece should be context: curator/ and for the manager-acl-app it should be context: ../. Is there a way around those absolute paths with docker-compose config?

Body:
You can use --project-directory  option with docker-compose config.

Change your script to below

#!/bin/bash

ymls=`ls docker-compose.*.yml`
compose_string=""
DIR_PATH="." #Change it to Project Directory or current directory
for file in $ymls
do
    compose_string="${compose_string} -f ${file} --project-directory $DIR_PATH"
done

docker-compose ${compose_string} config > docker-compose.yml

Ref:- https://docs.docker.com/compose/reference/overview/

Please check --project-directory in the above link


问:
How to print a string before using "*" to unpack list
Is it possible to print a string before using the * operator when unpacking a tuple:

```<code>m = ['b', 'a', 'e']
print(*m, sep = ',')

b, a, e
</code>```

I tried to print something before it:

```<code>print("String: " + *m, sep = ",")
</code>```

My desired output would be:

```<code>String: b, a, e
</code>```

Is it possible to have a string print before this, and what would be the correct syntax?

答:
Try using this code:</p>

```<code>print(",".join(m))
</code>```

Body:
Is it possible to print a string before using the * operator when unpacking a tuple:

m = ['b', 'a', 'e']
print(*m, sep = ',')

b, a, e

I tried to print something before it:

print("String: " + *m, sep = ",")

My desired output would be:

String: b, a, e

Is it possible to have a string print before this, and what would be the correct syntax?

Body:
Try using this code:

print(",".join(m))


问:
How to schedule a task with airflow
Unfortunately even after reading the many questions here and the FAQ page of the airflow website, I still don't understand how airflow schedules tasks. I have a very simple example task here:

```<code>from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime, timedelta

default_args = {
    "depends_on_past": False,
    "start_date": datetime(2020, 5, 29),
    "email_on_failure": False,
    "email_on_retry": False,
    "retries": 1,
    "retry_delay": timedelta(minutes=5),
}

dag = DAG(
    "example_dag_one",
    schedule_interval="30 8 * * *",
    catchup=False,
    default_args=default_args,
)

with dag:

    t1 = BashOperator(task_id="print_hello", bash_command="echo hello", dag=dag)

    t1

</code>```

My naiv view would be that this task would be run on May 29th 08:30. But as the time passes, airflow has not scheduled that task. If I change the cron expression to something like: '* 8 * * *' It will schedule a task every minute.

When I however use the same DAG with a start date of yesterday (so May 28th in that case) the task will be scheduled at 08:30, yet it's execution date is the 28th (even though it ran on May 29th) and the start date in the web ui is May 29th. This is VERY confusing.

What I want from airflow in the end is simple: "Here is python code, run it on this time day". So how could I achieve that. Again let's say I want to schedule a task on 08:30 every day starting tomorrow.

答:
The answer can be found in Airflow official documentation:

Note that if you run a DAG on a schedule_interval of one day, the run stamped 2016-01-01 will be trigger soon after 2016-01-01T23:59. In other words, the job instance is started once the period it covers has ended.

Let’s Repeat That The scheduler runs your job one schedule_interval AFTER the start date, at the END of the period.

So applying to your case, if you put start date 29th of May, with the original cron, it will run every day at 08:30 starting from tomorrow 30th of May.

Anyway, if you don't need a dag specifically at some point in the day, you can just set schedule interval to '@daily', and it will be triggered at the beginning (00:00) of each day. If there are a lot of dags with @daily, don't worry, the scheduler and the workers will know how to handle it to execute all of them. If you have dags that depend on other dags, there are mechanisms to concatenate them so that you still don't have to worry about specifying hours.

Title: How to schedule a task with airflow

Body:
Unfortunately even after reading the many questions here and the FAQ page of the airflow website, I still don't understand how airflow schedules tasks. I have a very simple example task here:

from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime, timedelta

default_args = {
    "depends_on_past": False,
    "start_date": datetime(2020, 5, 29),
    "email_on_failure": False,
    "email_on_retry": False,
    "retries": 1,
    "retry_delay": timedelta(minutes=5),
}

dag = DAG(
    "example_dag_one",
    schedule_interval="30 8 * * *",
    catchup=False,
    default_args=default_args,
)

with dag:

    t1 = BashOperator(task_id="print_hello", bash_command="echo hello", dag=dag)

    t1

My naiv view would be that this task would be run on May 29th 08:30. But as the time passes, airflow has not scheduled that task. If I change the cron expression to something like: '* 8 * * *' It will schedule a task every minute.

When I however use the same DAG with a start date of yesterday (so May 28th in that case) the task will be scheduled at 08:30, yet it's execution date is the 28th (even though it ran on May 29th) and the start date in the web ui is May 29th. This is VERY confusing.

What I want from airflow in the end is simple: "Here is python code, run it on this time day". So how could I achieve that. Again let's say I want to schedule a task on 08:30 every day starting tomorrow.


问:
Too Many versions of python on my computer
I have too many versions of python on my computer. And, when I try to run my code, my module like pandas, selenium, etc said this error message:

ModuleNotFoundError: No module named 'pandas'.

I have pip and conda install everything but neither version of python works when I choose each of them in VS Code interpreter.

Do you have a solution to uninstall each version of python?

Command prompt:

答: just type Apps and Features in you pc's search bar and uninstall every version of python you see there and re install the one that you need</p>


问:
d3 Stacked bar chart show x values without skipping
i have created following d3 stacked bar chart

```<code>var ContainersStackedBarChart = function() {
"use strict";

var stackedBarChartData = [{
    key: 'Packed',
    'color' : COLOR_RED,
    values: [
        { x:1, y: 10}, { x:2, y: 15}, { x:3, y: 16}, { x:4, y: 20}, { x:5, y: 57}, { x:6, y: 42}, { x:7, y: 12}, { x:8, y: 65}, { x:9, y: 34}, { x:10, y: 52}
    ]
},{
    key: 'Un-Packed',
    'color' : COLOR_ORANGE,
    values: [
        { x:1, y: 10}, { x:2, y: 15}, { x:3, y: 16}, { x:4, y: 45}, { x:5, y: 67}, { x:6, y: 34}, { x:7, y: 43}, { x:8, y: 65}, { x:9, y: 32}, { x:10, y: 12},

    ]
}];

nv.addGraph({
    generate: function() {
        var stackedBarChart = nv.models.multiBarChart()
            .stacked(true)
            .showControls(false);

        var svg = d3.select('#containersbycarrier').append('svg').datum(stackedBarChartData);
        svg.transition().duration(0).call(stackedBarChart);
        return stackedBarChart;
    }
});
};
</code>```

but the problem when data incrase it is not showing x axis values

i want to show full x axis labels with maybe by reducing the bar width.

i tried using this

```<code>svg.scale.ordinal().range([0, stackedBarChartData.length * 50]);
</code>```

but didnt not work

答:
You Need to Add .reduceXTicks(false) to show all ticks.

var stackedBarChartData = [{
    key: 'Packed',
    'color' : 'red',
    values: [
        { x:1, y: 10}, { x:2, y: 15}, { x:3, y: 16}, { x:4, y: 20}, { x:5, y: 57}, { x:6, y: 42}, { x:7, y: 12}, { x:8, y: 65}, { x:9, y: 34}, { x:10, y: 52}
    ]
},{
    key: 'Un-Packed',
    'color' : 'green',
    values: [
        { x:1, y: 10}, { x:2, y: 15}, { x:3, y: 16}, { x:4, y: 45}, { x:5, y: 67}, { x:6, y: 34}, { x:7, y: 43}, { x:8, y: 65}, { x:9, y: 32}, { x:10, y: 12},

    ]
}];

nv.addGraph({
    generate: function() {
        var stackedBarChart = nv.models.multiBarChart()
            .stacked(true)
            .reduceXTicks(false)
            .showControls(false);

        var svg = d3.select('#containersbycarrier').append('svg').datum(stackedBarChartData);

       svg.transition().duration(0).call(stackedBarChart);
        return stackedBarChart;
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://cdn.rawgit.com/novus/nvd3/v1.8.1/build/nv.d3.min.js"></script>
<div id="containersbycarrier"></div></code>```

Body:
i have created following d3 stacked bar chart

var ContainersStackedBarChart = function() {
"use strict";

var stackedBarChartData = [{
    key: 'Packed',
    'color' : COLOR_RED,
    values: [
        { x:1, y: 10}, { x:2, y: 15}, { x:3, y: 16}, { x:4, y: 20}, { x:5, y: 57}, { x:6, y: 42}, { x:7, y: 12}, { x:8, y: 65}, { x:9, y: 34}, { x:10, y: 52}
    ]
},{
    key: 'Un-Packed',
    'color' : COLOR_ORANGE,
    values: [
        { x:1, y: 10}, { x:2, y: 15}, { x:3, y: 16}, { x:4, y: 45}, { x:5, y: 67}, { x:6, y: 34}, { x:7, y: 43}, { x:8, y: 65}, { x:9, y: 32}, { x:10, y: 12},

    ]
}];

nv.addGraph({
    generate: function() {
        var stackedBarChart = nv.models.multiBarChart()
            .stacked(true)
            .showControls(false);

        var svg = d3.select('#containersbycarrier').append('svg').datum(stackedBarChartData);
        svg.transition().duration(0).call(stackedBarChart);
        return stackedBarChart;
    }
});
};

but the problem when data incrase it is not showing x axis values

i want to show full x axis labels with maybe by reducing the bar width.

i tried using this

svg.scale.ordinal().range([0, stackedBarChartData.length * 50]);

but didnt not work

Body:
You Need to Add .reduceXTicks(false) to show all ticks.

var stackedBarChartData = [{
    key: 'Packed',
    'color' : 'red',
    values: [
        { x:1, y: 10}, { x:2, y: 15}, { x:3, y: 16}, { x:4, y: 20}, { x:5, y: 57}, { x:6, y: 42}, { x:7, y: 12}, { x:8, y: 65}, { x:9, y: 34}, { x:10, y: 52}
    ]
},{
    key: 'Un-Packed',
    'color' : 'green',
    values: [
        { x:1, y: 10}, { x:2, y: 15}, { x:3, y: 16}, { x:4, y: 45}, { x:5, y: 67}, { x:6, y: 34}, { x:7, y: 43}, { x:8, y: 65}, { x:9, y: 32}, { x:10, y: 12},

    ]
}];

nv.addGraph({
    generate: function() {
        var stackedBarChart = nv.models.multiBarChart()
            .stacked(true)
            .reduceXTicks(false)
            .showControls(false);

        var svg = d3.select('#containersbycarrier').append('svg').datum(stackedBarChartData);

       svg.transition().duration(0).call(stackedBarChart);
        return stackedBarChart;
    }
});

<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://cdn.rawgit.com/novus/nvd3/v1.8.1/build/nv.d3.min.js"></script>
<div id="containersbycarrier"></div>


问:
Complex jquery selector that looks for a token in a string.split
I have an html table where one of the columns contains s with comma-delimited data.  I want to come up with a jQuery selector that returns all of the rows (
s are preferable, but the s will work for now) where one of the comma-delimited tokens  in a span tag matches a supplied string.

I started with something like the following:

```<code>$('td.col_8 span:contains("duck")')
</code>```

which will get me all spans in a particular column containing the word 'duck'.  However, it could also match fox, mallard-duck. Since 'duck' is not a unique token in that span, I wouldn't want that included in the match.

Is there a way to narrow my result set so I'm only including results where there's an exact match to a particular token in a column-delimited list?

(I'm using jQuery 1.2.3)

答:
Going off of Russ Cam's answer, here's what I came up with:

```<code>$('td.col_8 span').filter(function() {
  return $.inArray('quiet',$(this).html().split(', ')) !== -1;
});
</code>```

Of course, this assumes that the list will always be delimited with ,[space], but it should work for my immediate use case.

Body:
I have an html table where one of the columns contains s with comma-delimited data.  I want to come up with a jQuery selector that returns all of the rows (
s are preferable, but the s will work for now) where one of the comma-delimited tokens  in a span tag matches a supplied string.

I started with something like the following:

$('td.col_8 span:contains("duck")')

which will get me all spans in a particular column containing the word 'duck'.  However, it could also match fox, mallard-duck. Since 'duck' is not a unique token in that span, I wouldn't want that included in the match.

Is there a way to narrow my result set so I'm only including results where there's an exact match to a particular token in a column-delimited list?

(I'm using jQuery 1.2.3)

Body:
Going off of Russ Cam's answer, here's what I came up with:

$('td.col_8 span').filter(function() {
  return $.inArray('quiet',$(this).html().split(', ')) !== -1;
});

Of course, this assumes that the list will always be delimited with ,[space], but it should work for my immediate use case.


问:
How can I delete all texts in my data using dplyr?
If my data looks like this:

```<code>q2_3  q2_4  q2_5
<chr> <chr> <chr>
1    1A    2B   3C
2    4D    5E   6F
</code>```

How can I delete only texts?

I want only numbers to remain!

答:
You could remove all the characters which are not digits using \\D.

Using dplyr

```<code>library(dplyr)
df %>% mutate_all(~gsub('\\D', '', .))

#  q2_3 q2_4 q2_5
#1    1    2    3
#2    4    5    6
</code>```

Or in base R :

```<code>df[] <- lapply(df, function(x) gsub('\\D', '', x))
</code>```

data

```<code>df <- structure(list(q2_3 = c("1A", "4D"), q2_4 = c("2B", "5E"), q2_5 = c("3C",
"6F")), class = "data.frame", row.names = c("1", "2"))
</code>```

Body:
If my data looks like this:

q2_3  q2_4  q2_5
<chr> <chr> <chr>
1    1A    2B   3C
2    4D    5E   6F

How can I delete only texts?

I want only numbers to remain!

Body:
You could remove all the characters which are not digits using \\D.

Using dplyr

library(dplyr)
df %>% mutate_all(~gsub('\\D', '', .))

#  q2_3 q2_4 q2_5
#1    1    2    3
#2    4    5    6

Or in base R :

df[] <- lapply(df, function(x) gsub('\\D', '', x))

data

df <- structure(list(q2_3 = c("1A", "4D"), q2_4 = c("2B", "5E"), q2_5 = c("3C",
"6F")), class = "data.frame", row.names = c("1", "2"))


问:
Laravel 5.1 Route::controller with optional url params?
I have this code in routes

```<code>Route::controller('/orders/{from}/{to}', 'CartController');
</code>```

the link something like this

localhost/admin/orders/2020-01-01/2020-01-02

this will open all the records between 2 dates

But I have another link something like this

localhost/admin/orders/4212

to open specific row on a new tab

This 2 links falls for 1 function

called it

```<code> public function getIndex($from,$to){

 }
</code>```

can  I do this params optional? with 1 Route::controller('/orders/{from}/{to}', 'CartController'); in my route.php?

答:
You can set any of your parameters to be optional, just by appending ? at the end of the parameter name. Simple example:

```<code>Route::controller('/orders/{from?}/{to?}', 'CartController');
</code>```

Also, I jut noticed that you don't call any of your controller actions in your route definition. If you want this route to lead to your getIndex() method, change it to this:

```<code>Route::controller('/orders/{from?}/{to?}', 'CartController@getIndex');
</code>```

Read more on official documentation.

Body:
I have this code in routes

Route::controller('/orders/{from}/{to}', 'CartController');

the link something like this

localhost/admin/orders/2020-01-01/2020-01-02

this will open all the records between 2 dates

But I have another link something like this

localhost/admin/orders/4212

to open specific row on a new tab

This 2 links falls for 1 function

called it

 public function getIndex($from,$to){

 }

can  I do this params optional? with 1 Route::controller('/orders/{from}/{to}', 'CartController'); in my route.php?

Body:
You can set any of your parameters to be optional, just by appending ? at the end of the parameter name. Simple example:

Route::controller('/orders/{from?}/{to?}', 'CartController');

Also, I jut noticed that you don't call any of your controller actions in your route definition. If you want this route to lead to your getIndex() method, change it to this:

Route::controller('/orders/{from?}/{to?}', 'CartController@getIndex');

Read more on official documentation.


问:
Jupyter Notebook: Force cookie expiration and reset token
How can I remove access to a Jupyter Notebook server to previous users? I did a quick setup of a Jupyter Notebook server and provided access to a few users. Now that it's no longer needed, how can I force the authentication cookies to expire and reset the authentication token?

I think I should have used JupyterHub, but I didn't know about it then.

答: Stop the server, run jupyter notebook password and set/change your password.


问:
How can I run a Kotlin's maven project which using IDEA and don't using .m2 repository?
guys. I want to using IDEA to create a Kotlin's maven project.My maven repository is not the default location which is .m2. When I maven import,it using the location which I set, but when I build the project, the IDEA want to using /home/$USER/.m2/repository to search the jar.How can I fixed it?

```<code>Warning:Kotlin: Classpath entry points to a non-existent location: /home/wfb/.m2/repository/org/apache/commons/commons-lang3/3.4/commons-lang3-3.4.jar
Error:(3, 16) Kotlin: Cannot access built-in declaration 'kotlin.Array'. Ensure that you have a dependency on the Kotlin standard library
</code>```

I try to using terminal to run it and It doesn't have problems. When Using IDEA to run it , the tips like above

答:
1) Preferences > Build,Execution,Deployment > Build Tools > Maven

2) Check "Override" near "Local Repository" and input the path to your Maven local  repository

P.S. I'm using IDEA 2018.3, so on other versions the path to this setting might slightly differ

Body:
guys. I want to using IDEA to create a Kotlin's maven project.My maven repository is not the default location which is .m2. When I maven import,it using the location which I set, but when I build the project, the IDEA want to using /home/$USER/.m2/repository to search the jar.How can I fixed it?

Warning:Kotlin: Classpath entry points to a non-existent location: /home/wfb/.m2/repository/org/apache/commons/commons-lang3/3.4/commons-lang3-3.4.jar
Error:(3, 16) Kotlin: Cannot access built-in declaration 'kotlin.Array'. Ensure that you have a dependency on the Kotlin standard library

I try to using terminal to run it and It doesn't have problems. When Using IDEA to run it , the tips like above