问:
R Pick First Value Given Condition
```<code>data=data.frame("team"=c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5),
                "score"=c(4,8,10,3,10,5,4,2,7,7,5,6,5,9,1),
                "trial"=c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3),
                "sc3"=c(0,0,0,1,0,0,0,1,0,0,0,0,0,0,1),
                "sc7"=c(0,0,0,1,0,1,1,1,1,1,1,1,1,0,1),
                "sc9"=c(1,1,0,1,0,1,1,1,1,1,1,1,1,1,1),
                "sc3trial"=c(-99,-99,-99,1,1,1,2,2,2,-99,-99,-99,3,3,3),
                "sc7trial"=c(-99,-99,-99,1,1,1,1,1,1,1,1,1,1,1,1),
                "sc9trial"=c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1))
</code>```

I have data with column "team" and "score" and "trial". I want to create variables "sc3", "sc7", "sc9", "sc3trial", "sc7trial", "sc9trial" that follow these rules::

The rules are simple for "sc#". Note these are for each group:

For "sc3": if score <= 3, sc3 = 1. Otherwise sc3 = 0.

For "sc7": if score <= 7, sc7 = 1. Otherwise sc7 = 0.

For "sc9": if score <= 9, sc9 = 1. Otherwise sc9 = 0.

The rules are sort of also simple for "sc#trial". Note these are for each group:

For "sc3trial": If any "sc3" == 1, sc3trial records the trial when it first occurred. If no "sc3" equals to '1' then "sc3trial" equals to "-99"
  This logic applies the same for "sc7trial" and "sc9trial"

答:
We can use map to do the comparison with score

```<code>library(dplyr)
library(purrr)
map(c(3, 7, 9), ~ +(data$score <= .x)) %>%
     set_names(c('sc3', 'sc7', 'sc9')) %>%
     bind_cols(data %>% select(-c(sc3, sc7, sc9)), .)
</code>```

If we have only 3 variables, then

```<code>data %>%
   mutate(sc3 = + (score <=3), sc7 = +(score <=7), sc9 = +(score <= 9)) %>%
   group_by(team) %>%
   mutate(sc3trial = c(-99, 1)[(any(sc3 == 1)) + 1],
           sc7trial = c(-99, 1)[(any(sc7 == 1)) + 1]
          sc9trial = c(-99, 1)[(any(sc9 == 1)) + 1])
</code>```

Or in base R

```<code>nm1 <- c('sc3', 'sc7', 'sc9')
data[nm1] <- +(data[nm1] <= c(3, 7, 9)[col(data[nm1])])
</code>```

Title: R Pick First Value Given Condition

Body:
data=data.frame("team"=c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5),
                "score"=c(4,8,10,3,10,5,4,2,7,7,5,6,5,9,1),
                "trial"=c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3),
                "sc3"=c(0,0,0,1,0,0,0,1,0,0,0,0,0,0,1),
                "sc7"=c(0,0,0,1,0,1,1,1,1,1,1,1,1,0,1),
                "sc9"=c(1,1,0,1,0,1,1,1,1,1,1,1,1,1,1),
                "sc3trial"=c(-99,-99,-99,1,1,1,2,2,2,-99,-99,-99,3,3,3),
                "sc7trial"=c(-99,-99,-99,1,1,1,1,1,1,1,1,1,1,1,1),
                "sc9trial"=c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1))

I have data with column "team" and "score" and "trial". I want to create variables "sc3", "sc7", "sc9", "sc3trial", "sc7trial", "sc9trial" that follow these rules::

The rules are simple for "sc#". Note these are for each group:

For "sc3": if score <= 3, sc3 = 1. Otherwise sc3 = 0.

For "sc7": if score <= 7, sc7 = 1. Otherwise sc7 = 0.

For "sc9": if score <= 9, sc9 = 1. Otherwise sc9 = 0.

The rules are sort of also simple for "sc#trial". Note these are for each group:

For "sc3trial": If any "sc3" == 1, sc3trial records the trial when it first occurred. If no "sc3" equals to '1' then "sc3trial" equals to "-99"
  This logic applies the same for "sc7trial" and "sc9trial"

Body:
We can use map to do the comparison with score

library(dplyr)
library(purrr)
map(c(3, 7, 9), ~ +(data$score <= .x)) %>%
     set_names(c('sc3', 'sc7', 'sc9')) %>%
     bind_cols(data %>% select(-c(sc3, sc7, sc9)), .)

If we have only 3 variables, then

data %>%
   mutate(sc3 = + (score <=3), sc7 = +(score <=7), sc9 = +(score <= 9)) %>%
   group_by(team) %>%
   mutate(sc3trial = c(-99, 1)[(any(sc3 == 1)) + 1],
           sc7trial = c(-99, 1)[(any(sc7 == 1)) + 1]
          sc9trial = c(-99, 1)[(any(sc9 == 1)) + 1])

Or in base R

nm1 <- c('sc3', 'sc7', 'sc9')
data[nm1] <- +(data[nm1] <= c(3, 7, 9)[col(data[nm1])])


来源: stackexchange

问:
Initializing an Array of HashSet<string>, clarification needed
I initialize something like this

```<code>    public Dictionary<int, HashSet<string>[]> historgram = new Dictionary<int, HashSet<string>[]>()
    {
        {0, new HashSet<string>[3]},
        {1, new HashSet<string>[3]},
        {2, new HashSet<string>[3]},
    };
</code>```

I then

```<code>        if (historgram.TryGetValue(daysAgo, out data))
        {
            if (t.isTestAutomated)
            {
                if (data[0] == null)
                    data[0] = new HashSet<string>();

                data[0].Add(t.id);
            }
</code>```

The above works. If I have data to put, I initialize at run time

Once all is done, I write up a Json and end up with nulls for those instances where I didnt have anyting to put in. It looks something like this

```<code>"historgram": {
  "0": [ null, null, null ],
  "1": [ null, null, null ],
  "2": [ null, null, null ],
  "3": [ null, null, null ],
  "4": [
    [ "XXXX-2244" ],
    null,
    null
  ],
</code>```

Instead I'd like to end up with empty []. How can I pre-initialize HashSet to be empty straight away?

答:
I would recommend changing the string[] to a List so you can easily manage the size from 0 to 3 or more.

```<code>public static Dictionary<int, List<HashSet<string>>> historgram = new Dictionary<int, List<HashSet<string>>>()
{
    {0, new List<HashSet<string>>()},
    {1, new List<HashSet<string>>()},
    {2, new List<HashSet<string>>()},
};
</code>```

You can use the above in your code like this,

```<code>if (historgram.TryGetValue(2, out List<HashSet<string>> data))
if (data == null)
{
    data = new List<HashSet<string>>();
    data.Add(new HashSet<string>() { "XXXX-2244" });
}
else
{
    data.Add(new HashSet<string>() { "XXXX-2255" });
}
</code>```

At this point, your original histogram is also updated. Note that data is a reference to value of your dictionary's key.

```<code>
dynamic output = new ExpandoObject();
output.histogram = historgram;
Console.WriteLine(JsonConvert.SerializeObject(output, Formatting.Indented));

// Generates the following output...
{
  "histogram": {
    "0": [],
    "1": [],
    "2": [
      [
        "XXXX-2255"
      ]
    ]
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I initialize something like this

    public Dictionary<int, HashSet<string>[]> historgram = new Dictionary<int, HashSet<string>[]>()
    {
        {0, new HashSet<string>[3]},
        {1, new HashSet<string>[3]},
        {2, new HashSet<string>[3]},
    };

I then

        if (historgram.TryGetValue(daysAgo, out data))
        {
            if (t.isTestAutomated)
            {
                if (data[0] == null)
                    data[0] = new HashSet<string>();

                data[0].Add(t.id);
            }

The above works. If I have data to put, I initialize at run time

Once all is done, I write up a Json and end up with nulls for those instances where I didnt have anyting to put in. It looks something like this

"historgram": {
  "0": [ null, null, null ],
  "1": [ null, null, null ],
  "2": [ null, null, null ],
  "3": [ null, null, null ],
  "4": [
    [ "XXXX-2244" ],
    null,
    null
  ],

Instead I'd like to end up with empty []. How can I pre-initialize HashSet to be empty straight away?

Body:
I would recommend changing the string[] to a List so you can easily manage the size from 0 to 3 or more.

public static Dictionary<int, List<HashSet<string>>> historgram = new Dictionary<int, List<HashSet<string>>>()
{
    {0, new List<HashSet<string>>()},
    {1, new List<HashSet<string>>()},
    {2, new List<HashSet<string>>()},
};

You can use the above in your code like this,

if (historgram.TryGetValue(2, out List<HashSet<string>> data))
if (data == null)
{
    data = new List<HashSet<string>>();
    data.Add(new HashSet<string>() { "XXXX-2244" });
}
else
{
    data.Add(new HashSet<string>() { "XXXX-2255" });
}

At this point, your original histogram is also updated. Note that data is a reference to value of your dictionary's key.

dynamic output = new ExpandoObject();
output.histogram = historgram;
Console.WriteLine(JsonConvert.SerializeObject(output, Formatting.Indented));

// Generates the following output...
{
  "histogram": {
    "0": [],
    "1": [],
    "2": [
      [
        "XXXX-2255"
      ]
    ]
  }
}


问:
Add inner element via jQuery
I am using jquery 3 and I would like to add an inner span-tag with a styling.

var data = "test1, test2, test3";
var dataArr = data.split(',');
var restArr = dataArr.slice(1);

var $elem = $('', {
  'data-function': "addSynonym",
  'data-options': '[' + restArr.join(',') + ']'
});

$elem[0].innerText = dataArr[0]
console.log($elem[0])

// WANTED Output: test1```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

