问:
Change class for selected div only
I would like it to only change the class for the clicked div. Currently it will change the class for all divs. I have written this as a Blazor component.

```<code>@for (int i = 0; i < 5; i++)
{
    <div class="@divClass" @onclick="_ => ChangeDivClass()">@i</div>
}

@code
{
    String divClass;

    private void ChangeDivClass()
    {
        if (divClass == "red")
        {
            divClass = String.Empty;
        }
        else
        {
            divClass = "red";
        }
    }
}
</code>```

答:
Create a component for this behavior :

CustomComponent.razor

@Value

@code
{
    [Parameter]
    public int Value;

    string divClass;

    private void ChangeDivClass()
    {
        if (divClass == "red")
        {
            divClass = string.Empty;
        }
        else
        {
            divClass = "red";
        }
    }
}

```

<p>Your parent component become:</p>

<p><strong>ParentComponent.razor</strong></p>

```@for (int i = 0; i < 5; i++)
{
    <CustomComponet Value="@i" />
}
```

Title: Change class for selected div only

Body:
I would like it to only change the class for the clicked div. Currently it will change the class for all divs. I have written this as a Blazor component.

@for (int i = 0; i < 5; i++)
{

 ChangeDivClass()">@i

}

@code
{
    String divClass;

    private void ChangeDivClass()
    {
        if (divClass == "red")
        {
            divClass = String.Empty;
        }
        else
        {
            divClass = "red";
        }
    }
}

Body:
Create a component for this behavior :

CustomComponent.razor

<div class="@divClass" @onclick="ChangeDivClass">@Value</div>
@code
{
    [Parameter]
    public int Value;

    string divClass;

    private void ChangeDivClass()
    {
        if (divClass == "red")
        {
            divClass = string.Empty;
        }
        else
        {
            divClass = "red";
        }
    }
}

Your parent component become:

ParentComponent.razor

@for (int i = 0; i < 5; i++)
{
    <CustomComponet Value="@i" />
}


来源: stackexchange

问:
TSQL getting the maximum and minimum date for each person and his number
I have a dataset like this:

It is necessary to getting the minimum and maximum date, the person and his number from each frame:

The code sample below: enter link description here

Thanks a lot!

答:
This is an example of a gaps-and-islands problem.  I would recommend the difference of row numbers for this:</p>

```<code>select person, number_one, count(*) as cnt,
       min(person_date), max(person_date)
from (select t.*,
             row_number() over (partition by person order by person_date) as seqnum,
             row_number() over (partition by person, number_one order by person_date) as seqnum_2
      from t
     ) t
group by person, (seqnum - seqnum_2)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is an example of a gaps-and-islands problem.  I would recommend the difference of row numbers for this:

select person, number_one, count(*) as cnt,
       min(person_date), max(person_date)
from (select t.*,
             row_number() over (partition by person order by person_date) as seqnum,
             row_number() over (partition by person, number_one order by person_date) as seqnum_2
      from t
     ) t
group by person, (seqnum - seqnum_2)


问:
Bash: how to look for the next positional parameter in "case" code without hard-coding its value?
Given the "case" code snippet:

```<code>case $3 in
        -a)
            if [ "$4" == #some regex to match pattern ]; then
                #do some additional work
            else
                #proceed as usual
            fi
            ;;
</code>```

How could I better express my intention to look for a positional parameter which is located right next on the right-hand side of the current position $3 (or $3++, if that makes sense), instead of hard-coding it to $4 in the "if" statement?

EDIT:

the simplest usage of my script would look like this:

```<code>./script.sh company region -a LIST-123
</code>```

the first two mandatory positional arguments (company & region) are fixed.
Starting from the position $3, users have to provide at least one mandatory argument in the format of a preceding dash and a single letter (-a, -b, -c etc).
The single-letter mandatory arguments can have an optional argument (LIST-123 in the example above). If the optional argument is not provided, the script should resume as usual.

I want users to be able provide multiple mandatory-optional argument pairs. like this:

```<code>./script.sh company region -a LIST-123 -b LIST-456 -c LIST-789
</code>```

Also, to have flexibility to provide the mandatory single-letter args in any order:

```<code>./script.sh company region -c LIST-789 -b LIST-456 -a LIST-123
</code>```

And to be able to provide optional arguments only to certain mandatory single-letter args, but not all:

./script.sh company region -c LIST-789 -b -a LIST-123

答:
like this?

```<code>case $3:$4 in
     -a:[a-z]*) echo ok ;;
</code>```

Or

```<code>case $3:$4 in
     -a:[Tt]est) echo ok ;;
</code>```

Body:
Given the "case" code snippet:

case $3 in
        -a)
            if [ "$4" == #some regex to match pattern ]; then
                #do some additional work
            else
                #proceed as usual
            fi
            ;;

How could I better express my intention to look for a positional parameter which is located right next on the right-hand side of the current position $3 (or $3++, if that makes sense), instead of hard-coding it to $4 in the "if" statement?

EDIT:

the simplest usage of my script would look like this:

./script.sh company region -a LIST-123

the first two mandatory positional arguments (company & region) are fixed.
Starting from the position $3, users have to provide at least one mandatory argument in the format of a preceding dash and a single letter (-a, -b, -c etc).
The single-letter mandatory arguments can have an optional argument (LIST-123 in the example above). If the optional argument is not provided, the script should resume as usual.

I want users to be able provide multiple mandatory-optional argument pairs. like this:

./script.sh company region -a LIST-123 -b LIST-456 -c LIST-789

Also, to have flexibility to provide the mandatory single-letter args in any order:

./script.sh company region -c LIST-789 -b LIST-456 -a LIST-123

And to be able to provide optional arguments only to certain mandatory single-letter args, but not all:

./script.sh company region -c LIST-789 -b -a LIST-123

Body:
like this?

case $3:$4 in
     -a:[a-z]*) echo ok ;;

Or

case $3:$4 in
     -a:[Tt]est) echo ok ;;


问:
How can I ship my app with a pre-populated Core Data database?
My app uses Core Data and I want some default entries to be inside.
What's best practices of how to do that?</p>

答:
If you're already loading the pre-load data via a temporary routine for testing in your current code there's no reason you can't use the sqlite file it creates in the simulator's directory (no need to write a separate Mac app).

If you're not already filling that db you can still write an iOS app that does it. Odds are you've already written the methods for adding data to your store so you can use them to import the pre-load data as well.

Either way you'd grab the sqlite file from the simulator's directory and add it to your app's bundle; on first launch you'll copy it into the appropriate place in the app's directory before pointing Core Data to it. If it's really large the downside is that there will be a copy in the bundle and another on disk, but there's not much you can do about that other than grabbing the data over the network.

As others have suggested, if the amount of data is small you can just import it at first launch, using the methods you've already written for adding data as part of the normal app's workflow.

ContentLicense: CC BY-SA 3.0


答:
This looks like a gaps-and-islad problem. Here is one way to solve it using window functions:

```<code>select
    min(person_date) person_date_start,
    max(person_date) person_date_end,
    person,
    number_one
from (
    select
        t.*,
        row_number() over(order by person_date) rn1,
        row_number() over(partition by person, number_one order by person_date) rn2
    from mytable t
) t
group by person, number_one, rn1 - rn2
</code>```

It is quite unclear what is the logic to generate the id in the outer query. If you want to renumber the records, then you can use row_number():

```<code>select
    row_number() over(order by min(person_date)) id,
    min(person_date) person_date_start,
    max(person_date) person_date_end,
    person,
    number_one
</code>```

Title: TSQL getting the maximum and minimum date for each person and his number

Body:
I have a dataset like this:

It is necessary to getting the minimum and maximum date, the person and his number from each frame:

The code sample below: enter link description here

Thanks a lot!

Body:
This looks like a gaps-and-islad problem. Here is one way to solve it using window functions:

select
    min(person_date) person_date_start,
    max(person_date) person_date_end,
    person,
    number_one
from (
    select
        t.*,
        row_number() over(order by person_date) rn1,
        row_number() over(partition by person, number_one order by person_date) rn2
    from mytable t
) t
group by person, number_one, rn1 - rn2

It is quite unclear what is the logic to generate the id in the outer query. If you want to renumber the records, then you can use row_number():

select
    row_number() over(order by min(person_date)) id,
    min(person_date) person_date_start,
    max(person_date) person_date_end,
    person,
    number_one


问:
Using neo4j as data source for a WPF Autocomplete Box
I try to get a Autocomplete TextBox running with neo4j as Data Source, for this I need to get all founded elements returned as a List where I can "Search" inside.

I have a List and I have a connection to query neo4j DB to get all persons by their name, a MessageBox is displaying ,just for testing, if we receive data but if I enter a letter in my Textbox my App just freezes.

Code behind:

```<code>public partial class UserControlQueryDB : UserControl
{
    public UserControlQueryDB()
    {
        InitializeComponent();
        GetSuggestionsFromNeoAsync();
    }

    private async Task<List<string>> GetSuggestionsFromNeoAsync() {

IDriver driver = GraphDatabase.Driver("bolt://localhost:7687", AuthTokens.Basic("neo4j", "neo4j"));
IAsyncSession session = driver.AsyncSession(o => o.WithDatabase("neo4j"));

            var query2Neo = "MATCH (n:Person) RETURN n.Name";

            IResultCursor cursor = await session.RunAsync(query2Neo);
            List<string> found = await cursor.ToListAsync(record => record["name"].As<string>());

            await cursor.ConsumeAsync();
            await session.CloseAsync();
            await driver.CloseAsync();

        return found;
    }

    private void TextBox_KeyUp(object sender, KeyEventArgs e)
    {
        bool found = false;
        var border = (resultStack.Parent as ScrollViewer).Parent as Border;
        var data = GetSuggestionsFromNeoAsync();

        MessageBox.Show(data);

        string query = (sender as TextBox).Text;

        if (query.Length == 0)
        {
            // Clear
            resultStack.Children.Clear();
            border.Visibility = Visibility.Collapsed;
        }
        else
        {
            border.Visibility = Visibility.Visible;
        }

        // Clear the list
        resultStack.Children.Clear();

        // Add the result
        foreach (var obj in data.Result)
        {
            if (obj.ToLower().StartsWith(query.ToLower()))
            {
                // The word starts with this... Autocomplete must work
                addItem(obj);
                found = true;
            }
        }

        if (!found)
        {
            resultStack.Children.Add(new TextBlock() { Text = "No results found." });
        }
    }

    private void addItem(string text)
    {
        TextBlock block = new TextBlock();

        // Add the text
        block.Text = text;

        // A little style...
        block.Margin = new Thickness(2, 3, 2, 3);
        block.Cursor = Cursors.Hand;

        // Mouse events
        block.MouseLeftButtonUp += (sender, e) =>
        {
            textBox.Text = (sender as TextBlock).Text;
        };

        block.MouseEnter += (sender, e) =>
        {
            TextBlock b = sender as TextBlock;
            b.Background = Brushes.PeachPuff;
        };

        block.MouseLeave += (sender, e) =>
        {
            TextBlock b = sender as TextBlock;
            b.Background = Brushes.Transparent;
        };

    }

}
</code>```

Thats the Xaml:

```<code>        <StackPanel Orientation="Horizontal">
        <TextBox Width="300" Padding="5, 3, 5, 3" KeyUp="TextBox_KeyUp" Name="textBox" />
        <Border Width="298" Height="150" BorderBrush="Black" BorderThickness="1">
            <ScrollViewer VerticalScrollBarVisibility="Auto">
                <StackPanel Name="resultStack"></StackPanel>
            </ScrollViewer>
        </Border>
    </StackPanel>
</code>```

答:
Don't forget to await your async method in the event handler (and add the async keyword to the event handler's signature):

