问:
Jetpack Compose: UnsupportedOperationException when adding Entries to MPAndroidCharts dynamically
I try to display live data in an MPAndroidChart hosted in an AndroidView.

I get the graph but an UnsupportedOperationException happens when I call addEntry() to update the graph dynamically. Am I doing something wrong?

You find a demo repo in the comments.

@Composable
fun MyLineChart() {
    val mainViewModel = viewModel()
    val sensorData = mainViewModel.sensorFlow.collectAsState(SensorModel(0F,0F)).value

    AndroidView(modifier = Modifier.fillMaxSize(),
        factory = { context ->
            val lineChart = LineChart(context)
            var entries = listOf(Entry(1f,1f))

            val dataSet = LineDataSet(entries, "Label").apply { color = Color.Red.toArgb() }

            val lineData = LineData(dataSet)
            lineChart.data = lineData
            lineChart.invalidate()

            lineChart
        }){

        try {
            Log.d("TAG", "MyLineChart: Update --- Current thread id: ${Thread.currentThread()}")

            it.data.dataSets[0].addEntry(Entry(sensorData.x, sensorData.y))
            it.lineData.notifyDataChanged()
            it.notifyDataSetChanged()
            it.invalidate()
        } catch(ex: Exception) {
            Log.d("TAG", "MyLineChart: $ex")
        }
    }
}
```
<p>The data is sent to the view via the following <code>ViewModel</code>:</p>
<pre class="lang-kotlin prettyprint-override"><code>@HiltViewModel
class MainViewModel @Inject constructor(@ApplicationContext var appContext: Context) : ViewModel()  {
    private var rand: Random = Random(1)

    val sensorFlow: Flow<SensorModel> = flow<SensorModel> {

        while (true) {
            delay(1000L)
            Log.d("TAG", "sensorFlow: Current thread id: ${Thread.currentThread()}")
            emit(SensorModel(rand.nextFloat(), rand.nextFloat()))
        }
    }
}
</code>```

答:
try this code:</p>
```<code>        // it.data.dataSets[0].addEntry(Entry(sensorData.x, sensorData.y))

        val entryList =  mutableListOf<Entry>()
        entryList.add(Entry(sensorData.x, sensorData.y))

        val dataSet = LineDataSet(entryList, "Label").apply {
            color = Color.Red.toArgb()
        }

        it.data = LineData(dataSet)
</code>```

Body:
I try to display live data in an MPAndroidChart hosted in an AndroidView.

I get the graph but an UnsupportedOperationException happens when I call addEntry() to update the graph dynamically. Am I doing something wrong?

You find a demo repo in the comments.

@Composable
fun MyLineChart() {
    val mainViewModel = viewModel()
    val sensorData = mainViewModel.sensorFlow.collectAsState(SensorModel(0F,0F)).value

    AndroidView(modifier = Modifier.fillMaxSize(),
        factory = { context ->
            val lineChart = LineChart(context)
            var entries = listOf(Entry(1f,1f))

            val dataSet = LineDataSet(entries, "Label").apply { color = Color.Red.toArgb() }

            val lineData = LineData(dataSet)
            lineChart.data = lineData
            lineChart.invalidate()

            lineChart
        }){

        try {
            Log.d("TAG", "MyLineChart: Update --- Current thread id: ${Thread.currentThread()}")

            it.data.dataSets[0].addEntry(Entry(sensorData.x, sensorData.y))
            it.lineData.notifyDataChanged()
            it.notifyDataSetChanged()
            it.invalidate()
        } catch(ex: Exception) {
            Log.d("TAG", "MyLineChart: $ex")
        }
    }
}

The data is sent to the view via the following ViewModel:

@HiltViewModel
class MainViewModel @Inject constructor(@ApplicationContext var appContext: Context) : ViewModel()  {
    private var rand: Random = Random(1)

    val sensorFlow: Flow<SensorModel> = flow<SensorModel> {

        while (true) {
            delay(1000L)
            Log.d("TAG", "sensorFlow: Current thread id: ${Thread.currentThread()}")
            emit(SensorModel(rand.nextFloat(), rand.nextFloat()))
        }
    }
}

Body:
try this code:

        // it.data.dataSets[0].addEntry(Entry(sensorData.x, sensorData.y))

        val entryList =  mutableListOf<Entry>()
        entryList.add(Entry(sensorData.x, sensorData.y))

        val dataSet = LineDataSet(entryList, "Label").apply {
            color = Color.Red.toArgb()
        }

        it.data = LineData(dataSet)


来源: stackexchange

问:
trying to insert an array but Cannot access offset of type string on string laravel 8
i want to insert an array but it tells me Cannot access offset of type string on string

and i made foreach and when i do $return->request
it looks like

```<code>{
    _token: "qb7dTYdsDVtw1RJnQQARzJMEqIfHPeQbHobiC8u2",
    _method: "POST",
    name: "Wanda Rojas",
    phone: [
    "+1 (841) 393-5088",
    "+1 (769) 441-1936"
    ],
    address: "Et est cum delectus"
}
</code>```

and here is my model for clients

and i make phone field as array in protected $casts

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Client extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'address',
    ];

    protected $casts = [
        'phone' => 'array'
    ];
}
</code>```

here is my form

```<code><form action="{{route('clients.store')}}" method="POST">
        @csrf
        @method('POST')

        <input type="text" placeholder="add name" name="name"><br>
        @for ($i = 0; $i < 2; $i++) <div class="form-group">
            <label>@lang('site.phone')</label>
            <input type="text" name="phone[]" class="form-control">
            </div>
        @endfor
            <input type="text" placeholder="add address" name="address"><br>
            <button type="submit" class="btn btn-primary">add</button>
</form>
</code>```

and here is my controller at store method

```<code> public function store(Request $request)
{
    //return $request;

    $this->validate($request,[
        'name' => 'required',
        'phone' => 'required|array|min:1',
        'phone.*' => 'required',
        'address' => 'required'
    ]);

    $phone = $request->phone;
    foreach ($phone as $p){
        $add = new Client();
        $add->name = $request->name;
        $add->phone = $p['phone'];
        $add->address = $request->address;
        $add->save();
    };

    return redirect()->route('clients.index');
}
</code>```

答: You are iterating through the array of phone numbers so $p is the phone number. $add->phone = $p should resolve your issue.

ContentLicense: CC BY-SA 4.0

Body:
i want to insert an array but it tells me Cannot access offset of type string on string

and i made foreach and when i do $return->request
it looks like

{
    _token: "qb7dTYdsDVtw1RJnQQARzJMEqIfHPeQbHobiC8u2",
    _method: "POST",
    name: "Wanda Rojas",
    phone: [
    "+1 (841) 393-5088",
    "+1 (769) 441-1936"
    ],
    address: "Et est cum delectus"
}

and here is my model for clients

and i make phone field as array in protected $casts

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Client extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'address',
    ];

    protected $casts = [
        'phone' => 'array'
    ];
}

here is my form

<form action="{{route('clients.store')}}" method="POST">
        @csrf
        @method('POST')

        <input type="text" placeholder="add name" name="name">

        @for ($i = 0; $i < 2; $i++)

            @lang('site.phone')
            <input type="text" name="phone[]" class="form-control">

        @endfor
            <input type="text" placeholder="add address" name="address">

            <button type="submit" class="btn btn-primary">add</button>
</form>

and here is my controller at store method

 public function store(Request $request)
{
    //return $request;

    $this->validate($request,[
        'name' => 'required',
        'phone' => 'required|array|min:1',
        'phone.*' => 'required',
        'address' => 'required'
    ]);

    $phone = $request->phone;
    foreach ($phone as $p){
        $add = new Client();
        $add->name = $request->name;
        $add->phone = $p['phone'];
        $add->address = $request->address;
        $add->save();
    };

    return redirect()->route('clients.index');
}


问:
Unique coverage between a pair of values in SQL
I want to get a distinct list of Item_IDs per vendor pair, e.g. (A,B), (A,C), (B,C)
I have a table like this:

```<code>Item_ID | vendor
123         A
123         B
133         B
456         C
</code>```

I want to list ALL of the distinct Item_IDs between each pair of vendors, like below. Essentially, I want to know all of the Item_IDs which are "covered" (or present) between a pair of vendors.

```<code>Vendor1 | Vendor 2 | Item_ID
A           B         123
A           B         133
A           C         123
A           C         456
B           C         123
B           C         133
B           C         456
</code>```

I have tried using a self join, to get 2 vendors side by side, but struggling on how to list out the Item_IDs per pair.
Here is what I have so far:

```<code>select
  distinct a.vendor as vendor1, b.vendor as vendor2
from table a
join table b on a.vendor != b.vendor
            and a.vendor >= b.vendor -- to remove duplicate combinations
</code>```

答:
The following query works in SQL Server 2019 but I don't have the chance of testing it in Azure.

You can do:

```<code>with
v as (select distinct vendor as vendor from t)
select
  a.vendor as vendor1,
  b.vendor as vendor2,
  x.item_id
from v a
join v b on b.vendor > a.vendor
cross apply (
  select distinct item_id
  from t
  where t.vendor = a.vendor or t.vendor = b.vendor
) x
order by a.vendor, b.vendor
</code>```

Result:

```<code> vendor1  vendor2  item_id
 -------- -------- -------
 A        B        123
 A        B        133
 A        C        123
 A        C        456
 B        C        123
 B        C        133
 B        C        456
