问:
function to end clicks
I am doing a class project for tic-tac-toe (I am an absolute beginner and have only been coding for about 2 months and just recently got into javascript and jquery so please do not judge my very rusty skills lol). I am having a problem at the end of my game that after a winner is declared you can continue to click in empty squares on the board, is there a way to prevent this from happening? Code is below, thank you!
(I also know my winning conditions needs to be fixed a bit)

let currentPlayer = "X";

$(".cell").on('click', function() {
  if (currentPlayer == "X" && $(this).hasClass("takenByX" || "takenByO")) { //checks to see if square has been played
      (""); //does nothing
  } else if (currentPlayer == "X") {
      $(this).text("X").addClass("takenByX"); //change clicked square to x & adds class taken
       playerChange();} //runs player change function
    if(currentPlayer == "O" && $(this).hasClass("takenByX" || "takenByO")) { //checks to see if square has been played
       (""); //does nothing
  } else if (currentPlayer == "O") {
      $(this).text("0").addClass("takenByO"); //change clicked square to o & adds class taken
       playerChange(); //runs player change function
  }});

function playerChange() {
  if (currentPlayer === "X"){ //if current player is x, then switch to o
    currentPlayer = "O";
  } else {
    currentPlayer = "X"; //if current player is not x then switch to x
  }
  winner();
}

$("button").on('click', function() { //click function for restart game button
  $('.cell').text(""); //removes all added text from the cells
  $('.cell').removeClass("takenByX"); //removes the taken class from the cells
  $('.cell').removeClass("takenByO");
  $('h1').text("C R O S S E S & & N O U G H T S").append;
  if (currentPlayer == "O"){
    playerChange(); //changes back to player x so o doesnt play first
  }
});

function winner(){
   if (
       $(".cell1" && ".cell2" && ".cell3").hasClass("takenByX") || // -
       $(".cell1" && ".cell5" && ".cell9").hasClass("takenByX") || // \
       $(".cell1" && ".cell4" && ".cell7").hasClass("takenByX") || // |
       $(".cell2" && ".cell5" && ".cell8").hasClass("takenByX") || // |
       $(".cell3" && ".cell6" && ".cell9").hasClass("takenByX") || // |
       $(".cell4" && ".cell5" && ".cell6").hasClass("takenByX") || // -
       $(".cell7" && ".cell8" && ".cell9").hasClass("takenByX")    // -
   ){
         $('h1').text("Congratulations Winner!").append;
      } else {
        (""); //do nothing
      }}

   if (
       $(".cell1" && ".cell2" && ".cell3").hasClass("takenByO") || // -
       $(".cell1" && ".cell5" && ".cell9").hasClass("takenByO") || // \
       $(".cell1" && ".cell4" && ".cell7").hasClass("takenByO") || // |
       $(".cell2" && ".cell5" && ".cell8").hasClass("takenByO") || // |
       $(".cell3" && ".cell6" && ".cell9").hasClass("takenByO") || // |
       $(".cell4" && ".cell5" && ".cell6").hasClass("takenByO") || // -
       $(".cell7" && ".cell8" && ".cell9").hasClass("takenByO")    // -
   ){
         $('h1').text("Congratulations Winner!").append;
      } else {
        (""); //do nothing
      }

//if a winner is declared stop allowing clicks?

  ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    background-image: url("https://wallpaperboat.com/wp-content/uploads/2019/06/minimalist-desktop-11.jpg");
    font-family: 'Amatic SC', cursive;
}

h1 {
    font-size: 75px;
    align-items: center;
    text-align: center;
    text-shadow: 2px 2px #196775;
}

section {
    text-align: center;
}

.container {
    display: grid;
    grid-template-columns: repeat(3, auto);
    width: 600px;
    margin: 50px auto;
}

.cell {
    font-family: 'Major Mono Display', monospace;
    width: 200px;
    height: 200px;
    box-shadow: 0 0 0 1px #196775;
    border: 1px solid #196775;
    font-size: 150px;
    color: rgb(0, 35, 46);
    justify-content: center;
    text-align: center;
    padding-top: 20px;
}

.restart {
    transition-duration: 0.4s;
    background-color: lightsteelblue;
    font-family: 'Amatic SC', cursive;
    color: black;
    text-align: center;
    padding: 5px 5px;
    border: none;
    text-decoration: none;
    font-size: 30px;
    text-shadow: 1px 1px 1px #196775;
    box-shadow: 0 10px 15px 0 #196775;
    outline: none;

}
.restart:hover {
    box-shadow: 0 10px 15px 0 rgb(43, 43, 43);
    background-color: rgb(19, 114, 109);
    color: black;
}

footer {
    font-size: 20px;
    bottom: 0;
    width: 100%;
    justify-content: center;
    text-align: center;
    font-family: 'Amatic SC', cursive;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="https://fonts.googleapis.com/css2?family=Amatic+SC:wght@400;700&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Amatic+SC:wght@400;700&family=Major+Mono+Display&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="style.css">

    <title>crosses & noughts</title>

C R O S S E S && N O U G H T S

<button class="restart">Restart Game</button>

Made by Falon B. Landers

```

答:
you can prevent the click by adding this code </p>

```<code>$('.cell').off('click')
</code>```

<p>you can simply use the function anywhere you want to remove the eventlistener
try and use it right after you show the winner text </p>

Title: function to end clicks

Body:
I am doing a class project for tic-tac-toe (I am an absolute beginner and have only been coding for about 2 months and just recently got into javascript and jquery so please do not judge my very rusty skills lol). I am having a problem at the end of my game that after a winner is declared you can continue to click in empty squares on the board, is there a way to prevent this from happening? Code is below, thank you!
(I also know my winning conditions needs to be fixed a bit)

let currentPlayer = "X";

$(".cell").on('click', function() {
  if (currentPlayer == "X" && $(this).hasClass("takenByX" || "takenByO")) { //checks to see if square has been played
      (""); //does nothing
  } else if (currentPlayer == "X") {
      $(this).text("X").addClass("takenByX"); //change clicked square to x & adds class taken
       playerChange();} //runs player change function
    if(currentPlayer == "O" && $(this).hasClass("takenByX" || "takenByO")) { //checks to see if square has been played
       (""); //does nothing
  } else if (currentPlayer == "O") {
      $(this).text("0").addClass("takenByO"); //change clicked square to o & adds class taken
       playerChange(); //runs player change function
  }});

function playerChange() {
  if (currentPlayer === "X"){ //if current player is x, then switch to o
    currentPlayer = "O";
  } else {
    currentPlayer = "X"; //if current player is not x then switch to x
  }
  winner();
}

$("button").on('click', function() { //click function for restart game button
  $('.cell').text(""); //removes all added text from the cells
  $('.cell').removeClass("takenByX"); //removes the taken class from the cells
  $('.cell').removeClass("takenByO");
  $('h1').text("C R O S S E S & & N O U G H T S").append;
  if (currentPlayer == "O"){
    playerChange(); //changes back to player x so o doesnt play first
  }
});

function winner(){
   if (
       $(".cell1" && ".cell2" && ".cell3").hasClass("takenByX") || // -
       $(".cell1" && ".cell5" && ".cell9").hasClass("takenByX") || // \
       $(".cell1" && ".cell4" && ".cell7").hasClass("takenByX") || // |
       $(".cell2" && ".cell5" && ".cell8").hasClass("takenByX") || // |
       $(".cell3" && ".cell6" && ".cell9").hasClass("takenByX") || // |
       $(".cell4" && ".cell5" && ".cell6").hasClass("takenByX") || // -
       $(".cell7" && ".cell8" && ".cell9").hasClass("takenByX")    // -
   ){
         $('h1').text("Congratulations Winner!").append;
      } else {
        (""); //do nothing
      }}

   if (
       $(".cell1" && ".cell2" && ".cell3").hasClass("takenByO") || // -
       $(".cell1" && ".cell5" && ".cell9").hasClass("takenByO") || // \
       $(".cell1" && ".cell4" && ".cell7").hasClass("takenByO") || // |
       $(".cell2" && ".cell5" && ".cell8").hasClass("takenByO") || // |
       $(".cell3" && ".cell6" && ".cell9").hasClass("takenByO") || // |
       $(".cell4" && ".cell5" && ".cell6").hasClass("takenByO") || // -
       $(".cell7" && ".cell8" && ".cell9").hasClass("takenByO")    // -
   ){
         $('h1').text("Congratulations Winner!").append;
      } else {
        (""); //do nothing
      }

//if a winner is declared stop allowing clicks?

body {
    background-image: url("https://wallpaperboat.com/wp-content/uploads/2019/06/minimalist-desktop-11.jpg");
    font-family: 'Amatic SC', cursive;
}

h1 {
    font-size: 75px;
    align-items: center;
    text-align: center;
    text-shadow: 2px 2px #196775;
}

section {
    text-align: center;
}

.container {
    display: grid;
    grid-template-columns: repeat(3, auto);
    width: 600px;
    margin: 50px auto;
}

.cell {
    font-family: 'Major Mono Display', monospace;
    width: 200px;
    height: 200px;
    box-shadow: 0 0 0 1px #196775;
    border: 1px solid #196775;
    font-size: 150px;
    color: rgb(0, 35, 46);
    justify-content: center;
    text-align: center;
    padding-top: 20px;
}

.restart {
    transition-duration: 0.4s;
    background-color: lightsteelblue;
    font-family: 'Amatic SC', cursive;
    color: black;
    text-align: center;
    padding: 5px 5px;
    border: none;
    text-decoration: none;
    font-size: 30px;
    text-shadow: 1px 1px 1px #196775;
    box-shadow: 0 10px 15px 0 #196775;
    outline: none;

}
.restart:hover {
    box-shadow: 0 10px 15px 0 rgb(43, 43, 43);
    background-color: rgb(19, 114, 109);
    color: black;
}

footer {
    font-size: 20px;
    bottom: 0;
    width: 100%;
    justify-content: center;
    text-align: center;
    font-family: 'Amatic SC', cursive;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link href="https://fonts.googleapis.com/css2?family=Amatic+SC:wght@400;700&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Amatic+SC:wght@400;700&family=Major+Mono+Display&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="style.css">

    <title>crosses & noughts</title>

C R O S S E S && N O U G H T S

<button class="restart">Restart Game</button>

Made by Falon B. Landers

Body:
you can prevent the click by adding this code

$('.cell').off('click')

you can simply use the function anywhere you want to remove the eventlistener
try and use it right after you show the winner text


来源: stackexchange

问:
If a mail arrives in Outlook, start another method (Outlook freezes) Interlop.Outlook C# WPF
I have the following method part of a WPF app:

```<code>// This method check Emails
public void CheckForEmails()
{
    Outlook.Application application = null;
    Outlook.NameSpace nameSpace = null;

    if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
    {
        application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
    }
    else
    {
        application = new Outlook.Application();
        nameSpace = application.GetNamespace("MAPI");
        nameSpace.Logon("", "", Missing.Value, Missing.Value);
    }

    nameSpace = application.GetNamespace("MAPI");
    Outlook.MAPIFolder inbox = nameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
    //nameSpace.SendAndReceive(true);

    var items = inbox.Items;
    items.ItemAdd += AnyMethod;
}

//This method execute any method
public void AnyMethod(object Item)
{
    MessageBox.Show("GOOD!");
}

//This is the is the xaml.cs view which initialize the emailAction class if the window is open
public partial class PageView : UserControl
{
    public DownloadDeviceView()
    {
        InitializeComponent();
        DataContext = new DownloadDeviceViewModel();
        EmailAction emailAction = new EmailAction();
    }
}
</code>```

This method should execute the method AnyMethod() when a new e-mail is received in Outlook.

The problem is strangely always different: Sometimes everything works. Sometimes the method does not work at all. And sometimes Outlook freezes and nothing happens again.

答:
You must define the source object at the global scope (class-level) to get the event fired and keep the object alive, i.e. preventing it from being swiped by the garbage collector. For example:

```<code>Outlook.Items = null;
Outlook.Application application = null;
    Outlook.NameSpace nameSpace = null;

public void CheckForEmails()
{

    if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
    {
        application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
    }
    else
    {
        application = new Outlook.Application();
        nameSpace = application.GetNamespace("MAPI");
        nameSpace.Logon("", "", Missing.Value, Missing.Value);
    }

    nameSpace = application.GetNamespace("MAPI");
    Outlook.MAPIFolder inbox = nameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
    //nameSpace.SendAndReceive(true);

    items = inbox.Items;
    items.ItemAdd += AnyMethod;
}
</code>```

The ItemAdd event is not fired when you receive a lot of items at a time (more than sixteen). This is a known limitation of the Outlook object model and exists for decades.

I'd recommend using the NewMailEx event of the Application class instead. This event fires once for every received item that is processed by Microsoft Outlook. The item can be one of several different item types, for example, MailItem, MeetingItem, or SharingItem. The EntryIDsCollection string contains the Entry ID that corresponds to that item.

The NewMailEx event fires when a new message arrives in the Inbox and before client rule processing occurs. You can use the Entry ID returned in the EntryIDCollection array to call the NameSpace.GetItemFromID method and process the item.

ContentLicense: CC BY-SA 4.0

Body:
I have the following method part of a WPF app:

// This method check Emails
public void CheckForEmails()
{
    Outlook.Application application = null;
    Outlook.NameSpace nameSpace = null;

    if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
    {
        application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
    }
    else
    {
        application = new Outlook.Application();
        nameSpace = application.GetNamespace("MAPI");
        nameSpace.Logon("", "", Missing.Value, Missing.Value);
    }

    nameSpace = application.GetNamespace("MAPI");
    Outlook.MAPIFolder inbox = nameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
    //nameSpace.SendAndReceive(true);

    var items = inbox.Items;
    items.ItemAdd += AnyMethod;
}

//This method execute any method
public void AnyMethod(object Item)
{
    MessageBox.Show("GOOD!");
}

//This is the is the xaml.cs view which initialize the emailAction class if the window is open
public partial class PageView : UserControl
{
    public DownloadDeviceView()
    {
        InitializeComponent();
        DataContext = new DownloadDeviceViewModel();
        EmailAction emailAction = new EmailAction();
    }
}

This method should execute the method AnyMethod() when a new e-mail is received in Outlook.

The problem is strangely always different: Sometimes everything works. Sometimes the method does not work at all. And sometimes Outlook freezes and nothing happens again.

Body:
You must define the source object at the global scope (class-level) to get the event fired and keep the object alive, i.e. preventing it from being swiped by the garbage collector. For example:

Outlook.Items = null;
Outlook.Application application = null;
    Outlook.NameSpace nameSpace = null;

public void CheckForEmails()
{

    if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
    {
        application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
    }
    else
    {
        application = new Outlook.Application();
        nameSpace = application.GetNamespace("MAPI");
        nameSpace.Logon("", "", Missing.Value, Missing.Value);
    }

    nameSpace = application.GetNamespace("MAPI");
    Outlook.MAPIFolder inbox = nameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
    //nameSpace.SendAndReceive(true);

    items = inbox.Items;
    items.ItemAdd += AnyMethod;
}

The ItemAdd event is not fired when you receive a lot of items at a time (more than sixteen). This is a known limitation of the Outlook object model and exists for decades.

I'd recommend using the NewMailEx event of the Application class instead. This event fires once for every received item that is processed by Microsoft Outlook. The item can be one of several different item types, for example, MailItem, MeetingItem, or SharingItem. The EntryIDsCollection string contains the Entry ID that corresponds to that item.

The NewMailEx event fires when a new message arrives in the Inbox and before client rule processing occurs. You can use the Entry ID returned in the EntryIDCollection array to call the NameSpace.GetItemFromID method and process the item.


问:
Okhttp Interceptor issue
I'm trying to add a header to a simple okhttp (Get) request. How do I add the HttpHeader properly? Can I debug to ensure that my Header is actually sent to the server? </p>

```<code>        Request request = new Request.Builder()
                .url("URL")
                .build();

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request originalRequest = chain.request();
                        Request newRequest = originalRequest.newBuilder()
                                .addHeader("Header", "123")
                                .build();
                        return chain.proceed(newRequest);
                    }
                })
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
             }