```<code>private async void TextBox_KeyUp(object sender, KeyEventArgs e)
{
    bool found = false;
    var border = (resultStack.Parent as ScrollViewer).Parent as Border;
    var data = await GetSuggestionsFromNeoAsync(); //<--
...
</code>```

Body:
I try to get a Autocomplete TextBox running with neo4j as Data Source, for this I need to get all founded elements returned as a List where I can "Search" inside.

I have a List and I have a connection to query neo4j DB to get all persons by their name, a MessageBox is displaying ,just for testing, if we receive data but if I enter a letter in my Textbox my App just freezes.

Code behind:

public partial class UserControlQueryDB : UserControl
{
    public UserControlQueryDB()
    {
        InitializeComponent();
        GetSuggestionsFromNeoAsync();
    }

    private async Task<List<string>> GetSuggestionsFromNeoAsync() {

IDriver driver = GraphDatabase.Driver("bolt://localhost:7687", AuthTokens.Basic("neo4j", "neo4j"));
IAsyncSession session = driver.AsyncSession(o => o.WithDatabase("neo4j"));

            var query2Neo = "MATCH (n:Person) RETURN n.Name";

            IResultCursor cursor = await session.RunAsync(query2Neo);
            List<string> found = await cursor.ToListAsync(record => record["name"].As<string>());

            await cursor.ConsumeAsync();
            await session.CloseAsync();
            await driver.CloseAsync();

        return found;
    }

    private void TextBox_KeyUp(object sender, KeyEventArgs e)
    {
        bool found = false;
        var border = (resultStack.Parent as ScrollViewer).Parent as Border;
        var data = GetSuggestionsFromNeoAsync();

        MessageBox.Show(data);

        string query = (sender as TextBox).Text;

        if (query.Length == 0)
        {
            // Clear
            resultStack.Children.Clear();
            border.Visibility = Visibility.Collapsed;
        }
        else
        {
            border.Visibility = Visibility.Visible;
        }

        // Clear the list
        resultStack.Children.Clear();

        // Add the result
        foreach (var obj in data.Result)
        {
            if (obj.ToLower().StartsWith(query.ToLower()))
            {
                // The word starts with this... Autocomplete must work
                addItem(obj);
                found = true;
            }
        }

        if (!found)
        {
            resultStack.Children.Add(new TextBlock() { Text = "No results found." });
        }
    }

    private void addItem(string text)
    {
        TextBlock block = new TextBlock();

        // Add the text
        block.Text = text;

        // A little style...
        block.Margin = new Thickness(2, 3, 2, 3);
        block.Cursor = Cursors.Hand;

        // Mouse events
        block.MouseLeftButtonUp += (sender, e) =>
        {
            textBox.Text = (sender as TextBlock).Text;
        };

        block.MouseEnter += (sender, e) =>
        {
            TextBlock b = sender as TextBlock;
            b.Background = Brushes.PeachPuff;
        };

        block.MouseLeave += (sender, e) =>
        {
            TextBlock b = sender as TextBlock;
            b.Background = Brushes.Transparent;
        };

    }

}

Thats the Xaml:

        <StackPanel Orientation="Horizontal">
        <TextBox Width="300" Padding="5, 3, 5, 3" KeyUp="TextBox_KeyUp" Name="textBox" />
        <Border Width="298" Height="150" BorderBrush="Black" BorderThickness="1">
            <ScrollViewer VerticalScrollBarVisibility="Auto">
                <StackPanel Name="resultStack"></StackPanel>
            </ScrollViewer>
        </Border>
    </StackPanel>

Body:
Don't forget to await your async method in the event handler (and add the async keyword to the event handler's signature):