</code>```

See running example at db<>fiddle.

Body:
I want to get a distinct list of Item_IDs per vendor pair, e.g. (A,B), (A,C), (B,C)
I have a table like this:

Item_ID | vendor
123         A
123         B
133         B
456         C

I want to list ALL of the distinct Item_IDs between each pair of vendors, like below. Essentially, I want to know all of the Item_IDs which are "covered" (or present) between a pair of vendors.

Vendor1 | Vendor 2 | Item_ID
A           B         123
A           B         133
A           C         123
A           C         456
B           C         123
B           C         133
B           C         456

I have tried using a self join, to get 2 vendors side by side, but struggling on how to list out the Item_IDs per pair.
Here is what I have so far:

select
  distinct a.vendor as vendor1, b.vendor as vendor2
from table a
join table b on a.vendor != b.vendor
            and a.vendor >= b.vendor -- to remove duplicate combinations

Body:
The following query works in SQL Server 2019 but I don't have the chance of testing it in Azure.

You can do:

with
v as (select distinct vendor as vendor from t)
select
  a.vendor as vendor1,
  b.vendor as vendor2,
  x.item_id
from v a
join v b on b.vendor > a.vendor
cross apply (
  select distinct item_id
  from t
  where t.vendor = a.vendor or t.vendor = b.vendor
) x
order by a.vendor, b.vendor

Result:

 vendor1  vendor2  item_id
 -------- -------- -------
 A        B        123
 A        B        133
 A        C        123
 A        C        456
 B        C        123
 B        C        133
 B        C        456

See running example at db<>fiddle.


问:
Custom train-test split using two stratified classes
I am trying to use NLP techniques to predict the mental status of patients at the time doctor's notes were taken. I have two classes, suffix (multilabel) as well as mental_status (binary, Lucid or Delirium). I am trying to build train and test sets from a reduced list that meet the following specifications:

Shared unique suffix list

For each set for each suffix, at least one row for Lucid and Delirium

Any imbalances I will correct with sample weights (I am only trying to predict mental_status, but I need the data to also be balanced on suffix). I just need at least one row for each combination within the full Cartesian product of suffixes and mental_statuses.

For example, in the dataset below, only the DWM Communication suffixes would make it into the train-test split.

```<code>suffix              mental_status
DWN Communication   Lucid
DWN Communication   Delirium
DWN Communication   Lucid
DWN Communication   Delirium
DWN Communication   Lucid
DWN Psychiatry      Lucid
DWN Psychiatry      Delirium
DWN Psychiatry      Delirium
DWN Cardio stuff    Lucid
DWN Cardio stuff    Delirium
DWN Blood .....     Lucid
DWN Blood .....     Lucid
DWN Blood .....     Lucid
</code>```

The output I would want for the example above for train would be

```<code>DWN Communication   Lucid
DWN Communication   Delirium
DWN Communication   Lucid
</code>```

and test

```<code>DWN Communication   Lucid
DWN Communication   Delirium
</code>```

I've tried

```<code>df.groupby(['suffix','mental_status']).filter(lambda x: len(x) > 1)
</code>```

but it doesn't ensure there is one of each Delirium and Lucid for each suffix.

As another example,

```<code>    suf ms
11  blood   delirium
15  blood   delirium
0   blood   lucid
1   blood   lucid
5   blood   lucid
6   blood   lucid
10  blood   lucid
16  blood   lucid
3   psych   delirium
19  psych   delirium
4   psych   lucid
8   psych   lucid
9   psych   lucid
13  psych   lucid
14  psych   lucid
18  psych   lucid
7   stool   delirium
2   stool   lucid
12  stool   lucid
17  stool   lucid
</code>```

would be split into

```<code>    suf ms
11  blood   delirium
0   blood   lucid
1   blood   lucid
5   blood   lucid
6   blood   lucid
3   psych   delirium
4   psych   lucid
8   psych   lucid
9   psych   lucid
13  psych   lucid
</code>```

and

```<code>    suf ms
15  blood   delirium
10  blood   lucid
16  blood   lucid
19  psych   delirium
14  psych   lucid
18  psych   lucid
</code>```

Edit:

I think I arrived at a solution:

```<code>from sklearn.model_selection import train_test_split
def custom_split(df, test_size):
    f = lambda ms: (
        df[df.mental_status==ms]
        .groupby('suffix')
        .filter(lambda x:len(x)>=1/min(test_size,1-test_size))
        .suffix
    )
    delirium = f('Delirium')
    lucid = f('Lucid')
    valid_suffixes = set(delirium).intersection(lucid)
    df = df[df.suffix.isin(valid_suffixes)]
    df_train, df_test = train_test_split(df,test_size,random_state=9,
                                         stratify=df.mental_status+df.suffix)
    return df_train, df_test
</code>```

答:
Use a mask filter:

mask = df["DWN" in df['suffix']]
df = df[mask]
df.dropna(inplace=True)
```
<p>use Groupby</p>
```data="""index,suf,ms
11,blood,delirium
15,blood,delirium
0,blood,lucid
1,blood,lucid
5,blood,lucid
6,blood,lucid
10,blood,lucid
16,blood,lucid
3,psych,delirium
19,psych,delirium
4,psych,lucid
8,psych,lucid
9,psych,lucid
13,psych,lucid
14,psych,lucid
18,psych,lucid
7,stool,delirium
2,stool,lucid
12,stool,lucid
17,stool,lucid"""

df = pd.read_csv(io.StringIO(data), sep=',')
#print(df)
lst=[]
grouped=df.groupby(['suf','ms'])
for group in grouped.groups:
    lst.append(group)

print(lst)
```
<p>output:</p>
```[('blood', 'delirium'), ('blood', 'lucid'), ('psych', 'delirium'), ('psych', 'lucid'), ('stool', 'delirium'), ('stool', 'lucid')]
```

you can now use the tuples as filters

Body:
I am trying to use NLP techniques to predict the mental status of patients at the time doctor's notes were taken. I have two classes, suffix (multilabel) as well as mental_status (binary, Lucid or Delirium). I am trying to build train and test sets from a reduced list that meet the following specifications:

Shared unique suffix list

For each set for each suffix, at least one row for Lucid and Delirium

Any imbalances I will correct with sample weights (I am only trying to predict mental_status, but I need the data to also be balanced on suffix). I just need at least one row for each combination within the full Cartesian product of suffixes and mental_statuses.

For example, in the dataset below, only the DWM Communication suffixes would make it into the train-test split.

suffix              mental_status
DWN Communication   Lucid
DWN Communication   Delirium
DWN Communication   Lucid
DWN Communication   Delirium
DWN Communication   Lucid
DWN Psychiatry      Lucid
DWN Psychiatry      Delirium
DWN Psychiatry      Delirium
DWN Cardio stuff    Lucid
DWN Cardio stuff    Delirium
DWN Blood .....     Lucid
DWN Blood .....     Lucid
DWN Blood .....     Lucid

The output I would want for the example above for train would be

DWN Communication   Lucid
DWN Communication   Delirium
DWN Communication   Lucid

and test

DWN Communication   Lucid
DWN Communication   Delirium

I've tried

df.groupby(['suffix','mental_status']).filter(lambda x: len(x) > 1)

but it doesn't ensure there is one of each Delirium and Lucid for each suffix.

As another example,

    suf ms
11  blood   delirium
15  blood   delirium
0   blood   lucid
1   blood   lucid
5   blood   lucid
6   blood   lucid
10  blood   lucid
16  blood   lucid
3   psych   delirium
19  psych   delirium
4   psych   lucid
8   psych   lucid
9   psych   lucid
13  psych   lucid
14  psych   lucid
18  psych   lucid
7   stool   delirium
2   stool   lucid
12  stool   lucid
17  stool   lucid

would be split into

    suf ms
11  blood   delirium
0   blood   lucid
1   blood   lucid
5   blood   lucid
6   blood   lucid
3   psych   delirium
4   psych   lucid
8   psych   lucid
9   psych   lucid
13  psych   lucid

and

    suf ms
15  blood   delirium
10  blood   lucid
16  blood   lucid
19  psych   delirium
14  psych   lucid
18  psych   lucid

Edit:

I think I arrived at a solution:

from sklearn.model_selection import train_test_split
def custom_split(df, test_size):
    f = lambda ms: (
        df[df.mental_status==ms]
        .groupby('suffix')
        .filter(lambda x:len(x)>=1/min(test_size,1-test_size))
        .suffix
    )
    delirium = f('Delirium')
    lucid = f('Lucid')
    valid_suffixes = set(delirium).intersection(lucid)
    df = df[df.suffix.isin(valid_suffixes)]
    df_train, df_test = train_test_split(df,test_size,random_state=9,
                                         stratify=df.mental_status+df.suffix)
    return df_train, df_test

Body:
Use a mask filter:

mask = df["DWN" in df['suffix']]
df = df[mask]
df.dropna(inplace=True)

use Groupby

data="""index,suf,ms
11,blood,delirium
15,blood,delirium
0,blood,lucid
1,blood,lucid
5,blood,lucid
6,blood,lucid
10,blood,lucid
16,blood,lucid
3,psych,delirium
19,psych,delirium
4,psych,lucid
8,psych,lucid
9,psych,lucid
13,psych,lucid
14,psych,lucid
18,psych,lucid
7,stool,delirium
2,stool,lucid
12,stool,lucid
17,stool,lucid"""

df = pd.read_csv(io.StringIO(data), sep=',')
#print(df)
lst=[]
grouped=df.groupby(['suf','ms'])
for group in grouped.groups:
    lst.append(group)

print(lst)

output:

[('blood', 'delirium'), ('blood', 'lucid'), ('psych', 'delirium'), ('psych', 'lucid'), ('stool', 'delirium'), ('stool', 'lucid')]

you can now use the tuples as filters


问:
Google maps autocomplete, fix to the input
I'm trying to add a google maps autocomplete input to my ionic app. It works pretty well except when I scroll. As shown on the image:

So I tried different things like changing the position of .pac-container but it doesn't solve the problem.
When I inspect the page, it seems that the results container loads at the end of the page, so it's not easy to make the block stick to the input bar.