The final result should look like the following (notice the additional wanted " " before and after the tag:

test1

Any suggestions how to create the inner element?

I appreciate your replies!

答:
As I have mentioned in the comment section, maybe one solution can be to use html() to append the already found span. Similarly like using innerHTML.

About .html(htmlString) please read from the documentation:

Set the HTML contents of each element in the set of matched elements.

Working example:

var data = "test1, test2, test3";
var dataArr = data.split(',');
var restArr = dataArr.slice(1);

var $elem = $('', {
  'data-function': "addSynonym",
  'data-options': '[' + restArr.join(',') + ']'
});

$($elem[0]).html(`<span style="background-color: yellow;">${dataArr[0]}</span>`);
console.log($elem[0]);
console.log($elem[0].innerHTML);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

I hope that helps!

Title: Add inner element via jQuery

Body:
I am using jquery 3 and I would like to add an inner span-tag with a styling.

var data = "test1, test2, test3";
var dataArr = data.split(',');
var restArr = dataArr.slice(1);

var $elem = $('', {
  'data-function': "addSynonym",
  'data-options': '[' + restArr.join(',') + ']'
});

$elem[0].innerText = dataArr[0]
console.log($elem[0])

// WANTED Output: test1

The final result should look like the following (notice the additional wanted " " before and after the tag:

test1

Any suggestions how to create the inner element?

I appreciate your replies!

Body:
As I have mentioned in the comment section, maybe one solution can be to use html() to append the already found span. Similarly like using innerHTML.

About .html(htmlString) please read from the documentation:

Set the HTML contents of each element in the set of matched elements.

Working example:

var data = "test1, test2, test3";
var dataArr = data.split(',');
var restArr = dataArr.slice(1);

var $elem = $('<span>', {
  'data-function': "addSynonym",
  'data-options': '[' + restArr.join(',') + ']'
});

$($elem[0]).html(`<span style="background-color: yellow;">${dataArr[0]}</span>`);
console.log($elem[0]);
console.log($elem[0].innerHTML);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

I hope that helps!


问:
Why does the design look different than what's shown in emulator in android studio?
I'm trying to make a game app on Android Studio and when I try to run my app on the emulator, it look different than what's shown on the design. How can I fix this ?

this is my layout xml code:

```<code>                            <?xml version="1.0" encoding="utf-8"?>
                 <androidx.constraintlayout.widget.ConstraintLayout
               xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context=".MainActivity">

                <Button
                    android:id="@+id/button"
            style="@android:style/Widget.DeviceDefault.Light.Button.Small"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:background="@drawable/custom_button"
                    android:text="player1"
                    android:textAllCaps="false"
                    android:textSize="20sp"
                    tools:layout_editor_absoluteX="78dp"
                    tools:layout_editor_absoluteY="271dp" />

                <Button
                    android:id="@+id/button2"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:layout_marginBottom="280dp"
                    android:background="@drawable/custom_button"
                    android:text="player2"
                    android:textAllCaps="false"
                    android:textSize="20sp"
                    app:layout_constraintBottom_toBottomOf="parent"
                    tools:layout_editor_absoluteX="78dp" />

                <Button
                    android:id="@+id/button3"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:background="@drawable/custom_button"
                    android:text="New"
                    android:textAllCaps="false"
                    android:textSize="20sp"
                    tools:layout_editor_absoluteX="78dp"
                    tools:layout_editor_absoluteY="334dp" />

                <TextView
                    android:id="@+id/textView"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:padding="11dp"
                    android:text="TextView"
                    android:textColor="#000000"
                    android:textSize="20sp"
                    android:textStyle="bold"
                    tools:layout_editor_absoluteX="187dp"
                    tools:layout_editor_absoluteY="271dp" />

                <TextView
                    android:id="@+id/textView2"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:padding="11dp"
                    android:text="TextView"
                    android:textColor="#000000"
                    android:textSize="20sp"
                    android:textStyle="bold"
                    tools:layout_editor_absoluteX="187dp"
                    tools:layout_editor_absoluteY="334dp" />

                <TextView
                    android:id="@+id/textView3"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:padding="15dp"
                    android:text="TextView"
                    android:textColor="#000000"
                    android:textSize="20sp"
                    android:textStyle="bold"
                    tools:layout_editor_absoluteX="187dp"
                    tools:layout_editor_absoluteY="400dp" />
</code>```

thanks in advance

答:
You need to constrain your views when using the ConstraintLayout.

Check the guide on building UI with it:
https://developer.android.com/training/constraint-layout

Also, to quickly have something close to what you see, click on this button to get the layout editor's best guess of constraints to keep the views where they are now.

Body:
I'm trying to make a game app on Android Studio and when I try to run my app on the emulator, it look different than what's shown on the design. How can I fix this ?

this is my layout xml code:

                            <?xml version="1.0" encoding="utf-8"?>
                 <androidx.constraintlayout.widget.ConstraintLayout
               xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context=".MainActivity">

                <Button
                    android:id="@+id/button"
            style="@android:style/Widget.DeviceDefault.Light.Button.Small"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:background="@drawable/custom_button"
                    android:text="player1"
                    android:textAllCaps="false"
                    android:textSize="20sp"
                    tools:layout_editor_absoluteX="78dp"
                    tools:layout_editor_absoluteY="271dp" />

                <Button
                    android:id="@+id/button2"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:layout_marginBottom="280dp"
                    android:background="@drawable/custom_button"
                    android:text="player2"
                    android:textAllCaps="false"
                    android:textSize="20sp"
                    app:layout_constraintBottom_toBottomOf="parent"
                    tools:layout_editor_absoluteX="78dp" />

                <Button
                    android:id="@+id/button3"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:background="@drawable/custom_button"
                    android:text="New"
                    android:textAllCaps="false"
                    android:textSize="20sp"
                    tools:layout_editor_absoluteX="78dp"
                    tools:layout_editor_absoluteY="334dp" />

                <TextView
                    android:id="@+id/textView"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:padding="11dp"
                    android:text="TextView"
                    android:textColor="#000000"
                    android:textSize="20sp"
                    android:textStyle="bold"
                    tools:layout_editor_absoluteX="187dp"
                    tools:layout_editor_absoluteY="271dp" />

                <TextView
                    android:id="@+id/textView2"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:padding="11dp"
                    android:text="TextView"
                    android:textColor="#000000"
                    android:textSize="20sp"
                    android:textStyle="bold"
                    tools:layout_editor_absoluteX="187dp"
                    tools:layout_editor_absoluteY="334dp" />

                <TextView
                    android:id="@+id/textView3"
                    android:layout_width="100dp"
                    android:layout_height="51dp"
                    android:padding="15dp"
                    android:text="TextView"
                    android:textColor="#000000"
                    android:textSize="20sp"
                    android:textStyle="bold"
                    tools:layout_editor_absoluteX="187dp"
                    tools:layout_editor_absoluteY="400dp" />

thanks in advance


问:
access var outside function scope
I havethe following code and I'm trying to access selectedBrand var outside so to use it elsewhere in may code

```<code>var selectedBrand;
var brand_sel = d3.select('select')
    .on("change",function(b) {
        selectedBrand = d3.select("#brand").node().value;
    });

  console.log(selectedBrand)
</code>```

when I try to consollog selectedBrand I get undefined results.

I try almost everything I understand without success

many thanks for any help

答:
first of all thanks for the replay.
I'm quite new to javascript and I'm learning by doing. Probably I totally misunderstand js logic some where.

Anyway, probably I'll share the wrong request hoping it should solve my issue.
Coming back to the issue as it was at the beginning.

Let's say that I have a var like this

```<code>    var filteredMedia =nest1.filter(function(d) {
  return d.key == brand_sel})[0]
</code>```

where brand_sel must be updated both on page load and on change.

brand_sel is the value of the selected option of a dropdown.

using this code

```<code>    function update() {
   var brand_sel = d3.select("#brand").node().value
  return brand_sel;
}
var brand_sel = update();

console.log(update())
</code>```

everything works on page load.

Now I'm trying to run update function also on change in the following way but of course I'm still missing to understand somthing

```<code>d3.select('select').on("change", function(){
  update();
});
</code>```

Title: access var outside function scope

Body:
I havethe following code and I'm trying to access selectedBrand var outside so to use it elsewhere in may code

var selectedBrand;
var brand_sel = d3.select('select')
    .on("change",function(b) {
        selectedBrand = d3.select("#brand").node().value;
    });

  console.log(selectedBrand)

when I try to consollog selectedBrand I get undefined results.

I try almost everything I understand without success

many thanks for any help

Body:
first of all thanks for the replay.
I'm quite new to javascript and I'm learning by doing. Probably I totally misunderstand js logic some where.

Anyway, probably I'll share the wrong request hoping it should solve my issue.
Coming back to the issue as it was at the beginning.

Let's say that I have a var like this

    var filteredMedia =nest1.filter(function(d) {
  return d.key == brand_sel})[0]

where brand_sel must be updated both on page load and on change.

brand_sel is the value of the selected option of a dropdown.

using this code

    function update() {
   var brand_sel = d3.select("#brand").node().value
  return brand_sel;
}
var brand_sel = update();

console.log(update())

everything works on page load.

Now I'm trying to run update function also on change in the following way but of course I'm still missing to understand somthing

d3.select('select').on("change", function(){
  update();
});


问:
Weird table tag at markdown email
Laravel 6.2

Here's the view:

```<code>@component('mail::message')

    @component('mail::panel')
    Some text
    @endcomponent

    @component('mail::button', ['url' => config('app.url')])
    Name: {{$attendee->name}}
    @endcomponent

@endcomponent
</code>```

Between the panel and the button i get:

Does anyone knows the reason for this?

答:
Answered.
It was the indentation, markdown parses indents as formatting.</p>

```<code>@component('mail::message')

@component('mail::panel')
Some text
@endcomponent

@component('mail::button', ['url' => config('app.url')])
Name: {{$attendee->name}}
@endcomponent

@endcomponent
</code>```

Title: Weird table tag at markdown email

Body:
Laravel 6.2

Here's the view:

@component('mail::message')

    @component('mail::panel')
    Some text
    @endcomponent

    @component('mail::button', ['url' => config('app.url')])
    Name: {{$attendee->name}}
    @endcomponent

@endcomponent

Between the panel and the button i get:

Does anyone knows the reason for this?

Body:
Answered.
It was the indentation, markdown parses indents as formatting.

@component('mail::message')

@component('mail::panel')
Some text
@endcomponent

@component('mail::button', ['url' => config('app.url')])
Name: {{$attendee->name}}
@endcomponent

@endcomponent


问:
Android 2D game programming: using OpenGL or not?
I've just started to develop games on Android. My first game is a 2D game and I'm wondering whether I should use OpenGL or not.

Does anyone have some advice on this?

Thanks a lot,
Viet

答:
OpenGL ES all the way! There are some good videos from last years IO on android game dev and the frame rates you can achieve going opengl vs canvas.

http://www.youtube.com/watch?v=7-62tRHLcHk&feature=player_embedded

http://www.youtube.com/watch?v=U4Bk5rmIpic

Also there are a handful of great 2d frameworks to simplify the process, the best in my opinion being AndEngine

ContentLicense: CC BY-SA 3.0


问:
Why a program/browser running without GUI called Headless?
I'm curious about why headless means "without GUI". What is the etymology of headless? It seems there is no relationship between a head and GUI.

答:
From chromium's perspective, Headless Chrome is a way to run the google-chrome browser in a headless environment which is essentially, running Chrome without chrome. It is a tool for automated testing and server environments where you don't need a visible UI shell.

The concept of Headless Chrome was implemented through a --headless runtime switch which would use a regular Chrome binary as a headless. When the binary would be launched with this switch, the main entry-point would call into the Headless Shell entry-point, effectively starting that shell instead of Chrome. To make this possible Chromium Team removed the dependency from Headless to Ozone as Ozone is a build-time feature which is generally not enabled for regular Chrome builds. Essentially it meant implementing a new headless-specific
WindowTreeHost and modifying various graphics and input entrypoints to do something appropriate in headless mode. Though much of the were in platform-specific code, the main aim was to enable the shell to use an in-memory profile which is fully independent of the user’s actual profile.

There are three main changes for --headless were:

Turn Headless Shell into an embeddable library (instead of a standalone app).

The main Chrome entrypoint should dispatch into the Headless Shell entrypoint when --headless is used, i.e. launching Headless Shell instead of the regular Chrome UI.

Platform-specific changes to avoid window system dependencies in headless mode.

Where as the Cross-platform changes were in:

chrome/chrome_main.cc: Dispatch into HeadlessShellMain() when launched with --headless.

content/browser/compositor/gpu_process_transport_factory.cc: Use a software output device in headless mode.

References

A couple of references:

Headless Chrome architecture

Runtime headless mode on Windows OS


问:
Reading large JSON file in Deno
I often find myself reading a large JSON file (usually an array of objects) then manipulating each object and writing back to a new file.

To achieve this in Node (at least the reading the data portion) I usually do something like this using the stream-json module.

const fs = require('fs');
const StreamArray = require('stream-json/streamers/StreamArray');

const pipeline = fs.createReadStream('sample.json')
  .pipe(StreamArray.withParser());

pipeline.on('data', data => {
    //do something with each object in file
});
```

I've recently discovered Deno and would love to be able to do this workflow with Deno.

It looks like the readJSON method from the Standard Library reads the entire contents of the file into memory so I don't know if it would be a good fit for processing a large file.

Is there a way this can be done by streaming the data from the file using some of the lower level methods that are built into Deno?

答:
this is the code I used for a file with 13,147,089 lines of text.
Notice it's same as Roberts's code but used readLine() instead of readString('\n').
readLine() is a low-level line-reading primitive. Most callers should use readString('\n') instead or use a Scanner.`

```<code>import { BufReader } from "https://deno.land/std/io/bufio.ts";

export async function stream_file(filename: string) {
  const file = await Deno.open(filename);
  const bufReader = new BufReader(file);
  console.log("Reading data...");
  let line: string | any;
  let lineCount: number = 0;
  while ((line = await bufReader.readLine()) != Deno.EOF) {
    lineCount++;
    // do something with `line`.
  }
  file.close();
  console.log(`${lineCount} lines read.`);
}
</code>```

Title: Reading large JSON file in Deno

Body:
I often find myself reading a large JSON file (usually an array of objects) then manipulating each object and writing back to a new file.

To achieve this in Node (at least the reading the data portion) I usually do something like this using the stream-json module.

const fs = require('fs');
const StreamArray = require('stream-json/streamers/StreamArray');

const pipeline = fs.createReadStream('sample.json')
  .pipe(StreamArray.withParser());

pipeline.on('data', data => {
    //do something with each object in file
});

I've recently discovered Deno and would love to be able to do this workflow with Deno.

It looks like the readJSON method from the Standard Library reads the entire contents of the file into memory so I don't know if it would be a good fit for processing a large file.

Is there a way this can be done by streaming the data from the file using some of the lower level methods that are built into Deno?

Body:
this is the code I used for a file with 13,147,089 lines of text.
Notice it's same as Roberts's code but used readLine() instead of readString('\n').
readLine() is a low-level line-reading primitive. Most callers should use readString('\n') instead or use a Scanner.`

import { BufReader } from "https://deno.land/std/io/bufio.ts";

export async function stream_file(filename: string) {
  const file = await Deno.open(filename);
  const bufReader = new BufReader(file);
  console.log("Reading data...");
  let line: string | any;
  let lineCount: number = 0;
  while ((line = await bufReader.readLine()) != Deno.EOF) {
    lineCount++;
    // do something with `line`.
  }
  file.close();
  console.log(`${lineCount} lines read.`);
}


问:
using odbc to connect to Oracle database in c#
I'm trying to write a tool in c# which will connect to Oracle database and I'm required to use ODBC.

If I use the following code:

```<code>using System.Data.Odbc;
string str1 = "DATA SOURCE=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=abcd.efgh.net)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=service_name)));USER ID=user_id;PASSWORD=qassword";
OdbcConnection coon = new OdbcConnection();
coon.ConnectionString = str1;
coon.Open();
</code>```

I get the error message:

```<code>An unhandled exception of type 'System.Data.Odbc.OdbcException' occurred in System.Data.dll
Additional information: ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
</code>```

even if I change the connection string to:

```<code>string str2 = "Driver={Oracle in OraClient12home1};DATA SOURCE=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=abcd.efgh.net)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=service_name)));USER ID=user_id;PASSWORD=qassword";
</code>```

I get the same error message.
So I guess the problem is not the "Driver = {...}" part? But what did I get wrong in the "DATA SOURCE" part?

Thank you.

答:
Try this</p>

```<code>        using System.Data.Odbc;

        String connectionString = "Dsn=HP5ODBC;uid=system;pwd=manager";
        OdbcConnection coon = new OdbcConnection();
        coon.ConnectionString = connectionString;
        coon.Open();
        MessageBox.Show(coon.State.ToString());
</code>```

Body:
I'm trying to write a tool in c# which will connect to Oracle database and I'm required to use ODBC.

If I use the following code:

using System.Data.Odbc;
string str1 = "DATA SOURCE=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=abcd.efgh.net)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=service_name)));USER ID=user_id;PASSWORD=qassword";
OdbcConnection coon = new OdbcConnection();
coon.ConnectionString = str1;
coon.Open();

I get the error message:

An unhandled exception of type 'System.Data.Odbc.OdbcException' occurred in System.Data.dll
Additional information: ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

even if I change the connection string to:

string str2 = "Driver={Oracle in OraClient12home1};DATA SOURCE=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=abcd.efgh.net)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=service_name)));USER ID=user_id;PASSWORD=qassword";

I get the same error message.
So I guess the problem is not the "Driver = {...}" part? But what did I get wrong in the "DATA SOURCE" part?

Thank you.

Body:
Try this

        using System.Data.Odbc;

        String connectionString = "Dsn=HP5ODBC;uid=system;pwd=manager";
        OdbcConnection coon = new OdbcConnection();
        coon.ConnectionString = connectionString;
        coon.Open();
        MessageBox.Show(coon.State.ToString());


问:
Generate a list of characters based on pre-defined values
Hoping someone can help me out.
I am trying to create a basic little program that will generate a list of values from a pre-defined list of acceptable characters.

These characters will be - 'H', '/', 'L'.

The program should print these out in a random order with the majority of them being '/' with about 5% being 'L' and 5% being 'H'. (The percentages can vary).
And the program should ask or have a variable that can determine how many characters it will print (i.e. 5 or 5000).

An example of the print out Im looking for:

```<code>/
/
/
/
/
L
/
/
/
/
/
H
H
/
/
/
/
</code>```

Etc.

What would the best way be around this? Im really stumped and have no idea where to begin.
Obviously I would create a list of the said characters.
But how do I make the program favour one over the other based on percentages?

This is part of work that Im doing at my job where I have to generate a set of dummy data in various stages so this would save me hours of work if I can figure it out.

Any guidance or pointers would be appreciated.

Thank you

答:
Thanks for the pointers everyone.

I managed to figure it out based on the comments.

The end code:

```<code>#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
ofstream myfile;

void GenerateRandom() {
    int randomNumber;

    for (int index = 0; index < 100; index++) { //Index can be changed to generate more lines if needed
        randomNumber = (rand() % 100) + 1;

        if (randomNumber <= 2) {
            myfile << "H" << endl;
        }
        if (randomNumber > 2 && randomNumber <= 6) {
            myfile << "L" << endl;
        }
        else {
            myfile << "/" << endl;
        }
    }

};

int main()
{
    myfile.open("C:\\Users\\USERNAME\\Desktop\\Test.txt");
    GenerateRandom();
    myfile.close();
}
</code>```

Thanks for the help again!

Body:
Hoping someone can help me out.
I am trying to create a basic little program that will generate a list of values from a pre-defined list of acceptable characters.

These characters will be - 'H', '/', 'L'.

The program should print these out in a random order with the majority of them being '/' with about 5% being 'L' and 5% being 'H'. (The percentages can vary).
And the program should ask or have a variable that can determine how many characters it will print (i.e. 5 or 5000).

An example of the print out Im looking for:

/
/
/
/
/
L
/
/
/
/
/
H
H
/
/
/
/

Etc.

What would the best way be around this? Im really stumped and have no idea where to begin.
Obviously I would create a list of the said characters.
But how do I make the program favour one over the other based on percentages?

This is part of work that Im doing at my job where I have to generate a set of dummy data in various stages so this would save me hours of work if I can figure it out.

Any guidance or pointers would be appreciated.

Thank you

Body:
Thanks for the pointers everyone.

I managed to figure it out based on the comments.

The end code:

#include <iostream>
#include <cstdlib>
#include <fstream>
using namespace std;
ofstream myfile;

void GenerateRandom() {
    int randomNumber;

    for (int index = 0; index < 100; index++) { //Index can be changed to generate more lines if needed
        randomNumber = (rand() % 100) + 1;

        if (randomNumber <= 2) {
            myfile << "H" << endl;
        }
        if (randomNumber > 2 && randomNumber <= 6) {
            myfile << "L" << endl;
        }
        else {
            myfile << "/" << endl;
        }
    }

};

int main()
{
    myfile.open("C:\\Users\\USERNAME\\Desktop\\Test.txt");
    GenerateRandom();
    myfile.close();
}

Thanks for the help again!


问:
Can argv** be returned as a function return value
In C we should return pointer variable if define as 1- static stack 2- Heap-allocated 3-const address.

The question is:

Can  argv** variable  in main function be returned as a function return value without undefined behaviour?

答:
I can't imagine a situation which requires to return argv** from a function, but you get it from main (int argc, char* argv[]) so yes. You can pass it as a parameter to a function and return it to another function. They're like const for you.

You can't return pointer to the data allocated temporarily for the function's own needs. int* F{ int A; return &A; } will not work. But you can set int* A=(int*)malloc(sizeof(int)); and return A;: it'll be your tiny wrapper around the malloc function. You can even receive int* A as a parameter and return A+1; the rule you mentioned in the beginning actually means "there are some restrictions of allocation methods if you're planning to use the pointer after the function exits". You can break the rule without returning the value (for example, you can store the poiner in a global variable and it'll become invalid when the function exits, like void F{ int A; GlobPtr=&A; } which will cause the same problems).

But your function does not allocate argv, it's allocated before your code starts. So you can even shift it by one value as you extract parameters one-by-one, the returned pointer *nextargv[] will also point to valid memory area.


问:
bash script to rename files based on a calculation
I have a file system containing PNG images.  The layout of the filesystem is: ZOOM/X/Y.png where ZOOM, X, and Y are all integers.

I need to change the names of the PNG files.  Basically, I need to convert Y from its current value to 2^ZOOM-Y-1.  I've written a bash script to accomplish this task.  However, I suspect it can be optimized substantially.  (I also suspect that I may have been better off writing it in Perl, but that is another story.)

Here is the script.  Is this about as good as it gets?  Or can the performance be optimized?  Are there tools I can use that would profile the script for me and tell me where I'm spending all my execution time?

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

tiles=`ls -d */*/*`

for oldPath in $tiles
do
   oldY=`basename -s .png $oldPath`
   zoomX=`dirname $oldPath`
   zoom=`echo $zoomX | sed 's#\([^\]\)/.*#\1#'`
   newY=`echo 2^$zoom-$oldY-1|bc`
   mv ${zoomX}/${oldY}.png ${zoomX}/${newY}.png
done
</code>```

答:
It's likely that the overall throughput of your rename is limited by the filesystem.  Choosing the right filesystem and tuning it for this sort of operation would speed up the overall job much more than tweaking the script.

If you optimize the script you'll probably see less CPU consumed but the same total duration.  Since forking off the various subprocesses (basename, dirname, sed, bc) are probably more significant than the actual work you are probably right that a perl implementation would use less CPU because it can do all of those operations internally (including the mv).

Body:
I have a file system containing PNG images.  The layout of the filesystem is: ZOOM/X/Y.png where ZOOM, X, and Y are all integers.

I need to change the names of the PNG files.  Basically, I need to convert Y from its current value to 2^ZOOM-Y-1.  I've written a bash script to accomplish this task.  However, I suspect it can be optimized substantially.  (I also suspect that I may have been better off writing it in Perl, but that is another story.)

Here is the script.  Is this about as good as it gets?  Or can the performance be optimized?  Are there tools I can use that would profile the script for me and tell me where I'm spending all my execution time?

#!/bin/bash

tiles=`ls -d */*/*`

for oldPath in $tiles
do
   oldY=`basename -s .png $oldPath`
   zoomX=`dirname $oldPath`
   zoom=`echo $zoomX | sed 's#\([^\]\)/.*#\1#'`
   newY=`echo 2^$zoom-$oldY-1|bc`
   mv ${zoomX}/${oldY}.png ${zoomX}/${newY}.png
done


问:
robust pylint disable for an option recently introduced
We have several versions of pylint in various stages of our CI system (for good reasons: we want to test that our code works across a range of package versions).

Now, an option import-outside-toplevel was introduced as per pylint=2.4.0 (according to the changelog).

How do we disable that pylint error in a robust way (or conditional on pylint>=2.4.0)?

I have tried:

# pylint: disable=import-outside-toplevel

# pylint: disable=C0415

No disable.

In case 1 and 2, running pylint version 2.4.3 (on a CI stage aligned with anaconda=2019.03) causes E0012: Bad option value.  In case 3, running pylint version 2.4.2 (on a CI stage aligned with anaconda=2019.10) causes C0415: Import outside toplevel.

答:
For now, I am disabling the whole 'C' category for just the scope (in my case, a single line):

```<code>def blah(...):
    import foo.bar  # pylint: disable=C
</code>```

That works across pylint 2.3 to 2.5, although it isn't as specific as I would like.

Body:
For now, I am disabling the whole 'C' category for just the scope (in my case, a single line):

def blah(...):
    import foo.bar  # pylint: disable=C

That works across pylint 2.3 to 2.5, although it isn't as specific as I would like.


问:
How to import Vanilla JS ES6 modules in TypeScript?
I'm trying to import this library: spotlight, which is plain JS.

In my project I created a fake d.ts:

```<code>declare module 'spotlight.js'
</code>```

as suggested by VSCode, then I tried every single import combination:

```<code>import * as spotlight from 'spotlight';
import spotlight from 'spotlight';
import { spotlight } from 'spotlight';
</code>```

but inside my code the spotlight expression is always an empty object.

What am I missing?

答: The declare statement has to be in a separate file initially, also make sure that you provided the right path for import statement.</p>

Body:
I'm trying to import this library: spotlight, which is plain JS.

In my project I created a fake d.ts:

declare module 'spotlight.js'

as suggested by VSCode, then I tried every single import combination:

import * as spotlight from 'spotlight';
import spotlight from 'spotlight';
import { spotlight } from 'spotlight';

but inside my code the spotlight expression is always an empty object.

What am I missing?


问:
How to Parse Json generic array with inheritance items
my question is not same is this question.
if i want to explain lets assume we have these classes (A, B, C).

```<code>@Data
@NoArgsConstructor
class A {
    private Integer x;
    private String type;

    public A(String type, Integer x) {
        this.type = type;
        this.x = x;
    }
}
</code>```

```<code>@Data
class B extends A {
    private Integer y;

    public B(Integer x, Integer y) {
        super("B", x);
        this.y = y;
    }
}
</code>```

```<code>@Data
class C extends A {
    private Integer z;

    public C(Integer x, Integer z) {
        super("C", x);
        this.z = z;
    }
}
</code>```

know i want to parse an array which their base classes is A. and with property named type i want to convert each item to its specific class.
something like this code.

```<code>public static void main(String[] args) {
        Gson gson = new Gson();
        List<A> list = new ArrayList<>();
        A a = new A("A", 0);
        list.add(a);
        B b = new B(1, 2);
        list.add(b);
        C c = new C(3, 4);
        list.add(c);
        String serializedJson = gson.toJson(list);
        List<? extends A> deserializedList = gson.fromJson(serializedJson, new TypeToken<List<? extends A>>() {
        }.getType());
        for (A item : deserializedList) {
            System.out.println(item.getType());
            if (item instanceof B) {
                System.out.println(((B) item).getY());

            } else if (item instanceof C) {
                System.out.println(((C) item).getZ());

            }
        }
    }
</code>```

serialized json is something like this

```<code>[{"x":0,"type":"A"},{"y":2,"x":1,"type":"B"},{"z":4,"x":3,"type":"C"}]
</code>```

in real world, i have something like this json and want to parse it.
but when i run the code y and z properties not printed and objects are not instance of B or C.
how to achieve to this goal to parse and create each item with type property.

答:
I found the solution via Gson TypeAdapterFactory mechanism.
creating a class to implement com.google.gson.TypeAdapterFactory. for more detail see this link </p>

Body:
my question is not same is this question.
if i want to explain lets assume we have these classes (A, B, C).

@Data
@NoArgsConstructor
class A {
    private Integer x;
    private String type;

    public A(String type, Integer x) {
        this.type = type;
        this.x = x;
    }
}

@Data
class B extends A {
    private Integer y;

    public B(Integer x, Integer y) {
        super("B", x);
        this.y = y;
    }
}

@Data
class C extends A {
    private Integer z;

    public C(Integer x, Integer z) {
        super("C", x);
        this.z = z;
    }
}

know i want to parse an array which their base classes is A. and with property named type i want to convert each item to its specific class.
something like this code.

public static void main(String[] args) {
        Gson gson = new Gson();
        List list = new ArrayList<>();
        A a = new A("A", 0);
        list.add(a);
        B b = new B(1, 2);
        list.add(b);
        C c = new C(3, 4);
        list.add(c);
        String serializedJson = gson.toJson(list);
        List<? extends A> deserializedList = gson.fromJson(serializedJson, new TypeToken<List<? extends A>>() {
        }.getType());
        for (A item : deserializedList) {
            System.out.println(item.getType());
            if (item instanceof B) {
                System.out.println(((B) item).getY());

            } else if (item instanceof C) {
                System.out.println(((C) item).getZ());

            }
        }
    }

serialized json is something like this

[{"x":0,"type":"A"},{"y":2,"x":1,"type":"B"},{"z":4,"x":3,"type":"C"}]

in real world, i have something like this json and want to parse it.
but when i run the code y and z properties not printed and objects are not instance of B or C.
how to achieve to this goal to parse and create each item with type property.


问:
How to specify a port to run a create-react-app based project?
My project is based on create-react-app. npm start or yarn start by default will run the application on port 3000 and there is no option of specifying a port in the package.json.

How can I specify a port of my choice in this case? I want to run two of this project simultaneously (for testing), one in port 3005 and other is 3006

答:
In your package.json, go to scripts and use --port 4000 or set PORT=4000, like in the example below:

package.json (Windows):

```<code>"scripts": {
    "start": "set PORT=4000 && react-scripts start"
}
</code>```

package.json (Ubuntu):

```<code>"scripts": {
    "start": "export PORT=4000 && react-scripts start"
}
</code>```

Body:
In your package.json, go to scripts and use --port 4000 or set PORT=4000, like in the example below:

package.json (Windows):

"scripts": {
    "start": "set PORT=4000 && react-scripts start"
}

package.json (Ubuntu):

"scripts": {
    "start": "export PORT=4000 && react-scripts start"
}


问:
How do I get count results?
I have this code. Running it directly it is supposed to return 100. But with this code it returns 1. Do I use the ? wrong or why does it return just 1?</p>

```<code>
 <?php

require '../notWebsite/dbh.php';
session_start();
$userID = (int)$_SESSION['userID'];

$sqlCount = "SELECT COUNT(groupID) FROM savedbyuser WHERE userID = ?";
$stmt = mysqli_stmt_init($conn);

if(!mysqli_stmt_prepare($stmt, $sqlCount)) {
header("Location: ../GymnasieArbeteHemsida.php?error=countError");
 exit();
}
else {
mysqli_stmt_bind_param($stmt, "i", $userID);
mysqli_stmt_execute($stmt);

$count = mysqli_stmt_execute($stmt);
echo $count;
     exit();
}

mysqli_stmt_close($stmt);
mysqli_close($conn);

?>

</code>```

答:
Hi as stated in manual https://www.php.net/manual/en/mysqli-stmt.execute.php

```<code>Returns TRUE on success or FALSE on failure.
</code>```

so this

```<code>$count = mysqli_stmt_execute($stmt);
echo $count;
</code>```

translates to

```<code>$count = true;
echo $count;
// print 1
</code>```

in manual focus on

```<code>Note:

When using mysqli_stmt_execute(), the mysqli_stmt_fetch() function must be used to fetch the data prior to performing any additional queries.
</code>```

leads to https://www.php.net/manual/en/mysqli-stmt.fetch.php and so on...

Title: How do I get count results?

Body:
I have this code. Running it directly it is supposed to return 100. But with this code it returns 1. Do I use the ? wrong or why does it return just 1?

 <?php

require '../notWebsite/dbh.php';
session_start();
$userID = (int)$_SESSION['userID'];

$sqlCount = "SELECT COUNT(groupID) FROM savedbyuser WHERE userID = ?";
$stmt = mysqli_stmt_init($conn);

if(!mysqli_stmt_prepare($stmt, $sqlCount)) {
header("Location: ../GymnasieArbeteHemsida.php?error=countError");
 exit();
}
else {
mysqli_stmt_bind_param($stmt, "i", $userID);
mysqli_stmt_execute($stmt);

$count = mysqli_stmt_execute($stmt);
echo $count;
     exit();
}

mysqli_stmt_close($stmt);
mysqli_close($conn);

?>

Body:
Hi as stated in manual https://www.php.net/manual/en/mysqli-stmt.execute.php

Returns TRUE on success or FALSE on failure.

so this

$count = mysqli_stmt_execute($stmt);
echo $count;

translates to

$count = true;
echo $count;
// print 1

in manual focus on

Note:

When using mysqli_stmt_execute(), the mysqli_stmt_fetch() function must be used to fetch the data prior to performing any additional queries.

leads to https://www.php.net/manual/en/mysqli-stmt.fetch.php and so on...


问:
How can i get calories data from any health band?
I work on some application that using calories data.

I want get this data from any health bands that can be connect to android or ios phones.

the exact problem is that i don't want use google fit api or ios health kit and i want get data directly from hardwares and no matter what company build that.

Please help me.Thanks

答: This isn't possible.  You would need to individually integrate every brand of health band, as they're all completely different.</p>


问:
Swift check for nil in optional array
I have an Optional array and need to check a member for nil. Unfortunately that doesn't work like I have expected it to do. It seems like I have to unwrap it however at runtime I don't know whether the value in question is a String, an Int, another array etc. so casting doesn't help (I think)

```<code>var nilString: String? = nil

let arr = [1, nilString] as [Any]?

print(nilString)
print(arr?[1])

if (arr?[1] == nil) {
    print("is nil") // doesn't work
}

if case Optional<Any>.none = arr?[1] {
    print("nil")     //would expect this one
} else {             //but
    print("not nil") //<-- gets printed
}
</code>```

Alternative ideas on the structure are also welcomed.

答: Your problem there is that you have declared your Array type as optional instead of declaring its elements.  You just need to change your array declaration to[Any?]. Note that the use of Any it is not useful in most situations. I've been coding in Swift for more than 5 years and I've never needed to declare an element type as Any.

Title: Swift check for nil in optional array

Body:
I have an Optional array and need to check a member for nil. Unfortunately that doesn't work like I have expected it to do. It seems like I have to unwrap it however at runtime I don't know whether the value in question is a String, an Int, another array etc. so casting doesn't help (I think)

var nilString: String? = nil

let arr = [1, nilString] as [Any]?

print(nilString)
print(arr?[1])

if (arr?[1] == nil) {
    print("is nil") // doesn't work
}

if case Optional<Any>.none = arr?[1] {
    print("nil")     //would expect this one
} else {             //but
    print("not nil") //<-- gets printed
}

Alternative ideas on the structure are also welcomed.


问:
Installation of metadata-extractor
I'm stuck on installation.
I downloaded Maven, but I'm not sure which file within
the metadata-extractor folder (that I downloaded from the repo) to use as the target.

I tried all the files at the top level.
All attempts have failed, e.g.

java -jar metadata-extractor-2.13.0.jar build.gradle

com.drew.imaging.ImageProcessingException: File format could not be determined

I am using v2.13.0 of the meta-data extractor

答: I've just started to code and took interest in this project but also had issues using it. Instead of using Maven i just downloaded the source code from github and threw the 'com' folder into my myproject/src folder. Then i downloaded the xmpcore-6.1.10.jar library and added it to the Build Path. Got it working that way. I hope someone will give you a better solution but if you just wanna do something right away, you can try this solution. </p>

Title: Installation of metadata-extractor


问:
How to create CNN model using keras?
I want to create one CNN model including all nSeizures models instead of creating model for each seizure file, but i got this error < AttributeError: 'NoneType' object has no attribute 'fit_generator'>.</p>

```<code>for i in range(0, nSeizure):
            print(nSeizure)
            print('SEIZURE OUT: '+str(i+1))
            print('Training start')
           ## create model
            model = createModel()
            filesPath=getFilesPathWithoutSeizure(i, indexPat)
           ## create one model including all nSeizures models
            for model in range(0, nSeizure):
                mylist.append(model)
                data=mylist.append(model)
                history=data.fit_generator(generate_arrays_for_training(indexPat, filesPath, end=75),
                                validation_data=generate_arrays_for_training(indexPat, filesPath,
                                start=75),
                                #steps_per_epoch=10000, epochs=10)
                                steps_per_epoch=int((len(filesPath)-int(len(filesPath)/100*25))),
                                validation_steps=int((len(filesPath)-int(len(filesPath)/100*75))),
                                verbose=2,
                                epochs=300, max_queue_size=2, shuffle=True, callbacks=[callback])
</code>```

答:
mylist.append(model) returns None.
when you call data.fit_generator it effectively means None.fit_generator.
Consider rewriting the code.

Title: How to create CNN model using keras?

Body:
I want to create one CNN model including all nSeizures models instead of creating model for each seizure file, but i got this error < AttributeError: 'NoneType' object has no attribute 'fit_generator'>.

for i in range(0, nSeizure):
            print(nSeizure)
            print('SEIZURE OUT: '+str(i+1))
            print('Training start')
           ## create model
            model = createModel()
            filesPath=getFilesPathWithoutSeizure(i, indexPat)
           ## create one model including all nSeizures models
            for model in range(0, nSeizure):
                mylist.append(model)
                data=mylist.append(model)
                history=data.fit_generator(generate_arrays_for_training(indexPat, filesPath, end=75),
                                validation_data=generate_arrays_for_training(indexPat, filesPath,
                                start=75),
                                #steps_per_epoch=10000, epochs=10)
                                steps_per_epoch=int((len(filesPath)-int(len(filesPath)/100*25))),
                                validation_steps=int((len(filesPath)-int(len(filesPath)/100*75))),
                                verbose=2,
                                epochs=300, max_queue_size=2, shuffle=True, callbacks=[callback])


问:
Add inner element via jQuery
I am using jquery 3 and I would like to add an inner span-tag with a styling.

var data = "test1, test2, test3";
var dataArr = data.split(',');
var restArr = dataArr.slice(1);

var $elem = $('', {
  'data-function': "addSynonym",
  'data-options': '[' + restArr.join(',') + ']'
});

$elem[0].innerText = dataArr[0]
console.log($elem[0])

// WANTED Output: test1```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

The final result should look like the following (notice the additional wanted " " before and after the tag:

test1

Any suggestions how to create the inner element?

I appreciate your replies!

答:
You could continue in the same way and use the html attribute to pass the inner element

var data = "test1, test2, test3";
var dataArr = data.split(',');
var restArr = dataArr.slice(1);

var $elem = $('', {
  'data-function': "addSynonym",
  'data-options': '[' + restArr.join(',').trim() + ']',
  'html': $('', {
    'text': dataArr[0],
    'css': {
      backgroundColor: 'yellow'
    }
  })
});

// without spaces
console.log($elem[0].outerHTML)
// with spaces
console.log(` ${$elem[0].outerHTML} `);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

Title: Add inner element via jQuery

Body:
I am using jquery 3 and I would like to add an inner span-tag with a styling.

var data = "test1, test2, test3";
var dataArr = data.split(',');
var restArr = dataArr.slice(1);

var $elem = $('', {
  'data-function': "addSynonym",
  'data-options': '[' + restArr.join(',') + ']'
});

$elem[0].innerText = dataArr[0]
console.log($elem[0])

// WANTED Output: test1

The final result should look like the following (notice the additional wanted " " before and after the tag:

test1

Any suggestions how to create the inner element?

I appreciate your replies!

Body:
You could continue in the same way and use the html attribute to pass the inner element

var data = "test1, test2, test3";
var dataArr = data.split(',');
var restArr = dataArr.slice(1);

var $elem = $('<span>', {
  'data-function': "addSynonym",
  'data-options': '[' + restArr.join(',').trim() + ']',
  'html': $('<span>', {
    'text': dataArr[0],
    'css': {
      backgroundColor: 'yellow'
    }
  })
});

// without spaces
console.log($elem[0].outerHTML)
// with spaces
console.log(` ${$elem[0].outerHTML} `);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


答:
var data = "test1, test2, test3";
var dataArr = data.split(',');
var restArr = dataArr.slice(1);

var $elem = $('', {
  'data-function': "addSynonym",
  'data-options': '[' + restArr.join(',') + ']'
});

var $innerElem = $('' + dataArr[0] + '').css({
  backgroundColor: "yellow"
})

$elem.append($innerElem);

console.log($elem[0].outerHTML)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

Title: Add inner element via jQuery

Body:
var data = "test1, test2, test3";
var dataArr = data.split(',');
var restArr = dataArr.slice(1);

var $elem = $('<span>', {
  'data-function': "addSynonym",
  'data-options': '[' + restArr.join(',') + ']'
});

var $innerElem = $('<span>' + dataArr[0] + '</span>').css({
  backgroundColor: "yellow"
})

$elem.append($innerElem);

console.log($elem[0].outerHTML)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


问:
R Pick First Value Given Condition
```<code>data=data.frame("team"=c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5),
                "score"=c(4,8,10,3,10,5,4,2,7,7,5,6,5,9,1),
                "trial"=c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3),
                "sc3"=c(0,0,0,1,0,0,0,1,0,0,0,0,0,0,1),
                "sc7"=c(0,0,0,1,0,1,1,1,1,1,1,1,1,0,1),
                "sc9"=c(1,1,0,1,0,1,1,1,1,1,1,1,1,1,1),
                "sc3trial"=c(-99,-99,-99,1,1,1,2,2,2,-99,-99,-99,3,3,3),
                "sc7trial"=c(-99,-99,-99,1,1,1,1,1,1,1,1,1,1,1,1),
                "sc9trial"=c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1))
</code>```

I have data with column "team" and "score" and "trial". I want to create variables "sc3", "sc7", "sc9", "sc3trial", "sc7trial", "sc9trial" that follow these rules::

The rules are simple for "sc#". Note these are for each group:

For "sc3": if score <= 3, sc3 = 1. Otherwise sc3 = 0.

For "sc7": if score <= 7, sc7 = 1. Otherwise sc7 = 0.

For "sc9": if score <= 9, sc9 = 1. Otherwise sc9 = 0.

The rules are sort of also simple for "sc#trial". Note these are for each group:

For "sc3trial": If any "sc3" == 1, sc3trial records the trial when it first occurred. If no "sc3" equals to '1' then "sc3trial" equals to "-99"
  This logic applies the same for "sc7trial" and "sc9trial"

答:
For the first 3 columns the code beloew works, but I didn't uderstand what you want for sc3trial, sc7trial and sc9trial.</p>

```<code>  data$sc3 = ifelse(data$score <= 3, 1, 0)
  data$sc7 = ifelse(data$score <= 7, 1, 0)
  data$sc7 = ifelse(data$score <= 9, 1, 0)
</code>```

Title: R Pick First Value Given Condition

Body:
data=data.frame("team"=c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5),
                "score"=c(4,8,10,3,10,5,4,2,7,7,5,6,5,9,1),
                "trial"=c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3),
                "sc3"=c(0,0,0,1,0,0,0,1,0,0,0,0,0,0,1),
                "sc7"=c(0,0,0,1,0,1,1,1,1,1,1,1,1,0,1),
                "sc9"=c(1,1,0,1,0,1,1,1,1,1,1,1,1,1,1),
                "sc3trial"=c(-99,-99,-99,1,1,1,2,2,2,-99,-99,-99,3,3,3),
                "sc7trial"=c(-99,-99,-99,1,1,1,1,1,1,1,1,1,1,1,1),
                "sc9trial"=c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1))

I have data with column "team" and "score" and "trial". I want to create variables "sc3", "sc7", "sc9", "sc3trial", "sc7trial", "sc9trial" that follow these rules::

The rules are simple for "sc#". Note these are for each group:

For "sc3": if score <= 3, sc3 = 1. Otherwise sc3 = 0.

For "sc7": if score <= 7, sc7 = 1. Otherwise sc7 = 0.

For "sc9": if score <= 9, sc9 = 1. Otherwise sc9 = 0.

The rules are sort of also simple for "sc#trial". Note these are for each group:

For "sc3trial": If any "sc3" == 1, sc3trial records the trial when it first occurred. If no "sc3" equals to '1' then "sc3trial" equals to "-99"
  This logic applies the same for "sc7trial" and "sc9trial"

Body:
For the first 3 columns the code beloew works, but I didn't uderstand what you want for sc3trial, sc7trial and sc9trial.

  data$sc3 = ifelse(data$score <= 3, 1, 0)
  data$sc7 = ifelse(data$score <= 7, 1, 0)
  data$sc7 = ifelse(data$score <= 9, 1, 0)


问:
Why do you need timeout in milliseconds and Why do I have to declare 2 Classes with separate run () methods for separate blocks
Im having issue with understanding some background things going on in my multithreaded application.

My question number 1:

I have a class (called SyncClass) which is responsible for creating synchronized blocks within 2 instance methods, called test1() and test2(). The test1() is supposed to increment an integer by 1 and then print it out and test2() which is supposed to do the same thing. These methods are supposed to increment the integer as long as the value is smaller than 10. So basically when test1() has incremented the value with 1, then it should hand it over to the other method test2() which should do the same thing until the condition is met.

At the moment these 2 methods have wait(2000), because if I have a simple wait with no limit then the program just keep executing with only partial result printed to the screen and then it just hangs.

There must probably be a better wait to solve it without needing the timeout, or ?

My question number 2:

I have an external class (called TheRunner) with another member class (called InnerRunner) where both implement Runnable where the outer class is having run()-method to run the test1()-method and the inner class to run the test2()-method.

Is there no way that I can have only one class implementing the Runnable to run the both test1() and test2() methods inside it (i.e. inside the run()-method)?

The code for the SyncClass looks like below:

```<code>package test;

public class SyncClass {

    int i = 0;
    boolean b = true;

    public void test1() {
        synchronized (this) {
            while((b == true) && (i < 10)) {
                i++;
                System.out.println("test 1:");
                System.out.println(i);
                b = false;

                try {
                    wait(2000);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }

    }

    public void test2() {
        synchronized (this) {
            while((b == false) && (i < 10)) {
                i++;
                System.out.println("test 2:");
                System.out.println(i);
                b = true;

                try {
                    wait(2000);
                    notify();
                } catch (InterruptedException e) {

                    e.printStackTrace();
                }

            }
        }
    }

}
</code>```

And then I have the other class which is implementing Runnable's to run the above methods:

```<code>package test;

public class TheRunner implements Runnable {

    SyncClass sync;

    public TheRunner(SyncClass sync) {
        this.sync = sync;
    }

    @Override
    public void run() {
        sync.test1();

    }

class InnerRunner implements Runnable{

    SyncClass sync;

    public InnerRunner(SyncClass sync) {
        this.sync = sync;
    }

    @Override
    public void run() {
        sync.test2();
    }

}

    public static void main(String[] args) {

        SyncClass sync = new SyncClass();
        TheRunner runner = new TheRunner(sync);
        TheRunner.InnerRunner innerRunner = runner.new InnerRunner(sync);

        Thread t1 = new Thread(runner);
        Thread t2 = new Thread(innerRunner);
        t1.start();
        t2.start();

    }
}
</code>```

If I remove the wait(2000) and replaces it with simple wait() then the output will be only:

test1:

1

test2:

2

..but it should continue up to 10, i.e. next iteration should be test1: 3, test2: 4, etc which it does when I change it with wait(2000). I dont really understand this?

答:
This is a lot of code, with a lot of misconceptions. I've simplified this example and it does not require timeouts or passing a value to wait. What you should use in a real code, is an AtomicInteger but here I've used an int[] so you can hopefully understand what is going on. Whenever you wait you need to ensure that some form of notify is invoked. Let's start with a single Runnable I've named Counter. Like,

```<code>public class Counter implements Runnable {
    private static int[] ai = { 0 };
    private int threadId;

    public Counter(int threadId) {
        this.threadId = threadId;
    }

    @Override
    public void run() {
        synchronized (ai) {
            int v;
            while ((v = ai[0]) < 10) {
                if (v % 2 != threadId % 2) {
                    System.out.printf("%s test%d %d%n",
                            Thread.currentThread().getName(),
                            threadId, ai[0]++);
                    ai.notifyAll();
                } else {
                    System.out.printf("%s test%d wait%n",
                            Thread.currentThread().getName(), threadId);
                    try {
                        ai.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
</code>```

We can then test it (the join(s) aren't strictly necessary, but I like to wait for the code to complete) like

```<code>public static void main(String[] args) {
    Thread t1 = new Thread(new Counter(1));
    Thread t2 = new Thread(new Counter(2));
    t1.start();
    t2.start();
    try {
        t1.join();
        t2.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
</code>```

which should (consistently) result in

```<code>Thread-0 test1 0
Thread-0 test1 wait
Thread-1 test2 1
Thread-1 test2 wait
Thread-0 test1 2
Thread-0 test1 wait
Thread-1 test2 3
Thread-1 test2 wait
Thread-0 test1 4
Thread-0 test1 wait
Thread-1 test2 5
Thread-1 test2 wait
Thread-0 test1 6
Thread-0 test1 wait
Thread-1 test2 7
Thread-1 test2 wait
Thread-0 test1 8
Thread-0 test1 wait
Thread-1 test2 9
</code>```

Body:
Im having issue with understanding some background things going on in my multithreaded application.

My question number 1:

I have a class (called SyncClass) which is responsible for creating synchronized blocks within 2 instance methods, called test1() and test2(). The test1() is supposed to increment an integer by 1 and then print it out and test2() which is supposed to do the same thing. These methods are supposed to increment the integer as long as the value is smaller than 10. So basically when test1() has incremented the value with 1, then it should hand it over to the other method test2() which should do the same thing until the condition is met.

At the moment these 2 methods have wait(2000), because if I have a simple wait with no limit then the program just keep executing with only partial result printed to the screen and then it just hangs.

There must probably be a better wait to solve it without needing the timeout, or ?

My question number 2:

I have an external class (called TheRunner) with another member class (called InnerRunner) where both implement Runnable where the outer class is having run()-method to run the test1()-method and the inner class to run the test2()-method.

Is there no way that I can have only one class implementing the Runnable to run the both test1() and test2() methods inside it (i.e. inside the run()-method)?

The code for the SyncClass looks like below:

package test;

public class SyncClass {

    int i = 0;
    boolean b = true;

    public void test1() {
        synchronized (this) {
            while((b == true) && (i < 10)) {
                i++;
                System.out.println("test 1:");
                System.out.println(i);
                b = false;

                try {
                    wait(2000);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }

    }

    public void test2() {
        synchronized (this) {
            while((b == false) && (i < 10)) {
                i++;
                System.out.println("test 2:");
                System.out.println(i);
                b = true;

                try {
                    wait(2000);
                    notify();
                } catch (InterruptedException e) {

                    e.printStackTrace();
                }

            }
        }
    }

}

And then I have the other class which is implementing Runnable's to run the above methods:

package test;

public class TheRunner implements Runnable {

    SyncClass sync;

    public TheRunner(SyncClass sync) {
        this.sync = sync;
    }

    @Override
    public void run() {
        sync.test1();

    }

class InnerRunner implements Runnable{

    SyncClass sync;

    public InnerRunner(SyncClass sync) {
        this.sync = sync;
    }

    @Override
    public void run() {
        sync.test2();
    }

}

    public static void main(String[] args) {

        SyncClass sync = new SyncClass();
        TheRunner runner = new TheRunner(sync);
        TheRunner.InnerRunner innerRunner = runner.new InnerRunner(sync);

        Thread t1 = new Thread(runner);
        Thread t2 = new Thread(innerRunner);
        t1.start();
        t2.start();

    }
}

If I remove the wait(2000) and replaces it with simple wait() then the output will be only:

test1:

1

test2:

2

..but it should continue up to 10, i.e. next iteration should be test1: 3, test2: 4, etc which it does when I change it with wait(2000). I dont really understand this?

Body:
This is a lot of code, with a lot of misconceptions. I've simplified this example and it does not require timeouts or passing a value to wait. What you should use in a real code, is an AtomicInteger but here I've used an int[] so you can hopefully understand what is going on. Whenever you wait you need to ensure that some form of notify is invoked. Let's start with a single Runnable I've named Counter. Like,

public class Counter implements Runnable {
    private static int[] ai = { 0 };
    private int threadId;

    public Counter(int threadId) {
        this.threadId = threadId;
    }

    @Override
    public void run() {
        synchronized (ai) {
            int v;
            while ((v = ai[0]) < 10) {
                if (v % 2 != threadId % 2) {
                    System.out.printf("%s test%d %d%n",
                            Thread.currentThread().getName(),
                            threadId, ai[0]++);
                    ai.notifyAll();
                } else {
                    System.out.printf("%s test%d wait%n",
                            Thread.currentThread().getName(), threadId);
                    try {
                        ai.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

We can then test it (the join(s) aren't strictly necessary, but I like to wait for the code to complete) like

public static void main(String[] args) {
    Thread t1 = new Thread(new Counter(1));
    Thread t2 = new Thread(new Counter(2));
    t1.start();
    t2.start();
    try {
        t1.join();
        t2.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

which should (consistently) result in

Thread-0 test1 0
Thread-0 test1 wait
Thread-1 test2 1
Thread-1 test2 wait
Thread-0 test1 2
Thread-0 test1 wait
Thread-1 test2 3
Thread-1 test2 wait
Thread-0 test1 4
Thread-0 test1 wait
Thread-1 test2 5
Thread-1 test2 wait
Thread-0 test1 6
Thread-0 test1 wait
Thread-1 test2 7
Thread-1 test2 wait
Thread-0 test1 8
Thread-0 test1 wait
Thread-1 test2 9


问:
how to access complex object in php
I have the following data structure $all =

```<code>[0] => stdClass Object
    (
        [abc@gmail.com] => Array
            (
                [usr] => 130
                [fname] => Bob
                [lname] => thekid
                [email] => abc@gmail.com
                [news] => 0
                [wres] => 1
                [SWAGLeaders] => 0
                [cca-cpg] => 1
                [cleanup-cpg] => 0
                [gas-cpg] => 1
                [pollinators-cpg] => 0
                [climate-int] => 0
                [composting-int] => 0
                [energy-int] => 1
                [other-int] => 0
                [pollinators-int] => 0
                [recycling-int] => 0
                [transport-int] => 1
                [trees-int] => 0
                [water-int] => 0
            )

    )
</code>```

How do I access the inner keys/values?

I tried print_r($all[0]['abc@gmail.com']); but that produced nothing

also, is 'abc@gmail.com' a key? or a variable?  I thought it was a key whose value is the array and then inside the array we have  additional key/value pairs

答:
That is clearly an object (denoted by the stdClass Object in that output), not an array. You can access it with $all->{"abc@gmail.com"}. This is how you force complex interpolation in place of a PHP symbol, where the symbol violates PHP's naming rules. So for example, object properties with dashes, or other illegal symbols, in them can be forced to be evaluated as strings and then as property names by wrapping them in strings and then in braces: $obj->{"this-is-ok"} whereas $obj->this-is-not.

As a side note, if this object comes from JSON, you can always force it to be stored as an array by utilizing the second argument of json_decode(), which if set to true will force the object to be built as an array instead. For some people this may make the dereferencing of keys easier. So if $all["abc@gmail.com"] seems more natural to you than $all->{"abc@gmail.com"} that might be the better approach.

Title: how to access complex object in php

Body:
I have the following data structure $all =

[0] => stdClass Object
    (
        [abc@gmail.com] => Array
            (
                [usr] => 130
                [fname] => Bob
                [lname] => thekid
                [email] => abc@gmail.com
                [news] => 0
                [wres] => 1
                [SWAGLeaders] => 0
                [cca-cpg] => 1
                [cleanup-cpg] => 0
                [gas-cpg] => 1
                [pollinators-cpg] => 0
                [climate-int] => 0
                [composting-int] => 0
                [energy-int] => 1
                [other-int] => 0
                [pollinators-int] => 0
                [recycling-int] => 0
                [transport-int] => 1
                [trees-int] => 0
                [water-int] => 0
            )

    )

How do I access the inner keys/values?

I tried print_r($all[0]['abc@gmail.com']); but that produced nothing

also, is 'abc@gmail.com' a key? or a variable?  I thought it was a key whose value is the array and then inside the array we have  additional key/value pairs


问:
see if value exists in multiple arrays, change value in one array if it does
Say that I had the following two arrays:

var arrToChangeAndCompare = [{name:'Bob'},{name:'Joe'},{name:'Alise'},{name:'Joe1'}];
var arrToCompare = [{name:'Frank'},{name:'Joe'},{name:'Jen'},{name:'Joe1'}];```
</div>
</div>
</p>

<p>And I want to first array to only contain unique names in the array its in, but also unique names compared to the second array (arrToCompare). To be clear, I don't want to REMOVE values that are not unique, I want to CHANGE them in "arrToChangeAndCompare" so they are then unique to both arrays. Keep in mind that if there are non-unique values in "arrToCompare", this does not matter. The only rule is that the "arrToChangeAndCompare" only has unique names in its array and names that are unique compared to "arrToCompare" as well.</p>

<p>I have the following code that almost does what I want, but it doesn't check the second array again once it changes a value in the first array to be unique, which results in the "arr" array to have all unique values, but the "arr" values are not unique in both arrays (Joe1 exists in the first array and the second array). </p>

<p><strong>ALMOST WORKING CODE</strong>
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = [{name:'Bob'},{name:'Joe'},{name:'Alise'},{name:'Joe1'}];
var arr2 = [{name:'Frank'},{name:'Joe'},{name:'Jen'},{name:'Joe1'}];

var arr3;
arr2.forEach(e2 => {
    arr3 = arr.map(e => {
        var name = e.name.match(/[a-zA-Z]*/)[0]
        if (e2.name === name) {
            var number = e.name.match(/[0-9]+/)
            if (number) {
                e.name = name + (+number[0] + 1)
            } else {
                e.name = name + 1
            }
        }
        return e
    })
})
console.log(arr3)</code>```

The expected output of arrays listed at the top would be one array that looks like this:

[
  {
    "name": "Bob"
  },
  {
    "name": "Joe2"
  },
  {
    "name": "Alise"
  },
  {
    "name": "Joe3"
  }
]```