private async void TextBox_KeyUp(object sender, KeyEventArgs e)
{
    bool found = false;
    var border = (resultStack.Parent as ScrollViewer).Parent as Border;
    var data = await GetSuggestionsFromNeoAsync(); //<--
...


问:
NGRX effect incorrectly triggering multiple actions
I have the following NGRX effects defined in a single class. The loadPage$ effect works fine. The loadSection$ effect works, but for some reason is triggering both the SetPages action and the SetSections action even though I'm only returning the SetSections action. Any ideas?

Effects

```<code>  @Effect()
  loadPages$: Observable<Action> = this.actions$.pipe(
    ofType<GetPages>(GET_PAGES),
    switchMap(() => {
      return this.loanService
        .getPages()
        .pipe(
          pluck('data', 'pages'),
          tap((pages: Page[]) => pages[0].active = true),
          map(pages => new SetPages(pages))
        );
    })
  );

  @Effect()
  loadSections$: Observable<Action> = this.actions$.pipe(
    ofType<SelectPage>(SELECT_PAGE),
    switchMap((action: SelectPage) => {
      console.log('loadPageSection$::action:', action);
      return this.loanService
        .getPageSections(action.payload)
        .pipe(
          pluck('data', 'pageSections'),
          map(sections => new SetSections(sections))
        );
    })
  );
</code>```

Actions:
All the actions defined in a single file.

```<code>export const GET_PAGES = 'GET_PAGES';
export const SELECT_PAGE = 'SELECT_PAGE';
export const SET_PAGES = 'SET_PAGES';
export const SET_SECTIONS = 'SET_SECTIONS';

export class GetPages implements Action {
  readonly type = GET_PAGES;
}

export class SelectPage implements Action {
  readonly type = SELECT_PAGE;

  constructor(public payload: string) {
  }
}

export class SetPages implements Action {
  readonly type = SET_PAGES;

  constructor(public payload: Page[]) {
  }
}

export class SetSections implements Action {
  readonly type = SET_SECTIONS;

  constructor(public payload: Section[]) {
  }
}

export type LoanActions = GetPages | SelectPage | SetPages | SetSections;
</code>```

Reducers:
When I put a console.log under SET_PAGES and SET_SECTIONS, I see both instances logged during the loadSection$ effect.

```<code>export function loanReducer(state: LoanState = initialState, action: LoanActions) {
  switch (action.type) {
    case SELECT_PAGE:
      const pages = [ ...state.pages ];
      deactivatePage(pages);
      activatePage(action.payload, pages);
      return { ...state, pages };

    case SET_PAGES:
      return { ...state, pages: [ ...action.payload ] };

    case SET_SECTIONS:
      return { ...state, sections: [ ...action.payload ] };

    case GET_PAGES:
    default:
      return state;
  }
}
</code>```

EDIT adding active/deactivate functions

```<code>export const deactivatePage = (pages: Page[]) => chain(pages).find(page => page.active).set('active', false).value();

export const activatePage = (id: string, pages: Page[]) => chain(pages).find(obj => obj.id === id).set('active', true).value();
</code>```

The action is triggered from a button click inside a custom component:
this.store.dispatch(new SelectPage(page.id))

答:
I found the culprit. I'm using a GraphQL backend and the Apollo client in my Angular app to query the server. I was using the Apollo client's watchQuery method to fetch the data.

According to the watchQuery documentation

As you know, Apollo.query method returns an Observable that emits a result, just once. Apollo.watchQuery also does the same, except it can emit multiple results. (The GraphQL query itself is still only sent once, but the watchQuery observable can also update if, for example, another query causes the object to be updated within Apollo Client's global cache.)

When toggling the active flag on the data, it must trigger the watchQuery's cache to be udpated thus triggering the other Ngrx effect. Converting my watchQuery to a plain query solved the issue.

Body:
I have the following NGRX effects defined in a single class. The loadPage$ effect works fine. The loadSection$ effect works, but for some reason is triggering both the SetPages action and the SetSections action even though I'm only returning the SetSections action. Any ideas?

Effects

  @Effect()
  loadPages$: Observable<Action> = this.actions$.pipe(
    ofType<GetPages>(GET_PAGES),
    switchMap(() => {
      return this.loanService
        .getPages()
        .pipe(
          pluck('data', 'pages'),
          tap((pages: Page[]) => pages[0].active = true),
          map(pages => new SetPages(pages))
        );
    })
  );

  @Effect()
  loadSections$: Observable<Action> = this.actions$.pipe(
    ofType<SelectPage>(SELECT_PAGE),
    switchMap((action: SelectPage) => {
      console.log('loadPageSection$::action:', action);
      return this.loanService
        .getPageSections(action.payload)
        .pipe(
          pluck('data', 'pageSections'),
          map(sections => new SetSections(sections))
        );
    })
  );

Actions:
All the actions defined in a single file.

export const GET_PAGES = 'GET_PAGES';
export const SELECT_PAGE = 'SELECT_PAGE';
export const SET_PAGES = 'SET_PAGES';
export const SET_SECTIONS = 'SET_SECTIONS';

export class GetPages implements Action {
  readonly type = GET_PAGES;
}

export class SelectPage implements Action {
  readonly type = SELECT_PAGE;

  constructor(public payload: string) {
  }
}

export class SetPages implements Action {
  readonly type = SET_PAGES;

  constructor(public payload: Page[]) {
  }
}

export class SetSections implements Action {
  readonly type = SET_SECTIONS;

  constructor(public payload: Section[]) {
  }
}

export type LoanActions = GetPages | SelectPage | SetPages | SetSections;

Reducers:
When I put a console.log under SET_PAGES and SET_SECTIONS, I see both instances logged during the loadSection$ effect.

export function loanReducer(state: LoanState = initialState, action: LoanActions) {
  switch (action.type) {
    case SELECT_PAGE:
      const pages = [ ...state.pages ];
      deactivatePage(pages);
      activatePage(action.payload, pages);
      return { ...state, pages };

    case SET_PAGES:
      return { ...state, pages: [ ...action.payload ] };

    case SET_SECTIONS:
      return { ...state, sections: [ ...action.payload ] };

    case GET_PAGES:
    default:
      return state;
  }
}

EDIT adding active/deactivate functions

export const deactivatePage = (pages: Page[]) => chain(pages).find(page => page.active).set('active', false).value();

export const activatePage = (id: string, pages: Page[]) => chain(pages).find(obj => obj.id === id).set('active', true).value();

The action is triggered from a button click inside a custom component:
this.store.dispatch(new SelectPage(page.id))


问:
Java: Converting a String to JSONArray, or Spliting an String the right way
I have an unusual qustion which looks as the following:

Question 1: How can i split a String the right way so that i get the json-File Entries separated from one another.

Or Question: How do i convert a String to JSONArray.

The JSON:

```<code>[
   {
   "id":"123483",
      "content":{
         "amount":"460",
         "price":"2.15",
         "name":"Post-it Block weiß",
         "weight":"0.3",
         "category":"Notizzettel"
 }
},
   {
      "id":"501993",
      "content":{
         "amount":"83",
         "price":"25.0",
         "name":"Trennstreifen 5x 100 bunt",
         "weight":"0.024",
         "category":"Register"

   }

}
]
</code>```

What i tried: // content succesfully encapsulates all the json content.

```<code>Path path = Paths.get("src/com/json/inventory.json");
String content = new String(Files.readAllBytes(path), Charset.defaultCharset());

JSONArray jsonArray = new JSONArray();
JSONObject jsnobject = new JSONObject(content);
jsonArray.put(jsnobject);
</code>```

The Errors with JSONArray: Errors

答:
You must do new JSONArray(content); not new JSONObject(content);

Because if you do the second way, java try to cast the array into a single object.

You can see more information in this post

Body:
I have an unusual qustion which looks as the following:

Question 1: How can i split a String the right way so that i get the json-File Entries separated from one another.

Or Question: How do i convert a String to JSONArray.

The JSON:

[
   {
   "id":"123483",
      "content":{
         "amount":"460",
         "price":"2.15",
         "name":"Post-it Block weiß",
         "weight":"0.3",
         "category":"Notizzettel"
 }
},
   {
      "id":"501993",
      "content":{
         "amount":"83",
         "price":"25.0",
         "name":"Trennstreifen 5x 100 bunt",
         "weight":"0.024",
         "category":"Register"

   }

}
]

What i tried: // content succesfully encapsulates all the json content.

Path path = Paths.get("src/com/json/inventory.json");
String content = new String(Files.readAllBytes(path), Charset.defaultCharset());

JSONArray jsonArray = new JSONArray();
JSONObject jsnobject = new JSONObject(content);
jsonArray.put(jsnobject);

The Errors with JSONArray: Errors


问:
F# Add element created in a for loop to a list
I want to add an element to a list. The elements will be created inside of a for loop. What I currently have is

```<code>let MaxCubeVolume tpList =
    let list1 = []
    printfn "%A" list1
    for l,w,h in tpList do
        let vol = CubeVolume l w h
        let list = vol::list1
        printfn "%A" list
</code>```

Where list1 is the main list I am trying to add to, and list is what I am trying to use to add to that list. CubeVolume is working, it takes 3 floats and returns the volume of a cube. tpList is a list of tuples which contain 3 floats. Where I'm lost is how I add the vol to the main list?

答:
In addition to Fyodor's answer (which is pretty comprehensive), a general F# solution for what you've named your function (finding the maximum value of the result of a computation of a sequence) would be to compose the map and max functions.  These functions exist on the standard F# collection modules (Seq, List, and Array), and you can chain them together using the |> operator:

let maxCubeVolume tpList =
    tpList |> Seq.map (fun (l,w,h) -> CubeVolume l w h) |> Seq.max
```

<p>You could also compose them together using the <code>>></code> operator instead:</p>

<pre class="lang-ml prettyprint-override"><code>List.map (fun (l,w,h) -> CubeVolume l w h) >> List.max
</code>```

There's also a built-in function maxBy on the standard F# collections that returns the element in the collection which has the maximum value for a given function.  This would return the cube itself (the one with the maximum volume) rather than the computed value for the volume. Here's an example using Seq (the most general of the F# collection types):

let maxCubeVolume tpList =
    tpList |> Seq.maxBy (fun (l,w,h) -> CubeVolume l w h)
```

Body:
I want to add an element to a list. The elements will be created inside of a for loop. What I currently have is

let MaxCubeVolume tpList =
    let list1 = []
    printfn "%A" list1
    for l,w,h in tpList do
        let vol = CubeVolume l w h
        let list = vol::list1
        printfn "%A" list

Where list1 is the main list I am trying to add to, and list is what I am trying to use to add to that list. CubeVolume is working, it takes 3 floats and returns the volume of a cube. tpList is a list of tuples which contain 3 floats. Where I'm lost is how I add the vol to the main list?

Body:
In addition to Fyodor's answer (which is pretty comprehensive), a general F# solution for what you've named your function (finding the maximum value of the result of a computation of a sequence) would be to compose the map and max functions.  These functions exist on the standard F# collection modules (Seq, List, and Array), and you can chain them together using the |> operator:

let maxCubeVolume tpList =
    tpList |> Seq.map (fun (l,w,h) -> CubeVolume l w h) |> Seq.max

You could also compose them together using the >> operator instead:

List.map (fun (l,w,h) -> CubeVolume l w h) >> List.max

There's also a built-in function maxBy on the standard F# collections that returns the element in the collection which has the maximum value for a given function.  This would return the cube itself (the one with the maximum volume) rather than the computed value for the volume. Here's an example using Seq (the most general of the F# collection types):

let maxCubeVolume tpList =
    tpList |> Seq.maxBy (fun (l,w,h) -> CubeVolume l w h)


问:
presenting menus in tkinter
I'm writing a connect-4 game with Tkinter, and I would to present several menu options to the user during the course of the game.

The problem is that the menus tend to be presented together, as in the piece of code below.  For example, in present_player_choice(), I'd like to present a menu for playerA, get an answer, and then present a menu for playerB.  This is not that crucial here, but it's a problem I keep running across.

after() does not seem to be the answer, as I do not want the menu to disappear after a certain space of time, but rather to disappear after the user has submitted an answer.

Also: In writing an 'ok' button for the menu, I've used 'quit.'  But quit closes the entire widget!  I want the gui to continue, and simply the menu to close, not the entire GUI!

I know these questions sound rather clueless, but I've been working on this for a while and am genuinely confused.  Thanks in advance for any help.

```<code>from tkinter import *
class GUI:

def __init__(self, root):
    self.__root = root
    self.__player_A = None
    self.__player_B = None

def assign_player(self, player, identity):
    if player == "player A":
        self.__player_A = identity
    elif player == "player B":
        self.__player_B = identity
    print("Player A is:  " + str(self.__player_A))
    print("Player B is:  " + str(self.__player_B))

def present_player_choice(self):
    self.ask_choose_player("player A")
    self.ask_choose_player("player B")
    Button(self.__root, text="OK", command=quit).pack(anchor=W)

def ask_choose_player(self, player):

    Label(self.__root, text="Who would you like to play " + player + "?").pack(anchor=W)
    var = IntVar()
    Radiobutton(self.__root, text="human", variable=var,
                command=lambda:self.assign_player(player, HUMAN), value=1).pack(anchor=W)
    Radiobutton(self.__root, text="computer", variable=var,
                command=lambda:self.assign_player(player, COMPUTER), value=2).pack(anchor=W)

if __name__ == '__main__':

root = Tk()
gui = GUI(root)
gui.present_player_choice()
mainloop()
</code>```

答:
The quickest way to do this is to add a Frame to your class that we can use to reset the content and then move the call for player B into a condition in the assign_player method to update the frame for player B when a selection is chosen.

You may also want to add tristatevalue=0 to your radio buttons so that there is no default selection.

Example:

```<code>import tkinter as tk

class GUI:
    def __init__(self, root):
        self.__root = root
        self.__player_A = None
        self.__player_B = None
        self.frame = None

    def assign_player(self, player, identity):
        if player == "player A":
            self.__player_A = identity
            print("Player A is:  " + str(self.__player_A))
            self.ask_choose_player("player B")
            tk.Button(self.__root, text="OK", command=quit).pack(anchor=tk.W)
        elif player == "player B":
            self.__player_B = identity
            print("Player B is:  " + str(self.__player_B))
            self.frame.destroy()

    def present_player_choice(self):
        self.ask_choose_player("player A")

    def ask_choose_player(self, player):
        if self.frame is None:
            self.frame = tk.Frame(self.__root)
        else:
            self.frame.destroy()
            self.frame = tk.Frame(self.__root)

        self.frame.pack(fill='both', expand=1)
        tk.Label(self.frame, text="Who would you like to play " + player + "?").pack(anchor=tk.W)
        var = tk.IntVar()

        tk.Radiobutton(self.frame, text="human", variable=var, tristatevalue=0,
                       command=lambda: self.assign_player(player, 'human'), value=1).pack(anchor=tk.W)
        tk.Radiobutton(self.frame, text="computer", variable=var, tristatevalue=0,
                       command=lambda: self.assign_player(player, 'pc'), value=2).pack(anchor=tk.W)

if __name__ == '__main__':
    root = tk.Tk()
    gui = GUI(root)
    gui.present_player_choice()
    root.mainloop()
</code>```

Before/after selection:

Title: presenting menus in tkinter

Body:
I'm writing a connect-4 game with Tkinter, and I would to present several menu options to the user during the course of the game.

The problem is that the menus tend to be presented together, as in the piece of code below.  For example, in present_player_choice(), I'd like to present a menu for playerA, get an answer, and then present a menu for playerB.  This is not that crucial here, but it's a problem I keep running across.

after() does not seem to be the answer, as I do not want the menu to disappear after a certain space of time, but rather to disappear after the user has submitted an answer.

Also: In writing an 'ok' button for the menu, I've used 'quit.'  But quit closes the entire widget!  I want the gui to continue, and simply the menu to close, not the entire GUI!

I know these questions sound rather clueless, but I've been working on this for a while and am genuinely confused.  Thanks in advance for any help.

from tkinter import *
class GUI:

def __init__(self, root):
    self.__root = root
    self.__player_A = None
    self.__player_B = None

def assign_player(self, player, identity):
    if player == "player A":
        self.__player_A = identity
    elif player == "player B":
        self.__player_B = identity
    print("Player A is:  " + str(self.__player_A))
    print("Player B is:  " + str(self.__player_B))

def present_player_choice(self):
    self.ask_choose_player("player A")
    self.ask_choose_player("player B")
    Button(self.__root, text="OK", command=quit).pack(anchor=W)

def ask_choose_player(self, player):

    Label(self.__root, text="Who would you like to play " + player + "?").pack(anchor=W)
    var = IntVar()
    Radiobutton(self.__root, text="human", variable=var,
                command=lambda:self.assign_player(player, HUMAN), value=1).pack(anchor=W)
    Radiobutton(self.__root, text="computer", variable=var,
                command=lambda:self.assign_player(player, COMPUTER), value=2).pack(anchor=W)

if __name__ == '__main__':

root = Tk()
gui = GUI(root)
gui.present_player_choice()
mainloop()

Body:
The quickest way to do this is to add a Frame to your class that we can use to reset the content and then move the call for player B into a condition in the assign_player method to update the frame for player B when a selection is chosen.

You may also want to add tristatevalue=0 to your radio buttons so that there is no default selection.

Example:

import tkinter as tk

class GUI:
    def __init__(self, root):
        self.__root = root
        self.__player_A = None
        self.__player_B = None
        self.frame = None

    def assign_player(self, player, identity):
        if player == "player A":
            self.__player_A = identity
            print("Player A is:  " + str(self.__player_A))
            self.ask_choose_player("player B")
            tk.Button(self.__root, text="OK", command=quit).pack(anchor=tk.W)
        elif player == "player B":
            self.__player_B = identity
            print("Player B is:  " + str(self.__player_B))
            self.frame.destroy()

    def present_player_choice(self):
        self.ask_choose_player("player A")

    def ask_choose_player(self, player):
        if self.frame is None:
            self.frame = tk.Frame(self.__root)
        else:
            self.frame.destroy()
            self.frame = tk.Frame(self.__root)

        self.frame.pack(fill='both', expand=1)
        tk.Label(self.frame, text="Who would you like to play " + player + "?").pack(anchor=tk.W)
        var = tk.IntVar()

        tk.Radiobutton(self.frame, text="human", variable=var, tristatevalue=0,
                       command=lambda: self.assign_player(player, 'human'), value=1).pack(anchor=tk.W)
        tk.Radiobutton(self.frame, text="computer", variable=var, tristatevalue=0,
                       command=lambda: self.assign_player(player, 'pc'), value=2).pack(anchor=tk.W)

if __name__ == '__main__':
    root = tk.Tk()
    gui = GUI(root)
    gui.present_player_choice()
    root.mainloop()

Before/after selection:


问:
Woocommerce - change default value tax class
I am using woocommerce and I want change default value Tax class it's possible do it when create or update product.
Thanks.

答:
To update/change this.

This setting has to enabled Under WooCommerce > Settings > General

It then this adds the Tax tab.

Under there you can add additional Tax Classes

This will add the option to the top of that page to allow you to configure that class.

This is setup in a way that "standard" is the bulk of your tax that you would collect but could do different ones when needed.

The "standard" doesn't show up to the frontend user so no need to worry about the verbiage.


问:
Attribute Error: On selenium-python script
I am using Selenium-python script for web test automation. When ever I use selenium inbuilt commands, I will get Attribute error during run time.

Ex: selenium.WindowFocus("preview_email") throws "AttributeError: class selenium has no attribute 'WindowFocus'"

I am new to test automation. Help me to sort out this problem.

答:
I have never used the Python client personally, but a quick glance at the selenium.py file reveals that there is a window_focus command which gives the currently "selected" window focus ("selected" in Selenium terms is the window that Selenium is currently executing commands against and not necessarially the window that has user focus).

Executing the select_window command with a window ID will set tell Selenium which window you want to execute commands against.

I have had some trouble w/ popups in general and the way the Selenium IDE and RC clients attempt to locate new windows and/or there parents.  Good luck.

OwnerDisplayName: sridhar

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Benjamin Lee


问:
Create wide (desummarized) R data.table
I have a compact data.frame or data.table containing row-wise info on ranges (dt.compact).

```<code>dt.compact = data.table(chr=c('chr1','chr1','chr2','chr2'),start = c(1,5,2,7), stop = c(3,7,3,8))

# Output dt.compact
 chr start stop
1: chr1     1    3
2: chr1     5    7
3: chr2     2    3
4: chr2     7    8
</code>```

Now, I want a simple way to generate a wide data.frame or table with one row per position. Output should look like following:

```<code># Output
do.call(data.table, list(V1 = c(rep('chr1', 6),rep('chr2', 4)), V2 = c(1:3, 5:7, 2:3, 7:8)))

     V1 V2
 1: chr1  1
 2: chr1  2
 3: chr1  3
 4: chr1  5
 5: chr1  6
 6: chr1  7
 7: chr2  2
 8: chr2  3
 9: chr2  7
10: chr2  8

</code>```

Any suggestions how to achieve this? I thought about mapply (myOwnFunction, ...), but maybe there is already a built-in solution?

Any thoughts are wellcome

答:
I don't have a built-in solution, here is a tidyverse method:

```<code>dt.compact %>%
  mutate(rng=map2(start, stop, ~.x:.y)) %>%
  select(-start, -stop) %>%
  unnest(cols=rng)
</code>```

Title: Create wide (desummarized) R data.table

Body:
I have a compact data.frame or data.table containing row-wise info on ranges (dt.compact).

dt.compact = data.table(chr=c('chr1','chr1','chr2','chr2'),start = c(1,5,2,7), stop = c(3,7,3,8))

# Output dt.compact
 chr start stop
1: chr1     1    3
2: chr1     5    7
3: chr2     2    3
4: chr2     7    8

Now, I want a simple way to generate a wide data.frame or table with one row per position. Output should look like following:

# Output
do.call(data.table, list(V1 = c(rep('chr1', 6),rep('chr2', 4)), V2 = c(1:3, 5:7, 2:3, 7:8)))

     V1 V2
 1: chr1  1
 2: chr1  2
 3: chr1  3
 4: chr1  5
 5: chr1  6
 6: chr1  7
 7: chr2  2
 8: chr2  3
 9: chr2  7
10: chr2  8

Any suggestions how to achieve this? I thought about mapply (myOwnFunction, ...), but maybe there is already a built-in solution?

Any thoughts are wellcome

Body:
I don't have a built-in solution, here is a tidyverse method:

dt.compact %>%
  mutate(rng=map2(start, stop, ~.x:.y)) %>%
  select(-start, -stop) %>%
  unnest(cols=rng)


问:
TF2 - hub.text_embedding_column still to be implemented
I'm migrating an old TensorFlow 1.x training script and I got some problem with hub.text_embedding_column function. At the moment, the following code does not work

```<code># Python 3.6.9
import tensorflow as tf # tf.__version__ 2.1.0
import tensorflow_hub as hub # hub.__version__ 0.7.0

module_spec = hub.load_module_spec('https://tfhub.dev/google/universal-sentence-encoder/4')
text_column = hub.text_embedding_column(key='test_col', module_spec=module_spec)
</code>```

The error that I got is:

RuntimeError: Missing implementation that supports: loader(*('/tmp/tfhub_modules/29abffb443cb0a0ca9c72e8e3863b76d85028490',), **{})

I tried help(hub.text_embedding_column) and the help returns me

TODO(b/131678043): This does not work yet with TF2.

Do you know any workaround to use text_embedding_column with TF2? I'm able to load the model using hub.load('https://tfhub.dev/google/universal-sentence-encoder/4') but then I don't know what to do with it.

Thank you all (:

答:
Following this github issue I was able to solve my problem, at least for now. It's still based on tf.compact.v1.placeholder but at least I can use hub.text_embedding_column.

```<code># Python 3.6.9
import tensorflow as tf # tf.__version__ 2.1.0
import tensorflow_hub as hub # hub.__version__ 0.7.0

def build_module_fn(model_url):
    def module_fn():
        text_input = tf.compat.v1.placeholder(dtype=tf.string, shape=[None])
        embed_layer = hub.KerasLayer(
            model_url,
            input_shape=[],  # Expects a tensor of shape [batch_size] as input.
            dtype=tf.string)  # Expects a tf.string input tensor
        embeddings = embed_layer(text_input)
        hub.add_signature(inputs=text_input, outputs=embeddings)
    return module_fn

module_spec = hub.create_module_spec(build_module_fn('https://tfhub.dev/google/universal-sentence-encoder/4'))
hub.text_embedding_column(key='text', module_spec=module_spec)
</code>```

Hope that this can help other people!

Body:
I'm migrating an old TensorFlow 1.x training script and I got some problem with hub.text_embedding_column function. At the moment, the following code does not work

# Python 3.6.9
import tensorflow as tf # tf.__version__ 2.1.0
import tensorflow_hub as hub # hub.__version__ 0.7.0

module_spec = hub.load_module_spec('https://tfhub.dev/google/universal-sentence-encoder/4')
text_column = hub.text_embedding_column(key='test_col', module_spec=module_spec)

The error that I got is:

RuntimeError: Missing implementation that supports: loader(*('/tmp/tfhub_modules/29abffb443cb0a0ca9c72e8e3863b76d85028490',), **{})

I tried help(hub.text_embedding_column) and the help returns me

TODO(b/131678043): This does not work yet with TF2.

Do you know any workaround to use text_embedding_column with TF2? I'm able to load the model using hub.load('https://tfhub.dev/google/universal-sentence-encoder/4') but then I don't know what to do with it.

Thank you all (:

Body:
Following this github issue I was able to solve my problem, at least for now. It's still based on tf.compact.v1.placeholder but at least I can use hub.text_embedding_column.

# Python 3.6.9
import tensorflow as tf # tf.__version__ 2.1.0
import tensorflow_hub as hub # hub.__version__ 0.7.0

def build_module_fn(model_url):
    def module_fn():
        text_input = tf.compat.v1.placeholder(dtype=tf.string, shape=[None])
        embed_layer = hub.KerasLayer(
            model_url,
            input_shape=[],  # Expects a tensor of shape [batch_size] as input.
            dtype=tf.string)  # Expects a tf.string input tensor
        embeddings = embed_layer(text_input)
        hub.add_signature(inputs=text_input, outputs=embeddings)
    return module_fn

module_spec = hub.create_module_spec(build_module_fn('https://tfhub.dev/google/universal-sentence-encoder/4'))
hub.text_embedding_column(key='text', module_spec=module_spec)

Hope that this can help other people!


问:
Error Code: 1248. Every derived table must have its own alias
```<code>SELECT dept_name,avg_salary
FROM (SELECT dept_name,AVG(salary) AS avg_salary
        FROM instructor
        group by dept_name)
WHERE avg_salary>42000;
</code>```

答:
Add the alias to the derived table. For example:

```<code>SELECT dept_name,avg_salary
FROM (SELECT dept_name,AVG(salary) AS avg_salary
      FROM instructor group by dept_name) x
WHERE avg_salary>42000;
</code>```

Do you see the x I added?

Body:
Add the alias to the derived table. For example:

SELECT dept_name,avg_salary
FROM (SELECT dept_name,AVG(salary) AS avg_salary
      FROM instructor group by dept_name) x
WHERE avg_salary>42000;

Do you see the x I added?


问:
RegEx that match react router path declaration
I have a map of routes with react router path as keys, eg:

const routes = [
  {
    page: "mySettings",
    label: "pages.mySettings",
    path: "/professionels/mes-reglages.html",
    exact: true
  },
  {
    page: "viewUser",
    label: "pages.viewUser",
    path: "/users/:id/view.html",
    exact: true
  }
];
```

I want from a location retrieved with useHistory().location.pathname, to match all the path that match the key in react-router terms, eg:

(pathname) => get(routesMap, "/professionels/mes-reglages.html") => should match routesMap.get('/professionels/mes-reglages.html')

(pathname) => get(routesMap, "/users/11/view.html") => should match routesMap.get('/users/:id/view.html')

and all react-router paths so this should work too:

(pathname) => get(routesMap, "/users/11/settings/10/items/24/view.html") => should match routesMap.get('/users/:userId/settings/:settingId/items/:id/view.html')

I have started here, any idea how I can do that with a regexp?

https://codesandbox.io/s/youthful-wing-fjgm1

答:
Based on your comments i adjusted the code a bit and wrote a rapper function for your lookup.
The following rules you have to watch out for when creating the urls:

The last id always gets replaced by {id}

All other ids get replaced by url part to id without plural and "Id" attached ("/users/111" -> "/users/{userId}")

This would be the function:

const getRouteFromPath = (map, url) => {
  if (url.match(/\/\d+\//g).length > 1) {
    let allowedUrlPart = getAllowedIdQualifier(map);
    let urlParts = url.match(/(?<=\/)\w+(?=\/\d+\/)/g);
    urlParts.forEach(val => {
      if (!allowedUrlPart.includes(val)) {
        urlParts = urlParts.slice(urlParts.indexOf(val), 1);
      }
    });
    urlParts.forEach((val, key, arr) => {
      if (key === arr.length - 1) {
        let regex = new RegExp("(?<=/" + val + "/)\\d+", "g");
        let replacement = ":id";
        url = url.replace(regex, replacement);
      } else {
        let regex = new RegExp("(?<=/" + val + "/)\\d+", "g");
        let replacement = ":" + val.slice(0, -1) + "Id";
        url = url.replace(regex, replacement);
      }
    });
    return map.get(url);
  } else {
    url = url.replace(/\/\d+\//g, "/:id/");
    return map.get(url);
  }
};

const getAllowedIdQualifier = map => {
  let allowedQualifiers = [];
  map.forEach(val => {
    let allowed = val.path.match(/(?<=\/)\w+(?=\/:)/g);
    allowed.forEach(e => {
      if (!allowedQualifiers.includes(e)) {
        allowedQualifiers.push(e);
      }
    });
  });
  return allowedQualifiers;
};

export default getRouteFromPath;

```

As parameter you pass in the url to match as first parameter and the map of routes as the second paramter and call the function getRoute() instead of the direct map.get() call you where using before.

Here is the example with the urls adjusted to follow the rules, since you need some rules to be able to apply RegEx.

EDIT:

I adjusted the script, so that it reads the map first and determines the allowed paths which accept a id and then check the possible ids from an actual url against it.

https://codesandbox.io/s/kind-moon-9oyj9?fontsize=14&hidenavigation=1&theme=dark

Body:
I have a map of routes with react router path as keys, eg:

const routes = [
  {
    page: "mySettings",
    label: "pages.mySettings",
    path: "/professionels/mes-reglages.html",
    exact: true
  },
  {
    page: "viewUser",
    label: "pages.viewUser",
    path: "/users/:id/view.html",
    exact: true
  }
];

I want from a location retrieved with useHistory().location.pathname, to match all the path that match the key in react-router terms, eg:

(pathname) => get(routesMap, "/professionels/mes-reglages.html") => should match routesMap.get('/professionels/mes-reglages.html')

(pathname) => get(routesMap, "/users/11/view.html") => should match routesMap.get('/users/:id/view.html')

and all react-router paths so this should work too:

(pathname) => get(routesMap, "/users/11/settings/10/items/24/view.html") => should match routesMap.get('/users/:userId/settings/:settingId/items/:id/view.html')

I have started here, any idea how I can do that with a regexp?

https://codesandbox.io/s/youthful-wing-fjgm1

Body:
Based on your comments i adjusted the code a bit and wrote a rapper function for your lookup.
The following rules you have to watch out for when creating the urls:

The last id always gets replaced by {id}

All other ids get replaced by url part to id without plural and "Id" attached ("/users/111" -> "/users/{userId}")

This would be the function:

const getRouteFromPath = (map, url) => {
  if (url.match(/\/\d+\//g).length > 1) {
    let allowedUrlPart = getAllowedIdQualifier(map);
    let urlParts = url.match(/(?<=\/)\w+(?=\/\d+\/)/g);
    urlParts.forEach(val => {
      if (!allowedUrlPart.includes(val)) {
        urlParts = urlParts.slice(urlParts.indexOf(val), 1);
      }
    });
    urlParts.forEach((val, key, arr) => {
      if (key === arr.length - 1) {
        let regex = new RegExp("(?<=/" + val + "/)\\d+", "g");
        let replacement = ":id";
        url = url.replace(regex, replacement);
      } else {
        let regex = new RegExp("(?<=/" + val + "/)\\d+", "g");
        let replacement = ":" + val.slice(0, -1) + "Id";
        url = url.replace(regex, replacement);
      }
    });
    return map.get(url);
  } else {
    url = url.replace(/\/\d+\//g, "/:id/");
    return map.get(url);
  }
};

const getAllowedIdQualifier = map => {
  let allowedQualifiers = [];
  map.forEach(val => {
    let allowed = val.path.match(/(?<=\/)\w+(?=\/:)/g);
    allowed.forEach(e => {
      if (!allowedQualifiers.includes(e)) {
        allowedQualifiers.push(e);
      }
    });
  });
  return allowedQualifiers;
};

export default getRouteFromPath;

As parameter you pass in the url to match as first parameter and the map of routes as the second paramter and call the function getRoute() instead of the direct map.get() call you where using before.

Here is the example with the urls adjusted to follow the rules, since you need some rules to be able to apply RegEx.

EDIT:

I adjusted the script, so that it reads the map first and determines the allowed paths which accept a id and then check the possible ids from an actual url against it.

https://codesandbox.io/s/kind-moon-9oyj9?fontsize=14&hidenavigation=1&theme=dark


问:
tips for implementing AsyncTask
Hi all i've an app that places a circle on a bitmapa and with a slidebar alters the rgb values of the pixels within the circle. i'd like to use asynctask to speed up the process of altering the pixels. i'm not sure where to start. i've commented out some code at the bottom of the activity file as this is my first attept at it:). could anyone point me in the correct direction in how to implement this. The activity invokes a custom view(touchview), as i understand the asynctask must be instantiated on the UI thread. i'm thinking of initializing the slidebar ect in onPreExecute(), but not sure how to put all the worker stuff in doInBackground(). Any help will be appreciated, thanks Matt.

```<code>public class Jjilapp extends Activity {

    private Button b1;

    private static final String TAG = "*********jjil";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG, "***********inside oncreate about to set contentview = ");
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.touchview);
        final TouchView touchView = (TouchView)findViewById(R.id.touchview);
        final HorizontalSlider slider = (HorizontalSlider)findViewById(R.id.slider);

        touchView.initSlider(slider);

        b1 = (Button)findViewById(R.id.button1);
        b1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.e(TAG, "onClickButton1");

            }
        });

    }//end of oncreate

   /* private class UpdateCirclePixels extends AsyncTask<Integer,Integer,Integer>{

        @Override
        protected void onPreExecute(){
            final TouchView touchView = (TouchView)findViewById(R.id.touchview);
            final HorizontalSlider slider = (HorizontalSlider)findViewById(R.id.slider);

            touchView.initSlider(slider);

        }

        @Override
        protected Integer doInBackground(Integer... arg0) {
            // TODO Auto-generated method stub

            publishProgress(progress);
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... progress){

        }

    }//end of AsyncTask     */

}//end of jjilapp
</code>```

.

```<code>public class TouchView extends View{

    private File tempFile;
    private byte[] imageArray;
    private Bitmap bgr;
    private Bitmap bm;
    private Paint pTouch;
    private int centreX = 1;
    private int centreY = 1;
    private int radius = 50;
    private int Progress;
    private static final String TAG = "*********TouchView";

    public TouchView(Context context) {
        super(context);
       // TouchView(context, null);
    }

    public TouchView(Context context, AttributeSet attr) {
        super(context,attr);

        tempFile = new File(Environment.getExternalStorageDirectory().
                getAbsolutePath() + "/"+"image.jpg");

        imageArray = new byte[(int)tempFile.length()];

     try{

            InputStream is = new FileInputStream(tempFile);
            BufferedInputStream bis = new BufferedInputStream(is);
            DataInputStream dis = new DataInputStream(bis);

            int i = 0;

            while (dis.available() > 0) {
            imageArray[i] = dis.readByte();
            i++;
            }

            dis.close();

       } catch (Exception e) {

               e.printStackTrace();
            }

        BitmapFactory.Options bfo = new BitmapFactory.Options();
        bfo.inSampleSize = 1;

        bm = BitmapFactory.decodeByteArray(imageArray, 0, imageArray.length, bfo);
        bgr = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), bm.getConfig());
        bgr = bm.copy(bm.getConfig(), true);

        pTouch = new Paint(Paint.ANTI_ALIAS_FLAG);
        pTouch.setXfermode(new PorterDuffXfermode(Mode.SRC_OUT));
        pTouch.setColor(Color.TRANSPARENT);
        pTouch.setStyle(Paint.Style.STROKE);

        //pTouch.setMaskFilter(new BlurMaskFilter(15, Blur.NORMAL));

    }// end of touchView constructor

    public void findCirclePixels(){

        for (int i=centreX-50; i < centreX+50; ++i) {
            for (int y=centreY-50; y <centreY+50 ; ++y) {

    if( Math.sqrt( Math.pow(i - centreX, 2) + ( Math.pow(y - centreY, 2) ) ) <= radius ){

                    bgr.setPixel(i,y,Color.rgb(Progress+50,Progress,Progress+100));
                }
            }
        }

        }// end of changePixel()

    @Override
    public boolean onTouchEvent(MotionEvent ev) {

        switch (ev.getAction()) {

            case MotionEvent.ACTION_DOWN: {

                centreX = (int) ev.getX();
                centreY = (int) ev.getY();
                findCirclePixels();
                invalidate();

                break;
            }

            case MotionEvent.ACTION_MOVE: {

                    centreX = (int) ev.getX();
                    centreY = (int) ev.getY();
                    findCirclePixels();
                    invalidate();
                    break;

            }

            case MotionEvent.ACTION_UP:

                break;

        }
        return true;
    }//end of onTouchEvent

    public void initSlider(final HorizontalSlider slider)
    {
        Log.e(TAG, "******setting up slider*********** ");
        slider.setOnProgressChangeListener(changeListener);
    }

    private OnProgressChangeListener changeListener = new OnProgressChangeListener() {

        @Override
        public void onProgressChanged(View v, int progress) {
            // TODO Auto-generated method stub

            setProgress(progress);
            Log.e(TAG, "***********progress = "+Progress);

        }
    };

    @Override
    public void onDraw(Canvas canvas){
        super.onDraw(canvas);

        canvas.drawBitmap(bgr, 0, 0, null);
        canvas.drawCircle(centreX, centreY, radius,pTouch);

    }//end of onDraw

    protected void setProgress(int progress2) {
        this.Progress = progress2;
        findCirclePixels();
        invalidate();

    }

}
</code>```

答:
AsyncTask is easy to use: just do your stuff in doInBackground(...) and it will run in a separate thread.

However, take into account that you can't touch the views in that separate thread or you'll get a CalledFromWrongThreadException. Only the original thread that created a view hierarchy can touch its views.

However, if you really need to touch the views you can use:

```<code>runOnUiThread(new Runnable() {
    @Override
    public void run() {
        //do your stuff here
    }
});
</code>```

Title: tips for implementing AsyncTask

Body:
Hi all i've an app that places a circle on a bitmapa and with a slidebar alters the rgb values of the pixels within the circle. i'd like to use asynctask to speed up the process of altering the pixels. i'm not sure where to start. i've commented out some code at the bottom of the activity file as this is my first attept at it:). could anyone point me in the correct direction in how to implement this. The activity invokes a custom view(touchview), as i understand the asynctask must be instantiated on the UI thread. i'm thinking of initializing the slidebar ect in onPreExecute(), but not sure how to put all the worker stuff in doInBackground(). Any help will be appreciated, thanks Matt.

public class Jjilapp extends Activity {

    private Button b1;

    private static final String TAG = "*********jjil";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG, "***********inside oncreate about to set contentview = ");
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.touchview);
        final TouchView touchView = (TouchView)findViewById(R.id.touchview);
        final HorizontalSlider slider = (HorizontalSlider)findViewById(R.id.slider);

        touchView.initSlider(slider);

        b1 = (Button)findViewById(R.id.button1);
        b1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.e(TAG, "onClickButton1");

            }
        });

    }//end of oncreate

   /* private class UpdateCirclePixels extends AsyncTask<Integer,Integer,Integer>{

        @Override
        protected void onPreExecute(){
            final TouchView touchView = (TouchView)findViewById(R.id.touchview);
            final HorizontalSlider slider = (HorizontalSlider)findViewById(R.id.slider);

            touchView.initSlider(slider);

        }

        @Override
        protected Integer doInBackground(Integer... arg0) {
            // TODO Auto-generated method stub

            publishProgress(progress);
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... progress){

        }

    }//end of AsyncTask     */

}//end of jjilapp

.

public class TouchView extends View{

    private File tempFile;
    private byte[] imageArray;
    private Bitmap bgr;
    private Bitmap bm;
    private Paint pTouch;
    private int centreX = 1;
    private int centreY = 1;
    private int radius = 50;
    private int Progress;
    private static final String TAG = "*********TouchView";

    public TouchView(Context context) {
        super(context);
       // TouchView(context, null);
    }

    public TouchView(Context context, AttributeSet attr) {
        super(context,attr);

        tempFile = new File(Environment.getExternalStorageDirectory().
                getAbsolutePath() + "/"+"image.jpg");

        imageArray = new byte[(int)tempFile.length()];

     try{

            InputStream is = new FileInputStream(tempFile);
            BufferedInputStream bis = new BufferedInputStream(is);
            DataInputStream dis = new DataInputStream(bis);

            int i = 0;

            while (dis.available() > 0) {
            imageArray[i] = dis.readByte();
            i++;
            }

            dis.close();

       } catch (Exception e) {

               e.printStackTrace();
            }

        BitmapFactory.Options bfo = new BitmapFactory.Options();
        bfo.inSampleSize = 1;

        bm = BitmapFactory.decodeByteArray(imageArray, 0, imageArray.length, bfo);
        bgr = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), bm.getConfig());
        bgr = bm.copy(bm.getConfig(), true);

        pTouch = new Paint(Paint.ANTI_ALIAS_FLAG);
        pTouch.setXfermode(new PorterDuffXfermode(Mode.SRC_OUT));
        pTouch.setColor(Color.TRANSPARENT);
        pTouch.setStyle(Paint.Style.STROKE);

        //pTouch.setMaskFilter(new BlurMaskFilter(15, Blur.NORMAL));

    }// end of touchView constructor

    public void findCirclePixels(){

        for (int i=centreX-50; i < centreX+50; ++i) {
            for (int y=centreY-50; y <centreY+50 ; ++y) {

    if( Math.sqrt( Math.pow(i - centreX, 2) + ( Math.pow(y - centreY, 2) ) ) <= radius ){

                    bgr.setPixel(i,y,Color.rgb(Progress+50,Progress,Progress+100));
                }
            }
        }

        }// end of changePixel()

    @Override
    public boolean onTouchEvent(MotionEvent ev) {

        switch (ev.getAction()) {

            case MotionEvent.ACTION_DOWN: {

                centreX = (int) ev.getX();
                centreY = (int) ev.getY();
                findCirclePixels();
                invalidate();

                break;
            }

            case MotionEvent.ACTION_MOVE: {

                    centreX = (int) ev.getX();
                    centreY = (int) ev.getY();
                    findCirclePixels();
                    invalidate();
                    break;

            }

            case MotionEvent.ACTION_UP:

                break;

        }
        return true;
    }//end of onTouchEvent

    public void initSlider(final HorizontalSlider slider)
    {
        Log.e(TAG, "******setting up slider*********** ");
        slider.setOnProgressChangeListener(changeListener);
    }

    private OnProgressChangeListener changeListener = new OnProgressChangeListener() {

        @Override
        public void onProgressChanged(View v, int progress) {
            // TODO Auto-generated method stub

            setProgress(progress);
            Log.e(TAG, "***********progress = "+Progress);

        }
    };

    @Override
    public void onDraw(Canvas canvas){
        super.onDraw(canvas);

        canvas.drawBitmap(bgr, 0, 0, null);
        canvas.drawCircle(centreX, centreY, radius,pTouch);

    }//end of onDraw

    protected void setProgress(int progress2) {
        this.Progress = progress2;
        findCirclePixels();
        invalidate();

    }

}

Body:
AsyncTask is easy to use: just do your stuff in doInBackground(...) and it will run in a separate thread.

However, take into account that you can't touch the views in that separate thread or you'll get a CalledFromWrongThreadException. Only the original thread that created a view hierarchy can touch its views.

However, if you really need to touch the views you can use:

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        //do your stuff here
    }
});


问:
Force Jupyter to use Python 3.7 executable instead of Python 3.8
This one is literally driving me nuts.

I installed Python3.8 on macOS and used python3 -m install ipykernel to make Jupyter use this new version.

However, now I completely removed Python3.8 from the system, reinstalled Python3.7 and want to stick to it for the time being.

Despite thoroughly uninstalling, removing, erasing any Jupyter/Notebook/Ipykernel module and then re-installing them under Python3.7's pip3, nothing does the trick: Jupyter will still look for the (absent) Python@3.8 installation.

This is what gets displayed in the logs when opening a notebook and trying to start the kernel:

```<code>[E 13:25:29.942 NotebookApp] Failed to run command:
    ['/usr/local/opt/python@3.8/bin/python3.8', '-m', 'ipykernel_launcher', '-f', '/Users/jivan/Library/Jupyter/runtime/kernel-fe88c716-f146-4328-b1f7-6199f2b44d12.json']
        PATH='/Users/jivan/.cargo/bin:/Users/jivan/.cargo/bin:/usr/local/sbin:/Users/jivan/google-cloud-sdk/bin:/Users/jivan/.cargo/bin:/Users/jivan/.local/bin:/usr/local/sbin:/Users/jivan/bin:/usr/local/bin:/Users/jivan/.cargo/bin:/usr/local/opt/python@3.8/bin:/Users/jivan/.cargo/bin:/Users/jivan/.cargo/bin:/usr/local/sbin:/Users/jivan/google-cloud-sdk/bin:/Users/jivan/.cargo/bin:/Users/jivan/.local/bin:/usr/local/sbin:/Users/jivan/bin:/usr/local/bin:/Users/jivan/.cargo/bin:/Users/jivan/.cargo/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin:/Library/Apple/bin:/opt/X11/bin'
        with kwargs:
    {'stdin': -1, 'stdout': None, 'stderr': None, 'cwd': '/Users/jivan/Downloads/dresses', 'start_new_session': True}