</code>```

<p>I've looked for basic simple examples but they are with Retrofit, GSON, Interfaces, or in Kotlin. Need to understand it codewise. </p>

答:
To check your request and to add headers, you can use interceptors.

To add headers, (copied from gist):

```<code>OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request original = chain.request();

        Request request = original.newBuilder()
            .header("User-Agent", "Your-App-Name")
            .header("Accept", "application/vnd.yourapi.v1.full+json")
            .method(original.method(), original.body())
            .build();

        return chain.proceed(request);
    }
}

OkHttpClient client = httpClient.build();
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(API_BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(client)
    .build();
</code>```

To see your headers, you can use sample example provided here:

```<code>class LoggingInterceptor implements Interceptor {
  @Override public Response intercept(Interceptor.Chain chain) throws IOException {
    Request request = chain.request();

    long t1 = System.nanoTime();
    logger.info(String.format("Sending request %s on %s%n%s",
        request.url(), chain.connection(), request.headers()));

    Response response = chain.proceed(request);

    long t2 = System.nanoTime();
    logger.info(String.format("Received response for %s in %.1fms%n%s",
        response.request().url(), (t2 - t1) / 1e6d, response.headers()));

    return response;
  }
}
</code>```

Title: Okhttp Interceptor issue

Body:
I'm trying to add a header to a simple okhttp (Get) request. How do I add the HttpHeader properly? Can I debug to ensure that my Header is actually sent to the server?

        Request request = new Request.Builder()
                .url("URL")
                .build();

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request originalRequest = chain.request();
                        Request newRequest = originalRequest.newBuilder()
                                .addHeader("Header", "123")
                                .build();
                        return chain.proceed(newRequest);
                    }
                })
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
             }

I've looked for basic simple examples but they are with Retrofit, GSON, Interfaces, or in Kotlin. Need to understand it codewise.

Body:
To check your request and to add headers, you can use interceptors.

To add headers, (copied from gist):

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request original = chain.request();

        Request request = original.newBuilder()
            .header("User-Agent", "Your-App-Name")
            .header("Accept", "application/vnd.yourapi.v1.full+json")
            .method(original.method(), original.body())
            .build();

        return chain.proceed(request);
    }
}

OkHttpClient client = httpClient.build();
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(API_BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(client)
    .build();

To see your headers, you can use sample example provided here:

class LoggingInterceptor implements Interceptor {
  @Override public Response intercept(Interceptor.Chain chain) throws IOException {
    Request request = chain.request();

    long t1 = System.nanoTime();
    logger.info(String.format("Sending request %s on %s%n%s",
        request.url(), chain.connection(), request.headers()));

    Response response = chain.proceed(request);

    long t2 = System.nanoTime();
    logger.info(String.format("Received response for %s in %.1fms%n%s",
        response.request().url(), (t2 - t1) / 1e6d, response.headers()));

    return response;
  }
}


问:
How to select all items when I click on all from dropdown list using jquery and selectize.js?
I am having an issue to display all the items from dropdown when I click on all. Basically, I have implemented multiselect using https://harvesthq.github.io/chosen/. I just want when user click on all option from dropdown then all the items from dropdown list should be display in mutliselect box instead of all option as display in image. Can anyone help me. Thanks

```<code>html

<select data-placeholder="Type here to find device" id="logs"  name="tags[]"  multiple class="chosen-select form-control" onchange="checkLogging()" required>
<option value="" selected></option>
<option value="ALL">All</option>
<option value="ASA" >Cisco ASA</option>
<option value="ISE"> CISCO ISE</option>
<option value="MS">Microsoft Windows</option>
<option value="ATA">Microsoft ATA</option>
<option value="Alliance">SWIFT Alliance</option>
<option value="Proxy">Bluecoat Proxy</option>
<option value="Csp"> Symantec CSP</option>
</select>
</code>```

js

```<code>$(function() {
    var filter = $('#logs');
    filter.on('change', function() {
      if (this.selectedIndex) return; //not `Select All`
      filter.find('option:gt(0)').prop('selected', true);
      filter.find('option').eq(0).prop('selected', false);
    });
  });
</code>```

答:
You can do it like this:

$(function() {
   var filter = $('#logs');
   filter.on('change', function() {
      if ($(this).val() == ",ALL") {
         filter.val('').trigger('chosen:updated');
         filter.find('option:not([value="ALL"])').attr('selected', 'selected');
         filter.trigger('chosen:updated');
      }
   });
});
```

Working Fiddle.

Body:
I am having an issue to display all the items from dropdown when I click on all. Basically, I have implemented multiselect using https://harvesthq.github.io/chosen/. I just want when user click on all option from dropdown then all the items from dropdown list should be display in mutliselect box instead of all option as display in image. Can anyone help me. Thanks

html

<select data-placeholder="Type here to find device" id="logs"  name="tags[]"  multiple class="chosen-select form-control" onchange="checkLogging()" required>
<option value="" selected></option>
<option value="ALL">All</option>
<option value="ASA" >Cisco ASA</option>
<option value="ISE"> CISCO ISE</option>
<option value="MS">Microsoft Windows</option>
<option value="ATA">Microsoft ATA</option>
<option value="Alliance">SWIFT Alliance</option>
<option value="Proxy">Bluecoat Proxy</option>
<option value="Csp"> Symantec CSP</option>
</select>

js

$(function() {
    var filter = $('#logs');
    filter.on('change', function() {
      if (this.selectedIndex) return; //not `Select All`
      filter.find('option:gt(0)').prop('selected', true);
      filter.find('option').eq(0).prop('selected', false);
    });
  });

Body:
You can do it like this:

$(function() {
   var filter = $('#logs');
   filter.on('change', function() {
      if ($(this).val() == ",ALL") {
         filter.val('').trigger('chosen:updated');
         filter.find('option:not([value="ALL"])').attr('selected', 'selected');
         filter.trigger('chosen:updated');
      }
   });
});

Working Fiddle.


问:
How to convert timedelta to hours
I have a timedelta Dataframe

```<code>JC time
1 3days 21:02:05
2 1days 23:50:07
3 6days 19:28:36
</code>```

but i want

```<code>1 93:02:05
2 47:50:07
3 163:28:36
</code>```

How can I convert it?

答:
You could do as follows to convert a timedelta to the number of hours, minutes and seconds in the format you want:

def convert_to_hours(delta):
    total_seconds = delta.total_seconds()
    hours = str(int(total_seconds // 3600)).zfill(2)
    minutes = str(int((total_seconds % 3600) // 60)).zfill(2)
    seconds = str(int(total_seconds % 60)).zfill(2)
    return f"{hours}:{minutes}:{seconds}"

delta = timedelta(days=3, hours=21, minutes=2, seconds=5)
# 3 days, 21:02:05

convert_to_hours(delta)
# 93:02:05
```

<p>And to convert your dataframe, you can do something like this:</p>

<pre class="lang-py prettyprint-override"><code>df["time"] = df["time"].apply(convert_to_hours)
</code>```

Title: How to convert timedelta to hours

Body:
I have a timedelta Dataframe

JC time
1 3days 21:02:05
2 1days 23:50:07
3 6days 19:28:36

but i want

1 93:02:05
2 47:50:07
3 163:28:36

How can I convert it?

Body:
You could do as follows to convert a timedelta to the number of hours, minutes and seconds in the format you want:

def convert_to_hours(delta):
    total_seconds = delta.total_seconds()
    hours = str(int(total_seconds // 3600)).zfill(2)
    minutes = str(int((total_seconds % 3600) // 60)).zfill(2)
    seconds = str(int(total_seconds % 60)).zfill(2)
    return f"{hours}:{minutes}:{seconds}"

delta = timedelta(days=3, hours=21, minutes=2, seconds=5)
# 3 days, 21:02:05

convert_to_hours(delta)
# 93:02:05

And to convert your dataframe, you can do something like this:

df["time"] = df["time"].apply(convert_to_hours)


问:
mysql return multiple results with group by
Please note this is regarding a homework problem, the homework is done and works to the spec, but it's slow so I'm trying to lessen how many SQL calls I make. And I'm still learning my SQL-fu.

My table looks like:

```<code>Ticker |Name                  |Industry
A      |Agilent Technologies  |Information Technology
AA     |Alcoa Inc             |Materials
AAPL   |Apple Inc.            |Information Technology
</code>```

Right now I am running a SQL statement like this in a loop. Each iteration I change which industry to look at.

```<code>SELECT ticker FROM company WHERE industry = 'Information Technology'
</code>```

But that means I have to make a call to the database for each industry just to get the tickers related to it. What I want is to make one database call that returns multiple results. So the first result would be a list of all the tickers for the first industry, the second result would be all the tickers for the second industry etc.

I tried this SQL, but it just gave me one ticker for each industry, not a full list

```<code>SELECT ticker, industry FROM company GROUP BY industry
</code>```

答:
This should work for you:</p>

```<code>SELECT GROUP_CONCAT(Ticker) as Tickers, industry FROM company GROUP BY industry
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Please note this is regarding a homework problem, the homework is done and works to the spec, but it's slow so I'm trying to lessen how many SQL calls I make. And I'm still learning my SQL-fu.

My table looks like:

Ticker |Name                  |Industry
A      |Agilent Technologies  |Information Technology
AA     |Alcoa Inc             |Materials
AAPL   |Apple Inc.            |Information Technology

Right now I am running a SQL statement like this in a loop. Each iteration I change which industry to look at.

SELECT ticker FROM company WHERE industry = 'Information Technology'

But that means I have to make a call to the database for each industry just to get the tickers related to it. What I want is to make one database call that returns multiple results. So the first result would be a list of all the tickers for the first industry, the second result would be all the tickers for the second industry etc.

I tried this SQL, but it just gave me one ticker for each industry, not a full list

SELECT ticker, industry FROM company GROUP BY industry

Body:
This should work for you:

SELECT GROUP_CONCAT(Ticker) as Tickers, industry FROM company GROUP BY industry


问:
Merging several lists to create a data frame in R
Apologies in advance if this has already been asked elsewhere, but I've tried different attempts and nothing has worked so far.

I study the data from 23 devices mesuring air pollution. For each device, I am interested in 4 parameters (mean, max, min and std). I finally obtain 4 lists with 23 values, representing the parameters for each device.

```<code>    var_names <- ls(envir = globalenv(), pattern = "^Device")
    Corrected_values<- mget(var_names)

    Device_mean <- lapply(Corrected_values, mean)
    Device_max <- lapply(Corrected_values, max)
    Device_min <- lapply(Corrected_values, min)
    Device_sd <- lapply(Corrected_values, sd)
</code>```

Now I wish to create a data frame "Device" that will be a merge of these 4 lists. This data frame (or matrix) with 4 columns and 23 rows will then be exportable for further uses. Up to now, all my attempts resulted in a wrong matrix.

```<code>    # rename the column names
    cols <- c("Mean", "Maximum", "Minimum", "Stdv")
</code>```

Thanks for you help

答:
Actually what Rui Barradas proposes works but it appears to be because the

```<code>    f <- function(x){
      data.frame(Mean = mean(x), Maximum = max(x), Minimum = min(x), Stdv = sd(x))
    }
</code>```

automatically recognizes what "Mean = mean(x), Maximum = max(x), Minimum = min(x), Stdv = sd(x)" means whitout using the 4 lists created beforehand in the script.
Unfortunately, it does not work if I wish to add some other lists created. Indeed, now imagine I have 8 lists instead of the first 4 lists presented before:

```<code>var_names <- ls(envir = globalenv(), pattern = "^Device")
Corr_values<- mget(var_names)

Device_mean <- lapply(Corr_values, mean) #list 1
Device_max <- lapply(Corr_values, max) #list2
Device_min <- lapply(Corr_values, min) #list3
Device_sd <- lapply(Corr_values, sd) #list4

hours_per_year <- 365*24
multiply <- function(x, factor) {
x * hours_per_year}
Device_average_annual_dose <- lapply(Device_mean, multiply, factor = hours_per_year) #list5

var_names_dates <- ls(envir = globalenv(), pattern = "^Date")
Corr_dates<- mget(var_names_dates)
Device_hours_with_values <- lapply(Corr_dates, length) #list6

a <- (100/hours_per_year)
multiply <- function(x, factor) {
x * a}
Device_availability <- lapply(Device_hours_with_values, multiply, factor = a) #list7

subtract_me = 100
Device_unavailability <- lapply(Device_availability, function(x, subt_amnt) subt_amnt - x,subt_amnt = subtract_me) #list8
</code>```

These 8 lists are correctly stored in R. but in this case, when I try what you propose to me to merge the 8 lists by using the 8 list names, I receive the error message:

```<code>    Error in max(x) : invalid 'type' (list) of argument
</code>```

I do not understand because these are precisely some lists that I whish to merge...

Body:
Apologies in advance if this has already been asked elsewhere, but I've tried different attempts and nothing has worked so far.

I study the data from 23 devices mesuring air pollution. For each device, I am interested in 4 parameters (mean, max, min and std). I finally obtain 4 lists with 23 values, representing the parameters for each device.

    var_names <- ls(envir = globalenv(), pattern = "^Device")
    Corrected_values<- mget(var_names)

    Device_mean <- lapply(Corrected_values, mean)
    Device_max <- lapply(Corrected_values, max)
    Device_min <- lapply(Corrected_values, min)
    Device_sd <- lapply(Corrected_values, sd)

Now I wish to create a data frame "Device" that will be a merge of these 4 lists. This data frame (or matrix) with 4 columns and 23 rows will then be exportable for further uses. Up to now, all my attempts resulted in a wrong matrix.

    # rename the column names
    cols <- c("Mean", "Maximum", "Minimum", "Stdv")

Thanks for you help

Body:
Actually what Rui Barradas proposes works but it appears to be because the

    f <- function(x){
      data.frame(Mean = mean(x), Maximum = max(x), Minimum = min(x), Stdv = sd(x))
    }

automatically recognizes what "Mean = mean(x), Maximum = max(x), Minimum = min(x), Stdv = sd(x)" means whitout using the 4 lists created beforehand in the script.
Unfortunately, it does not work if I wish to add some other lists created. Indeed, now imagine I have 8 lists instead of the first 4 lists presented before:

var_names <- ls(envir = globalenv(), pattern = "^Device")
Corr_values<- mget(var_names)

Device_mean <- lapply(Corr_values, mean) #list 1
Device_max <- lapply(Corr_values, max) #list2
Device_min <- lapply(Corr_values, min) #list3
Device_sd <- lapply(Corr_values, sd) #list4

hours_per_year <- 365*24
multiply <- function(x, factor) {
x * hours_per_year}
Device_average_annual_dose <- lapply(Device_mean, multiply, factor = hours_per_year) #list5

var_names_dates <- ls(envir = globalenv(), pattern = "^Date")
Corr_dates<- mget(var_names_dates)
Device_hours_with_values <- lapply(Corr_dates, length) #list6

a <- (100/hours_per_year)
multiply <- function(x, factor) {
x * a}
Device_availability <- lapply(Device_hours_with_values, multiply, factor = a) #list7

subtract_me = 100
Device_unavailability <- lapply(Device_availability, function(x, subt_amnt) subt_amnt - x,subt_amnt = subtract_me) #list8

These 8 lists are correctly stored in R. but in this case, when I try what you propose to me to merge the 8 lists by using the 8 list names, I receive the error message:

    Error in max(x) : invalid 'type' (list) of argument

I do not understand because these are precisely some lists that I whish to merge...


问:
Finding the sum of non-zero individual values in nested dictionaries
So I wrote this code, I am trying to find the sum of each non-zero rating of each book, in order to find the average of the ratings of each book, without including the zero ratings of each book.

This is what I have tried to do, it is working. But I couldn't figure out how to find the sum of each rating of each book and to find the average.

```<code>books = ['book1', 'book2', 'book3']
biglist = [{'user1' : {'book1' : 0, 'book2' : -2, 'book3' : 3}},
            {'user2' : {'book1' : 5, 'book2' : 0, 'book3' : -3}},
            {'user3' : {'book1' : 1, 'book2' : 5, 'book3' : 3}}]

total = dict()
count = 0
for list_item in biglist:
    for key, value in list_item.items():
        for key2, value2 in value.items():
            total[key2] = value2 + total.get(key2,0)
            for book in books:
                if value2 != 0 and book == key2:
                        count += 1
                        print(f"Found non-zero value, [{key2} : {value2}]
</code>```

答:
Something that should work with your datastructure. Collect all ratings, and then filter the individual lists. </p>

```<code>big_dict = {}
for book in books:
    big_dict[book] = []

# collect all ratings
for d in biglist:
    for _, ratings in d.items():
        for book in books:
            big_dict[book].append(ratings.get(book))

for book, rating in big_dict.items():
    # compute averages of filtered list
    average_rating = np.mean([a for a in rating if a != 0])
    print(book, average_rating)
</code>```

Body:
So I wrote this code, I am trying to find the sum of each non-zero rating of each book, in order to find the average of the ratings of each book, without including the zero ratings of each book.

This is what I have tried to do, it is working. But I couldn't figure out how to find the sum of each rating of each book and to find the average.

books = ['book1', 'book2', 'book3']
biglist = [{'user1' : {'book1' : 0, 'book2' : -2, 'book3' : 3}},
            {'user2' : {'book1' : 5, 'book2' : 0, 'book3' : -3}},
            {'user3' : {'book1' : 1, 'book2' : 5, 'book3' : 3}}]

total = dict()
count = 0
for list_item in biglist:
    for key, value in list_item.items():
        for key2, value2 in value.items():
            total[key2] = value2 + total.get(key2,0)
            for book in books:
                if value2 != 0 and book == key2:
                        count += 1
                        print(f"Found non-zero value, [{key2} : {value2}]

Body:
Something that should work with your datastructure. Collect all ratings, and then filter the individual lists.

big_dict = {}
for book in books:
    big_dict[book] = []

# collect all ratings
for d in biglist:
    for _, ratings in d.items():
        for book in books:
            big_dict[book].append(ratings.get(book))

for book, rating in big_dict.items():
    # compute averages of filtered list
    average_rating = np.mean([a for a in rating if a != 0])
    print(book, average_rating)


问:
Honeycomb webview flickering jittering
My app has a scrollview and a webview inside a LinearLayout.

When the Ads from millenial come in it happens some jittering and some webview parts get white.

I have tried ALL possible parameter combination and nothing works.

Does anyone a better solution or even a explanation?

Notice the blank text in the bottom:

Notice 9 10 11 and 11 sections:

thanks

答: The answer to this was removing millenial ads. It seems that their animation to bring the ad visible was interfering with the webview stuff.</p>

Title: Honeycomb webview flickering jittering


问:
Karate assertions for dynamic response
Response Actual:

```<code>{
"data": [
    {
      "last_name": "Bluth",
      "id": 1,
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg",
      "first_name": "George",
      "email": "george.bluth@reqres.in"
    },
    {
      "last_name": "Weaver",
      "id": 2,
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg",
      "first_name": "Janet",
      "email": "janet.weaver@reqres.in"
    }
  ]
}
</code>```

I have a Database object where it return array of first_name's

Expected:

```<code>{"George","Janet"}
</code>```

I am using scenario outline here as i have bunch of tests need to be check and output is dynamic. How can we write the assertions for this type of scenarios ???
something like response.data[].first_name == expected ??

答:
Sample Code:

```<code>Feature: Array Match

Scenario:
    * def act =
    """
{
  "per_page": 6,
  "total": 12,
  "ad": {
    "company": "StatusCode Weekly",
    "text": "A weekly newsletter focusing on software development, infrastructure, the server, performance, and the stack end of things.",
    "url": "http://statuscode.org/"
  },
  "data": [
    {
      "last_name": "Bluth",
      "id": 1,
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg",
      "first_name": "George",
      "email": "george.bluth@reqres.in"
    },
    {
      "last_name": "Weaver",
      "id": 2,
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg",
      "first_name": "Janet",
      "email": "janet.weaver@reqres.in"
    },
    {
      "last_name": "Wong",
      "id": 3,
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg",
      "first_name": "Emma",
      "email": "emma.wong@reqres.in"
    },
    {
      "last_name": "Holt",
      "id": 4,
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg",
      "first_name": "Eve",
      "email": "eve.holt@reqres.in"
    },
    {
      "last_name": "Morris",
      "id": 5,
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/stephenmoon/128.jpg",
      "first_name": "Charles",
      "email": "charles.morris@reqres.in"
    },
    {
      "last_name": "Ramos",
      "id": 6,
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg",
      "first_name": "Tracey",
      "email": "tracey.ramos@reqres.in"
    }
  ],
  "page": 1,
  "total_pages": 2
}
    """
    * def exp = ["George","Janet","Emma","Eve","Charles","Tracey"]
    * match $act.data[*].first_name == exp
</code>```

Reference Link: https://github.com/intuit/karate#get-short-cut

Title: Karate assertions for dynamic response

Body:
Response Actual:

{
"data": [
    {
      "last_name": "Bluth",
      "id": 1,
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg",
      "first_name": "George",
      "email": "george.bluth@reqres.in"
    },
    {
      "last_name": "Weaver",
      "id": 2,
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg",
      "first_name": "Janet",
      "email": "janet.weaver@reqres.in"
    }
  ]
}

I have a Database object where it return array of first_name's

Expected:

{"George","Janet"}

I am using scenario outline here as i have bunch of tests need to be check and output is dynamic. How can we write the assertions for this type of scenarios ???
something like response.data[].first_name == expected ??

Body:
Sample Code:

Feature: Array Match

Scenario:
    * def act =
    """
{
  "per_page": 6,
  "total": 12,
  "ad": {
    "company": "StatusCode Weekly",
    "text": "A weekly newsletter focusing on software development, infrastructure, the server, performance, and the stack end of things.",
    "url": "http://statuscode.org/"
  },
  "data": [
    {
      "last_name": "Bluth",
      "id": 1,
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg",
      "first_name": "George",
      "email": "george.bluth@reqres.in"
    },
    {
      "last_name": "Weaver",
      "id": 2,
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg",
      "first_name": "Janet",
      "email": "janet.weaver@reqres.in"
    },
    {
      "last_name": "Wong",
      "id": 3,
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg",
      "first_name": "Emma",
      "email": "emma.wong@reqres.in"
    },
    {
      "last_name": "Holt",
      "id": 4,
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg",
      "first_name": "Eve",
      "email": "eve.holt@reqres.in"
    },
    {
      "last_name": "Morris",
      "id": 5,
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/stephenmoon/128.jpg",
      "first_name": "Charles",
      "email": "charles.morris@reqres.in"
    },
    {
      "last_name": "Ramos",
      "id": 6,
      "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg",
      "first_name": "Tracey",
      "email": "tracey.ramos@reqres.in"
    }
  ],
  "page": 1,
  "total_pages": 2
}
    """
    * def exp = ["George","Janet","Emma","Eve","Charles","Tracey"]
    * match $act.data[*].first_name == exp

Reference Link: https://github.com/intuit/karate#get-short-cut


问:
How to delete tableView cell and remove data from firebase
Stuck, trying to swipe left on an event so that it deletes from the TableView and deletes from Firebase real-time-database. This is what I have so far. Stuck on implementing so that it goes with my working project.

Firebase database

Table View

```<code>    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        let ref = Database.database().reference(fromURL: yourProjectURL)
        let eventRef = ref.child("events").child(postEvents[indexPath.row].key)
        // ^^ this only works if the value is set to the firebase uid, otherwise you need to pull that data from somewhere else.
        postEvents.removeValue()
        postEvents.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
    }
}
</code>```

what goes in ".reference(fromURL: yourProjectURL)" for me? is It ->  .child("events")

Event Class

```<code>struct Events {

let eventId: String
let eventName: String
let city: String
let state: String
let country: String
let startDate: String
let endDate: String
let itinerary: String
let isPrivate: Bool
var members: [String]
var isJoined : Bool
let creator : String

init?(eventId: String, dict: [String: Any]) {

    //let dateFormatter = DateFormatter()
    //dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss +zzzz"

    guard let eventName = dict["eventName"] as? String,
        let city = dict["city"] as? String,
        let country = dict["country"] as? String,
        let state = dict["state"] as? String,
        let startDate = dict["startDate"] as? String,
        let endDate = dict["endDate"] as? String,
        let itinerary = dict["itinerary"] as? String,
        let creator = dict["creator"] as? String,
        let eventType = dict["eventType"] as? String

        else { return nil }

    self.eventName = eventName
    self.city = city
    self.country = country
    self.state = state
    self.startDate = startDate
    self.endDate = endDate
    self.itinerary = itinerary
    self.isPrivate = eventType == "private" ? true : false
    self.eventId = eventId
    var members = [String]()
    if let dic = dict["members"] as? [String:String] {
        for (_,value) in dic {
            members.append(value)
        }
    }
    self.isJoined =  members.contains(Auth.auth().currentUser!.uid)
    self.members = members
    self.creator = creator

}}
</code>```

On postEvents.removeValue() I get an error "Value of type '[Events]' has no member 'removeValue'". How do I fix that?

答:
To delete a node in Firebase, first establish the path to that node by creating a reference to it, and then removeValue on that reference (or set the ref to nil which also removes it)

In brief

```<code>let eventToDelete = dataSource[indexPath.row] //get the event from the dataSource
let firebaseKey = eventToDelete.eventId //assuming the eventId is the node key
let eventRef = my_firebase.child("events").child(firebaseKey)
eventRef.removeValue()  //or eventRef.setValue(nil)
</code>```

Body:
Stuck, trying to swipe left on an event so that it deletes from the TableView and deletes from Firebase real-time-database. This is what I have so far. Stuck on implementing so that it goes with my working project.

Firebase database

Table View

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        let ref = Database.database().reference(fromURL: yourProjectURL)
        let eventRef = ref.child("events").child(postEvents[indexPath.row].key)
        // ^^ this only works if the value is set to the firebase uid, otherwise you need to pull that data from somewhere else.
        postEvents.removeValue()
        postEvents.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
    }
}

what goes in ".reference(fromURL: yourProjectURL)" for me? is It ->  .child("events")

Event Class

struct Events {

let eventId: String
let eventName: String
let city: String
let state: String
let country: String
let startDate: String
let endDate: String
let itinerary: String
let isPrivate: Bool
var members: [String]
var isJoined : Bool
let creator : String

init?(eventId: String, dict: [String: Any]) {

    //let dateFormatter = DateFormatter()
    //dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss +zzzz"

    guard let eventName = dict["eventName"] as? String,
        let city = dict["city"] as? String,
        let country = dict["country"] as? String,
        let state = dict["state"] as? String,
        let startDate = dict["startDate"] as? String,
        let endDate = dict["endDate"] as? String,
        let itinerary = dict["itinerary"] as? String,
        let creator = dict["creator"] as? String,
        let eventType = dict["eventType"] as? String

        else { return nil }

    self.eventName = eventName
    self.city = city
    self.country = country
    self.state = state
    self.startDate = startDate
    self.endDate = endDate
    self.itinerary = itinerary
    self.isPrivate = eventType == "private" ? true : false
    self.eventId = eventId
    var members = [String]()
    if let dic = dict["members"] as? [String:String] {
        for (_,value) in dic {
            members.append(value)
        }
    }
    self.isJoined =  members.contains(Auth.auth().currentUser!.uid)
    self.members = members
    self.creator = creator

}}

On postEvents.removeValue() I get an error "Value of type '[Events]' has no member 'removeValue'". How do I fix that?

Body:
To delete a node in Firebase, first establish the path to that node by creating a reference to it, and then removeValue on that reference (or set the ref to nil which also removes it)

In brief

let eventToDelete = dataSource[indexPath.row] //get the event from the dataSource
let firebaseKey = eventToDelete.eventId //assuming the eventId is the node key
let eventRef = my_firebase.child("events").child(firebaseKey)
eventRef.removeValue()  //or eventRef.setValue(nil)


问:
How does a JavaScript front-end framework handle routing?
A few days ago I tried making a routing system with pure javascript without a framework

But I can only do it using hash

I know that you can use history.pushState

But then when I reload the page, the browser will think it's a different URL and send a GET request to that new URL

I also tried to intercept the request using a service worker, but that doesn't seem to work either

So, how can a JavaScript framework like Vue/React/Angular handle routing without hash and manage to redirect the request?

答:
But then when I reload the page, the browser will think it's a different URL and send a GET request to that new URL

Yes. That's the point.

pushState is a way of saying "I am changing the page with JavaScript. The state I'm changing it to is the same as you would get if you went to this URL.".

This lets bookmarks, search engines, and back/forward work.

So, how can a JavaScript framework like Vue/React/Angular handle routing without hash and manage to redirect the request?

They can't, at least not by themselves. You need something on the server to generate the page in the right state. e.g. a server-side rendering framework compatible with the frontend framework you are using.


问:
SQL Connection class won't connect when run from a Blazor App
I am trying to use the following code to query a database from a Blazor web page, the exception is as follows

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 44 - Could not compose Service Principal Name (SPN) for Windows Integrated Authentication. Possible causes are server(s) incorrectly specified to connection API calls, Domain Name System (DNS) lookup failure or memory shortage)

System.PlatformNotSupportedException: System.Net.Dns:GetHostByName is not supported on this platform.

at System.Net.Dns.GetHostByName (System.String hostName) <0x38c58e8 + 0x0001c> in :0
  ...

When I run the same code in a traditional web or console app the connection opens/closes instantly.

```<code>public class MySQLHelper
{
    public static SqlConnection GetConnection()
    {
        string m_connectionString = "connection string here";
        SqlConnection sqlConn = new SqlConnection(m_connectionString);
        sqlConn.Open(); // fails to open when called from a regular registered 'service' in Blazor

        return sqlConn;
    }
}
</code>```

Thoughts?

答:
System.PlatformNotSupportedException:

Indicates that you are trying this from a Blazor WebAssembly app.

A lot of API's are not (cannot be) supported on Wasm, Blazor is limited to the Browser security rules.

You cannot access a database directly from WebAssembly (or JavaScript).

Either use the JS IndexDb for small DBs on the client computer (that means not shared between users) or use a Server for Data access. Take a look at the "Blazor Server" or the "Blazor WebAssembly Hosted" project models.

Body:
I am trying to use the following code to query a database from a Blazor web page, the exception is as follows

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 44 - Could not compose Service Principal Name (SPN) for Windows Integrated Authentication. Possible causes are server(s) incorrectly specified to connection API calls, Domain Name System (DNS) lookup failure or memory shortage)

System.PlatformNotSupportedException: System.Net.Dns:GetHostByName is not supported on this platform.

at System.Net.Dns.GetHostByName (System.String hostName) <0x38c58e8 + 0x0001c> in :0
  ...

When I run the same code in a traditional web or console app the connection opens/closes instantly.

public class MySQLHelper
{
    public static SqlConnection GetConnection()
    {
        string m_connectionString = "connection string here";
        SqlConnection sqlConn = new SqlConnection(m_connectionString);
        sqlConn.Open(); // fails to open when called from a regular registered 'service' in Blazor

        return sqlConn;
    }
}

Thoughts?


问:
How do i disable a function in a function?
I have a game over function here:

```<code>function gameOver() {
    ctx.fillStyle = "#f00";
    ctx.fillText ("GAME OVER!", 424, 236.25);
}
</code>```

I also have a score function here:

```<code>function Score() {
    ctx.fillStyle = "#000"
    ctx.font = "27px Ariel";
    ctx.fillText ("Score: " + score, 18.89, 30);
}
</code>```

What i want is when i call the game over function then i want the score to not be visible. How can i do that???

I have tried:

```<code>function gameOver() {
    ctx.fillStyle = "#f00";
    ctx.fillText ("GAME OVER!", 424, 236.25);
    Score() = "none";
}
</code>```

but it obviously didn't work, lol. Im kind of new to this, sorry.

答:
I think you are calling your score function after your gameOver function. Call the score function first.

What you can also do (to answer your question) is set the score function to something else:

let Score = () => { original score function body here };

Then inside gameOver, you can set:

Score = () => {}; // empty function does nothing

Body:
I have a game over function here:

function gameOver() {
    ctx.fillStyle = "#f00";
    ctx.fillText ("GAME OVER!", 424, 236.25);
}

I also have a score function here:

function Score() {
    ctx.fillStyle = "#000"
    ctx.font = "27px Ariel";
    ctx.fillText ("Score: " + score, 18.89, 30);
}

What i want is when i call the game over function then i want the score to not be visible. How can i do that???

I have tried:

function gameOver() {
    ctx.fillStyle = "#f00";
    ctx.fillText ("GAME OVER!", 424, 236.25);
    Score() = "none";
}

but it obviously didn't work, lol. Im kind of new to this, sorry.


问:
phpmyadmin - count(): Parameter must be an array or an object that implements Countable
I've uploaded the backup to a table, opening the table I see this:

```<code>Warning in ./libraries/sql.lib.php#601
count(): Parameter must be an array or an object that implements Countable

Backtrace

./libraries/sql.lib.php#2038: PMA_isRememberSortingOrder(array)
./libraries/sql.lib.php#1984: PMA_executeQueryAndGetQueryResponse(
array,
boolean true,
string 'alternativegirls',
string 'tgp_photo',
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
string '',
string './themes/pmahomme/img/',
NULL,
NULL,
NULL,
string 'SELECT * FROM `tgp_photo`',
NULL,
NULL,
)
./sql.php#216: PMA_executeQueryAndSendQueryResponse(
array,
boolean true,
string 'alternativegirls',
string 'tgp_photo',
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
string '',
string './themes/pmahomme/img/',
NULL,
NULL,
NULL,
string 'SELECT * FROM `tgp_photo`',
NULL,
NULL,
)
./index.php#53: include(./sql.php)
</code>```

Inside phpMyAdmin...

PHP is 7.2, the server is Ubuntu 16.04, installed yesterday.

Looking for I saw that some have this error in their code, but I did not find anyone who received it in phpMyAdmin...

What should I do? Is that my error? A phpmyadmin error? wait update ? I go back to PHP 7.1?

答:
Add the phpmyadmin ppa</p>

```<code>sudo add-apt-repository ppa:phpmyadmin/ppa
sudo apt-get update
sudo apt-get upgrade
</code>```

Body:
I've uploaded the backup to a table, opening the table I see this:

Warning in ./libraries/sql.lib.php#601
count(): Parameter must be an array or an object that implements Countable

Backtrace

./libraries/sql.lib.php#2038: PMA_isRememberSortingOrder(array)
./libraries/sql.lib.php#1984: PMA_executeQueryAndGetQueryResponse(
array,
boolean true,
string 'alternativegirls',
string 'tgp_photo',
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
string '',
string './themes/pmahomme/img/',
NULL,
NULL,
NULL,
string 'SELECT * FROM `tgp_photo`',
NULL,
NULL,
)
./sql.php#216: PMA_executeQueryAndSendQueryResponse(
array,
boolean true,
string 'alternativegirls',
string 'tgp_photo',
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
string '',
string './themes/pmahomme/img/',
NULL,
NULL,
NULL,
string 'SELECT * FROM `tgp_photo`',
NULL,
NULL,
)
./index.php#53: include(./sql.php)

Inside phpMyAdmin...

PHP is 7.2, the server is Ubuntu 16.04, installed yesterday.

Looking for I saw that some have this error in their code, but I did not find anyone who received it in phpMyAdmin...

What should I do? Is that my error? A phpmyadmin error? wait update ? I go back to PHP 7.1?

Body:
Add the phpmyadmin ppa

sudo add-apt-repository ppa:phpmyadmin/ppa
sudo apt-get update
sudo apt-get upgrade


问:
Select id and save it in a variable with Entity Framework
I am identified a login with Windows Forms and Entity Framework. I want to be able to select the user ID and add it to a variable to use it as a kind of session variable system wide.

This is the code I am using

```<code>using (var context = new AppDbContext())
{
    var id = context.user.Where(x => x.email == textBox1.Text)
                         .Select(x => x.userId ).SingleOrDefault();
}

MessageBox.Show("Id" +id);
</code>```

I get this message by box:

idMicrosoft.EntityFrameworkCore.Query.Internal.EntityQueryable'1 [system.model.user]

What is the best way to get the id and save it in a variable and thus be able to use it in other forms?

答:
I'd write this query as

```<code>var id = context.user.SingleOrDefault(u => u.Email == textBox1.Text)?.UserId
</code>```

Make sure you guard your code around what it means if id is null. If it can't be null and should only be one, Single() will work.

Body:
I am identified a login with Windows Forms and Entity Framework. I want to be able to select the user ID and add it to a variable to use it as a kind of session variable system wide.

This is the code I am using

using (var context = new AppDbContext())
{
    var id = context.user.Where(x => x.email == textBox1.Text)
                         .Select(x => x.userId ).SingleOrDefault();
}

MessageBox.Show("Id" +id);

I get this message by box:

idMicrosoft.EntityFrameworkCore.Query.Internal.EntityQueryable'1 [system.model.user]

What is the best way to get the id and save it in a variable and thus be able to use it in other forms?

Body:
I'd write this query as

var id = context.user.SingleOrDefault(u => u.Email == textBox1.Text)?.UserId

Make sure you guard your code around what it means if id is null. If it can't be null and should only be one, Single() will work.


问:
Get page URL from markup in Razor Pages
In MVC, I think we used @Html.Url() to get the URL of a page from the markup. In Razor Pages, this no longer appears to be available.

Razor Pages has some great tag helpers that help create page links. But what if you want a page URL, such as from JavaScript? Does Razor Pages have any tools for getting the URL string?

答:
This will bring the current page url:

@Url.RouteUrl(ViewContext.RouteData.Values);
```

<h3>[UPDATE]</h3>

<p>The above implementation will return current page url without <code>QueryString</code> values e.g. <code>/Users/Index</code></p>

<p>To include <code>QueryString</code> values after <code>?</code> use below implementation:</p>

<pre class="lang-html prettyprint-override"><code>@{
    var routeUrl = Url.RouteUrl(ViewContext.RouteData.Values);
    var qsPath = ViewContext.HttpContext.Request.QueryString.Value;
    var returnUrl = $"{routeUrl}{qsPath}";
}
</code>```

The end result will include route and query string values:

// returnUrl = "/Users/Index?p=1&s=5"
```

Title: Get page URL from markup in Razor Pages

Body:
This will bring the current page url:

@Url.RouteUrl(ViewContext.RouteData.Values);

[UPDATE]

The above implementation will return current page url without QueryString values e.g. /Users/Index

To include QueryString values after ? use below implementation:

@{
    var routeUrl = Url.RouteUrl(ViewContext.RouteData.Values);
    var qsPath = ViewContext.HttpContext.Request.QueryString.Value;
    var returnUrl = $"{routeUrl}{qsPath}";
}

The end result will include route and query string values:

// returnUrl = "/Users/Index?p=1&s=5"


问:
What is Java 8 functional way to implement switch-like construction without "switch" and "if" statements using only java.util
I wrote next code without using if statements and creating own functional API.
And it checks some condition.

```<code>import java.util.*;

public class Test {
    public static void main(String[] args) {
        String smth = new Random().nextBoolean() ? "something" : null;

        Optional.ofNullable(smth)
                .filter(i -> !i.isEmpty())
                .<Runnable>map(i -> () -> System.out.println("Success " + i))
                .orElse(() -> System.out.println("error"))
                .run();
    }
}
</code>```

How can I implement switch statement using only java.util.*?

答:
JMPL is simple java library, which could emulate some of the features pattern matching, using Java 8 features.
This library support many patterns, which could see in many languages, such C#, Scala, Rust, Swift.</p>

```<code>    matches(data).as(
      new Person("man"),    () ->  System.out.println("man");
      new Person("woman"),  () ->  System.out.println("woman");
      new Person("child"),  () ->  System.out.println("child");
      Null.class,           () ->  System.out.println("Null value "),
      Else.class,           () ->  System.out.println("Default value: " + data)
   );

   matches(data).as(
      Integer.class, i  -> { System.out.println(i * i); },
      Byte.class,    b  -> { System.out.println(b * b); },
      Long.class,    l  -> { System.out.println(l * l); },
      String.class,  s  -> { System.out.println(s * s); },
      Null.class,    () -> { System.out.println("Null value "); },
      Else.class,    () -> { System.out.println("Default value: " + data); }
   );

   matches(figure).as(
      Rectangle.class, (int w, int h) -> System.out.println("square: " + (w * h)),
      Circle.class,    (int r)        -> System.out.println("square: " + (2 * Math.PI * r)),
      Else.class,      ()             -> System.out.println("Default square: " + 0)
   );
</code>```

Body:
I wrote next code without using if statements and creating own functional API.
And it checks some condition.

import java.util.*;

public class Test {
    public static void main(String[] args) {
        String smth = new Random().nextBoolean() ? "something" : null;

        Optional.ofNullable(smth)
                .filter(i -> !i.isEmpty())
                .<Runnable>map(i -> () -> System.out.println("Success " + i))
                .orElse(() -> System.out.println("error"))
                .run();
    }
}

How can I implement switch statement using only java.util.*?

Body:
JMPL is simple java library, which could emulate some of the features pattern matching, using Java 8 features.
This library support many patterns, which could see in many languages, such C#, Scala, Rust, Swift.

    matches(data).as(
      new Person("man"),    () ->  System.out.println("man");
      new Person("woman"),  () ->  System.out.println("woman");
      new Person("child"),  () ->  System.out.println("child");
      Null.class,           () ->  System.out.println("Null value "),
      Else.class,           () ->  System.out.println("Default value: " + data)
   );

   matches(data).as(
      Integer.class, i  -> { System.out.println(i * i); },
      Byte.class,    b  -> { System.out.println(b * b); },
      Long.class,    l  -> { System.out.println(l * l); },
      String.class,  s  -> { System.out.println(s * s); },
      Null.class,    () -> { System.out.println("Null value "); },
      Else.class,    () -> { System.out.println("Default value: " + data); }
   );

   matches(figure).as(
      Rectangle.class, (int w, int h) -> System.out.println("square: " + (w * h)),
      Circle.class,    (int r)        -> System.out.println("square: " + (2 * Math.PI * r)),
      Else.class,      ()             -> System.out.println("Default square: " + 0)
   );


问:
Google Chrome showing black border on focus state for button user agent styles
Recently i was working on a web design project, and noticed something odd, after the last Google Chrome update. The default border style(user agent style) for button is changed, and which is looking visually annoying to me.

Is there any method to modify/restore the default browser styles, i.e., user agent styles permanently?

here are some images of the problem:

i have also checked other websites and even google

also checked the dev tool, found this border styles applied on the focus state of the button

答:
This is because the new chrome update
https://developers.google.com/web/updates/2020/05/nic83#forms

you can override black outline in most cases by

```<code>*,*:focus,*:hover{
    outline:none;
}
</code>```

and you can see this article

https://web.dev/style-focus/#use-:focus-visible-to-selectively-show-a-focus-indicator

if you want to remove outline just for mouse user.

Body:
This is because the new chrome update
https://developers.google.com/web/updates/2020/05/nic83#forms

you can override black outline in most cases by

*,*:focus,*:hover{
    outline:none;
}

and you can see this article

https://web.dev/style-focus/#use-:focus-visible-to-selectively-show-a-focus-indicator

if you want to remove outline just for mouse user.


问:
ng build and ng build --prod not loading style or script files
In my application I can able to build and do the prodution build but when I try to run those version getting the error in the console.

style or script files faild to load .
@angular/cli": "~9.1.1",

Please see the imageenter image description here

THanks

答:
It looks that you do not properly configured your deployment sever. When you build, you are not using Angular-CLI anymore. Your shuld be using a Server (like, for example, Apache or Nginx). And, in that given server environment, you need to enable rewrite rules; otherwise it will not work and you get 404 errors (as you show).

Take a look to Angular's deployment guide: https://angular.io/guide/deployment#server-configuration They give you file examples depending on server type.


问:
Exclude current observation from computation in dplyr pipe
I want to exclude the current observation from the function I am applying to my data in a dplyr pipe, because I want to know the value without this observation.

To keep it simple, let's compute the mean including the current observation and excluding this observation. The solution should be applicable to other computations or function (in my case, the Gini function from DescTools package).

Let's say we look at ice prices of three different ices (ice_id = ice identifier) at three different days (day).

```<code>da <- data.frame(ice_id = c(1,1,1,2,2,2,3,3,3), day = c(1,2,3,1,2,3,1,2,3), price = c(1.60,1.90,1.80,2.10,2.05,2.30,0.50,0.40,0.35))
da
  ice_id day price
1      1   1  1.60
2      1   2  1.90
3      1   3  1.80
4      2   1  2.10
5      2   2  2.05
6      2   3  2.30
7      3   1  0.50
8      3   2  0.40
9      3   3  0.35
</code>```

I want to add one column indicating the mean price of the ice including this day and one column indicating the mean price of the ice excluding this day.

```<code>da = da %>%
  group_by(ice_id) %>%
  mutate(mean_price = mean(price),
         mean_price_without = ?)
</code>```

How can I add the mean price without the current observation itself?

答:
For a general case to remove current observation and perform calculation, you could use map_dbl

```<code>library(dplyr)
library(purrr)
da %>%
  group_by(ice_id) %>%
  mutate(mean_price = mean(price),
         mean_price_without = map_dbl(day, ~mean(price[-.x])))
         #Or
         #mean_price_without = map_dbl(day, ~mean(price[day != .x])))
         #mean_price_without = map_dbl(row_number(), ~mean(price[-.x])))

#  ice_id   day price mean_price mean_price_without
#   <dbl> <dbl> <dbl>      <dbl>              <dbl>
#1      1     1  1.6       1.77               1.85
#2      1     2  1.9       1.77               1.7
#3      1     3  1.8       1.77               1.75
#4      2     1  2.1       2.15               2.17
#5      2     2  2.05      2.15               2.2
#6      2     3  2.3       2.15               2.08
#7      3     1  0.5       0.417              0.375
#8      3     2  0.4       0.417              0.425
#9      3     3  0.35      0.417              0.45
</code>```

Body:
I want to exclude the current observation from the function I am applying to my data in a dplyr pipe, because I want to know the value without this observation.

To keep it simple, let's compute the mean including the current observation and excluding this observation. The solution should be applicable to other computations or function (in my case, the Gini function from DescTools package).

Let's say we look at ice prices of three different ices (ice_id = ice identifier) at three different days (day).

da <- data.frame(ice_id = c(1,1,1,2,2,2,3,3,3), day = c(1,2,3,1,2,3,1,2,3), price = c(1.60,1.90,1.80,2.10,2.05,2.30,0.50,0.40,0.35))
da
  ice_id day price
1      1   1  1.60
2      1   2  1.90
3      1   3  1.80
4      2   1  2.10
5      2   2  2.05
6      2   3  2.30
7      3   1  0.50
8      3   2  0.40
9      3   3  0.35

I want to add one column indicating the mean price of the ice including this day and one column indicating the mean price of the ice excluding this day.

da = da %>%
  group_by(ice_id) %>%
  mutate(mean_price = mean(price),
         mean_price_without = ?)

How can I add the mean price without the current observation itself?

Body:
For a general case to remove current observation and perform calculation, you could use map_dbl

library(dplyr)
library(purrr)
da %>%
  group_by(ice_id) %>%
  mutate(mean_price = mean(price),
         mean_price_without = map_dbl(day, ~mean(price[-.x])))
         #Or
         #mean_price_without = map_dbl(day, ~mean(price[day != .x])))
         #mean_price_without = map_dbl(row_number(), ~mean(price[-.x])))

#  ice_id   day price mean_price mean_price_without
#   <dbl> <dbl> <dbl>      <dbl>              <dbl>
#1      1     1  1.6       1.77               1.85
#2      1     2  1.9       1.77               1.7
#3      1     3  1.8       1.77               1.75
#4      2     1  2.1       2.15               2.17
#5      2     2  2.05      2.15               2.2
#6      2     3  2.3       2.15               2.08
#7      3     1  0.5       0.417              0.375
#8      3     2  0.4       0.417              0.425
#9      3     3  0.35      0.417              0.45


问:
IShellLink::SetIconLocation translates my icon path into %Program Files% which is WRONG
Does anyone know how to correct for this behavior?

Currently, when our installer installs our application, it obtains an IShellLink, then loads it up with the data necessary for our shortcut icon (in the start menu & desktop), and then uses IPersistFile::Save to write out the shortcut.

The problem is that the path specified for the icon, via IShellLink::SetIconLocation, is transformed into using %ProgramFiles%... which... for x64, is WRONG.

I've noticed that lots of other 32 bit software has this failing under x64 - but then I assumed that they were using %ProgamFiles% themselves, as a literal element in their .lnk creation code.  However, it appears to be that IShellLink is forcing this bug into existence, and I don't have a work-around (or perhaps that the link property editor in the shell is responsible for the problem and the underlying link is okay).

A few Google searches have turned up nothing... has anyone else encountered this or know of an article / example of how to force x64 windows to not muck this up?

Clarifying example:

```<code>hr = m_shell_link->SetIconLocation("C:\\Program Files (x86)\\Acme\\Prog.exe", 0);
</code>```

Will result in a shortcut which has the correct icon, but when you press "Change icon" in the shortcut properties page, will report "Windows can't find the file %ProgramFiles%\Acme\Prog.exe.")

答:
Convert the name into a short filename, and it will only convert the drive letter, yet keep the correct path.</p>

```<code>        PWCHAR pIcon = L"C:\\Program Files (x86)\\Myfoo\\Bar.exe";
        DWORD dwLen = GetShortPathName(pIcon, NULL, 0);
        PWCHAR pShort = NULL;
        if (dwLen) {
            pShort = new WCHAR[dwLen];
            dwLen = GetShortPathName(pIcon, pShort, dwLen);
            if (!dwLen) {
                delete [] pShort;
                pShort = NULL;
            }
        }

        if (NULL == pShort) {
            psl->SetIconLocation(pIcon,iTmp);
        } else {
            psl->SetIconLocation(pShort,iTmp);
        }
        delete [] pShort;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Does anyone know how to correct for this behavior?

Currently, when our installer installs our application, it obtains an IShellLink, then loads it up with the data necessary for our shortcut icon (in the start menu & desktop), and then uses IPersistFile::Save to write out the shortcut.

The problem is that the path specified for the icon, via IShellLink::SetIconLocation, is transformed into using %ProgramFiles%... which... for x64, is WRONG.

I've noticed that lots of other 32 bit software has this failing under x64 - but then I assumed that they were using %ProgamFiles% themselves, as a literal element in their .lnk creation code.  However, it appears to be that IShellLink is forcing this bug into existence, and I don't have a work-around (or perhaps that the link property editor in the shell is responsible for the problem and the underlying link is okay).

A few Google searches have turned up nothing... has anyone else encountered this or know of an article / example of how to force x64 windows to not muck this up?

Clarifying example:

hr = m_shell_link->SetIconLocation("C:\\Program Files (x86)\\Acme\\Prog.exe", 0);

Will result in a shortcut which has the correct icon, but when you press "Change icon" in the shortcut properties page, will report "Windows can't find the file %ProgramFiles%\Acme\Prog.exe.")

Body:
Convert the name into a short filename, and it will only convert the drive letter, yet keep the correct path.

        PWCHAR pIcon = L"C:\\Program Files (x86)\\Myfoo\\Bar.exe";
        DWORD dwLen = GetShortPathName(pIcon, NULL, 0);
        PWCHAR pShort = NULL;
        if (dwLen) {
            pShort = new WCHAR[dwLen];
            dwLen = GetShortPathName(pIcon, pShort, dwLen);
            if (!dwLen) {
                delete [] pShort;
                pShort = NULL;
            }
        }

        if (NULL == pShort) {
            psl->SetIconLocation(pIcon,iTmp);
        } else {
            psl->SetIconLocation(pShort,iTmp);
        }
        delete [] pShort;


问:
pandas-like operations with index alignment in DolphinDB
In pandas, if I do binary operations on two DataFrames or Series with different indices, their indices are aligned, and rows with the same index value are computed like this:

```<code>>>> s1 = pd.Series([1,2,3,4], index=["a","a","b","c"])
>>> s2 = pd.Series([10,20,30,40], index=["a","a","a","c"])
>>> s1 + s2
a    11.0
a    21.0
a    31.0
a    12.0
a    22.0
a    32.0
b     NaN
c    44.0
dtype: float64
</code>```

I would like to know how to do an index-aligned operation in DolphinDB, for example:

```<code>s1 = table([1,2,3,4] as val, ["a","a","b","c"] as index)
s2 = table([10,20,30,40] as val, ["a","a","a","c"] as index)

// How do I do an index-aligned add operation?
</code>```

答:
You can use DolphinDB Orca API</p>

```<code>import dolphindb.orca as orca
s1=orca.Series([1,2,3,4], index=["a","a","b","c"])
s2=orca.Series([10,20,30,40], index=["a","a","a","c"])
s1+s2
>>> s1+s2
a    11.0
a    21.0
a    31.0
a    12.0
a    22.0
a    32.0
b     NaN
c    44.0
dtype: float64
</code>```

Body:
In pandas, if I do binary operations on two DataFrames or Series with different indices, their indices are aligned, and rows with the same index value are computed like this:

>>> s1 = pd.Series([1,2,3,4], index=["a","a","b","c"])
>>> s2 = pd.Series([10,20,30,40], index=["a","a","a","c"])
>>> s1 + s2
a    11.0
a    21.0
a    31.0
a    12.0
a    22.0
a    32.0
b     NaN
c    44.0
dtype: float64

I would like to know how to do an index-aligned operation in DolphinDB, for example:

s1 = table([1,2,3,4] as val, ["a","a","b","c"] as index)
s2 = table([10,20,30,40] as val, ["a","a","a","c"] as index)

// How do I do an index-aligned add operation?

Body:
You can use DolphinDB Orca API

import dolphindb.orca as orca
s1=orca.Series([1,2,3,4], index=["a","a","b","c"])
s2=orca.Series([10,20,30,40], index=["a","a","a","c"])
s1+s2
>>> s1+s2
a    11.0
a    21.0
a    31.0
a    12.0
a    22.0
a    32.0
b     NaN
c    44.0
dtype: float64


问:
Transform Numpy Arrays to specific 2 dimensional Form
Currently I work with numpy and have to transform large data sets. Starting point are some one-dimensional arrays. These should be combined to a large 2 dimensional array. I attach a small example how it should look like.

# Returns 16 arrays with four numbers in each array (from 0 to 3)
array = [np.arange(4) for i in range(16)]

# Each of these arrays should be transformed to become a two-dimensional shape=(2,2)
array.reshape((2,2))

1. Step:
# Subsequently, the first of all of them are to be brought together:
[[0,1,0,1,0,1,0,1,0,1, ...,0,1],
[2,3,2,3,2,3,2,3,2,3, ...,2,3]]

2. Step:
# Afterwards, the arrays are to be wrapped on the basis of a length (let's say 8). The result should look like this:
[[0,1,0,1,0,1,0,1],
[2,3,2,3,2,3,2,3],
[0,1,0,1,0,1,0,1],
[2,3,2,3,2,3,2,3]]

```

This is only a miniature example. I'm actually working with an array with the length of 64 that is to be converted to an array with the shape=(8, 8). And at the end I want to create a 2 dimensional array with the dimensions 416x416.

Edit: So my current question is, how do I get to the first and second step in the example above?

答:
Assuming that you have created array (as you described), try the following code:

```<code>chunkSize = 8      # No of columns in the result
# Reshape and bring together
array2 = np.hstack([ arr.reshape(2,2) for arr in array ])
# The final result
result = np.vstack(np.hsplit(array2, [ (n + 1) * chunkSize
    for n in range(int(array2.shape[1] / chunkSize) - 1) ]))
</code>```

Body:
Currently I work with numpy and have to transform large data sets. Starting point are some one-dimensional arrays. These should be combined to a large 2 dimensional array. I attach a small example how it should look like.

# Returns 16 arrays with four numbers in each array (from 0 to 3)
array = [np.arange(4) for i in range(16)]

# Each of these arrays should be transformed to become a two-dimensional shape=(2,2)
array.reshape((2,2))

1. Step:
# Subsequently, the first of all of them are to be brought together:
[[0,1,0,1,0,1,0,1,0,1, ...,0,1],
[2,3,2,3,2,3,2,3,2,3, ...,2,3]]

2. Step:
# Afterwards, the arrays are to be wrapped on the basis of a length (let's say 8). The result should look like this:
[[0,1,0,1,0,1,0,1],
[2,3,2,3,2,3,2,3],
[0,1,0,1,0,1,0,1],
[2,3,2,3,2,3,2,3]]

This is only a miniature example. I'm actually working with an array with the length of 64 that is to be converted to an array with the shape=(8, 8). And at the end I want to create a 2 dimensional array with the dimensions 416x416.

Edit: So my current question is, how do I get to the first and second step in the example above?

Body:
Assuming that you have created array (as you described), try the following code:

chunkSize = 8      # No of columns in the result
# Reshape and bring together
array2 = np.hstack([ arr.reshape(2,2) for arr in array ])
# The final result
result = np.vstack(np.hsplit(array2, [ (n + 1) * chunkSize
    for n in range(int(array2.shape[1] / chunkSize) - 1) ]))


问:
How can I customize Java Date Format
From the java doc, the MEDIUM format is:
MEDIUM is longer, such as Jan 12, 1952

https://docs.oracle.com/javase/1.5.0/docs/api/java/text/DateFormat.html

How can I customize it so that I does not display the year? And spell out "Jan" to January?

Do I need to do that myself?
* chop off the string after the ','
* have a table which map the month short name (Jan) to its long name (January)?

Thank you.

答:
In addition to the possibility of using SimpleDateFormat, there also exists DateTimeFormatter.

I think that DateTimeFormatter is the better option, because

It was introduced more recently (Java 8)

It is thread-save

One example:

```<code>import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Time {
  public static void main(String[] args) {
   LocalDateTime time = LocalDateTime.now();

   DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd. MMM");
   String timeDate = time.format(formatter);
   System.out.println(timeDate);
  }
}
</code>```

This will produce something like 30. May as output.

More information can be found here and there.

Title: How can I customize Java Date Format

Body:
In addition to the possibility of using SimpleDateFormat, there also exists DateTimeFormatter.

I think that DateTimeFormatter is the better option, because

It was introduced more recently (Java 8)

It is thread-save

One example:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Time {
  public static void main(String[] args) {
   LocalDateTime time = LocalDateTime.now();

   DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd. MMM");
   String timeDate = time.format(formatter);
   System.out.println(timeDate);
  }
}

This will produce something like 30. May as output.

More information can be found here and there.


问:
problem with declaring variable in php?
i have a variables like $srange0 , $srange1, $srange2 $srange3.

i am using to declare some value to each value using for loop.

```<code>for($i=0;$i<=3;$i++){
  $srange.$i = $i;
}
</code>```

but its not working ?

is there any alternative solution for this

答:
The properway to add these dynamic variables will be like this</p>

```<code>for($i=0;$i<=3;$i++){
   $name = 'srange'.$i;
   $$name = $i;
}
</code>```

Title: problem with declaring variable in php?

Body:
i have a variables like $srange0 , $srange1, $srange2 $srange3.

i am using to declare some value to each value using for loop.

for($i=0;$i<=3;$i++){
  $srange.$i = $i;
}

but its not working ?

is there any alternative solution for this

Body:
The properway to add these dynamic variables will be like this

for($i=0;$i<=3;$i++){
   $name = 'srange'.$i;
   $$name = $i;
}


答: What you're doing here with gameOver() is to change style and text, then immediately call Score() that overwrites your style and text. Just remove it from there and it should be fine :)

Title: How do i disable a function in a function?

Body:
I have a game over function here:

function gameOver() {
    ctx.fillStyle = "#f00";
    ctx.fillText ("GAME OVER!", 424, 236.25);
}

I also have a score function here:

function Score() {
    ctx.fillStyle = "#000"
    ctx.font = "27px Ariel";
    ctx.fillText ("Score: " + score, 18.89, 30);
}

What i want is when i call the game over function then i want the score to not be visible. How can i do that???

I have tried:

function gameOver() {
    ctx.fillStyle = "#f00";
    ctx.fillText ("GAME OVER!", 424, 236.25);
    Score() = "none";
}

but it obviously didn't work, lol. Im kind of new to this, sorry.


问:
I want to show error message in form validation when user doesn't put input
I wanted to make form validation. There is no syntax error but it doesnot work as I wanted.Is it due to error in js or Html elements? I watched a video but it works perfectly fine in that video but does not work for me. I am still a beginner in Javascript. I think Html and css works fine. Error on email is shown in username whereas error on email is shown what is written in Html element.
Here is image of result

    const form= document.getElementById('form');
    const username= document.getElementById('username');
    const email= document.getElementById('email');
    const password= document.getElementById('password');

    function showError(input,message){
    const formControl=input.parentElement;
    formControl.className='form-control error';
    const small= document.querySelector('small');
    small.innerText=message;
    }

    function showSuccess(input){
        const formControl=input.parentElement;
        formControl.className='form-control success';
    }

    function CheckErrors(inputArr){
        inputArr.forEach(function(input){
    if(input.value.trim()===''){
      showError(input,`${input.id} is required`);
    }
        });

    }

    form.addEventListener('submit',function(e){
        e.preventDefault();
        CheckErrors([username,email]);
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>:root{
    --success-color:aqua;
    --error-color:red;
}
.form-control.success input{
    border-color: var(--success-color);
}
.form-control.error input{
    border-color: var(--error-color);
}
.form-control small{
    color:var(--error-color);
    position: absolute;
    bottom: 0;
    left: 0;
    visibility: hidden;
}
.form-control.error small{
    visibility: visible;
}</code>```

    <form id="form" class="form">

Register

          Username
          <input type="text" id="username" placeholder="Enter Username">
          Errors

        Email
        <input type="text" id="email" placeholder="Enter Email">
        Errors

```

答:
You need to use  nextElementSibling not querySelector that will select only the first one found.

const form = document.getElementById('form');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');

function showError(input, message) {
  const formControl = input.parentElement;
  formControl.className = 'form-control error';
  const small = input.nextElementSibling; // update here
  small.innerText = message;
}

function showSuccess(input) {
  const formControl = input.parentElement;
  formControl.className = 'form-control success';
}

function CheckErrors(inputArr) {
  inputArr.forEach(function(input) {
    if (input.value.trim() === '') {
      showError(input, `${input.id} is required`);
    }
  });

}

form.addEventListener('submit', function(e) {
  e.preventDefault();
  CheckErrors([username, email]);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>:root {
  --success-color: aqua;
  --error-color: red;
}

.form-control.success input {
  border-color: var(--success-color);
}

.form-control.error input {
  border-color: var(--error-color);
}

.form-control small {
  color: var(--error-color);
  visibility: hidden;
}

.form-control.error small {
  visibility: visible;
}</code>```

  <form id="form" class="form">

Register

      Username
      <input type="text" id="username" placeholder="Enter Username">
      Errors

      Email
      <input type="text" id="email" placeholder="Enter Email">
      Errors
      <input type="submit">

  </form>```

Body:
I wanted to make form validation. There is no syntax error but it doesnot work as I wanted.Is it due to error in js or Html elements? I watched a video but it works perfectly fine in that video but does not work for me. I am still a beginner in Javascript. I think Html and css works fine. Error on email is shown in username whereas error on email is shown what is written in Html element.
Here is image of result

    const form= document.getElementById('form');
    const username= document.getElementById('username');
    const email= document.getElementById('email');
    const password= document.getElementById('password');

    function showError(input,message){
    const formControl=input.parentElement;
    formControl.className='form-control error';
    const small= document.querySelector('small');
    small.innerText=message;
    }

    function showSuccess(input){
        const formControl=input.parentElement;
        formControl.className='form-control success';
    }

    function CheckErrors(inputArr){
        inputArr.forEach(function(input){
    if(input.value.trim()===''){
      showError(input,`${input.id} is required`);
    }
        });

    }

    form.addEventListener('submit',function(e){
        e.preventDefault();
        CheckErrors([username,email]);
    });

:root{
    --success-color:aqua;
    --error-color:red;
}
.form-control.success input{
    border-color: var(--success-color);
}
.form-control.error input{
    border-color: var(--error-color);
}
.form-control small{
    color:var(--error-color);
    position: absolute;
    bottom: 0;
    left: 0;
    visibility: hidden;
}
.form-control.error small{
    visibility: visible;
}

    <form id="form" class="form">

Register

          Username
          <input type="text" id="username" placeholder="Enter Username">
          Errors

        Email
        <input type="text" id="email" placeholder="Enter Email">
        Errors

Body:
You need to use  nextElementSibling not querySelector that will select only the first one found.

const form = document.getElementById('form');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');

function showError(input, message) {
  const formControl = input.parentElement;
  formControl.className = 'form-control error';
  const small = input.nextElementSibling; // update here
  small.innerText = message;
}

function showSuccess(input) {
  const formControl = input.parentElement;
  formControl.className = 'form-control success';
}

function CheckErrors(inputArr) {
  inputArr.forEach(function(input) {
    if (input.value.trim() === '') {
      showError(input, `${input.id} is required`);
    }
  });

}

form.addEventListener('submit', function(e) {
  e.preventDefault();
  CheckErrors([username, email]);
});

:root {
  --success-color: aqua;
  --error-color: red;
}

.form-control.success input {
  border-color: var(--success-color);
}

.form-control.error input {
  border-color: var(--error-color);
}

.form-control small {
  color: var(--error-color);
  visibility: hidden;
}

.form-control.error small {
  visibility: visible;
}

<div class="container">
  <form id="form" class="form">
    <h2>Register</h2>
    <div class="form-control">
      <label for="username">Username</label>
      <input type="text" id="username" placeholder="Enter Username">
      <small>Errors</small>
    </div>
    <div class="form-control">
      <label for="email">Email</label>
      <input type="text" id="email" placeholder="Enter Email">
      <small>Errors</small>
      <input type="submit">
    </div>
  </form>


问:
Non-unary type constructor bounded by unary type constructor
The title is attempting to describe the following subtyping

```<code>implicitly[Map[Int, String] <:< Iterable[(Int, String)]]
</code>```

Type parameter A is inferred to (Int, String) here

```<code>def foo[A](cc: Iterable[A]): A = cc.head
lazy val e: (Int, String) = foo(Map.empty[Int, String])
</code>```

however attempting to achieve similar effect using type parameter bounds the best I can do is explicitly specifying arity of the type constructor like so

```<code>def foo[F[x,y] <: Iterable[(x,y)], A, B](cc: F[A, B]): (A, B) = cc.head
lazy val e: (Int, String) = foo(Map.empty[Int, String])
</code>```

because the following errors

```<code>def foo[F[x] <: Iterable[x], A](cc: F[A]) = cc.head
lazy val e: (Int, String) = foo(Map.empty[Int, String])
// type mismatch;
// [error]  found   : A
// [error]  required: (Int, String)
// [error]   lazy val e: (Int, String) = foo(Map.empty[Int, String])
// [error]                                  ^
</code>```

Hence using Iterable as upper bound it seems we need one signature to handle unary type constructors Seq and Set, and a separate signature to handle 2-arity type constructor Map

```<code>def foo[F[x] <: Iterable[x], A](cc: F[A]): A                  // When F is Seq or Set
def foo[F[x,y] <: Iterable[(x,y)], A, B](cc: F[A, B]): (A, B) // When F is Map
</code>```

Is there a way to have a single signature using type bounds that works for all three? Putting it differently, how could we write, say, an extension method that works across all collections?

答:
I think the issue here is that F is set to Map, and kindness is wrong. You would have to have say: I have some type X, that extends F[A], so that when I upcast it, I can use it as F[A] - which in turn we want to be a subtype of Iterable[A]. If we ask about it this way, it sounds hard.

Which is why I personally would just stay at:

```<code>@ def foo[A](x: Iterable[A]): A = x.head
defined function foo

@ foo(List(1 -> "test"))
res24: (Int, String) = (1, "test")

@ foo(Map(1 -> "test"))
res25: (Int, String) = (1, "test")
</code>```

"Give me any x that is an instance of Iterable[A] for A".

If I had to do some derivation... I would probably also go this way. I think this limitation is the reason CanBuildFrom works the way it works - providing matching for part of the type is hard, especially in cases like Map, so let's provide a whole type at once as a parameter, to limit the number of inference needed.

Body:
The title is attempting to describe the following subtyping

implicitly[Map[Int, String] <:< Iterable[(Int, String)]]

Type parameter A is inferred to (Int, String) here

def foo[A](cc: Iterable[A]): A = cc.head
lazy val e: (Int, String) = foo(Map.empty[Int, String])

however attempting to achieve similar effect using type parameter bounds the best I can do is explicitly specifying arity of the type constructor like so

def foo[F[x,y] <: Iterable[(x,y)], A, B](cc: F[A, B]): (A, B) = cc.head
lazy val e: (Int, String) = foo(Map.empty[Int, String])

because the following errors

def foo[F[x] <: Iterable[x], A](cc: F[A]) = cc.head
lazy val e: (Int, String) = foo(Map.empty[Int, String])
// type mismatch;
// [error]  found   : A
// [error]  required: (Int, String)
// [error]   lazy val e: (Int, String) = foo(Map.empty[Int, String])
// [error]                                  ^

Hence using Iterable as upper bound it seems we need one signature to handle unary type constructors Seq and Set, and a separate signature to handle 2-arity type constructor Map

def foo[F[x] <: Iterable[x], A](cc: F[A]): A                  // When F is Seq or Set
def foo[F[x,y] <: Iterable[(x,y)], A, B](cc: F[A, B]): (A, B) // When F is Map

Is there a way to have a single signature using type bounds that works for all three? Putting it differently, how could we write, say, an extension method that works across all collections?

Body:
I think the issue here is that F is set to Map, and kindness is wrong. You would have to have say: I have some type X, that extends F[A], so that when I upcast it, I can use it as F[A] - which in turn we want to be a subtype of Iterable[A]. If we ask about it this way, it sounds hard.

Which is why I personally would just stay at:

@ def foo[A](x: Iterable[A]): A = x.head
defined function foo

@ foo(List(1 -> "test"))
res24: (Int, String) = (1, "test")

@ foo(Map(1 -> "test"))
res25: (Int, String) = (1, "test")

"Give me any x that is an instance of Iterable[A] for A".

If I had to do some derivation... I would probably also go this way. I think this limitation is the reason CanBuildFrom works the way it works - providing matching for part of the type is hard, especially in cases like Map, so let's provide a whole type at once as a parameter, to limit the number of inference needed.