EXPLANATION OF OUTPUT

Bob is unique, so no actual is done for the first object in arrToChangeAndCompare

Joe is not unique compared to the arrtoCompare, so its number needs to be changed. But, since Joe1 exists in arrToChangeAndCompare as well, it has to be incremented again to Joe2

Alise is unique to both arrays, so no actual is done for the third object in arrToChangeAndCompare

Joe1 is not unique compared to arrtoCompare, so Joe1 must be incremented to Joe2, But since Joe2 also exists in arrToChangeAndCompare, it must then be incremented to Joe3

All values in arrToChangeAndCompare are now unique compared to its own array and arrtoCompare

Please ask additional questions as needed. Your help is much appreciated!

答:
You could take a Set with name and the letter parts of name and check against.

If not found add string to set and return the value.

If found take letters, digits and increment the numerical value until no more combined string is in the set. Then update the set and return the new string.

var array1 = [{ name: 'Bob', foo: 42 }, { name: 'Bob', bar: 42 }, { name: 'Bob' }, { name: 'Joe' }, { name: 'Joe' }, { name: 'Joe' }, { name: 'Alise' }, { name: 'Joe1' }],
    array2 = [{ name: 'Frank' }, { name: 'Joe' }, { name: 'Jen' }, { name: 'Joe1' }],
    items = array2.reduce((s, { name }) => s.add(name).add(name.match(/^\D+/)[0]), new Set),
    result = array1.map(({ name, ...o }) => {
        if (!items.has(name)) {
            items.add(name);
            return { name, ...o };
        }
        var [letters, digits = 0] = name.split(/(\d+)/);
        digits = +digits;
        while (items.has(letters + ++digits));
        items.add(letters + digits);
        return { name: letters + digits, ...o };
    });

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
Say that I had the following two arrays:

var arrToChangeAndCompare = [{name:'Bob'},{name:'Joe'},{name:'Alise'},{name:'Joe1'}];
var arrToCompare = [{name:'Frank'},{name:'Joe'},{name:'Jen'},{name:'Joe1'}];

And I want to first array to only contain unique names in the array its in, but also unique names compared to the second array (arrToCompare). To be clear, I don't want to REMOVE values that are not unique, I want to CHANGE them in "arrToChangeAndCompare" so they are then unique to both arrays. Keep in mind that if there are non-unique values in "arrToCompare", this does not matter. The only rule is that the "arrToChangeAndCompare" only has unique names in its array and names that are unique compared to "arrToCompare" as well.

I have the following code that almost does what I want, but it doesn't check the second array again once it changes a value in the first array to be unique, which results in the "arr" array to have all unique values, but the "arr" values are not unique in both arrays (Joe1 exists in the first array and the second array).

ALMOST WORKING CODE

var arr = [{name:'Bob'},{name:'Joe'},{name:'Alise'},{name:'Joe1'}];
var arr2 = [{name:'Frank'},{name:'Joe'},{name:'Jen'},{name:'Joe1'}];

var arr3;
arr2.forEach(e2 => {
    arr3 = arr.map(e => {
        var name = e.name.match(/[a-zA-Z]*/)[0]
        if (e2.name === name) {
            var number = e.name.match(/[0-9]+/)
            if (number) {
                e.name = name + (+number[0] + 1)
            } else {
                e.name = name + 1
            }
        }
        return e
    })
})
console.log(arr3)