</code>```

The /usr/local/opt/python@3.8/bin/python3.8 line refers to the now-removed Python3.8 installation and I would like to force Jupyter to target Python3.7 executable instead.

Note: when I type python3 in a terminal, it points to the 3.7 version:

```<code>$ python3
Python 3.7.6 (default, Feb 11 2020, 07:50:21)
[Clang 11.0.0 (clang-1100.0.33.17)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
</code>```

Is there a configuration file that it not removed during uninstall, and which I should modify? I'm guessing that some config file somewhere specifies the hardcoded /usr/local/opt/python@3.8/bin/python3.8 and Jupyter reads this file, but that's just a hypothesis. I haven't been able to find any file containing this text in the system so far.

UPDATE

Part of the traceback shows the following lines, which lead me to think that Jupyter is rightly launched from Python3.7 but then, for some reason, is trying to spawn a subprocess with Python3.8. Weird.

```<code>      File "/usr/local/lib/python3.7/site-packages/jupyter_client/manager.py", line 204, in _launch_kernel
        return launch_kernel(kernel_cmd, **kw)
      File "/usr/local/lib/python3.7/site-packages/jupyter_client/launcher.py", line 138, in launch_kernel
        proc = Popen(cmd, **kwargs)
      File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/subprocess.py", line 800, in __init__
        restore_signals, start_new_session)
      File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/subprocess.py", line 1551, in _execute_child
        raise child_exception_type(errno_num, err_msg, err_filename)
    FileNotFoundError: [Errno 2] No such file or directory: '/usr/local/opt/python@3.8/bin/python3.8': '/usr/local/opt/python@3.8/bin/python3.8'