I already searched everywhere and didn't fidn any suitable solution ? Does someone have an idea how to do it ?
(It's actually just a simple code like this:

function initialize() {
    var options = {componentRestrictions: {country: 'uk'}, types: ['geocode']}
    new google.maps.places.Autocomplete(
        (document.getElementById('autocomplete')),
        options
    );
}

initialize();
```

jsfiddle

Thanks

答: In my case, I had to set the css as html,body{overflow-x:visible;} to make the pac-container fixed to the input field.

Body:
I'm trying to add a google maps autocomplete input to my ionic app. It works pretty well except when I scroll. As shown on the image:

So I tried different things like changing the position of .pac-container but it doesn't solve the problem.
When I inspect the page, it seems that the results container loads at the end of the page, so it's not easy to make the block stick to the input bar.

I already searched everywhere and didn't fidn any suitable solution ? Does someone have an idea how to do it ?
(It's actually just a simple code like this:

function initialize() {
    var options = {componentRestrictions: {country: 'uk'}, types: ['geocode']}
    new google.maps.places.Autocomplete(
        (document.getElementById('autocomplete')),
        options
    );
}

initialize();

jsfiddle

Thanks


问:
Excel: Merge two columns into one column with alternating values
how can I merge two columns of data into one like the following:</p>

```<code>Col1    Col2    Col3
========================
A       1       A
B       2       1
C       3       B
                2
                C
                3
</code>```

答:
And here we add column A and D
two different formulas depending on if you add the formula to an odd row or an even row.

https://1drv.ms/x/s!AncAhUkdErOkguUaToQkVkl5Qw-l_g?e=5d9gVM

Odd Start row

```<code>=INDEX($A$2:$D$9;ROUND(ROW(A1)/2;0);IF(MOD(ROW()-ROW($A$2);2)=1;4;1))
</code>```

Even Start row

```<code>=INDEX($A$2:$D$9;ROUND(ROW(A1)/2;0);IF(MOD(ROW()-ROW($A$1);2)=1;4;1))
</code>```

What is A1 in the picture is the cell directly above your first data cell.

If you want to place it on a different sheet you just add the sheet name:

```<code>=INDEX(MySheet!$A$2:$D$9;ROUND(ROW(MySheet!A1)/2;0);IF(MOD(ROW()-ROW(MySheet!$A$2);2)=1;4;1))
=INDEX(MySheet!$A$2:$D$9;ROUND(ROW(MySheet!A1)/2;0);IF(MOD(ROW()-ROW(MySheet!$A$1);2)=1;4;1))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
how can I merge two columns of data into one like the following:

Col1    Col2    Col3
========================
A       1       A
B       2       1
C       3       B
                2
                C
                3

Body:
And here we add column A and D
two different formulas depending on if you add the formula to an odd row or an even row.

https://1drv.ms/x/s!AncAhUkdErOkguUaToQkVkl5Qw-l_g?e=5d9gVM

Odd Start row

=INDEX($A$2:$D$9;ROUND(ROW(A1)/2;0);IF(MOD(ROW()-ROW($A$2);2)=1;4;1))

Even Start row

=INDEX($A$2:$D$9;ROUND(ROW(A1)/2;0);IF(MOD(ROW()-ROW($A$1);2)=1;4;1))

What is A1 in the picture is the cell directly above your first data cell.

If you want to place it on a different sheet you just add the sheet name:

=INDEX(MySheet!$A$2:$D$9;ROUND(ROW(MySheet!A1)/2;0);IF(MOD(ROW()-ROW(MySheet!$A$2);2)=1;4;1))
=INDEX(MySheet!$A$2:$D$9;ROUND(ROW(MySheet!A1)/2;0);IF(MOD(ROW()-ROW(MySheet!$A$1);2)=1;4;1))


问:
How to solve Angular Firebase v.7 issue: Cannot use 'in' operator to search for '_delegate' in users/xxxxx
I am using the new Angular Firebase v.7 with Angular and I am getting an error: Cannot use 'in' operator to search for '_delegate' in users/1QAvZYg6aqe0GhA13tmVAINa.

There is a similar question ( Firebase Error: TypeError: Cannot use 'in' operator to search for '_delegate' in undefined ) but it is unanswered and I have been trying  to little avail to find one myself. Perhaps I am overlooking something very simple.

The code

The service responsible for creating the document is in data.service.ts as looks like this:

```<code>import { Injectable } from '@angular/core';
import {
    collection, deleteDoc, doc, DocumentSnapshot, Firestore, onSnapshot,
    query, QuerySnapshot, setDoc, Timestamp as fTimestamp, Unsubscribe
} from '@angular/fire/firestore';
import { firstValueFrom, lastValueFrom, Observable, Subject } from 'rxjs';
import { take } from 'rxjs/operators';

export interface FirestoreExtDoc<T> {
    data: Observable<T>;
    unsubscribe: Unsubscribe;
}
export interface FirestoreExtCol<T> {
    data: Observable<T[]>;
    unsubscribe: Unsubscribe;
}

@Injectable({
  providedIn: 'root'
})
export class DataService {
  constructor(private db: Firestore) { }
    upsert<DocumentData>(ref: string, data: any): Promise<void> {
        const docRef = doc(this.db, ref);
        const timestamp = fTimestamp.now();
        const newData = {
            ...data,
            updatedAt: timestamp,
            createdAt: timestamp,
        };
        const updatedData = {
            ...data,
            updatedAt: timestamp,
        };
        const snapshot = lastValueFrom(this.getDoc<DocumentData>(ref).data.pipe(take(1)));
        return snapshot.then(
            snap => (snap as any).exists ?
                setDoc(docRef, updatedData, { merge: true }) :
                setDoc(docRef, newData, { merge: true })
            );
    };
}
</code>```

In my auth.service.ts I import the above data service and call the upsert method like this:

```<code>import { Injectable } from '@angular/core';
import {
  Auth,
  signInWithEmailAndPassword,
  GoogleAuthProvider,
  authState,
  createUserWithEmailAndPassword,
  updateProfile,
  UserInfo,
  signInWithPopup,
  sendPasswordResetEmail
} from '@angular/fire/auth';
import {
  doc,
  collection,
  collectionGroup,
  setDoc,
  updateDoc,
  deleteDoc,
  docSnapshots,
  docData,
  getDoc
} from '@angular/fire/firestore';
import { User } from '@core/interfaces/user';

import { concatMap, from, Observable, of, switchMap } from 'rxjs';
import { DataService } from './data.service';

@Injectable({
  providedIn: 'root',
})
export class AuthService {

  currentUser$ = authState(this.auth);

  constructor(
    private auth: Auth,
    private dataService: DataService
    ) {}

  signUp(name: string, email: string, password: string): Observable<any> {
    return from(
      createUserWithEmailAndPassword(this.auth, email, password)
    ).pipe(switchMap(({ user }) => updateProfile(user, { displayName: name }).then((data) => { this.dataService.upsert(`users/${user.uid}`, data) }) ));
  }
}
</code>```

答:
In case you decide to go with a Cloud Function, the below code I use across several different apps and projects and it works faultlessly every time a user either signs up or is created by an 'Admin' user...

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

admin.initializeApp();

const db = admin.firestore();

/**
 * Add user to firestore
 */
const creatProfile = (userRecord) => {
    const uid = userRecord.uid;
    const admin = false;
    const email = userRecord.email;
    const photoURL = userRecord.photoUrl || 'enter shortened url for default image';
    const name = userRecord.displayName || 'New User';
    const spouse = userRecord.spouse || 'TBA';
    const forumUserName = userRecord.forumUserName || 'New Username set by admin';
    const address = userRecord.address || 'TBA';
    const suburb = userRecord.suburb || 'TBA';
    const state = userRecord.state || 'QLD';
    const postCode = userRecord.postCode || '2000';
    const homePhone = userRecord.homePhone || '02 1234 5678';
    const mobilePhone = userRecord.mobilePhone || '0400 123 456';
    const memNum = userRecord.memNum || 123;
    const timestamp = FieldValue.serverTimestamp();
    const memType = userRecord.memType || 'Nominated';
    const memStatus = userRecord.memStatus || `Pending`;
    const isStateCoord = userRecord.isStateCoord || false;
    const stateCoordState = userRecord.stateCoordState || 'QLD';
    //const newUserRef = db.doc(`users/${uid}`)

    // Convert any date to timestamp for consistency

    return db
        .collection(`users`)
        .doc(userRecord.uid)
        .set({
        uid: uid,
        email: email,
        photoURL: photoURL,
        fullName: name,
        mDOB: timestamp,
        spouse: spouse,
        sDOB: timestamp,
        forumUserName: forumUserName,
        address: address,
        suburb: suburb,
        state: state,
        postCode: postCode,
        homePhone: homePhone,
        mobilePhone: mobilePhone,
        memNum: memNum,
        memType: memType,
        memStatus: memStatus,
        memDueDate: timestamp,
        lastLoginDate: timestamp,
        joined: timestamp,
        updated: timestamp,
        admin: admin,
        isAdmin: isAdmin,
        isStateCoord: isStateCoord,
        stateCoordState: stateCoordState,

    })

        .catch(console.error);
};

exports.authOnCreate = functions.auth.user().onCreate(creatProfile);
</code>```

All of the info in const createProfile are variables and can be what ever you need them to be.

Body:
I am using the new Angular Firebase v.7 with Angular and I am getting an error: Cannot use 'in' operator to search for '_delegate' in users/1QAvZYg6aqe0GhA13tmVAINa.

There is a similar question ( Firebase Error: TypeError: Cannot use 'in' operator to search for '_delegate' in undefined ) but it is unanswered and I have been trying  to little avail to find one myself. Perhaps I am overlooking something very simple.

The code

The service responsible for creating the document is in data.service.ts as looks like this:

import { Injectable } from '@angular/core';
import {
    collection, deleteDoc, doc, DocumentSnapshot, Firestore, onSnapshot,
    query, QuerySnapshot, setDoc, Timestamp as fTimestamp, Unsubscribe
} from '@angular/fire/firestore';
import { firstValueFrom, lastValueFrom, Observable, Subject } from 'rxjs';
import { take } from 'rxjs/operators';

export interface FirestoreExtDoc<T> {
    data: Observable<T>;
    unsubscribe: Unsubscribe;
}
export interface FirestoreExtCol<T> {
    data: Observable<T[]>;
    unsubscribe: Unsubscribe;
}

@Injectable({
  providedIn: 'root'
})
export class DataService {
  constructor(private db: Firestore) { }
    upsert<DocumentData>(ref: string, data: any): Promise<void> {
        const docRef = doc(this.db, ref);
        const timestamp = fTimestamp.now();
        const newData = {
            ...data,
            updatedAt: timestamp,
            createdAt: timestamp,
        };
        const updatedData = {
            ...data,
            updatedAt: timestamp,
        };
        const snapshot = lastValueFrom(this.getDoc<DocumentData>(ref).data.pipe(take(1)));
        return snapshot.then(
            snap => (snap as any).exists ?
                setDoc(docRef, updatedData, { merge: true }) :
                setDoc(docRef, newData, { merge: true })
            );
    };
}

In my auth.service.ts I import the above data service and call the upsert method like this:

import { Injectable } from '@angular/core';
import {
  Auth,
  signInWithEmailAndPassword,
  GoogleAuthProvider,
  authState,
  createUserWithEmailAndPassword,
  updateProfile,
  UserInfo,
  signInWithPopup,
  sendPasswordResetEmail
} from '@angular/fire/auth';
import {
  doc,
  collection,
  collectionGroup,
  setDoc,
  updateDoc,
  deleteDoc,
  docSnapshots,
  docData,
  getDoc
} from '@angular/fire/firestore';
import { User } from '@core/interfaces/user';

import { concatMap, from, Observable, of, switchMap } from 'rxjs';
import { DataService } from './data.service';

@Injectable({
  providedIn: 'root',
})
export class AuthService {

  currentUser$ = authState(this.auth);

  constructor(
    private auth: Auth,
    private dataService: DataService
    ) {}

  signUp(name: string, email: string, password: string): Observable<any> {
    return from(
      createUserWithEmailAndPassword(this.auth, email, password)
    ).pipe(switchMap(({ user }) => updateProfile(user, { displayName: name }).then((data) => { this.dataService.upsert(`users/${user.uid}`, data) }) ));
  }
}

Body:
In case you decide to go with a Cloud Function, the below code I use across several different apps and projects and it works faultlessly every time a user either signs up or is created by an 'Admin' user...

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

admin.initializeApp();

const db = admin.firestore();

/**
 * Add user to firestore
 */
const creatProfile = (userRecord) => {
    const uid = userRecord.uid;
    const admin = false;
    const email = userRecord.email;
    const photoURL = userRecord.photoUrl || 'enter shortened url for default image';
    const name = userRecord.displayName || 'New User';
    const spouse = userRecord.spouse || 'TBA';
    const forumUserName = userRecord.forumUserName || 'New Username set by admin';
    const address = userRecord.address || 'TBA';
    const suburb = userRecord.suburb || 'TBA';
    const state = userRecord.state || 'QLD';
    const postCode = userRecord.postCode || '2000';
    const homePhone = userRecord.homePhone || '02 1234 5678';
    const mobilePhone = userRecord.mobilePhone || '0400 123 456';
    const memNum = userRecord.memNum || 123;
    const timestamp = FieldValue.serverTimestamp();
    const memType = userRecord.memType || 'Nominated';
    const memStatus = userRecord.memStatus || `Pending`;
    const isStateCoord = userRecord.isStateCoord || false;
    const stateCoordState = userRecord.stateCoordState || 'QLD';
    //const newUserRef = db.doc(`users/${uid}`)

    // Convert any date to timestamp for consistency

    return db
        .collection(`users`)
        .doc(userRecord.uid)
        .set({
        uid: uid,
        email: email,
        photoURL: photoURL,
        fullName: name,
        mDOB: timestamp,
        spouse: spouse,
        sDOB: timestamp,
        forumUserName: forumUserName,
        address: address,
        suburb: suburb,
        state: state,
        postCode: postCode,
        homePhone: homePhone,
        mobilePhone: mobilePhone,
        memNum: memNum,
        memType: memType,
        memStatus: memStatus,
        memDueDate: timestamp,
        lastLoginDate: timestamp,
        joined: timestamp,
        updated: timestamp,
        admin: admin,
        isAdmin: isAdmin,
        isStateCoord: isStateCoord,
        stateCoordState: stateCoordState,

    })

        .catch(console.error);
};

exports.authOnCreate = functions.auth.user().onCreate(creatProfile);

All of the info in const createProfile are variables and can be what ever you need them to be.


问:
How select and remove rows based on position for a specific range in R
Suppose I have two data frames like this:

```<code>df1 <- data.frame(a = c(1,2,4,0,0),
             b = c(0,3,5,5,0),
             c = c(0,0,6,7,6))

df2 <- data.frame(a = c(3,6,8,0,0),
             b = c(0,9,10,4,0),
             c = c(0,0,1,4,9))
</code>```

And then I joint it, like

```<code>df3 <- full_join(df1, df2)
print(df3)

   a  b c
1  1  0 0
2  2  3 0
3  4  5 6
4  0  5 7
5  0  0 6
6  3  0 0
7  6  9 0
8  8 10 1
9  0  4 4
10 0  0 9
</code>```

Note that I have always the same pattern, with zeros in rows 1 and 2; and in rows 9 and 10. And I also have zeros between rows 4 and 7.
I want to remove, only, the zeros between rows 4 and 7.
So, I can solve it, like:

```<code>df3[4,1] <- NA
df3[5,1] <- NA
df3[5,2] <- NA
df3[6,2] <- NA
df3[6,3] <- NA
df3[7,3] <- NA

new.df3 <-  as.data.frame(lapply(df3, na.omit))
print(new.df3)

  a  b c
1 1  0 0
2 2  3 0
3 4  5 6
4 3  5 7
5 6  9 6
6 8 10 1
7 0  4 4
8 0  0 9
</code>```

But it is not elegant and very time-consuming.
Any thoughts? I really appreciate it, thanks in advance.
Best!

答:
First, you find which one is zero between rows 4 and 7.

```<code>to_remove <- apply(df3[4:7, ], 1, function(x) which(x == 0))
</code>```

Then, you substitute them by NAs.

```<code>for(i in seq(length(to_remove))){
  df3[as.numeric(names(to_remove))[i], to_remove[[i]]] <- NA
}
</code>```

And, finally, drop them.

```<code>new.df3 <-  as.data.frame(lapply(df3, na.omit))
print(new.df3)
</code>```

Body:
Suppose I have two data frames like this:

df1 <- data.frame(a = c(1,2,4,0,0),
             b = c(0,3,5,5,0),
             c = c(0,0,6,7,6))

df2 <- data.frame(a = c(3,6,8,0,0),
             b = c(0,9,10,4,0),
             c = c(0,0,1,4,9))

And then I joint it, like

df3 <- full_join(df1, df2)
print(df3)

   a  b c
1  1  0 0
2  2  3 0
3  4  5 6
4  0  5 7
5  0  0 6
6  3  0 0
7  6  9 0
8  8 10 1
9  0  4 4
10 0  0 9

Note that I have always the same pattern, with zeros in rows 1 and 2; and in rows 9 and 10. And I also have zeros between rows 4 and 7.
I want to remove, only, the zeros between rows 4 and 7.
So, I can solve it, like:

df3[4,1] <- NA
df3[5,1] <- NA
df3[5,2] <- NA
df3[6,2] <- NA
df3[6,3] <- NA
df3[7,3] <- NA

new.df3 <-  as.data.frame(lapply(df3, na.omit))
print(new.df3)

  a  b c
1 1  0 0
2 2  3 0
3 4  5 6
4 3  5 7
5 6  9 6
6 8 10 1
7 0  4 4
8 0  0 9

But it is not elegant and very time-consuming.
Any thoughts? I really appreciate it, thanks in advance.
Best!

Body:
First, you find which one is zero between rows 4 and 7.

to_remove <- apply(df3[4:7, ], 1, function(x) which(x == 0))

Then, you substitute them by NAs.

for(i in seq(length(to_remove))){
  df3[as.numeric(names(to_remove))[i], to_remove[[i]]] <- NA
}

And, finally, drop them.

new.df3 <-  as.data.frame(lapply(df3, na.omit))
print(new.df3)


问:
Trying to compile contract but getting "ParserError: Source "@openzeppelin/contracts/token/ERC1155/IERC1155.sol" not found: File not found."
I am trying to compile a contract so that I can start the brownie console but I keep getting the error for the contracts I am trying to import.

```<code>ParserError: Source "@openzeppelin/contracts/token/ERC1155/IERC1155.sol" not found: File not found.

--> contracts/DutchAuction.sol:3:1:

  |
3 | import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^`
</code>```

How would I go about fixing this? Much appreciated!

答: I struggled with the same issue for days. I realized my mistake: the config file was named brownie_config.yaml (with underscore) instead of brownie-config.yaml (with dash)

Body:
I am trying to compile a contract so that I can start the brownie console but I keep getting the error for the contracts I am trying to import.

ParserError: Source "@openzeppelin/contracts/token/ERC1155/IERC1155.sol" not found: File not found.

--> contracts/DutchAuction.sol:3:1:

  |
3 | import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^`

How would I go about fixing this? Much appreciated!


问:
How to convert a list of characters that is stored in a single value (per record) into a format that can be analyzed? R
So I have the following data. In this dataframe I have a username, date, and a list of packages. My goal is to transform that column packages into a format I can analyze.

```<code>> print(data_example)
# A tibble: 4 x 3
  username date     packages
  <chr>    <chr>    <chr>
1 John     1/5/2015 "compiler 4.1.2, magrittr 2.0.1, ellipsis 0.3.2, tools 4.1.2, pillar 1.6.4"
2 Karen    1/5/2015 "compiler 4.1.2, tools 4.1.2\""
3 Mike     1/5/2015 "evaluate 0.14, highr 0.9, httr 1.4.2, pillar 1.6.4, rlang 0.4.12"
4 Zoe      1/6/2015 "httr 1.4.2, viridisLite 0.4.0, jsonlite 1.7.2, splines 4.1.2"
</code>```

I tried doing something like this but this doesn't really give me much value.

```<code>packages <- as.list(parsed_log$packages)
</code>```

My goal would be to try doing a "pivot longer" and get an outcome like this? I'm not sure if this is the best way to analyze this kind of data.

```<code>username   date      packages
John       1/5/2015  compiler 4.1.2
John       1/5/2015  magrittr 2.0.1
John       1/5/2015  ellipsis 0.3.2
John       1/5/2015  tools 4.1.2
ect...
</code>```

答:
One option is to use stringi to split:

```<code>s <- strsplit(as.character(df$packages), ',')
data.frame(
  packages = unlist(s),
  date = rep(df$date, length(s)),
  username = rep(df$username, length(s))
)

             packages     date username
1      compiler 4.1.2 1/5/2015     John
2      magrittr 2.0.1 1/5/2015    Karen
3      ellipsis 0.3.2 1/5/2015     Mike
4         tools 4.1.2 1/6/2015      Zoe
5        pillar 1.6.4 1/5/2015     John
6      compiler 4.1.2 1/5/2015    Karen
7      tools 4.1.2\\" 1/5/2015     Mike
8       evaluate 0.14 1/6/2015      Zoe
9           highr 0.9 1/5/2015     John
10         httr 1.4.2 1/5/2015    Karen
11       pillar 1.6.4 1/5/2015     Mike
12       rlang 0.4.12 1/6/2015      Zoe
13         httr 1.4.2 1/5/2015     John
14  viridisLite 0.4.0 1/5/2015    Karen
15     jsonlite 1.7.2 1/5/2015     Mike
16      splines 4.1.2 1/6/2015      Zoe
</code>```

Another option is to use cSplit from splitstackshape:

```<code>library(splitstackshape)
cSplit(df, "packages", ",", direction = "long")
</code>```

data.table option:

```<code>library(data.table)
dt <- as.data.table(df)
dt[, strsplit(as.character(packages), ","), by = c("username", "date")]
</code>```

Data (Thanks @PaulS for the data)

```<code>df <- structure(list(username = c("John", "Karen", "Mike", "Zoe"),
                     date = c("1/5/2015", "1/5/2015", "1/5/2015", "1/6/2015"),
                     packages = c("compiler 4.1.2, magrittr 2.0.1, ellipsis 0.3.2, tools 4.1.2, pillar 1.6.4",
                                  "compiler 4.1.2, tools 4.1.2\\\"", "evaluate 0.14, highr 0.9, httr 1.4.2, pillar 1.6.4, rlang 0.4.12",
                                  "httr 1.4.2, viridisLite 0.4.0, jsonlite 1.7.2, splines 4.1.2"
                     )), class = "data.frame", row.names = c(NA, -4L))
</code>```

Body:
So I have the following data. In this dataframe I have a username, date, and a list of packages. My goal is to transform that column packages into a format I can analyze.

> print(data_example)
# A tibble: 4 x 3
  username date     packages
  <chr>    <chr>    <chr>
1 John     1/5/2015 "compiler 4.1.2, magrittr 2.0.1, ellipsis 0.3.2, tools 4.1.2, pillar 1.6.4"
2 Karen    1/5/2015 "compiler 4.1.2, tools 4.1.2\""
3 Mike     1/5/2015 "evaluate 0.14, highr 0.9, httr 1.4.2, pillar 1.6.4, rlang 0.4.12"
4 Zoe      1/6/2015 "httr 1.4.2, viridisLite 0.4.0, jsonlite 1.7.2, splines 4.1.2"

I tried doing something like this but this doesn't really give me much value.

packages <- as.list(parsed_log$packages)

My goal would be to try doing a "pivot longer" and get an outcome like this? I'm not sure if this is the best way to analyze this kind of data.

username   date      packages
John       1/5/2015  compiler 4.1.2
John       1/5/2015  magrittr 2.0.1
John       1/5/2015  ellipsis 0.3.2
John       1/5/2015  tools 4.1.2
ect...

Body:
One option is to use stringi to split:

s <- strsplit(as.character(df$packages), ',')
data.frame(
  packages = unlist(s),
  date = rep(df$date, length(s)),
  username = rep(df$username, length(s))
)

             packages     date username
1      compiler 4.1.2 1/5/2015     John
2      magrittr 2.0.1 1/5/2015    Karen
3      ellipsis 0.3.2 1/5/2015     Mike
4         tools 4.1.2 1/6/2015      Zoe
5        pillar 1.6.4 1/5/2015     John
6      compiler 4.1.2 1/5/2015    Karen
7      tools 4.1.2\\" 1/5/2015     Mike
8       evaluate 0.14 1/6/2015      Zoe
9           highr 0.9 1/5/2015     John
10         httr 1.4.2 1/5/2015    Karen
11       pillar 1.6.4 1/5/2015     Mike
12       rlang 0.4.12 1/6/2015      Zoe
13         httr 1.4.2 1/5/2015     John
14  viridisLite 0.4.0 1/5/2015    Karen
15     jsonlite 1.7.2 1/5/2015     Mike
16      splines 4.1.2 1/6/2015      Zoe

Another option is to use cSplit from splitstackshape:

library(splitstackshape)
cSplit(df, "packages", ",", direction = "long")

data.table option:

library(data.table)
dt <- as.data.table(df)
dt[, strsplit(as.character(packages), ","), by = c("username", "date")]

Data (Thanks @PaulS for the data)

df <- structure(list(username = c("John", "Karen", "Mike", "Zoe"),
                     date = c("1/5/2015", "1/5/2015", "1/5/2015", "1/6/2015"),
                     packages = c("compiler 4.1.2, magrittr 2.0.1, ellipsis 0.3.2, tools 4.1.2, pillar 1.6.4",
                                  "compiler 4.1.2, tools 4.1.2\\\"", "evaluate 0.14, highr 0.9, httr 1.4.2, pillar 1.6.4, rlang 0.4.12",
                                  "httr 1.4.2, viridisLite 0.4.0, jsonlite 1.7.2, splines 4.1.2"
                     )), class = "data.frame", row.names = c(NA, -4L))


问:
Google Play Developer API - editId parameter
I'm trying to use this api from google:
https://developers.google.com/android-publisher/api-ref/rest/v3/edits.apks/list

This endpoint requires two parameters:

packageName (Package name of the app)

editId (Identifier of the edit)

I understand what they mean by the packageName, but what do they mean with the editId parameter? Where do i find this editId? I literally have no clue.

Any tips would be highly appreciated!

答:
Google Play "Edit" methods allow you to prepare a number of changes to your app and then deploy them all at once. You first need to insert an "Edit" [1] that will hold all the changes you want to make to the app. In other words, it is required to label all interactions by inserting an "Edit".

"When you first create an edit, the edit is a copy of the current deployed state of the app. You can then modify the edit by calling the Edits methods." [2]

[1] https://developers.google.com/android-publisher/api-ref/rest/v3/edits/insert

[2] https://developers.google.com/android-publisher/edits


问:
JQUERY load an array of elements into a DIV
I have an array of DIV elements in an array called 'noactiveMsg'.
I want to load these DIV elements into a DIV called $('#chatCenterMembers').

I've tried:

```<code>noactiveMsg.appendTo($('#chatCenterMembers'));
</code>```

But this doesn't work.
Can someone advice on the syntax to load an array of elements/objects into a div?

code to made the array:

```<code>var noactiveMsg=[];
 $('div.chatmember').each(function() {
 if($(this).children().children('div').hasClass('chatactivestatus_offline')) {
 alert('offline');
 noactiveMsg.push($(this));
 }
 });
</code>```

答:
If each element of your array is a jQuery object, you can try this:

Some sample html:

```<code><div>
    <p>Some stuff below!</p>
</div>
</code>```

The jQuery stuff:

```<code>$(function(){
    var foo = [];
    foo.push( $('<p>hello</p>') );
    foo.push( $('<p>world</p>') );
    foo.push( $('<p>Adam</p>') );

    // this will fail because each element is a
    // separate jQuery object
    // $('div').append( foo );

    // instead try this
    $.each(foo, function(){
        $('div').append(this);
    })
});
</code>```

see it work on jsFiddle

I also answered a similar question just recently

Body:
I have an array of DIV elements in an array called 'noactiveMsg'.
I want to load these DIV elements into a DIV called $('#chatCenterMembers').

I've tried:

noactiveMsg.appendTo($('#chatCenterMembers'));

But this doesn't work.
Can someone advice on the syntax to load an array of elements/objects into a div?

code to made the array:

var noactiveMsg=[];
 $('div.chatmember').each(function() {
 if($(this).children().children('div').hasClass('chatactivestatus_offline')) {
 alert('offline');
 noactiveMsg.push($(this));
 }
 });

Body:
If each element of your array is a jQuery object, you can try this:

Some sample html:

<div>
    <p>Some stuff below!</p>
</div>

The jQuery stuff:

$(function(){
    var foo = [];
    foo.push( $('<p>hello</p>') );
    foo.push( $('<p>world</p>') );
    foo.push( $('<p>Adam</p>') );

    // this will fail because each element is a
    // separate jQuery object
    // $('div').append( foo );

    // instead try this
    $.each(foo, function(){
        $('div').append(this);
    })
});

see it work on jsFiddle

I also answered a similar question just recently


问:
How can I specify a branch/tag when adding a Git submodule?
How does git submodule add -b work?

After adding a submodule with a specific branch, a new cloned repository (after git submodule update --init) will be at a specific commit, not the branch itself (git status on the submodule shows "Not currently on any branch").

I can't find any information on .gitmodules or .git/config about the submodule's branch or any specific commit, so how does Git figure it out?

Also, is it possible to specify a tag instead of a branch?

I'm using version 1.6.5.2.

答:
Existing answers have the second step missing and overloaded with details.

To switch an existing submodule to track a new remote url and/or a new branch:

Edit the source of truth in .gitmodules.

For example, from

```<code>[submodule "api"]
    path = api
    url = https://github.com/<original_repo>/api.git
</code>```

to

```<code>[submodule "api"]
    path = api
    url = https://github.com/<another_repo>/api.git
    branch = work-in-progress
</code>```

You can also use hexsha for a commit hash. Or tag, but see 3.

git submodule sync: Updates the description of submodules cached by git in .git/modules from the just-edited source of truth specified in .gitmodules.

Only if you specify a tag: git submodule foreach --recursive 'git fetch --tags' to fetch tags.

git submodule update --init --recursive --remote: Updates the checked-out submodules in the working copy.

Commit the changes.

Body:
Existing answers have the second step missing and overloaded with details.

To switch an existing submodule to track a new remote url and/or a new branch:

Edit the source of truth in .gitmodules.

For example, from

[submodule "api"]
    path = api
    url = https://github.com/<original_repo>/api.git

to

[submodule "api"]
    path = api
    url = https://github.com/<another_repo>/api.git
    branch = work-in-progress

You can also use hexsha for a commit hash. Or tag, but see 3.

git submodule sync: Updates the description of submodules cached by git in .git/modules from the just-edited source of truth specified in .gitmodules.

Only if you specify a tag: git submodule foreach --recursive 'git fetch --tags' to fetch tags.

git submodule update --init --recursive --remote: Updates the checked-out submodules in the working copy.

Commit the changes.


问:
AWS DMS replicate only selected columns
I'm using AWS DMS to CDC from MySQL on-premise database to AWS S3.

Is it feasible to transfer only a few columns from the source table to target? I have a table with more than 50 columns and only need 10.

If I want to transfer 5 tables from the source, is it best practice to create 1 replication task for each table, or put all 5 in one?

答:
Yes, by using transformations.

If your replication tasks are full-load-and-cdc, then, definitely no. Because each replication task will end up with the redo logs being transferred to your replication instance, consuming memory CPU power, and network bandwidth.

Title: AWS DMS replicate only selected columns


问:
Entity Framework Core 6 - many-to-many update
I'm trying to create a update for EF Core 6 many-to-many on SQL Server but I am really confused. I have stock.cs class and location.cs class

```<code>public class Stock : BaseModel
{
    public Stock()
    {
        this.Locations = new List<Location>();
    }

    [Key]
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string Guid { get; set; } = string.Empty;
    public string RackBarNumber { get; set; } = string.Empty;
    public string ShelveNumber { get; set; } = string.Empty;
    public string ShelveName { get; set; } = string.Empty;

    public virtual List<Location>? Locations { get; set; }
}

public class Location : BaseModel
{
    public Location()
    {
        this.Stocks = new List<Stock>();
    }

    [Key]
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string? Description { get; set; }

    public virtual List<Stock>? Stocks { get; set; }
}
</code>```

I use this as my DTO for getting all my current locations

```<code>public class StockLocations
{
    public Stock Stock { get; set; }
    public virtual ICollection<Location> currentLocations { get; set; }
}
</code>```

Now the StockController is the piece of code which updates the fields, I am able to create and delete in the StockLocation table that EF Core creates. But when I try many updates at once it just goes haywire.

This is my last attempt:

```<code>[HttpPut("{id}")]
public async Task<IActionResult> PutStock(int id, StockLocations stockLocation)
{
    await _userService.ConfirmUser(User);

    stockLocation.Stock.UpdatedAt = DateTime.Now;

    List<Location> removedLocations = new List<Location>();

    if (id != stockLocation.Stock.Id)
    {
        return BadRequest();
    }

    _context.Entry(stockLocation.Stock).State = EntityState.Modified;

    try
    {
        await _context.SaveChangesAsync();

        // Add new items to the database
        foreach (var item in stockLocation.Stock.Locations)
        {
            if (!stockLocation.currentLocations.Any(x => x.Id == item.Id))
            {
                _context.Entry(item).State = EntityState.Modified;
                await _context.SaveChangesAsync();
            }
        }

        // Create a list of removed locations to be removed from the database
        foreach (Location location in stockLocation.currentLocations)
        {
            if (!stockLocation.Stock.Locations.Any(x => x.Id == location.Id))
            {
                removedLocations.Add(location);
            }
        }

        foreach (var item in removedLocations)
        {
            /*
            Stock stock = _context.Stocks.Include(x => x.Locations).Single(x =>             x.Id == id);
            Location locationToDelete = stock.Locations.Find(x => x.Id == item.Id);

            stock.Locations.Remove(locationToDelete);
            await _context.SaveChangesAsync();
            */
        }
    }
    catch (DbUpdateConcurrencyException)
    {
        return NoContent();
    }

    return NoContent();
}
</code>```

Anyone who is willing to tell me how I can approach this properly?

答:
Since you need to update StockLocations I will recommend that tyou just pull the record from the database such as:</p>
```<code>        var record = await  _context.StockLocations
            .Include(a=>a.Location).Include(a=>a.Stock)
            .FirstOrDefaultAsync(a=>a.id == id);

        if(record == null) {
        thrown new NotFoundException();
        }

    stockLocation.Stock.UpdatedAt = DateTime.Now;
     await _context.SaveChangesAsync();

 // other code
 // add new location to the db if they don't exist
 var locations = stockLocation.Location;
  foreach(var loc in locations) {
    var findLocation =
    _context.Locations.FirstOrDefault(a=>a.Name.ToLower() ==
   loc.Name.ToLower()) ;
   if(findLocation == null){
  // does not exist and can be added
   }

}
</code>```

Body:
I'm trying to create a update for EF Core 6 many-to-many on SQL Server but I am really confused. I have stock.cs class and location.cs class

public class Stock : BaseModel
{
    public Stock()
    {
        this.Locations = new List<Location>();
    }

    [Key]
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string Guid { get; set; } = string.Empty;
    public string RackBarNumber { get; set; } = string.Empty;
    public string ShelveNumber { get; set; } = string.Empty;
    public string ShelveName { get; set; } = string.Empty;

    public virtual List<Location>? Locations { get; set; }
}

public class Location : BaseModel
{
    public Location()
    {
        this.Stocks = new List<Stock>();
    }

    [Key]
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string? Description { get; set; }

    public virtual List<Stock>? Stocks { get; set; }
}

I use this as my DTO for getting all my current locations

public class StockLocations
{
    public Stock Stock { get; set; }
    public virtual ICollection<Location> currentLocations { get; set; }
}

Now the StockController is the piece of code which updates the fields, I am able to create and delete in the StockLocation table that EF Core creates. But when I try many updates at once it just goes haywire.

This is my last attempt:

[HttpPut("{id}")]
public async Task<IActionResult> PutStock(int id, StockLocations stockLocation)
{
    await _userService.ConfirmUser(User);

    stockLocation.Stock.UpdatedAt = DateTime.Now;

    List<Location> removedLocations = new List<Location>();

    if (id != stockLocation.Stock.Id)
    {
        return BadRequest();
    }

    _context.Entry(stockLocation.Stock).State = EntityState.Modified;

    try
    {
        await _context.SaveChangesAsync();

        // Add new items to the database
        foreach (var item in stockLocation.Stock.Locations)
        {
            if (!stockLocation.currentLocations.Any(x => x.Id == item.Id))
            {
                _context.Entry(item).State = EntityState.Modified;
                await _context.SaveChangesAsync();
            }
        }

        // Create a list of removed locations to be removed from the database
        foreach (Location location in stockLocation.currentLocations)
        {
            if (!stockLocation.Stock.Locations.Any(x => x.Id == location.Id))
            {
                removedLocations.Add(location);
            }
        }

        foreach (var item in removedLocations)
        {
            /*
            Stock stock = _context.Stocks.Include(x => x.Locations).Single(x =>             x.Id == id);
            Location locationToDelete = stock.Locations.Find(x => x.Id == item.Id);

            stock.Locations.Remove(locationToDelete);
            await _context.SaveChangesAsync();
            */
        }
    }
    catch (DbUpdateConcurrencyException)
    {
        return NoContent();
    }

    return NoContent();
}

Anyone who is willing to tell me how I can approach this properly?

Body:
Since you need to update StockLocations I will recommend that tyou just pull the record from the database such as:

        var record = await  _context.StockLocations
            .Include(a=>a.Location).Include(a=>a.Stock)
            .FirstOrDefaultAsync(a=>a.id == id);

        if(record == null) {
        thrown new NotFoundException();
        }

    stockLocation.Stock.UpdatedAt = DateTime.Now;
     await _context.SaveChangesAsync();

 // other code
 // add new location to the db if they don't exist
 var locations = stockLocation.Location;
  foreach(var loc in locations) {
    var findLocation =
    _context.Locations.FirstOrDefault(a=>a.Name.ToLower() ==
   loc.Name.ToLower()) ;
   if(findLocation == null){
  // does not exist and can be added
   }

}


问:
Can I configure a turn on/off on a GKE node?
I have a GKE cluster with 1 node-pool and 2 nodes in it, one with node affinity to only accept pods of production and the other to development and testing pods. For financial purposes, I want to configure like a cronJob or something similar on the dev/test node so I can spend less money but I don't know if that's possible.</p>

答:
Yes, you can add another node pool named test so you can have two node pools; one to develop and one to test. You can also turn on the auto [scaling]1 in your development pool, this feature of GKE will allow you to save money because it automatically resizes your GKE Cluster node pool based on the demand workload when your production pool is not demanding and you can put a maximum of pods to limit the numbers of pods deployed; in case of your workload increase the demand.

Once you have configured the production pool, you can create the new test node pool with a fixed size of one node.

Then, you will use a node selector in your pods to make sure that they can run in the production node pool. And you could use an anti-affinity rule to ensure that two of your training pods cannot be scheduled on the same node.


问:
Single Sign On: Is it necessary/preferred to keep a table of linked accounts?
I build websites and authentication/account management systems. In our database, we have an user table that (conceptually) looks

```<code>TABLE: USER
 id |      name |   email_address (unique)
====|===========|=========================
 88 | Ben Ghazi | bgazi@gmail.com
</code>```

We wanted to allow Single-Sign-On from Google. So we added a Database table that (conceptually) looks like this:

```<code>TABLE: SSO_LINK
 id | our_account_id | sso_provider_name | sso_provider_account_id
====|================|===================|=========================
 99 |             88 |            GOOGLE |                  xyz983
</code>```

The row in the above table indicates that if Google account #xyz983 ever tries to login, we should log them in as our user #88.

I'm now implementing Google SSO on a new project from scratch. I'm designing how it will work. I am realizing that perhaps this SSO_LINK table was completely unnecessary. Instead of maintaining a list of linked accounts and checking against it, we could just match the email address that Google provides us. If that email matches any of our users, then simply log that user in. That should work. Right?

However, I suspect that most serious implementation of SSO maintain the SSO_LINK table. What is best practice in this case and why?

答:
Well, it depends.

In a simple world , you must take the token part as a successfull user authentication and check if the email is ok, then, you can proceed further and logged in your user.

In an enhanced and secured way, few tips :

You can check the data around the connection if it smells logical about that user :

in the middle of the night, we usually sleep

in this is a new device/computer/cellphone inside a country
reputed for bad users or an ip of any monkey private or public WLAN
used as open proxies or anything like that.

You can use any verifier service provider is a good way yo authenticate your users, but there is another ways : LDAP protocol with OpenLDAP (Free, Open Source Software) or Active Directory (if you are using a Windows Server).

Please, I hope your are hashing or crypting with strong algorithms user passwords and use a smart secured system of your own to not expose privacy concerns. If you are doing that well, you're better than some very big IT companies in USA/Europe. Time is money and user concerns are not their concerns until the RGPD has raised inside the law, so we are working a lot about that since years, and we will continue.

Body:
I build websites and authentication/account management systems. In our database, we have an user table that (conceptually) looks

TABLE: USER
 id |      name |   email_address (unique)
====|===========|=========================
 88 | Ben Ghazi | bgazi@gmail.com

We wanted to allow Single-Sign-On from Google. So we added a Database table that (conceptually) looks like this:

TABLE: SSO_LINK
 id | our_account_id | sso_provider_name | sso_provider_account_id
====|================|===================|=========================
 99 |             88 |            GOOGLE |                  xyz983

The row in the above table indicates that if Google account #xyz983 ever tries to login, we should log them in as our user #88.

I'm now implementing Google SSO on a new project from scratch. I'm designing how it will work. I am realizing that perhaps this SSO_LINK table was completely unnecessary. Instead of maintaining a list of linked accounts and checking against it, we could just match the email address that Google provides us. If that email matches any of our users, then simply log that user in. That should work. Right?

However, I suspect that most serious implementation of SSO maintain the SSO_LINK table. What is best practice in this case and why?


问:
Why not able to add proctime by call addColumns?
```<code>tableEnv.fromDataStream(xxxStream).addColumns('processTime.proctime)
</code>```

The above code will throw excetion:

```<code>org.apache.flink.table.api.ValidationException: Window properties can only be used on windowed tables.
</code>```

but this will works

```<code>tableEnv.fromDataStream(xxxStream, 'id,  ......, 'processTime.proctime)
</code>```

But I must repeat all the columns in this way.

答:
Found some workaround for that, not sure if it could be done easier though:</p>
```<code>Table tmpTable = tableEnv.fromDataStream(my_pojo_datastream);
Schema newSchema = Schema.newBuilder()
   .fromResolvedSchema(tmpTable.getResolvedSchema())
   .columnByExpression("proc_time", "PROCTIME()")
   .build();

Table tmpTableWithProcTIme = tableEnv.fromDataStream(my_pojo_datastream, newSchema);
</code>```

Body:
tableEnv.fromDataStream(xxxStream).addColumns('processTime.proctime)

The above code will throw excetion:

org.apache.flink.table.api.ValidationException: Window properties can only be used on windowed tables.

but this will works

tableEnv.fromDataStream(xxxStream, 'id,  ......, 'processTime.proctime)

But I must repeat all the columns in this way.

Body:
Found some workaround for that, not sure if it could be done easier though:

Table tmpTable = tableEnv.fromDataStream(my_pojo_datastream);
Schema newSchema = Schema.newBuilder()
   .fromResolvedSchema(tmpTable.getResolvedSchema())
   .columnByExpression("proc_time", "PROCTIME()")
   .build();

Table tmpTableWithProcTIme = tableEnv.fromDataStream(my_pojo_datastream, newSchema);


问:
python - convert curl command
I have this curl command.

This works

```<code>curl -O -H "X-Api:3433432" -X GET "https://website.com/file.zip"
</code>```

Trying to figure it out how to convert it to something python understands.

```<code>curl -O -H "X-Api:3433432" -X GET "https://website/file.zip"
</code>```

答:
Perhaps you're looking for the "Requests" module?
It allows you to create a GET request in a similar way you would use a curl command.

You can find some documentation at:
https://www.w3schools.com/PYTHON/ref_requests_get.asp

Edit: There's also https://curlconverter.com/ which should convert it automatically for you.

Title: python - convert curl command

Body:
I have this curl command.

This works

curl -O -H "X-Api:3433432" -X GET "https://website.com/file.zip"

Trying to figure it out how to convert it to something python understands.

curl -O -H "X-Api:3433432" -X GET "https://website/file.zip"


问:
Blazor Server App component suddenly throwing null reference exception
Today a Blazor Server App I've been developing daily for a couple of weeks suddenly started throwing an exception in _Host.cshtml when I launch it in debug mode from within Visual Studio 2022.  The error is shown in the attached image.

Current state of _Host.cshtml

```<code>@page "/"
@namespace Ano.Blazor.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = "_Layout";
}

<component type="typeof(App)" render-mode="ServerPrerendered" />
<link rel="stylesheet" href="_content/Radzen.Blazor/css/standard-base.css"/>
<script src="_content/Radzen.Blazor/Radzen.Blazor.js"></script>
</code>```

Here is App.razor, the component that seems to be throwing an exception in _Host.cshtml

```<code><CascadingAuthenticationState>
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    <Ano.Blazor.Pages.RedirectToLogin></Ano.Blazor.Pages.RedirectToLogin>
                </NotAuthorized>
            </AuthorizeRouteView>
            <FocusOnNavigate RouteData="@routeData" Selector="h1" />
        </Found>
        <NotFound>
            <PageTitle>Not found</PageTitle>
            <LayoutView Layout="@typeof(MainLayout)">
                <p role="alert">Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>
</code>```

The odd thing about this is that I had not made any changes to _Host.cshtml or App.razor when the exception first appeared.  What I had just done was add scaffolded items for Identity, specifically the ConfirmEmail razor page.

The use of Radzen components was added yesterday and has been causing no issues.  But to rule it out I tried running the app with references to the Radzen css and js removed.  The exception persisted.

I have combed through every file in the solution at this point, looking for anything that could cause this.  The app builds and rebuilds without errors.  The exception doesn't tell me much about where the problem could be.

For comparison, I cloned the previous push to a separate folder, launched the solution in a new instance of VS 2022, ran the app in debug mode and it started normally.  This got me thinking perhaps the solution itself is at fault.  Corrupted?  I deleted the .vs folder and allowed the original solution to recreate it but afterward the exception persists.

Has anyone seen this problem before?

答: It seems any issue in your routes will cause this error. I was attempting to bind a querystring parameter ("/{parameter}?{variable}") and received the same error.</p>

Body:
Today a Blazor Server App I've been developing daily for a couple of weeks suddenly started throwing an exception in _Host.cshtml when I launch it in debug mode from within Visual Studio 2022.  The error is shown in the attached image.

Current state of _Host.cshtml

@page "/"
@namespace Ano.Blazor.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = "_Layout";
}

<component type="typeof(App)" render-mode="ServerPrerendered" />
<link rel="stylesheet" href="_content/Radzen.Blazor/css/standard-base.css"/>

Here is App.razor, the component that seems to be throwing an exception in _Host.cshtml

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                <NotAuthorized>
                    <Ano.Blazor.Pages.RedirectToLogin></Ano.Blazor.Pages.RedirectToLogin>
                </NotAuthorized>
            </AuthorizeRouteView>
            <FocusOnNavigate RouteData="@routeData" Selector="h1" />
        </Found>
        <NotFound>
            <PageTitle>Not found</PageTitle>
            <LayoutView Layout="@typeof(MainLayout)">

Sorry, there's nothing at this address.

            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

The odd thing about this is that I had not made any changes to _Host.cshtml or App.razor when the exception first appeared.  What I had just done was add scaffolded items for Identity, specifically the ConfirmEmail razor page.

The use of Radzen components was added yesterday and has been causing no issues.  But to rule it out I tried running the app with references to the Radzen css and js removed.  The exception persisted.

I have combed through every file in the solution at this point, looking for anything that could cause this.  The app builds and rebuilds without errors.  The exception doesn't tell me much about where the problem could be.

For comparison, I cloned the previous push to a separate folder, launched the solution in a new instance of VS 2022, ran the app in debug mode and it started normally.  This got me thinking perhaps the solution itself is at fault.  Corrupted?  I deleted the .vs folder and allowed the original solution to recreate it but afterward the exception persists.

Has anyone seen this problem before?


问:
Displaying cds data in powerapps portal
I was trying to display cds data in powerapps portal web page

This is the code i used

code

Total record size was displaying but the table is empty

here is output screenshot

output

答:
You have to set the table permissions for the custom entity you are fetching.

In portal management

Under security > Table Permissions

Create new > Choose your table

Add appropriate permissions

Hit Save and Close

In Portal studio

Pres sync configuration and browse the website. And press "Ctrl+F5"

Hope it helps.

Title: Displaying cds data in powerapps portal


问:
Codility - Stonewall problem: 100% on correctness but 0% on performance
I'm working on the stonewall exercise of codility. Getting 100% on the correctness tests, but failing all of the performance tests. I'm having trouble envisiging why my solution may be fine for smaller inputs but is going so wrong for larger inputs. Is anyone able to offer feedback about what might be wrong with my solution? I've found this one quite challenging. Taken me a few days of revisiting just to get to this stage! Thanks in advance.

The problem

You are going to build a stone wall. The wall should be straight and N
meters long, and its thickness should be constant; however, it should
have different heights in different places. The height of the wall is
specified by an array H of N positive integers. H[I] is the height of
the wall from I to I+1 meters to the right of its left end. In
particular, H[0] is the height of the wall's left end and H[N−1] is
the height of the wall's right end.

The wall should be built of cuboid stone blocks (that is, all sides of
such blocks are rectangular). Your task is to compute the minimum
number of blocks needed to build the wall.

Write a function:

```<code>function solution(H);
</code>```

that, given an array H of N positive integers specifying the height of
the wall, returns the minimum number of blocks needed to build it.

For example, given array H containing N = 9 integers:   H[0] = 8

H[1] = 8    H[2] = 5   H[3] = 7    H[4] = 9    H[5] = 8   H[6] = 7

H[7] = 4    H[8] = 8

the function should return 7. The figure shows one possible
arrangement of seven blocks.

Write an efficient algorithm for the following assumptions:

```<code>    N is an integer within the range [1..100,000];
    each element of array H is an integer within the range [1..1,000,000,000].
</code>```

My solution

```<code>function solution(H) {

    let stones = 0
    let absoluteMinimum = Infinity;
    let prevStones = []
    for (let i = 0; i < H.length; i++) {
        if (H[i] < absoluteMinimum) {
            stones ++
            absoluteMinimum = H[i]
            prevStones = [H[i]]
        } else if (prevStones.includes(H[i])) {
            while (prevStones.includes(H[i])) {
                prevStones.pop()
            }
            prevStones.push(H[i])
        } else if (H[i] != H[i-1]) {
            prevStones.push(H[i])
            stones ++
        }
    }
    return stones
}
</code>```

Here is the summary of my attempt including test results.
https://app.codility.com/demo/results/training2V8Y42-AUQ/

答:
Following @Teemu's comment, and noting that the code simply is searching prevStones for the existence of a specific height, suggest creating another array that holds the counts of the heights in prevStonesCount.

Eg, if setting prevStones = [ 8 ] then set prevStonesCount[ 8 ] = 1, as there is one stone in the prevStones array of height 8.

Now, rather than having to perform prevStones.includes( 8 ), simply check if 0 < prevStonesCount[ 8 ].  (That is, .includes() searches the entire prevStones array for a height of 8, whereas prevStonesCount[ 8 ] in one step indicates whether any stones of height 8 are in the prevStones array.)

Thus, anytime performing a prevStones.push( x ) or prevStones.pop( x ), make the corresponding adjustment of prevStonesCount[ x ] += 1 or prevStonesCount[ x ] -= 1, respectively.

Note also that within the first if where prevStones = [H[i]], that the prevStones array is essentially cleared and set to an initial value.  This means that the prevStonesCount array will also need to be cleared, and then set prevStonesCount[ H[i] ] = 1.

Body:
I'm working on the stonewall exercise of codility. Getting 100% on the correctness tests, but failing all of the performance tests. I'm having trouble envisiging why my solution may be fine for smaller inputs but is going so wrong for larger inputs. Is anyone able to offer feedback about what might be wrong with my solution? I've found this one quite challenging. Taken me a few days of revisiting just to get to this stage! Thanks in advance.

The problem

You are going to build a stone wall. The wall should be straight and N
meters long, and its thickness should be constant; however, it should
have different heights in different places. The height of the wall is
specified by an array H of N positive integers. H[I] is the height of
the wall from I to I+1 meters to the right of its left end. In
particular, H[0] is the height of the wall's left end and H[N−1] is
the height of the wall's right end.

The wall should be built of cuboid stone blocks (that is, all sides of
such blocks are rectangular). Your task is to compute the minimum
number of blocks needed to build the wall.

Write a function:

function solution(H);

that, given an array H of N positive integers specifying the height of
the wall, returns the minimum number of blocks needed to build it.

For example, given array H containing N = 9 integers:   H[0] = 8

H[1] = 8    H[2] = 5   H[3] = 7    H[4] = 9    H[5] = 8   H[6] = 7

H[7] = 4    H[8] = 8

the function should return 7. The figure shows one possible
arrangement of seven blocks.

Write an efficient algorithm for the following assumptions:

    N is an integer within the range [1..100,000];
    each element of array H is an integer within the range [1..1,000,000,000].

My solution

function solution(H) {

    let stones = 0
    let absoluteMinimum = Infinity;
    let prevStones = []
    for (let i = 0; i < H.length; i++) {
        if (H[i] < absoluteMinimum) {
            stones ++
            absoluteMinimum = H[i]
            prevStones = [H[i]]
        } else if (prevStones.includes(H[i])) {
            while (prevStones.includes(H[i])) {
                prevStones.pop()
            }
            prevStones.push(H[i])
        } else if (H[i] != H[i-1]) {
            prevStones.push(H[i])
            stones ++
        }
    }
    return stones
}

Here is the summary of my attempt including test results.
https://app.codility.com/demo/results/training2V8Y42-AUQ/


问:
How do filter with multiple contains in pyspark
I'm going to do a query with pyspark to filter row who contains at least one word in array. For example, the dataframe is:

```<code>     "content"                "other"
My father is big.              ...
My mother is beautiful.        ...
I'm going to travel.           ...
</code>```

I have an array:

```<code>array=["mother","father"]
</code>```

And the output must be this:

```<code>     "content"                "other"
My father is big.              ...
My mother is beautiful.        ...
</code>```

A simple filter for word in array.

答:
Taking some the same configuration as @wwnde,

```<code>data= [
  (1,"My father is big."),
  (2, "My mother is beautiful"),
  (3,"I'm going to travel.")
]
df=spark.createDataFrame(data, ("id",'content'))

</code>```

Solution

```<code>words = ["father", "mother"]
conditions = " or ".join([f"content like '%{word}%'" for word in words])

(
    df
    .filter(F.expr(conditions))
    .show(truncate=False)
)
+---+----------------------+
|id |content               |
+---+----------------------+
|1  |My father is big.     |
|2  |My mother is beautiful|
+---+----------------------+
</code>```

Body:
I'm going to do a query with pyspark to filter row who contains at least one word in array. For example, the dataframe is:

     "content"                "other"
My father is big.              ...
My mother is beautiful.        ...
I'm going to travel.           ...

I have an array:

array=["mother","father"]

And the output must be this:

     "content"                "other"
My father is big.              ...
My mother is beautiful.        ...

A simple filter for word in array.

Body:
Taking some the same configuration as @wwnde,

data= [
  (1,"My father is big."),
  (2, "My mother is beautiful"),
  (3,"I'm going to travel.")
]
df=spark.createDataFrame(data, ("id",'content'))

Solution

words = ["father", "mother"]
conditions = " or ".join([f"content like '%{word}%'" for word in words])

(
    df
    .filter(F.expr(conditions))
    .show(truncate=False)
)
+---+----------------------+
|id |content               |
+---+----------------------+
|1  |My father is big.     |
|2  |My mother is beautiful|
+---+----------------------+


问:
Jenkins REST API: get a build number of a job that just started
I'm starting the job by issuing this request

```<code>/POST /jenkins/job/jobName/build
</code>```

but it returns nothing. I want to get the build number that just has started.

答:
Although late , posting an answer so it can benefit any other seekers :

We can get the latest/current build no. using the following API :

```<code><JENKINS_URI>/job/<JOB_NAME>/lastBuild/buildNumber
</code>```

This will provide the current executing or the last successful build.

Example :

```<code>curl -X GET <JENKINS_URI>/<JOB_NAME>/lastBuild/buildNumber --user <user>:<key>
o/p : 20
</code>```

Body:
I'm starting the job by issuing this request

/POST /jenkins/job/jobName/build

but it returns nothing. I want to get the build number that just has started.

Body:
Although late , posting an answer so it can benefit any other seekers :

We can get the latest/current build no. using the following API :

<JENKINS_URI>/job/<JOB_NAME>/lastBuild/buildNumber

This will provide the current executing or the last successful build.

Example :

curl -X GET <JENKINS_URI>/<JOB_NAME>/lastBuild/buildNumber --user <user>:<key>
o/p : 20


问:
How to call Javascript function inside WTForms radio element?
I'm new to wtforms and flask. I'm trying to do so that when that a user changes the radio buttons, the text would change. However, currently the onchange does not work, nor does onclick and when I remove it, the text appears but does not change at all when the buttons are changed and remains the same.

```<code>    {{ wtf.form_field(form.doc, class="form-control", onchange="myFunction()") }}

    </div>
   <p id="demo"></p>

<script>

  function myFunction(){

         if (document.getElementById('doc-0').checked) {
              value = document.getElementById('doc-0').value;
              document.getElementById("demo").innerHTML = "You selected: " + value;
          }

       else if ( document.getElementById('doc-1').checked) {
              rate_value = document.getElementById('doc-1').value;
              document.getElementById("demo").innerHTML = "You selected: " + value;

        }
        else if (document.getElementById('doc-2').checked) {
              rate_value = document.getElementById('doc-2').value;
              document.getElementById("demo").innerHTML = "You selected:" + value;

        }

        else {

          document.getElementById("demo").innerHTML = "You selected: NOTHING" ;
        }
     }

        </script>
</code>```

Could someone point out what I'm doing wrong and what I should do. Thank you so much for the help!

答:
You're almost there.

A wtforms.RadioField consists of several input fields. An event listener must be registered manually for each of these input fields. I recommend a separate script block for this.

```<code>{% extends "bootstrap/base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block content %}
  <div class="container">
    <form class="form form-horizontal" method="post" role="form">
      {{ form.hidden_tag() }}
      {{ wtf.form_errors(form, hiddens="only") }}

      {{ form.doc.label }}
      {{ wtf.form_field(form.doc) }}
    </form>
    <output id="result">You selected nothing.</output>
  </div>
{% endblock %}

{% block scripts %}
{{super()}}
<script type="text/javascript">
  (() => {
    // Select all input fields by name and iterate over them.
    const elems = document.querySelectorAll('input[name="doc"]');
    elems.forEach(elem => {
      // Register an event listener for the change event.
      elem.addEventListener('change', evt => {
        // Update the text as soon as there is a change.
        const value = evt.target.value;
        const label = evt.target.parentElement.textContent.trim();
        const output = document.getElementById('result');
        output.innerHTML = `You selected ${label} (${value}).`;
      });
    });
  })();
</script>
{% endblock %}
</code>```

Body:
I'm new to wtforms and flask. I'm trying to do so that when that a user changes the radio buttons, the text would change. However, currently the onchange does not work, nor does onclick and when I remove it, the text appears but does not change at all when the buttons are changed and remains the same.

    {{ wtf.form_field(form.doc, class="form-control", onchange="myFunction()") }}

Could someone point out what I'm doing wrong and what I should do. Thank you so much for the help!

Body:
You're almost there.

A wtforms.RadioField consists of several input fields. An event listener must be registered manually for each of these input fields. I recommend a separate script block for this.

{% extends "bootstrap/base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block content %}
  <div class="container">
    <form class="form form-horizontal" method="post" role="form">
      {{ form.hidden_tag() }}
      {{ wtf.form_errors(form, hiddens="only") }}

      {{ form.doc.label }}
      {{ wtf.form_field(form.doc) }}
    </form>
    <output id="result">You selected nothing.</output>
  </div>
{% endblock %}

{% block scripts %}
{{super()}}
<script type="text/javascript">
  (() => {
    // Select all input fields by name and iterate over them.
    const elems = document.querySelectorAll('input[name="doc"]');
    elems.forEach(elem => {
      // Register an event listener for the change event.
      elem.addEventListener('change', evt => {
        // Update the text as soon as there is a change.
        const value = evt.target.value;
        const label = evt.target.parentElement.textContent.trim();
        const output = document.getElementById('result');
        output.innerHTML = `You selected ${label} (${value}).`;
      });
    });
  })();
</script>
{% endblock %}


问:
Console.log displays elements from array of objects correctly but innerHTML does not
Console.log(data[i].title) displays the correct output but when I try to display it using innerHTML only one result is returned.

I am new to coding and I am working on a web-scrapper project. I have a server running that grabs the headlines of NBC news and inputs the data into an array. When I try to display the data on my frontend using console.log it returns the right results but when I try to display the results on my html page it just returns the final result. The results are shown in the attached image.

Results

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="styles.css">

        <input type="text" id="input"></input>

        <button id="submit" type="submit">Submit</button>

```
</div>
</div>
</p>
<p><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>const PORT= 8000;
const axios = require('axios')
const cheerio = require('cheerio');
const express = require('express')
const cors= require('cors');
const { html } = require('cheerio/lib/static');
// to run this use 'npm run start' in the terminal

const url = 'https://www.nbcnews.com/';
const app = express();
app.use(cors())
app.get('/results', (req, res) => {
    axios(url)
    //var x = req.body.input
    .then(response=> {
        const article= []
        const html=response.data;
        const $=cheerio.load(html);
        $('.alacarte__headline', html).each(function(){
            const title= $(this).text()
            //._13svhQIUZqD9PVzFcLwOKT styled-outbound-link
            article.push({
                title
            })

        })
        res.json(article)
    }).catch(err => console.log(err))

})

app.listen(PORT, () => console.log(`listening on port ${PORT}`))</code>```

const feedDisplay= document.querySelector('#list');
fetch('http://localhost:8000/results')
    .then(response => {
        return response.json()

    })
    .then(data=> {
        var x= ''
        for(i=0; i<data.length; i++) {

            console.log(data[i].title)
            document.getElementById("p").innerHTML=(data[i].title)

        }```

答:
Here:
document.getElementById("p").innerHTML=(data[i].title) you are setting new value of innerHTML. This replaces previous value.

You can use array map method to get list of all titles and then join them using array join method.

I used ' ' space as separator, but you can replace it with any string.

const feedDisplay= document.querySelector('#list');
fetch('http://localhost:8000/results')
    .then(response => {
        return response.json()

    })
    .then(data => {
        document.getElementById("p").innerHTML = data.map(d => d.title).join(' ')
    }```

Body:
Console.log(data[i].title) displays the correct output but when I try to display it using innerHTML only one result is returned.

I am new to coding and I am working on a web-scrapper project. I have a server running that grabs the headlines of NBC news and inputs the data into an array. When I try to display the data on my frontend using console.log it returns the right results but when I try to display the results on my html page it just returns the final result. The results are shown in the attached image.

Results

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="styles.css">

        <input type="text" id="input"></input>

        <button id="submit" type="submit">Submit</button>

const PORT= 8000;
const axios = require('axios')
const cheerio = require('cheerio');
const express = require('express')
const cors= require('cors');
const { html } = require('cheerio/lib/static');
// to run this use 'npm run start' in the terminal

const url = 'https://www.nbcnews.com/';
const app = express();
app.use(cors())
app.get('/results', (req, res) => {
    axios(url)
    //var x = req.body.input
    .then(response=> {
        const article= []
        const html=response.data;
        const $=cheerio.load(html);
        $('.alacarte__headline', html).each(function(){
            const title= $(this).text()
            //._13svhQIUZqD9PVzFcLwOKT styled-outbound-link
            article.push({
                title
            })

        })
        res.json(article)
    }).catch(err => console.log(err))

})

app.listen(PORT, () => console.log(`listening on port ${PORT}`))

const feedDisplay= document.querySelector('#list');
fetch('http://localhost:8000/results')
    .then(response => {
        return response.json()

    })
    .then(data=> {
        var x= ''
        for(i=0; i<data.length; i++) {

            console.log(data[i].title)
            document.getElementById("p").innerHTML=(data[i].title)

        }


问:
Generate a sequence of numbers evenly distributed across the given range in R
I need to generate 625 different numbers between 1e-321 and 1e-200. However, when I use seq() function, it doesn't give me a good distribution.

```<code>seq(from = 1e-321, to = 1e-200, by = ((1e-200 - 1e-321)/624))
</code>```

gives an output like this where only one value has -322 power (which is out of my range) and all others are in 1e-203, 1e-201, 1e-200 range.

I need an output, so all 625 numbers would be evenly distributed across the given range.

答:
It sounds, as @merv noted, that you want your numbers to be spaced evenly in log space, eg with a similar number in each order of magnitude. Here's one way. 1e-321 is the same as 10^-321, so we could raise 10 to a series of exponents which themselves are evenly spaced.

```<code>10^seq(from = -321, to = -200, length.out = 625)
</code>```

You'll note the output has 5 or 6 values for each order of magnitude, with each value about 1.563x the prior value. 1.563^624 (b/c there are 624 changes between 625 numbers) is approx. e+121 which is what we want -- 1e-200 is 121 orders of magnitude larger than 1e-321.

Body:
I need to generate 625 different numbers between 1e-321 and 1e-200. However, when I use seq() function, it doesn't give me a good distribution.

seq(from = 1e-321, to = 1e-200, by = ((1e-200 - 1e-321)/624))

gives an output like this where only one value has -322 power (which is out of my range) and all others are in 1e-203, 1e-201, 1e-200 range.

I need an output, so all 625 numbers would be evenly distributed across the given range.

Body:
It sounds, as @merv noted, that you want your numbers to be spaced evenly in log space, eg with a similar number in each order of magnitude. Here's one way. 1e-321 is the same as 10^-321, so we could raise 10 to a series of exponents which themselves are evenly spaced.

10^seq(from = -321, to = -200, length.out = 625)

You'll note the output has 5 or 6 values for each order of magnitude, with each value about 1.563x the prior value. 1.563^624 (b/c there are 624 changes between 625 numbers) is approx. e+121 which is what we want -- 1e-200 is 121 orders of magnitude larger than 1e-321.


问:
Is there a way to not inherit "virtualness" of a function in a subclass?
Is it possible in C++ to have a class override a virtual function, but only have virtual dispatch when the function is called through the superclass (ie. not when it is called on something statically typed as the subclass)? I know this isn't what happens, but is there any way to achieve something close?

The reason for wanting this is that I have two classes which both expose a flush() function. The vast majority of the time in my program, I am calling flush() directly on a subclass object that I know the type of, so I don't need virtual dispatch. However I want to add a superclass into the mix so that very infrequently I can pass a reference to an instance of either one of the classes into a doSomethingThenFlush() function, which would call flush() virtually.

I know I could use templates instead of virtual functions, and I know I could have two different functions (eg. flushVirtual() which just called flushNonVirtual(), and call flushNonVirtual() everywhere I don't need virtual dispatch). But these both seem a bit like throwing code at a problem which is largely syntactical. Is there any more elegant way to achieve this?

Perhaps more importantly, does anyone know why virtualness is inherited in C++?

```<code>struct Base
{
  virtual ~Base(){}
  virtual void func();
};

struct Derived : public Base
{
  void func(){}
};

void callVirtually(Base &base)
{
  base.func();//this will use virtual dispatch
}

void callStatically(Derived &derived)
{
  derived.func();//I don't want/need this to use virtual dispatch
}

int main()
{
  Derived derived;
  callVirtually(derived);
  callStatically(derived);
}
</code>```

答:
In your specific example, if callStatically gets inlined, the compiler will probably avoid the virtual function dispatch because it can see the object's actual type (because it is a local variable).

Probably your compiler can also avoid a virtual dispatch for cases like this:

```<code>class Foo {
public:
    callStatically() { d.func() }
private:
    Derived d;
};
</code>```

The compiler is likely to perform this optimization whether or not callStatically is inlined, because it can see the actual type of the variable member.

But to my knowledge, there is no way to force the compiler to bypass the virtual call in general.

Body:
Is it possible in C++ to have a class override a virtual function, but only have virtual dispatch when the function is called through the superclass (ie. not when it is called on something statically typed as the subclass)? I know this isn't what happens, but is there any way to achieve something close?

The reason for wanting this is that I have two classes which both expose a flush() function. The vast majority of the time in my program, I am calling flush() directly on a subclass object that I know the type of, so I don't need virtual dispatch. However I want to add a superclass into the mix so that very infrequently I can pass a reference to an instance of either one of the classes into a doSomethingThenFlush() function, which would call flush() virtually.

I know I could use templates instead of virtual functions, and I know I could have two different functions (eg. flushVirtual() which just called flushNonVirtual(), and call flushNonVirtual() everywhere I don't need virtual dispatch). But these both seem a bit like throwing code at a problem which is largely syntactical. Is there any more elegant way to achieve this?

Perhaps more importantly, does anyone know why virtualness is inherited in C++?

struct Base
{
  virtual ~Base(){}
  virtual void func();
};

struct Derived : public Base
{
  void func(){}
};

void callVirtually(Base &base)
{
  base.func();//this will use virtual dispatch
}

void callStatically(Derived &derived)
{
  derived.func();//I don't want/need this to use virtual dispatch
}

int main()
{
  Derived derived;
  callVirtually(derived);
  callStatically(derived);
}

Body:
In your specific example, if callStatically gets inlined, the compiler will probably avoid the virtual function dispatch because it can see the object's actual type (because it is a local variable).

Probably your compiler can also avoid a virtual dispatch for cases like this:

class Foo {
public:
    callStatically() { d.func() }
private:
    Derived d;
};

The compiler is likely to perform this optimization whether or not callStatically is inlined, because it can see the actual type of the variable member.

But to my knowledge, there is no way to force the compiler to bypass the virtual call in general.