The expected output of arrays listed at the top would be one array that looks like this:

[
  {
    "name": "Bob"
  },
  {
    "name": "Joe2"
  },
  {
    "name": "Alise"
  },
  {
    "name": "Joe3"
  }
]

EXPLANATION OF OUTPUT

Bob is unique, so no actual is done for the first object in arrToChangeAndCompare

Joe is not unique compared to the arrtoCompare, so its number needs to be changed. But, since Joe1 exists in arrToChangeAndCompare as well, it has to be incremented again to Joe2

Alise is unique to both arrays, so no actual is done for the third object in arrToChangeAndCompare

Joe1 is not unique compared to arrtoCompare, so Joe1 must be incremented to Joe2, But since Joe2 also exists in arrToChangeAndCompare, it must then be incremented to Joe3

All values in arrToChangeAndCompare are now unique compared to its own array and arrtoCompare

Please ask additional questions as needed. Your help is much appreciated!

Body:
You could take a Set with name and the letter parts of name and check against.

If not found add string to set and return the value.

If found take letters, digits and increment the numerical value until no more combined string is in the set. Then update the set and return the new string.

var array1 = [{ name: 'Bob', foo: 42 }, { name: 'Bob', bar: 42 }, { name: 'Bob' }, { name: 'Joe' }, { name: 'Joe' }, { name: 'Joe' }, { name: 'Alise' }, { name: 'Joe1' }],
    array2 = [{ name: 'Frank' }, { name: 'Joe' }, { name: 'Jen' }, { name: 'Joe1' }],
    items = array2.reduce((s, { name }) => s.add(name).add(name.match(/^\D+/)[0]), new Set),
    result = array1.map(({ name, ...o }) => {
        if (!items.has(name)) {
            items.add(name);
            return { name, ...o };
        }
        var [letters, digits = 0] = name.split(/(\d+)/);
        digits = +digits;
        while (items.has(letters + ++digits));
        items.add(letters + digits);
        return { name: letters + digits, ...o };
    });

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How to set Textbox value at page load?
I have to set asp.net TextBox’s value at page load using JQuery.