</code>```

答:
I recommend re-installing Jupyter and not just the ipykernel package.

Otherwise, first get the location of the jupyter executable by running $(which jupyter) in terminal.

When you run cat $(which jupyter) in the terminal, you see that the first line in the file references the older python executable path.

Open this file in your editor and change the path to the result of running $(which python3) in the terminal

Body:
This one is literally driving me nuts.

I installed Python3.8 on macOS and used python3 -m install ipykernel to make Jupyter use this new version.

However, now I completely removed Python3.8 from the system, reinstalled Python3.7 and want to stick to it for the time being.

Despite thoroughly uninstalling, removing, erasing any Jupyter/Notebook/Ipykernel module and then re-installing them under Python3.7's pip3, nothing does the trick: Jupyter will still look for the (absent) Python@3.8 installation.

This is what gets displayed in the logs when opening a notebook and trying to start the kernel:

[E 13:25:29.942 NotebookApp] Failed to run command:
    ['/usr/local/opt/python@3.8/bin/python3.8', '-m', 'ipykernel_launcher', '-f', '/Users/jivan/Library/Jupyter/runtime/kernel-fe88c716-f146-4328-b1f7-6199f2b44d12.json']
        PATH='/Users/jivan/.cargo/bin:/Users/jivan/.cargo/bin:/usr/local/sbin:/Users/jivan/google-cloud-sdk/bin:/Users/jivan/.cargo/bin:/Users/jivan/.local/bin:/usr/local/sbin:/Users/jivan/bin:/usr/local/bin:/Users/jivan/.cargo/bin:/usr/local/opt/python@3.8/bin:/Users/jivan/.cargo/bin:/Users/jivan/.cargo/bin:/usr/local/sbin:/Users/jivan/google-cloud-sdk/bin:/Users/jivan/.cargo/bin:/Users/jivan/.local/bin:/usr/local/sbin:/Users/jivan/bin:/usr/local/bin:/Users/jivan/.cargo/bin:/Users/jivan/.cargo/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin:/Library/Apple/bin:/opt/X11/bin'
        with kwargs:
    {'stdin': -1, 'stdout': None, 'stderr': None, 'cwd': '/Users/jivan/Downloads/dresses', 'start_new_session': True}

The /usr/local/opt/python@3.8/bin/python3.8 line refers to the now-removed Python3.8 installation and I would like to force Jupyter to target Python3.7 executable instead.

Note: when I type python3 in a terminal, it points to the 3.7 version:

$ python3
Python 3.7.6 (default, Feb 11 2020, 07:50:21)
[Clang 11.0.0 (clang-1100.0.33.17)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

Is there a configuration file that it not removed during uninstall, and which I should modify? I'm guessing that some config file somewhere specifies the hardcoded /usr/local/opt/python@3.8/bin/python3.8 and Jupyter reads this file, but that's just a hypothesis. I haven't been able to find any file containing this text in the system so far.

UPDATE

Part of the traceback shows the following lines, which lead me to think that Jupyter is rightly launched from Python3.7 but then, for some reason, is trying to spawn a subprocess with Python3.8. Weird.

      File "/usr/local/lib/python3.7/site-packages/jupyter_client/manager.py", line 204, in _launch_kernel
        return launch_kernel(kernel_cmd, **kw)
      File "/usr/local/lib/python3.7/site-packages/jupyter_client/launcher.py", line 138, in launch_kernel
        proc = Popen(cmd, **kwargs)
      File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/subprocess.py", line 800, in __init__
        restore_signals, start_new_session)
      File "/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/subprocess.py", line 1551, in _execute_child
        raise child_exception_type(errno_num, err_msg, err_filename)
    FileNotFoundError: [Errno 2] No such file or directory: '/usr/local/opt/python@3.8/bin/python3.8': '/usr/local/opt/python@3.8/bin/python3.8'


问:
Using StateRestoreListener with Spring Cloud Kafka Streams binder
I'm going to use StateRestoreListener with Spring Cloud Kafka Streams binder.
I need to monitor the restoration progress of fault-tolerant state stores of my applications.
There is example in confluent https://docs.confluent.io/current/streams/monitoring.html#streams-monitoring-runtime-status .

In order to observe the restoration of all state stores you provide
  your application an instance of the
  org.apache.kafka.streams.processor.StateRestoreListener interface. You
  set the org.apache.kafka.streams.processor.StateRestoreListener by
  calling the KafkaStreams#setGlobalStateRestoreListener method.

The first problem is getting the Kafka Streams from the app. I solved this problem with using

```<code>StreamsBuilderFactoryBean streamsBuilderFactoryBean = context.getBean("&stream-builder-process", StreamsBuilderFactoryBean.class);
KafkaStreams kafkaStreams = streamsBuilderFactoryBean.getKafkaStreams();
</code>```

The second problem is setting StateRestoreListener to KafkaStreams, because I get error

java.lang.IllegalStateException: Can only set
  GlobalStateRestoreListener in CREATED state. Current state is: RUNNING

Is it possible to use StateRestoreListener in Spring Cloud Kafka Streams binder?
Thanks

答:
You can do that by using a StreamsBuilderFactoryBeanCustomizer that gives you access to the underlying KafkaStreams object. If you are using binder versions 3.0 or above, this is the recommended approach. For e.g., you can provide the following bean in your application and customize it with the GlobalStateRestoreListener.

```<code>@Bean
public StreamsBuilderFactoryBeanCustomizer streamsBuilderFactoryBeanCustomizer() {
    return factoryBean -> {
        factoryBean.setKafkaStreamsCustomizer(new KafkaStreamsCustomizer() {
            @Override
            public void customize(KafkaStreams kafkaStreams) {
                kafkaStreams.setGlobalStateRestoreListener(...);
            }
        });
    };
}
</code>```

This blog has more details on this strategy.

Body:
I'm going to use StateRestoreListener with Spring Cloud Kafka Streams binder.
I need to monitor the restoration progress of fault-tolerant state stores of my applications.
There is example in confluent https://docs.confluent.io/current/streams/monitoring.html#streams-monitoring-runtime-status .

In order to observe the restoration of all state stores you provide
  your application an instance of the
  org.apache.kafka.streams.processor.StateRestoreListener interface. You
  set the org.apache.kafka.streams.processor.StateRestoreListener by
  calling the KafkaStreams#setGlobalStateRestoreListener method.

The first problem is getting the Kafka Streams from the app. I solved this problem with using

StreamsBuilderFactoryBean streamsBuilderFactoryBean = context.getBean("&stream-builder-process", StreamsBuilderFactoryBean.class);
KafkaStreams kafkaStreams = streamsBuilderFactoryBean.getKafkaStreams();

The second problem is setting StateRestoreListener to KafkaStreams, because I get error

java.lang.IllegalStateException: Can only set
  GlobalStateRestoreListener in CREATED state. Current state is: RUNNING

Is it possible to use StateRestoreListener in Spring Cloud Kafka Streams binder?
Thanks

Body:
You can do that by using a StreamsBuilderFactoryBeanCustomizer that gives you access to the underlying KafkaStreams object. If you are using binder versions 3.0 or above, this is the recommended approach. For e.g., you can provide the following bean in your application and customize it with the GlobalStateRestoreListener.

@Bean
public StreamsBuilderFactoryBeanCustomizer streamsBuilderFactoryBeanCustomizer() {
    return factoryBean -> {
        factoryBean.setKafkaStreamsCustomizer(new KafkaStreamsCustomizer() {
            @Override
            public void customize(KafkaStreams kafkaStreams) {
                kafkaStreams.setGlobalStateRestoreListener(...);
            }
        });
    };
}

This blog has more details on this strategy.


问:
Flutter TextFormField wrap text and automatically adapt height
In Flutter, how to utilize TextFormField widget which wrap it's text and auto-size height based on current text as user type?

答:
Simply set the maxLines property of your TextFormField widget to null it will automatically resize.

Tested on DartPad using this example:

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 100,
      child: TextFormField(maxLines: null),
    );
  }
}
```