Can somebody give me example ?

答:
If it is an ASP.NET TextBox Try this:</p>

```<code><script type="text/javascript">
    $(document).ready(function(){
        $('#<%= tb_ASPTextBox.ClientID %>').val("my value");
    });
</script>
</code>```

Title: How to set Textbox value at page load?

Body:
If it is an ASP.NET TextBox Try this:

<script type="text/javascript">
    $(document).ready(function(){
        $('#<%= tb_ASPTextBox.ClientID %>').val("my value");
    });
</script>


问:
Whats the difference between functions.database() and admin.database()
I am using firebase admin and firebase functions on my javascript server backend code, and i cant seem to figure out whats the difference between the fucntions and the admin database reference.
i can use both of them like this:</p>

```<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

admin.database.ref('reference');
functions.database.ref('reference');
</code>```

答:
The firebase-functions library is used only to declare Cloud Functions triggers for deployment with the Firebase CLI.

The firebase-admin library is the Firebase Admin SDK for node, and it's a collection of APIs to interact with Firebase and Google Cloud products.  It doesn't  deal with Cloud Functions at all, though you might use it in a Cloud Function.

When you write functions.database.ref('reference'), you are in the process of building a Realtime Database trigger.  It doesn't do anything until you complete the declaration and export the function so the Firebase CLI can find and deploy it.  I suggest reading the linked documentation in detail to figure out how that works.

When you write admin.database().ref('reference'), you are creating a Reference object that points to a location in Realtime Database.  You would use this to read and write the database.

Body:
I am using firebase admin and firebase functions on my javascript server backend code, and i cant seem to figure out whats the difference between the fucntions and the admin database reference.
i can use both of them like this:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

admin.database.ref('reference');
functions.database.ref('reference');


问:
How to find the variance between two groups in python pandas?
I have a dataframe like this,

```<code>ID   total_sec   is_weekday
1      300           1
1      200           0
2      280           1
2      260           0
3      190           1
4      290           0
5      500           1
5      520           0
</code>```

I want to find the ID with the largest variance between weekdays and weekends. If we missed the records for either weekdays or weekends, we calculate the variance as 0.
My expected output will be,

```<code>ID   variance
1       100
2       20
3       0
4       0
5       20
</code>```

答:
So long as you can guarantee you have 1-2 rows per ID and each row has a different 'is_weekday' value then you really just want the "peak-to-peak" (ptp) value. If not, figure out how to resolve duplicates on ['ID', 'is_weekday'] then use ptp.

```<code>import numpy as np

df.groupby('ID').total_sec.agg(np.ptp)
</code>```

```<code>ID
1    100
2     20
3      0
4      0
5     20
Name: total_sec, dtype: int64
</code>```