问:
Thai language is not showing in Java output
Unable to print Thai string value in Java console

```<code>public static void main(String [] args){
   String engParam = "Beautiful";
   String thaiParam = "สวย";
   System.out.println("Output :" + engParam + ":::" + thaiParam);}
</code>```

Output is showing like:

```<code>Output :Beautiful:::à?ªà??à?¢
</code>```

I think System.out.println will not be able to print the UTF-8 characters with default console settings. Is there any other way available to resolve this issue? help needed.

答: Set environment variable java_tool_options=-Dfile.encoding=utf8  in cmd use chcp 65001</p>

Body:
Unable to print Thai string value in Java console

public static void main(String [] args){
   String engParam = "Beautiful";
   String thaiParam = "สวย";
   System.out.println("Output :" + engParam + ":::" + thaiParam);}

Output is showing like:

Output :Beautiful:::à?ªà??à?¢

I think System.out.println will not be able to print the UTF-8 characters with default console settings. Is there any other way available to resolve this issue? help needed.


问:
How to implement Competition leaderboard using redis sorted set
I'm using Redis sorted set to maintain the leaderboard of my game. I have a scenario where I need to maintain the same rank of the users who have the same score as the Competition leaderboard. Eg.

```<code>| member | score | rank |
— — — — — — — — — — —
| member_1 | 50 | 1 |
| member_2 | 50 | 1 |
| member_3 | 30 | 3 |
| member_4 | 30 | 3 |
| member_5 | 10 | 5 |
</code>```