Body:
I have a dataframe like this,

ID   total_sec   is_weekday
1      300           1
1      200           0
2      280           1
2      260           0
3      190           1
4      290           0
5      500           1
5      520           0

I want to find the ID with the largest variance between weekdays and weekends. If we missed the records for either weekdays or weekends, we calculate the variance as 0.
My expected output will be,

ID   variance
1       100
2       20
3       0
4       0
5       20

Body:
So long as you can guarantee you have 1-2 rows per ID and each row has a different 'is_weekday' value then you really just want the "peak-to-peak" (ptp) value. If not, figure out how to resolve duplicates on ['ID', 'is_weekday'] then use ptp.

import numpy as np

df.groupby('ID').total_sec.agg(np.ptp)

ID
1    100
2     20
3      0
4      0
5     20
Name: total_sec, dtype: int64


问:
What should be the tenant admin url while creating SPO site collections in PnP PowerShell
I am using PnP PowerShell commandlets to create Site collection in SPO. I understand that we need to first connect to Tenant admin site before creating site collections as below

$tenantadminUrl = "https://tenantname-admin.sharepoint.com"

Connect-PnPOnline -url $tenantadminUrl -UseWebLogin

New-PnPTenantSite -Owner $item.Owner -TimeZone $item.TimeZone -Title $item.Title -Url $siteUrl -Template $item.Template -Lcid $item.Locale -Wait

for adminUrl, can we also run the above code if the url is "https://tenantname.sharepoint.com" i.e. without "-admin" part in the url?

Sample code of PnP PowerShell in Github uses without "-admin" part in its url(Link: https://github.com/SharePoint/PnP-PowerShell/blob/master/Samples/Provisioning.CreateSitesFromCsv/CreateSites.ps1)

$adminurl1 = "https://tenantname-admin.sharepoint.com"

$adminurl2 = "https://tenantname.sharepoint.com"

which of the above two urls is valid tenantAdmin Url?

Thanks,

答:
Only the URL with the "-admin" is your tenantAdmin URL.  You can connect to any site collection in your tenant to which have permissions using PowerShell (Connect-PnPOnline) and plenty of PowerShell commands that can be executed within those connections.  However, there are certain SharePoint Admin level actions which can only be executed when you are connection to your "-admin" site.  If you attempt to execute the New-PnPTenantSite command when you are connected to any site other than your "-admin" site, you will get 403 FORBIDDEN response, even if you are logged in as a SharePoint Administrator.

Look at it this way:  In your web browser of choice, open your "tenantname-admin.sharepoint.com" site in one tab, then open your non-admin root "tenantname.sharepoint.com" in another tab.  Notice how the "tenantname.sharepoint.com" appears as a "normal" SharePoint site collection?  It may house your App Catalog and other centralized pieces of data, but it still running on a standard SharePoint site template.  But your "tenantname-admin.sharepoint.com" opens the "SharePoint Admin Center", which, while it configures and interacts with your SharePoint sites, is not itself a SharePoint Site collection, but a specialized administrative interface.

While the documentation for PnP-Powershell will 'usually' warn you when you need to be connected to your "-admin" site, you can think of it this way -- if you were going to log in to the site through a browser and perform this action through the UI, would you have to log into your SharePoint Admin Center to do this action, or would you log into a specific SharePoint Site to perform this action.  Thus, when you are executing PowerShell commands, the same rules apply.


问:
Convert list of weekdays into intervals
I'm looking for a function that drops days of the week from a sequence of weekdays if 3 or more consecutive days follow each other. This is my test code (uses Test::More test framework)</p>

```<code>// function is($result, $expected, $message)
is(drop_days(""), "", 'Empty');
is(drop_days("Mo"), "Mo", 'One Day');
is(drop_days("Mo,Tu"), "Mo,Tu", 'Two Days');
is(drop_days("Mo,Tu,We"), "Mo-We", 'Three Days');
is(drop_days("Mo,Tu,We,Th,Fr,Sa,Su"), "Mo-Su", 'Seven Days');
is(drop_days("Mo,Tu,Th,Fr"), "Mo,Tu,Th,Fr", 'Four days with gap');
is(drop_days("Mo,Tu,We,Fr"), "Mo-We,Fr", '3 consecutive days, one single day');
is(drop_days("Mo,Tu,We,Fr,Sa,Su"), "Mo-We,Fr-Su", '2 pairs of 3 consecutive days');
</code>```

答:
sometimes the "dumb" approach is the smartest</p>

```<code>function drop_days($s) {
    static $map  = array(
        'Mo,Tu,We,Th,Fr,Sa,Su' => 'Mo-Su',
        'Mo,Tu,We,Th,Fr,Sa'    => 'Mo-Sa',
        'Mo,Tu,We,Th,Fr'       => 'Mo-Fr',
        'Mo,Tu,We,Th'          => 'Mo-Th',
        'Mo,Tu,We'             => 'Mo-We',
        'Tu,We,Th,Fr,Sa,Su'    => 'Tu-Su',
        'Tu,We,Th,Fr,Sa'       => 'Tu-Sa',
        'Tu,We,Th,Fr'          => 'Tu-Fr',
        'Tu,We,Th'             => 'Tu-Th',
        'We,Th,Fr,Sa,Su'       => 'We-Su',
        'We,Th,Fr,Sa'          => 'We-Sa',
        'We,Th,Fr'             => 'We-Fr',
        'Th,Fr,Sa,Su'          => 'Th-Su',
        'Th,Fr,Sa'             => 'Th-Sa',
        'Fr,Sa,Su'             => 'Fr-Su',
    );
    return strtr($s, $map);
}
</code>```

Title: Convert list of weekdays into intervals

Body:
I'm looking for a function that drops days of the week from a sequence of weekdays if 3 or more consecutive days follow each other. This is my test code (uses Test::More test framework)

// function is($result, $expected, $message)
is(drop_days(""), "", 'Empty');
is(drop_days("Mo"), "Mo", 'One Day');
is(drop_days("Mo,Tu"), "Mo,Tu", 'Two Days');
is(drop_days("Mo,Tu,We"), "Mo-We", 'Three Days');
is(drop_days("Mo,Tu,We,Th,Fr,Sa,Su"), "Mo-Su", 'Seven Days');
is(drop_days("Mo,Tu,Th,Fr"), "Mo,Tu,Th,Fr", 'Four days with gap');
is(drop_days("Mo,Tu,We,Fr"), "Mo-We,Fr", '3 consecutive days, one single day');
is(drop_days("Mo,Tu,We,Fr,Sa,Su"), "Mo-We,Fr-Su", '2 pairs of 3 consecutive days');

Body:
sometimes the "dumb" approach is the smartest

function drop_days($s) {
    static $map  = array(
        'Mo,Tu,We,Th,Fr,Sa,Su' => 'Mo-Su',
        'Mo,Tu,We,Th,Fr,Sa'    => 'Mo-Sa',
        'Mo,Tu,We,Th,Fr'       => 'Mo-Fr',
        'Mo,Tu,We,Th'          => 'Mo-Th',
        'Mo,Tu,We'             => 'Mo-We',
        'Tu,We,Th,Fr,Sa,Su'    => 'Tu-Su',
        'Tu,We,Th,Fr,Sa'       => 'Tu-Sa',
        'Tu,We,Th,Fr'          => 'Tu-Fr',
        'Tu,We,Th'             => 'Tu-Th',
        'We,Th,Fr,Sa,Su'       => 'We-Su',
        'We,Th,Fr,Sa'          => 'We-Sa',
        'We,Th,Fr'             => 'We-Fr',
        'Th,Fr,Sa,Su'          => 'Th-Su',
        'Th,Fr,Sa'             => 'Th-Sa',
        'Fr,Sa,Su'             => 'Fr-Su',
    );
    return strtr($s, $map);
}


问:
Can someone explain what is happening with this piece of micro python
Just started playing with a BBC micro:bit. One of the examples has this line of code

flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]

It generates set of images. In trying to figure out what is going on I wrote this piece of code

```<code>class Image:
    def __init__(self,*args):
        print ("init")
        for a in args:
            print (a)

    def invert(self, *args):
        print ("invert")
        for a in args:
            print (a)

flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]

print ( flash )
</code>```

which produces

```<code>python3 test.py
init
invert
Traceback (most recent call last):
  File "test.py", line 14, in <module>
    flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]
  File "test.py", line 14, in <listcomp>
    flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]
TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'
</code>```

Thanks

答:
Just discovered Image has a * operator, ie its not the unpack operator, which was the thing that was confusing me.

Thanks for the responses

Body:
Just started playing with a BBC micro:bit. One of the examples has this line of code

flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]

It generates set of images. In trying to figure out what is going on I wrote this piece of code

class Image:
    def __init__(self,*args):
        print ("init")
        for a in args:
            print (a)

    def invert(self, *args):
        print ("invert")
        for a in args:
            print (a)

flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]

print ( flash )

which produces

python3 test.py
init
invert
Traceback (most recent call last):
  File "test.py", line 14, in <module>
    flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]
  File "test.py", line 14, in <listcomp>
    flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]
TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'

Thanks


问:
Check if there is a string in a string
I was wondering if there is any way to check if a string is included in a string. For example if I have the string1: superman and string2: per I would  like to know that string2 is contained in string1 and that the first letter of string2 is in position 2 of the string array of string1. Is it possible to do some trick with some already built function to achieve this?

答:
You may use strcmp function.
The strcmp() function compares two strings and returns 0 if both strings are identical. Find more information from the following link.
https://www.programiz.com/c-programming/library-function/string.h/strcmp</p>

Title: Check if there is a string in a string