As of now, I'm using default implementation of Redis sorted set which returns the ranking lexicographically.

```<code>127.0.0.1:6379> zadd test-leaderboard 9 user1
(integer) 1
127.0.0.1:6379> zadd test-leaderboard 5 user2
(integer) 1
127.0.0.1:6379> zadd test-leaderboard 5 user3
(integer) 1
127.0.0.1:6379> zadd test-leaderboard 3 user4
(integer) 1
</code>```

If I query for user2 and user3 rank, I get a different result

```<code>127.0.0.1:6379> zrank test-leaderboard user2
(integer) 1
127.0.0.1:6379> zrank test-leaderboard user3
(integer) 2
</code>```

I checked Redis documentation, there is no such feature to do so. So I want to know what I have to do or what is the best way to implement this functionality.

Note: I have 10K records in SET and I need to maintain it at runtime and I'm using Java programming language.

答:
Sorted sets are sorted first by score, then lexicographically, that's why you get a different rank for user2 and user3.

You can combine ZSCORE, ZRANGEBYSCORE and ZRANK to normalize this. Basically, you get the score for user3, then get the first user lexicographically in a tie, and get the rank for that user.

```<code>> ZSCORE test-leaderboard user3
"5"
> ZRANGEBYSCORE test-leaderboard 5 5 LIMIT 0 1
1) "user2"
> ZRANK test-leaderboard user2
(integer) 1
</code>```

This gives you a rank, with ties ranked the same, but leaving gaps for ranking.

```<code>user4 => 0
user2 => 1
user3 => 1
user1 => 3
</code>```

If you want your ranks without gaps, you can either maintain the leaderboard with the list of users at a given score per entry (ZADD test-leaderboard 5 "user2,user3"), or maintain a separated sorted set with only unique scores. I would go with the second one for efficiency.

Adding a new player [O(log(N))]:

```<code>ZADD test-leaderboard 5 user2
ZADD test-ranks 5 5
</code>```

Delete a player [O(log(N))]:

```<code>> ZSCORE test-leaderboard user2
"5"
> ZREM test-leaderboard user2
(integer) 1
> ZRANGEBYSCORE test-leaderboard 5 5 LIMIT 0 1
1) "anotherUser" or (empty list or set)
if(empty set)
> ZREM test-ranks 5
</code>```

Update a player score [O(log(N))]:

```<code>> ZSCORE test-leaderboard user2
"5"
> ZADD test-leaderboard 10 user2
(integer) 1
> ZADD test-ranks 10 10
(integer) 1
> ZRANGEBYSCORE test-leaderboard 5 5 LIMIT 0 1
1) "anotherUser" or (empty list or set)
if(empty set)
> ZREM test-ranks 5
</code>```

Get the rank of a player [O(log(N))]:

```<code>> ZSCORE test-leaderboard user2
"5"
> ZRANK test-ranks 5
(integer) 1
</code>```

A couple of notes:

Use ZREVXXX commands if higher score is top rank.

ZRANK ranks the lowest score first, use ZREVRANK if you want the highest score ranked first. See ZREVRANK and ZREVRANGEBYSCORE.

Use Lua scripts

With Lua scripts, you can make your operations atomic and perform them faster.

Here an example. Instead of

```<code>> ZSCORE test-leaderboard user2
"5"
> ZRANK test-ranks 5
(integer) 1
</code>```

Use the script:

```<code>local score = redis.call('ZSCORE', KEYS[1], ARGV[1])
return redis.call('ZRANK', KEYS[2], score)
</code>```

Use as:

```<code>> EVAL "local score = redis.call('ZSCORE', KEYS[1], ARGV[1]) \n return redis.call('ZRANK', KEYS[2], score)" 2 test-leaderboard test-ranks user2
(integer) 1
</code>```

Body:
I'm using Redis sorted set to maintain the leaderboard of my game. I have a scenario where I need to maintain the same rank of the users who have the same score as the Competition leaderboard. Eg.

| member | score | rank |
— — — — — — — — — — —
| member_1 | 50 | 1 |
| member_2 | 50 | 1 |
| member_3 | 30 | 3 |
| member_4 | 30 | 3 |
| member_5 | 10 | 5 |

As of now, I'm using default implementation of Redis sorted set which returns the ranking lexicographically.

127.0.0.1:6379> zadd test-leaderboard 9 user1
(integer) 1
127.0.0.1:6379> zadd test-leaderboard 5 user2
(integer) 1
127.0.0.1:6379> zadd test-leaderboard 5 user3
(integer) 1
127.0.0.1:6379> zadd test-leaderboard 3 user4
(integer) 1

If I query for user2 and user3 rank, I get a different result

127.0.0.1:6379> zrank test-leaderboard user2
(integer) 1
127.0.0.1:6379> zrank test-leaderboard user3
(integer) 2

I checked Redis documentation, there is no such feature to do so. So I want to know what I have to do or what is the best way to implement this functionality.

Note: I have 10K records in SET and I need to maintain it at runtime and I'm using Java programming language.

Body:
Sorted sets are sorted first by score, then lexicographically, that's why you get a different rank for user2 and user3.

You can combine ZSCORE, ZRANGEBYSCORE and ZRANK to normalize this. Basically, you get the score for user3, then get the first user lexicographically in a tie, and get the rank for that user.

> ZSCORE test-leaderboard user3
"5"
> ZRANGEBYSCORE test-leaderboard 5 5 LIMIT 0 1
1) "user2"
> ZRANK test-leaderboard user2
(integer) 1

This gives you a rank, with ties ranked the same, but leaving gaps for ranking.

user4 => 0
user2 => 1
user3 => 1
user1 => 3

If you want your ranks without gaps, you can either maintain the leaderboard with the list of users at a given score per entry (ZADD test-leaderboard 5 "user2,user3"), or maintain a separated sorted set with only unique scores. I would go with the second one for efficiency.

Adding a new player [O(log(N))]:

ZADD test-leaderboard 5 user2
ZADD test-ranks 5 5

Delete a player [O(log(N))]:

> ZSCORE test-leaderboard user2
"5"
> ZREM test-leaderboard user2
(integer) 1
> ZRANGEBYSCORE test-leaderboard 5 5 LIMIT 0 1
1) "anotherUser" or (empty list or set)
if(empty set)
> ZREM test-ranks 5

Update a player score [O(log(N))]:

> ZSCORE test-leaderboard user2
"5"
> ZADD test-leaderboard 10 user2
(integer) 1
> ZADD test-ranks 10 10
(integer) 1
> ZRANGEBYSCORE test-leaderboard 5 5 LIMIT 0 1
1) "anotherUser" or (empty list or set)
if(empty set)
> ZREM test-ranks 5

Get the rank of a player [O(log(N))]:

> ZSCORE test-leaderboard user2
"5"
> ZRANK test-ranks 5
(integer) 1

A couple of notes:

Use ZREVXXX commands if higher score is top rank.

ZRANK ranks the lowest score first, use ZREVRANK if you want the highest score ranked first. See ZREVRANK and ZREVRANGEBYSCORE.

Use Lua scripts

With Lua scripts, you can make your operations atomic and perform them faster.

Here an example. Instead of

> ZSCORE test-leaderboard user2
"5"
> ZRANK test-ranks 5
(integer) 1

Use the script:

local score = redis.call('ZSCORE', KEYS[1], ARGV[1])
return redis.call('ZRANK', KEYS[2], score)

Use as:

> EVAL "local score = redis.call('ZSCORE', KEYS[1], ARGV[1]) \n return redis.call('ZRANK', KEYS[2], score)" 2 test-leaderboard test-ranks user2
(integer) 1


问:
PHPSpreadsheet incorrect date format code in ods and xls
I am trying to read spreadsheet documents using PHPSpreadsheet, I have a problem reading dates in the sheets, I want to read them in the way it is formatted, the dates are in YYYY-MM-DD format using cell number formatting, when I save the sheets in ods and xls formats I get incorrect date format and when I save the sheets in xlsx format the date format is correct, below is the code that I am using to read spreadsheets

```<code>$PHPSpreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);
foreach ($PHPSpreadsheet->getWorksheetIterator() as $worksheet) {
    foreach ($worksheet->getRowIterator() as $row) {
        $cellIterator = $row->getCellIterator();
        $cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
        foreach ($cellIterator as $cell) {
            if (!is_null($cell)) {
                if (\PhpOffice\PhpSpreadsheet\Shared\Date::isDateTime($cell)) {
                    echo $cell->getStyle()->getNumberFormat()->getFormatCode();
                    echo '<br>';
                    echo $cell->getValue();
                    echo '<br>';
                    echo $cell->getCalculatedValue();
                    echo '<br>';
                    echo $cell->getFormattedValue();
                    echo '<br>';

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

this is the output that I get for xlsx, ods, xls respectively

```<code>YYYY\-MM\-DD
43196
43196
2018-04-06

d-mmm-yy h:mm:ss
43196.041666667
43196.041666667
6-Apr-18 1:00:00

d-mmm-yy h:mm:ss
43196.041666667
43196.041666667
6-Apr-18 1:00:00
</code>```

The output that I get while saving in xlsx format is the correct format in the sheets, ods is the format that I will be using the most, am I doing anything wrong or is it a limitaion of PHPSpreadsheet.

答:
in current version 1.10.1 of PHPSpreadsheet the bug is fixed only for XLS, but NOT for ODS!

In Reader/Ods.php is always set NumberFormat::FORMAT_DATE_XLSX15 the lib actually is missing a correct detection of date formats specified in ODS file.

Body:
I am trying to read spreadsheet documents using PHPSpreadsheet, I have a problem reading dates in the sheets, I want to read them in the way it is formatted, the dates are in YYYY-MM-DD format using cell number formatting, when I save the sheets in ods and xls formats I get incorrect date format and when I save the sheets in xlsx format the date format is correct, below is the code that I am using to read spreadsheets

$PHPSpreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);
foreach ($PHPSpreadsheet->getWorksheetIterator() as $worksheet) {
    foreach ($worksheet->getRowIterator() as $row) {
        $cellIterator = $row->getCellIterator();
        $cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
        foreach ($cellIterator as $cell) {
            if (!is_null($cell)) {
                if (\PhpOffice\PhpSpreadsheet\Shared\Date::isDateTime($cell)) {
                    echo $cell->getStyle()->getNumberFormat()->getFormatCode();
                    echo '
';
                    echo $cell->getValue();
                    echo '
';
                    echo $cell->getCalculatedValue();
                    echo '
';
                    echo $cell->getFormattedValue();
                    echo '
';

                }
            }
        }
    }
}

this is the output that I get for xlsx, ods, xls respectively

YYYY\-MM\-DD
43196
43196
2018-04-06

d-mmm-yy h:mm:ss
43196.041666667
43196.041666667
6-Apr-18 1:00:00

d-mmm-yy h:mm:ss
43196.041666667
43196.041666667
6-Apr-18 1:00:00

The output that I get while saving in xlsx format is the correct format in the sheets, ods is the format that I will be using the most, am I doing anything wrong or is it a limitaion of PHPSpreadsheet.


问:
The error was: botocore.exceptions.NoCredentialsError: Unable to locate credential
Hi i am unable to solve these problem i am getting these , my ansible code is Unable to locate credentials

ansible code

```<code>---
 - name: main yaml file
   remote_user: ec2-user
   become: yes
   hosts: localhost
   roles:
      - s3
</code>```

roles:

```<code>- name: basic upload
  s3_sync:
   bucket: s3uploadlocust
   file_root: /home/ec2-user
   include: "*.csv"
   exclude: "*.txt,.*"
   permission: public-read
   file_change_strategy: force
   region: us-east-1
</code>```

Here my environment tools versions:

```<code>Name: boto3
Version: 1.12.2
Summary: The AWS SDK for Python
Home-page: https://github.com/boto/boto3
Author: Amazon Web Services
Author-email: UNKNOWN
License: Apache License 2.0
Location: /usr/local/lib/python2.7/site-packages
Requires: s3transfer, jmespath, botocore

Name: ansible
Version: 2.9.5
Summary: Radically simple IT automation
Home-page: https://ansible.com/
Author: Ansible, Inc.
Author-email: info@ansible.com
License: GPLv3+
Location: /usr/local/lib/python2.7/site-packages
Requires: jinja2, PyYAML, cryptography

Python 2.7.16
</code>```

答:
According to the module documentation, you can provide 2 more parameters: aws_access_key and aws_secret_key.
If they're not set then the value of the AWS_ACCESS_KEY_ID, AWS_ACCESS_KEY or EC2_ACCESS_KEY environment variable is used for aws_access_key.
And AWS_SECRET_ACCESS_KEY, AWS_SECRET_KEY, or EC2_SECRET_KEY environment variable is used for aws_secret_key.

Body:
Hi i am unable to solve these problem i am getting these , my ansible code is Unable to locate credentials

ansible code

---
 - name: main yaml file
   remote_user: ec2-user
   become: yes
   hosts: localhost
   roles:
      - s3

roles:

- name: basic upload
  s3_sync:
   bucket: s3uploadlocust
   file_root: /home/ec2-user
   include: "*.csv"
   exclude: "*.txt,.*"
   permission: public-read
   file_change_strategy: force
   region: us-east-1

Here my environment tools versions:

Name: boto3
Version: 1.12.2
Summary: The AWS SDK for Python
Home-page: https://github.com/boto/boto3
Author: Amazon Web Services
Author-email: UNKNOWN
License: Apache License 2.0
Location: /usr/local/lib/python2.7/site-packages
Requires: s3transfer, jmespath, botocore

Name: ansible
Version: 2.9.5
Summary: Radically simple IT automation
Home-page: https://ansible.com/
Author: Ansible, Inc.
Author-email: info@ansible.com
License: GPLv3+
Location: /usr/local/lib/python2.7/site-packages
Requires: jinja2, PyYAML, cryptography

Python 2.7.16


问:
Find item by key in Javascript
Quick rookie question please.

Suppose I have a javsacript object like so:

```<code>var meh=[["cars",27], ["bikes",85], ["skates",4]];
</code>```

To go through each data object here, I can do this:

```<code>$.each(meh, function(index,value){
    console.log(value) //returns ["cars",27] etc..
 });
</code>```

And considering I know the place of, say, cars, I can do this to access it:

```<code>console.log(meh[0][0]) //shows "Cars"
</code>```

and of course, if I want the value of cars, I need to do this:

```<code>console.log(meh[0][1]) //Shows 27
</code>```

Now, I have the string - Keys, like cars, bikes or skates

But I cant figure out this: How do I access their respective values?

meh["cars"] is returning undefined, since, as I understand, it cant find a description outside each object.

I can do meh[0]["cars"] but it defeats the point as the position of cars might change.

How do I access a value of something with their key please?

thanks.

答: You have your data structure in an array, so you are always going to have to access by the array syntax e.g. [0][1].  The arrays in JavaScript are not associative.  You could write a helper function which iterates around the array looking for the key you specify and returning the value back.  Or you could change your data structure to be Objects, which do support key lookup.</p>

Title: Find item by key in Javascript

Body:
Quick rookie question please.

Suppose I have a javsacript object like so:

var meh=[["cars",27], ["bikes",85], ["skates",4]];

To go through each data object here, I can do this:

$.each(meh, function(index,value){
    console.log(value) //returns ["cars",27] etc..
 });

And considering I know the place of, say, cars, I can do this to access it:

console.log(meh[0][0]) //shows "Cars"

and of course, if I want the value of cars, I need to do this:

console.log(meh[0][1]) //Shows 27

Now, I have the string - Keys, like cars, bikes or skates

But I cant figure out this: How do I access their respective values?

meh["cars"] is returning undefined, since, as I understand, it cant find a description outside each object.

I can do meh[0]["cars"] but it defeats the point as the position of cars might change.

How do I access a value of something with their key please?

thanks.


问:
How to find next birthday date from list of date from date now?
I'm struggling with this question? How can I find next birthday Date from my list of date ?
I got

```<code>const myArray = [
          {
            name: 'Joe Blow',
            date: 'Wednesday, November 25, 1992'
          },
          {
            name: 'Sam lol',
            date: 'Thursday, April 16, 1992'
          },
          {
            name: 'Eva lol',
            date: 'Thursday, February 26, 1991'
          }
        ];
        myArray.sort(function compare(a, b) {
          const dateA = new Date(a.date);
          const dateB = new Date(b.date);
          return dateA.getUTCDate() - dateB.getUTCDate();
        });
        // console.log(this.usersBirthdayDate);
        console.log(myArray);
</code>```

but I got Sam first cause he got 1992.. But I would like to display Thursday, February 26, 1991 first

Updated
my solution :

```<code>    sortByDateNoYear(adate, bdate) {
        let results;
        const lhdate = moment(adate.birthdayDate);
        const rhdate = moment(bdate.birthdayDate);
        results =
          lhdate.month() > rhdate.month()
            ? 1
            : lhdate.month() < rhdate.month()
            ? -1
            : 0;
        if (results === 0) {
          results =
            lhdate.date() > rhdate.date()
              ? 1
              : lhdate.date() < rhdate.date()
              ? -1
              : 0;
        }
        return results;
      }
 [array].sort(this.sortByDateNoYear);
</code>```

答:
you need to set the same year for all date and next year for birthday already passed. Then you can compare</p>

```<code>myArray.sort(function compare(a, b) {
          const now = new Date();
          const dateA = new Date(a.date);
          dateA.setYear(now.getFullYear());
          if (dataA.getTime() - now.getTime() < 0) {
             dateA.setYear(now.getFullYear() + 1)
          }
          const dateB = new Date(b.date);
          dateA.setYear(new Date().getFullYear());
          dateA.setYear(now.getFullYear());
          if (dataB.getTime() - now.getTime() < 0) {
             dateB.setYear(now.getFullYear() + 1)
          }
          return dateA.getTime() - dateB.getTime();
        });
</code>```

Body:
I'm struggling with this question? How can I find next birthday Date from my list of date ?
I got

const myArray = [
          {
            name: 'Joe Blow',
            date: 'Wednesday, November 25, 1992'
          },
          {
            name: 'Sam lol',
            date: 'Thursday, April 16, 1992'
          },
          {
            name: 'Eva lol',
            date: 'Thursday, February 26, 1991'
          }
        ];
        myArray.sort(function compare(a, b) {
          const dateA = new Date(a.date);
          const dateB = new Date(b.date);
          return dateA.getUTCDate() - dateB.getUTCDate();
        });
        // console.log(this.usersBirthdayDate);
        console.log(myArray);

but I got Sam first cause he got 1992.. But I would like to display Thursday, February 26, 1991 first

Updated
my solution :

    sortByDateNoYear(adate, bdate) {
        let results;
        const lhdate = moment(adate.birthdayDate);
        const rhdate = moment(bdate.birthdayDate);
        results =
          lhdate.month() > rhdate.month()
            ? 1
            : lhdate.month() < rhdate.month()
            ? -1
            : 0;
        if (results === 0) {
          results =
            lhdate.date() > rhdate.date()
              ? 1
              : lhdate.date() < rhdate.date()
              ? -1
              : 0;
        }
        return results;
      }
 [array].sort(this.sortByDateNoYear);

Body:
you need to set the same year for all date and next year for birthday already passed. Then you can compare

myArray.sort(function compare(a, b) {
          const now = new Date();
          const dateA = new Date(a.date);
          dateA.setYear(now.getFullYear());
          if (dataA.getTime() - now.getTime() < 0) {
             dateA.setYear(now.getFullYear() + 1)
          }
          const dateB = new Date(b.date);
          dateA.setYear(new Date().getFullYear());
          dateA.setYear(now.getFullYear());
          if (dataB.getTime() - now.getTime() < 0) {
             dateB.setYear(now.getFullYear() + 1)
          }
          return dateA.getTime() - dateB.getTime();
        });