问:
PHP foreach wrong value not work with expected
Something strange is happening in this script below. The last foreach values are copied to all objects.

 // Laravel eloquent payment Methods
 $paymentMethods = FormaPagamento::where("cod_loja", "=", $codLoja)
                                        ->select("code_payment")
                                        ->get();
```
<p>Array of orders with payment code</p>
<pre class="lang-php prettyprint-override"><code>$orderPayment = [];
        $orderPayment[] = (object)[
            "code_order" => 1,
            "amount_received" => "10.00",
            "code_payment" => 18,
            "code_motoboy" => 60
        ];

        $orderPayment[] = (object)[
            "code_order" => 2,
            "amount_received" => "22.50",
            "code_payment" => 1,
            "code_motoboy" => 70
        ];
        $orderPayment[] = (object)[
            "code_order" => 3,
            "amount_received" => "15.00",
            "code_payment" => 5,
            "code_motoboy" => 70
        ];
        $orderPayment[] = (object)[
            "code_order" => 4,
            "amount_received" => "3.01",
            "code_payment" => 5,
            "code_motoboy" => 70
        ];
</code>```

Array of motoboys

 $motoboys = [];
        $motoboys[] = (object)[
            "code_motoboy" => 60
        ];
        $motoboys[] = (object)[
            "code_motoboy" => 70
        ];
```
<pre class="lang-php prettyprint-override"><code>foreach ($motoboys as $motoboy){  // foreach each motoboy need calculate methods payments

// remove total accumulated previous motoboy
            foreach ($paymentMethods as $formaPgtoRemover){
                unset($formaPgtoRemover->accumulated_total);
            }

            // each order
            foreach ($orderPayment as $pedidoPgto){
                if ($pedidoPgto->code_motoboy==$motoboy->code_motoboy){ // if this order is from this motoboy
                    foreach ($paymentMethods as $formaPgto){ // acumulated total order
                        if ($formaPgto->code_payment==$pedidoPgto->code_payment){
                            $totalFormaPagamento = isset($formaPgto->accumulated_total) ? $formaPgto->accumulated_total : 0.00;
                            $totalFormaPagamento = (float) $totalFormaPagamento + (float) $pedidoPgto->amount_received;
                            $formaPgto->accumulated_total = number_format((float)$totalFormaPagamento, 2, '.', '');
                            break;
                        }
                    }
                }
            }

            $motoboy->payments= $paymentMethods;
        }
</code>```

Array expected (from each motoboy, acumulated total from same payment method, example 18.01 = $ 15.00 + $ 3.01;

[
    {   "code_motoboy" : 60,
        "payments" : [{"code_payment" : 18, "accumulated_total" : 10.00}]
    },
    {
        "code_motoboy" : 70,
        "payments" : [{"code_payment" : 1, "accumulated_total" : 22.50}, {"code_payment" : 5, "accumulated_total" : 18.01}]
    }
]
```
<p>Array returned;</p>
<pre class="lang-json prettyprint-override"><code>[
    {   "code_motoboy" : 60,
        "payments" : [{"code_payment" : 1, "accumulated_total" : 22.50}, {"code_payment" : 5, "accumulated_total" : 18.01}] // php copies last ocurrence of all previuos
    },
    {
        "code_motoboy" : 70,
        "payments" : [{"code_payment" : 1, "accumulated_total" : 22.50}, {"code_payment" : 5, "accumulated_total" : 18.01}]
    }
]

</code>```

Not work
$motoboy->payments = $paymentMethods;

Work if I tried
$motoboy->payments = "$paymentMethods";
$motoboy->payments = json_encode($paymentMethods);

I'm confused.

PHP confused foraech inside foreach.

Body:
Something strange is happening in this script below. The last foreach values are copied to all objects.

 // Laravel eloquent payment Methods
 $paymentMethods = FormaPagamento::where("cod_loja", "=", $codLoja)
                                        ->select("code_payment")
                                        ->get();

Array of orders with payment code

$orderPayment = [];
        $orderPayment[] = (object)[
            "code_order" => 1,
            "amount_received" => "10.00",
            "code_payment" => 18,
            "code_motoboy" => 60
        ];

        $orderPayment[] = (object)[
            "code_order" => 2,
            "amount_received" => "22.50",
            "code_payment" => 1,
            "code_motoboy" => 70
        ];
        $orderPayment[] = (object)[
            "code_order" => 3,
            "amount_received" => "15.00",
            "code_payment" => 5,
            "code_motoboy" => 70
        ];
        $orderPayment[] = (object)[
            "code_order" => 4,
            "amount_received" => "3.01",
            "code_payment" => 5,
            "code_motoboy" => 70
        ];

Array of motoboys

 $motoboys = [];
        $motoboys[] = (object)[
            "code_motoboy" => 60
        ];
        $motoboys[] = (object)[
            "code_motoboy" => 70
        ];

foreach ($motoboys as $motoboy){  // foreach each motoboy need calculate methods payments

// remove total accumulated previous motoboy
            foreach ($paymentMethods as $formaPgtoRemover){
                unset($formaPgtoRemover->accumulated_total);
            }

            // each order
            foreach ($orderPayment as $pedidoPgto){
                if ($pedidoPgto->code_motoboy==$motoboy->code_motoboy){ // if this order is from this motoboy
                    foreach ($paymentMethods as $formaPgto){ // acumulated total order
                        if ($formaPgto->code_payment==$pedidoPgto->code_payment){
                            $totalFormaPagamento = isset($formaPgto->accumulated_total) ? $formaPgto->accumulated_total : 0.00;
                            $totalFormaPagamento = (float) $totalFormaPagamento + (float) $pedidoPgto->amount_received;
                            $formaPgto->accumulated_total = number_format((float)$totalFormaPagamento, 2, '.', '');
                            break;
                        }
                    }
                }
            }

            $motoboy->payments= $paymentMethods;
        }

Array expected (from each motoboy, acumulated total from same payment method, example 18.01 = $ 15.00 + $ 3.01;

[
    {   "code_motoboy" : 60,
        "payments" : [{"code_payment" : 18, "accumulated_total" : 10.00}]
    },
    {
        "code_motoboy" : 70,
        "payments" : [{"code_payment" : 1, "accumulated_total" : 22.50}, {"code_payment" : 5, "accumulated_total" : 18.01}]
    }
]

Array returned;

[
    {   "code_motoboy" : 60,
        "payments" : [{"code_payment" : 1, "accumulated_total" : 22.50}, {"code_payment" : 5, "accumulated_total" : 18.01}] // php copies last ocurrence of all previuos
    },
    {
        "code_motoboy" : 70,
        "payments" : [{"code_payment" : 1, "accumulated_total" : 22.50}, {"code_payment" : 5, "accumulated_total" : 18.01}]
    }
]

Not work
$motoboy->payments = $paymentMethods;

Work if I tried
$motoboy->payments = "$paymentMethods";
$motoboy->payments = json_encode($paymentMethods);

I'm confused.

PHP confused foraech inside foreach.


来源: stackexchange

问:
How to implement Microsoft Active Directory LogonHours in Javascript?
I'm developing a web version implementation of the Microsoft Active Directory Logon Hour in HTML and Javascript like the image below:

MS Active Directory Logon Hour

So managers will be able to choose in my web app when their employees will be allowed to log on.

What the code does:

User selects the time and day of the week that he/she wants to allow employees to logon.

If a cell (corresponding to an hour of the week) is selected, then it's marked with 'one', otherwise 'zero'.

The code will give me a string of 21 bytes that'll be converted to hex and later inserted into the ms active directory logonhours attribute.

Example:

Sunday - Allowed time: 6 firtst hours

Byte = 11111110, 00000000, 00000000.

My code so far:

```<code><!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="stylesheet" href="style.css">
        <script src="index.js" defer></script>

        <title>Document</title>
    </head>
    <body>
        <div id="table"></div> <br>
        <div>Hex: <output readonly id="output"></input></div>
    </body>
</html>
</code>```
```<code>let isMouseDown = false;
let cellSelected = false;
let count = 0;

const weekDay = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

selectTable('table');

document.querySelector('body').addEventListener('click', (e) => {
    e.stopPropagation;
    setResult();
});

function setHead() {
    const hours = setHours();

    return `
        <tr style='font-weight:bolder'>
            <th></th>
            ${hours}
        </tr>
    `;
}

function setWeek() {
    return weekDay
        .map((day) => {
            let hours = setHours(day, false);
            count += 23;

            return `
                <tr>
                    <th>${day}</th>
                    ${hours}
                </tr>
            `;
        })
        .join('');
}

function setHours(day, isNumber = true) {
    let hours = '';
    let total = count + 23;

    const weekday = weekDay[weekDay.indexOf(day)];

    for (let i = count; i <= total; i++) {
        if (isNumber) hours += `<th>${i}</th>`;
        else hours += `<td data-week=${weekday} data-hour="${i}"></td>`;
    }

    return hours;
}

function setTable() {
    const head = setHead();
    const body = setWeek();

    return `
        <table class="table" width="100%">
            ${head}
            ${body}
        </table>
    `;
}

function selectTable(divID) {
    const table = setTable();

    document.getElementById(divID).innerHTML = table;

    const tableCell = document.querySelectorAll('#' + divID + ' td');

    tableCell.forEach((e) => {
        e.addEventListener('mousedown', () => {
            isMouseDown = true;
            e.classList.toggle('highlighted');
        });

        e.addEventListener('mouseover', () => {
            if (isMouseDown) {
                e.classList.toggle('highlighted');
                // cellSelected = true;
            }
        });

        e.addEventListener('mouseup', () => {
            isMouseDown = false;
        });
    });
}

function setResult() {
    const obj = [];

    const select = document.querySelectorAll('.highlighted');

    select.forEach((value) => {
        obj.push(parseInt(value.dataset.hour));
    });

    mountString(obj);
}

function mountString(value) {
    let string = '';

    for (let i = 0; i < 168; i++) {
        string = string + (value.includes(i) ? '1' : '0');
    }

    const separateString = string.split(/(........)/gu).join(',');

    const toArray = separateString.replace(/(,,)/g, ',').split(',');

    const removeWhiteSpace = toArray.filter((str) => {
        return /\S/.test(str);
    });

    const finalResult = removeWhiteSpace;

   //console.log(finalResult);

    toHexString(finalResult);
}

function toHexString(value) {
    // console.log(value);
    const hex = [];

    value.forEach((str) => {
        hex.push(parseInt(str, 2).toString(16).toUpperCase());
    });

    const mountHex = hex.map((str) => {
        if (!isNaN(str)) {
            return str.padStart(2, '0');
        }

        return str;
    });

    const hexadecimal = mountHex.join('');

    console.log('Hex: ', hexadecimal);

    insertHex(hexadecimal);
}

function insertHex(str) {
    // console.log(str);
    const output = document.querySelector('#output');

    output.innerHTML = str;
}

</code>```
```<code>table {
    border-collapse: collapse;
    table-layout: fixed;
}

th,
td {
    border: 1px solid #ddd;
    user-select: none;
}

th {
    padding: 10px;
    text-align: center;
    user-select: none;
    width: 40px;
}

table td.highlighted {
    background-color: #3b7efe;
}
</code>```

Sample - JsFiddle

My Problem:

Active directory uses UTC for the logonHours attribute and local timezone for GUI logonHour.

Example:
Let's say I want an employee to have access during 08:00am until 06:00pm.

My code would give me the following result when I select the corresponding time:

Binary:

00000000 00000000 00000000 00000001 11111111 10000000 00000011 11111111 00000000 00000111 11111110 00000000 00001111 11111100 00000000 00011111 11111000 00000000 00000000 00000000 00000000

Hex:

00000001FF8003FF0007FE00FFC001FF800000000

When I insert this hex or binary into the logonHour attribute the result is different from what I expected:

Desired result

Binary: Final Result (wrong)

Hex: Final Result (wrong)

I looked up all over the Internet and what I found was Powershell scripts, like the link below:

Manage AD User Logon Hours using PowerShell

Would somebody know how to apply the correct timezone (in my case UTC-3)?

ContentLicense: CC BY-SA 4.0

Body:
I'm developing a web version implementation of the Microsoft Active Directory Logon Hour in HTML and Javascript like the image below:

MS Active Directory Logon Hour

So managers will be able to choose in my web app when their employees will be allowed to log on.

What the code does:

User selects the time and day of the week that he/she wants to allow employees to logon.

If a cell (corresponding to an hour of the week) is selected, then it's marked with 'one', otherwise 'zero'.

The code will give me a string of 21 bytes that'll be converted to hex and later inserted into the ms active directory logonhours attribute.

Example:

Sunday - Allowed time: 6 firtst hours

Byte = 11111110, 00000000, 00000000.

My code so far:

<!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">

        <link rel="stylesheet" href="style.css">

        <title>Document</title>

Hex: <output readonly id="output"></input>

let isMouseDown = false;
let cellSelected = false;
let count = 0;

const weekDay = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

selectTable('table');

document.querySelector('body').addEventListener('click', (e) => {
    e.stopPropagation;
    setResult();
});

function setHead() {
    const hours = setHours();

    return `

            ${hours}

    `;
}

function setWeek() {
    return weekDay
        .map((day) => {
            let hours = setHours(day, false);
            count += 23;

            return `

                    ${day}
                    ${hours}

            `;
        })
        .join('');
}

function setHours(day, isNumber = true) {
    let hours = '';
    let total = count + 23;

    const weekday = weekDay[weekDay.indexOf(day)];

    for (let i = count; i <= total; i++) {
        if (isNumber) hours += `<th>${i}</th>`;
        else hours += `<td data-week=${weekday} data-hour="${i}"></td>`;
    }

    return hours;
}

function setTable() {
    const head = setHead();
    const body = setWeek();

    return `

            ${head}
            ${body}

    `;
}

function selectTable(divID) {
    const table = setTable();

    document.getElementById(divID).innerHTML = table;

    const tableCell = document.querySelectorAll('#' + divID + ' td');

    tableCell.forEach((e) => {
        e.addEventListener('mousedown', () => {
            isMouseDown = true;
            e.classList.toggle('highlighted');
        });

        e.addEventListener('mouseover', () => {
            if (isMouseDown) {
                e.classList.toggle('highlighted');
                // cellSelected = true;
            }
        });

        e.addEventListener('mouseup', () => {
            isMouseDown = false;
        });
    });
}

function setResult() {
    const obj = [];

    const select = document.querySelectorAll('.highlighted');

    select.forEach((value) => {
        obj.push(parseInt(value.dataset.hour));
    });

    mountString(obj);
}

function mountString(value) {
    let string = '';

    for (let i = 0; i < 168; i++) {
        string = string + (value.includes(i) ? '1' : '0');
    }

    const separateString = string.split(/(........)/gu).join(',');

    const toArray = separateString.replace(/(,,)/g, ',').split(',');

    const removeWhiteSpace = toArray.filter((str) => {
        return /\S/.test(str);
    });

    const finalResult = removeWhiteSpace;

   //console.log(finalResult);

    toHexString(finalResult);
}

function toHexString(value) {
    // console.log(value);
    const hex = [];

    value.forEach((str) => {
        hex.push(parseInt(str, 2).toString(16).toUpperCase());
    });

    const mountHex = hex.map((str) => {
        if (!isNaN(str)) {
            return str.padStart(2, '0');
        }

        return str;
    });

    const hexadecimal = mountHex.join('');

    console.log('Hex: ', hexadecimal);

    insertHex(hexadecimal);
}

function insertHex(str) {
    // console.log(str);
    const output = document.querySelector('#output');

    output.innerHTML = str;
}

table {
    border-collapse: collapse;
    table-layout: fixed;
}

th,
td {
    border: 1px solid #ddd;
    user-select: none;
}

th {
    padding: 10px;
    text-align: center;
    user-select: none;
    width: 40px;
}

table td.highlighted {
    background-color: #3b7efe;
}

Sample - JsFiddle

My Problem:

Active directory uses UTC for the logonHours attribute and local timezone for GUI logonHour.

Example:
Let's say I want an employee to have access during 08:00am until 06:00pm.

My code would give me the following result when I select the corresponding time:

Binary:

00000000 00000000 00000000 00000001 11111111 10000000 00000011 11111111 00000000 00000111 11111110 00000000 00001111 11111100 00000000 00011111 11111000 00000000 00000000 00000000 00000000

Hex:

00000001FF8003FF0007FE00FFC001FF800000000

When I insert this hex or binary into the logonHour attribute the result is different from what I expected:

Desired result

Binary: Final Result (wrong)

Hex: Final Result (wrong)

I looked up all over the Internet and what I found was Powershell scripts, like the link below:

Manage AD User Logon Hours using PowerShell

Would somebody know how to apply the correct timezone (in my case UTC-3)?


问:
can't run `/home/istiak/Android/Sdk/tools/bin/sdkmanager --install "cmdline-tools;latest"`
When I used flutter doctor,

```<code>[!] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    ✗ cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/linux#android-setup for
      more details
</code>```

it said to execute followed by flutter doctor --android-licenses

```<code>path/to/sdkmanager --install "cmdline-tools;latest"
</code>```

After locating the sdkmanager, I ran and got some error ->

Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
at com.android.repository.api.SchemaModule$SchemaModuleVersion.(SchemaModule.java:156)
at com.android.repository.api.SchemaModule.(SchemaModule.java:75)
at com.android.sdklib.repository.AndroidSdkHandler.(AndroidSdkHandler.java:81)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
... 5 more

I get the same error when I update sdkmanager

```<code>sdkmanager --update
</code>```

Body:
When I used flutter doctor,

[!] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    ✗ cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/linux#android-setup for
      more details

it said to execute followed by flutter doctor --android-licenses

path/to/sdkmanager --install "cmdline-tools;latest"

After locating the sdkmanager, I ran and got some error ->

Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema
at com.android.repository.api.SchemaModule$SchemaModuleVersion.(SchemaModule.java:156)
at com.android.repository.api.SchemaModule.(SchemaModule.java:75)
at com.android.sdklib.repository.AndroidSdkHandler.(AndroidSdkHandler.java:81)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:73)
at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.annotation.XmlSchema
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
... 5 more

I get the same error when I update sdkmanager

sdkmanager --update


问:
Wrong name of the shared file when choosing the app from Intent.createChooser
My app can share internally stored files with the androidx.core.content.FileProvider.
The intent and the chooser are created with the following snippet:

```<code>val shareIntent: Intent = Intent().apply {
    action = Intent.ACTION_SEND
    putExtra(
        Intent.EXTRA_STREAM,
        FileProvider.getUriForFile(this, authority, file, displayName),
    )
    type = document.mimeType.mediaType
}
startActivity(Intent.createChooser(shareIntent, getString(R.string.share_title)))
</code>```

I explicitly pass the displayName to the FileProvider, but in the app chooser, I see the file's local name (see image).

Is there a way to show the correct display name in the chooser?

Body:
My app can share internally stored files with the androidx.core.content.FileProvider.
The intent and the chooser are created with the following snippet:

val shareIntent: Intent = Intent().apply {
    action = Intent.ACTION_SEND
    putExtra(
        Intent.EXTRA_STREAM,
        FileProvider.getUriForFile(this, authority, file, displayName),
    )
    type = document.mimeType.mediaType
}
startActivity(Intent.createChooser(shareIntent, getString(R.string.share_title)))

I explicitly pass the displayName to the FileProvider, but in the app chooser, I see the file's local name (see image).

Is there a way to show the correct display name in the chooser?


问:
regex to capture select clause ignoring last bracket
I'm trying to capture SELECT clause from CTAS sql query using regex

Input:

```<code>CREATE TABLE IF NOT EXISTS table_new
AS (
  SELECT
CURRENT_TIMESTAMP::TIMESTAMP_NTZ AS tstamp
    )
</code>```

Or

```<code>CREATE TABLE IF NOT EXISTS table_new
AS
  SELECT
CURRENT_TIMESTAMP::TIMESTAMP_NTZ AS tstamp
</code>```

The select clause can be with or without paranthesis. Also there could be trailing spaces after the CTAS statement would like to ignore them.

The regex I used :

```<code>rgxselect =  re.compile(r"(((?:select|with)[\s\S]*))",re.MULTILINE|re.IGNORECASE)
s = rgxselect.search(item)
selectclause = s.groups()[0]

</code>```

This works if there are no paranthesis enclosing select clause. For both inputs, I would like to receive either

```<code>SELECT
CURRENT_TIMESTAMP::TIMESTAMP_NTZ AS tstamp
</code>```

or

```<code>(   SELECT
    CURRENT_TIMESTAMP::TIMESTAMP_NTZ AS tstamp)
</code>```

But when there are parenthesis, I get below

```<code>SELECT
        CURRENT_TIMESTAMP::TIMESTAMP_NTZ AS tstamp)
</code>```

Body:
I'm trying to capture SELECT clause from CTAS sql query using regex

Input:

CREATE TABLE IF NOT EXISTS table_new
AS (
  SELECT
CURRENT_TIMESTAMP::TIMESTAMP_NTZ AS tstamp
    )

Or

CREATE TABLE IF NOT EXISTS table_new
AS
  SELECT
CURRENT_TIMESTAMP::TIMESTAMP_NTZ AS tstamp

The select clause can be with or without paranthesis. Also there could be trailing spaces after the CTAS statement would like to ignore them.

The regex I used :

rgxselect =  re.compile(r"(((?:select|with)[\s\S]*))",re.MULTILINE|re.IGNORECASE)
s = rgxselect.search(item)
selectclause = s.groups()[0]

This works if there are no paranthesis enclosing select clause. For both inputs, I would like to receive either

SELECT
CURRENT_TIMESTAMP::TIMESTAMP_NTZ AS tstamp

or

(   SELECT
    CURRENT_TIMESTAMP::TIMESTAMP_NTZ AS tstamp)

But when there are parenthesis, I get below

SELECT
        CURRENT_TIMESTAMP::TIMESTAMP_NTZ AS tstamp)


问:
Widget is not rebuilding with Provider context.watch
I created a class LoginStore extending ChangeNotifier to state manage my application and i'm using Provider for dependency injection. According to the documentation, invoking context.watch() is enough to make the Widget listen for changes in the LoginStore and then rebuild, but something is wrong and this is not working.

This is my view:

```<code>import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:trade_magic/src/login/login_store.dart';

class TestView extends StatelessWidget {
  const TestView({super.key});

  @override
  Widget build(BuildContext context) {
    final store = context.watch<LoginStore>();
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Row(
            children: [
              Expanded(
                  child: TextField(
                onChanged: (value) => store.value.username = value,
              ))
            ],
          ),
          Expanded(child: Text(store.value.username))
        ],
      ),
    );
  }
}

</code>```

This is my store:

```<code>class LoginStore extends ValueNotifier<Login> {
  LoginStore(super.value);

  LoginStore.empty() : this(Login(username: "", password: ""));
}
</code>```

This is my model:

```<code>import 'dart:convert';

class Login {
  String username;

  String password;

  //set username(username) => this.username = username;

  Login({
    required this.username,
    required this.password,
  });

  Login copyWith({
    String? username,
    String? password,
  }) {
    return Login(
      username: username ?? this.username,
      password: password ?? this.password,
    );
  }

  Map<String, dynamic> toMap() {
    return <String, dynamic>{
      'username': username,
      'password': password,
    };
  }

  factory Login.fromMap(Map<String, dynamic> map) {
    return Login(
      username: map['username'] as String,
      password: map['password'] as String,
    );
  }

  String toJson() => json.encode(toMap());

  factory Login.fromJson(String source) =>
      Login.fromMap(json.decode(source) as Map<String, dynamic>);

  @override
  String toString() => 'Login(username: $username, password: $password)';

  @override
  bool operator ==(covariant Login other) {

    return other.username == username && other.password == password;
  }

  @override
  int get hashCode => username.hashCode ^ password.hashCode;
}

</code>```

This is App.dart:

```<code>import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:provider/provider.dart';
import 'package:trade_magic/src/login/login_store.dart';
//import 'package:trade_magic/src/login/login_view.dart';

import 'login/test_view.dart';
import 'sample_feature/sample_item_details_view.dart';
import 'sample_feature/sample_item_list_view.dart';
import 'settings/settings_controller.dart';
import 'settings/settings_view.dart';

class MyApp extends StatelessWidget {
  const MyApp({
    super.key,
    required this.settingsController,
  });

  final SettingsController settingsController;

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: settingsController,
      builder: (BuildContext context, Widget? child) {
        return MultiProvider(
          providers: [
            ChangeNotifierProvider<LoginStore>(
                create: (_) => LoginStore.empty())
          ],
          child: MaterialApp(
            restorationScopeId: 'app',

            localizationsDelegates: const [
              AppLocalizations.delegate,
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
            ],
            supportedLocales: const [
              Locale('en', ''), // English, no country code
              Locale('pt', 'BR')
            ],

            onGenerateTitle: (BuildContext context) =>
                AppLocalizations.of(context)!.appTitle,

            theme: ThemeData(),
            darkTheme: ThemeData.dark(),
            themeMode: settingsController.themeMode,

            onGenerateRoute: (RouteSettings routeSettings) {
              return MaterialPageRoute<void>(
                settings: routeSettings,
                builder: (BuildContext context) {
                  switch (routeSettings.name) {
                    case SettingsView.routeName:
                      return SettingsView(controller: settingsController);
                    case SampleItemDetailsView.routeName:
                      return const SampleItemDetailsView();
                    case SampleItemListView.routeName:
                    default:
                      return const TestView();
                  }
                },
              );
            },
          ),
        );
      },
    );
  }
}

</code>```

Most questions in stackoverflow deal with Future, but this is not the case. I checked if the value of LoginStore was really changing, and it was. I expected TestView to rebuild and update the value in the Text widget, but that not happened. Why? What am I doing wrong?

Body:
I created a class LoginStore extending ChangeNotifier to state manage my application and i'm using Provider for dependency injection. According to the documentation, invoking context.watch() is enough to make the Widget listen for changes in the LoginStore and then rebuild, but something is wrong and this is not working.

This is my view:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:trade_magic/src/login/login_store.dart';

class TestView extends StatelessWidget {
  const TestView({super.key});

  @override
  Widget build(BuildContext context) {
    final store = context.watch<LoginStore>();
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Row(
            children: [
              Expanded(
                  child: TextField(
                onChanged: (value) => store.value.username = value,
              ))
            ],
          ),
          Expanded(child: Text(store.value.username))
        ],
      ),
    );
  }
}

This is my store:

class LoginStore extends ValueNotifier<Login> {
  LoginStore(super.value);

  LoginStore.empty() : this(Login(username: "", password: ""));
}

This is my model:

import 'dart:convert';

class Login {
  String username;

  String password;

  //set username(username) => this.username = username;

  Login({
    required this.username,
    required this.password,
  });

  Login copyWith({
    String? username,
    String? password,
  }) {
    return Login(
      username: username ?? this.username,
      password: password ?? this.password,
    );
  }

  Map<String, dynamic> toMap() {
    return <String, dynamic>{
      'username': username,
      'password': password,
    };
  }

  factory Login.fromMap(Map<String, dynamic> map) {
    return Login(
      username: map['username'] as String,
      password: map['password'] as String,
    );
  }

  String toJson() => json.encode(toMap());

  factory Login.fromJson(String source) =>
      Login.fromMap(json.decode(source) as Map<String, dynamic>);

  @override
  String toString() => 'Login(username: $username, password: $password)';

  @override
  bool operator ==(covariant Login other) {

    return other.username == username && other.password == password;
  }

  @override
  int get hashCode => username.hashCode ^ password.hashCode;
}

This is App.dart:

import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:provider/provider.dart';
import 'package:trade_magic/src/login/login_store.dart';
//import 'package:trade_magic/src/login/login_view.dart';

import 'login/test_view.dart';
import 'sample_feature/sample_item_details_view.dart';
import 'sample_feature/sample_item_list_view.dart';
import 'settings/settings_controller.dart';
import 'settings/settings_view.dart';

class MyApp extends StatelessWidget {
  const MyApp({
    super.key,
    required this.settingsController,
  });

  final SettingsController settingsController;

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: settingsController,
      builder: (BuildContext context, Widget? child) {
        return MultiProvider(
          providers: [
            ChangeNotifierProvider<LoginStore>(
                create: (_) => LoginStore.empty())
          ],
          child: MaterialApp(
            restorationScopeId: 'app',

            localizationsDelegates: const [
              AppLocalizations.delegate,
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
            ],
            supportedLocales: const [
              Locale('en', ''), // English, no country code
              Locale('pt', 'BR')
            ],

            onGenerateTitle: (BuildContext context) =>
                AppLocalizations.of(context)!.appTitle,

            theme: ThemeData(),
            darkTheme: ThemeData.dark(),
            themeMode: settingsController.themeMode,

            onGenerateRoute: (RouteSettings routeSettings) {
              return MaterialPageRoute<void>(
                settings: routeSettings,
                builder: (BuildContext context) {
                  switch (routeSettings.name) {
                    case SettingsView.routeName:
                      return SettingsView(controller: settingsController);
                    case SampleItemDetailsView.routeName:
                      return const SampleItemDetailsView();
                    case SampleItemListView.routeName:
                    default:
                      return const TestView();
                  }
                },
              );
            },
          ),
        );
      },
    );
  }
}

Most questions in stackoverflow deal with Future, but this is not the case. I checked if the value of LoginStore was really changing, and it was. I expected TestView to rebuild and update the value in the Text widget, but that not happened. Why? What am I doing wrong?


问:
Is this React code that has child components inserting refs to a prop safe?
I am attempting to code a <List> component that is able to print the (x, y) coordinates of each <Row> entry that is added. The problem is that there is an intermediate <RowGroup> component that holds <Row> entries, where I plan on having the <RowGroup> be an abstract type.

I followed this answer regarding innerRef and this answer regarding pushing refs from children components, and I wrote the below code that seems to work.

But it feels kind of hack-ish. Apparently, you must use forwardRef to forward refs, and in this case I am using an innerRef prop and it works? Is it legal to push refs from the child component, into the parent's parent's ref list? I know you aren't supposed to do stuff like having an array of refs, and this feels like a different way to bypass that.

Is there a different way I should structure this code to be more valid? Are there any cases where this code wouldn't work?

```<code>import {useRef, useEffect, forwardRef, useImperativeHandle} from 'react';

function App() {
  const rowGroups = [
    {rows: [{text: "A"}, {text: "B"}, {text: "C"}]},
    {rows: [{text: "D"}, {text: "E"}]}
  ]
  return <List rowGroups={rowGroups}></List> // List should be: A B C {spacing} D E
}

const List = ({rowGroups}) => {

  let rowRefs = useRef([]);

  function handleClick() {
    for (let i = 0; i < rowRefs.current.length; i++) {
      const rect = rowRefs.current[i].getBoundingClientRect();
        console.log(rect.left, rect.top); // print coordinates of each row.
      }
  }

  return (
    <div>
    <div>
      {rowGroups.map((rowGroup, _) => (
        <RowGroup key={_} rowGroup={rowGroup} innerRef={rowRefs}/>
      ))}
    </div>
    <button onClick={() => handleClick()}></button>
    </div>
  );
}

const RowGroup = ({rowGroup, innerRef}) => {

  return (
    <div style={{padding: 50}}>
      {rowGroup.rows.map((row, _) => (

        <Row key={_} row={row} innerRef={innerRef}/>
      ))}
    </div>
  );
};

const Row = ({row, innerRef}) => {
    return (
        <div ref={(ref) => {innerRef.current.push(ref)}} style={{height: 50, width: 200}}>
            {row.text}
        </div>
    );
}

export default App;
</code>```

Thanks.

Body:
I am attempting to code a <List> component that is able to print the (x, y) coordinates of each <Row> entry that is added. The problem is that there is an intermediate <RowGroup> component that holds <Row> entries, where I plan on having the <RowGroup> be an abstract type.

I followed this answer regarding innerRef and this answer regarding pushing refs from children components, and I wrote the below code that seems to work.

But it feels kind of hack-ish. Apparently, you must use forwardRef to forward refs, and in this case I am using an innerRef prop and it works? Is it legal to push refs from the child component, into the parent's parent's ref list? I know you aren't supposed to do stuff like having an array of refs, and this feels like a different way to bypass that.

Is there a different way I should structure this code to be more valid? Are there any cases where this code wouldn't work?

import {useRef, useEffect, forwardRef, useImperativeHandle} from 'react';

function App() {
  const rowGroups = [
    {rows: [{text: "A"}, {text: "B"}, {text: "C"}]},
    {rows: [{text: "D"}, {text: "E"}]}
  ]
  return <List rowGroups={rowGroups}></List> // List should be: A B C {spacing} D E
}

const List = ({rowGroups}) => {

  let rowRefs = useRef([]);

  function handleClick() {
    for (let i = 0; i < rowRefs.current.length; i++) {
      const rect = rowRefs.current[i].getBoundingClientRect();
        console.log(rect.left, rect.top); // print coordinates of each row.
      }
  }

  return (

      {rowGroups.map((rowGroup, _) => (
        <RowGroup key={_} rowGroup={rowGroup} innerRef={rowRefs}/>
      ))}

    <button onClick={() => handleClick()}></button>

  );
}

const RowGroup = ({rowGroup, innerRef}) => {

  return (

      {rowGroup.rows.map((row, _) => (

        <Row key={_} row={row} innerRef={innerRef}/>
      ))}

  );
};

const Row = ({row, innerRef}) => {
    return (

 {innerRef.current.push(ref)}} style={{height: 50, width: 200}}>
            {row.text}

    );
}

export default App;

Thanks.


问:
Using subquery results as a condition of jsonb field indexed search
I have two following tables:

```<code>CREATE TABLE elements(
  id INT PRIMARY KEY,
  element_type INT,
  api_name VARCHAR(100) UNIQUE
);

CREATE TABLE entries(
  id INT PRIMARY KEY,
  elements JSONB
)
</code>```

entries.elements field stored a jsonb-array of elements in following format:

```<code>[
   {
     "id": elements.id
     "type": elements.element_type
     "value": <some_value>
   },
   {
     "id": elements.id
     "type": elements.element_type
     "value": <some_value>
   }
   ...
]
</code>```

The value field can be one of 3 types:

Literal (i.e. "abc", 12, true)

Array of literals (i.e. ["abc", "cbd"], [12, 21])

Array of objects (i.e. [{"node_id": <uuid>, "value": "abc"}, {"node_id": <uuid>, "value": "cba"}])

And I have index (maybe incorrect)

```<code>CREATE INDEX some_idx_name
ON entries
USING GIN (elements jsonb_ops)
</code>```

For example suppose that I have data in these tables:

```<code>INSERT INTO elements(id, element_type, api_name) VALUES
(1, 1, 'el_number_1'),
(2, 2, 'el_datetime'),
(3, 3, 'el_files'),
(4, 1, 'el_number_2');

INSERT INTO entries(id, elements) VALUES
(1, '[{"id": 1, "type": 1, "value": 12}, {"id": 3, "type": 3, "value": [1, 2]}]'::JSONB),
(2, '[{"id": 4, "type": 1, "value": 12}, {"id": 2, "type": 2, "value": [{"date": "20.12.2022", "time": "16:18"}]}]'::JSONB);
</code>```

So if I want to find entry by elements I need to do something like this:

```<code>SELECT id
FROM entries
WHERE elements @? '$[*] ? (@.id == 4 && @.value = 12)'
</code>```

But how can I find entry by value of elements which was found by api_name?

```<code>-- DOES NOT WORK (only for example what I need)
SELECT id
FROM entries
WHERE elements @? '$[*] ? (@.id == (SELECT id FROM elements WHERE api_name = 'el_number_2') && @.value = 12)'
</code>```

Fiddle link

Body:
I have two following tables:

CREATE TABLE elements(
  id INT PRIMARY KEY,
  element_type INT,
  api_name VARCHAR(100) UNIQUE
);

CREATE TABLE entries(
  id INT PRIMARY KEY,
  elements JSONB
)

entries.elements field stored a jsonb-array of elements in following format:

[
   {
     "id": elements.id
     "type": elements.element_type
     "value": <some_value>
   },
   {
     "id": elements.id
     "type": elements.element_type
     "value": <some_value>
   }
   ...
]

The value field can be one of 3 types:

Literal (i.e. "abc", 12, true)

Array of literals (i.e. ["abc", "cbd"], [12, 21])

Array of objects (i.e. [{"node_id": <uuid>, "value": "abc"}, {"node_id": <uuid>, "value": "cba"}])

And I have index (maybe incorrect)

CREATE INDEX some_idx_name
ON entries
USING GIN (elements jsonb_ops)

For example suppose that I have data in these tables:

INSERT INTO elements(id, element_type, api_name) VALUES
(1, 1, 'el_number_1'),
(2, 2, 'el_datetime'),
(3, 3, 'el_files'),
(4, 1, 'el_number_2');

INSERT INTO entries(id, elements) VALUES
(1, '[{"id": 1, "type": 1, "value": 12}, {"id": 3, "type": 3, "value": [1, 2]}]'::JSONB),
(2, '[{"id": 4, "type": 1, "value": 12}, {"id": 2, "type": 2, "value": [{"date": "20.12.2022", "time": "16:18"}]}]'::JSONB);

So if I want to find entry by elements I need to do something like this:

SELECT id
FROM entries
WHERE elements @? '$[*] ? (@.id == 4 && @.value = 12)'

But how can I find entry by value of elements which was found by api_name?

-- DOES NOT WORK (only for example what I need)
SELECT id
FROM entries
WHERE elements @? '$[*] ? (@.id == (SELECT id FROM elements WHERE api_name = 'el_number_2') && @.value = 12)'

Fiddle link


问:
How to access the results of a Magma Routine
I am trying to access the results of the eigenvalue decomposition of a general real matrix, using the magma_sgeev routine. My code is as follows -

```<code>#include <cstdlib>
#include <iostream>
#include <map>

#include <typeindex>
#include <typeinfo>

#include <magma_v2.h>
#include <random>

#define N 10
#define LDA N
#define LDVL N
#define LDVR N

/* Main program */
int main()
{
    magma_init();
    /* Locals */
    int n = N, lda = LDA, ldvl = LDVL, ldvr = LDVR, info, lwork;
    float wkopt;
    float *work;
    /* Local arrays */
    float wr[N], wi[N], vl[LDVL * N], vr[LDVR * N];
    float *a = (float *)malloc(LDA * N * sizeof(float));
    for (int i = 0; i < LDA * N; i++)
        a[i] = rand();
    printf("Done populating matrix\n");

    lwork = -1;
    magma_sgeev_m(MagmaNoVec, MagmaNoVec, n, a, lda, wr, wi, vl, ldvl, vr, ldvr,
                  work, lwork, &info);

    lwork = (int)work[0];
    work = (float *)malloc(lwork * sizeof(float));
    printf("%d\n", lwork);

    magma_sgeev_m(MagmaNoVec, MagmaNoVec, n, a, lda, wr, wi, vl, ldvl, vr, ldvr,
                  work, lwork, &info);

    for (int i = 0; i < N; i++)
        printf("%f ", wr[i]);

    std::cout << std::endl;

    for (int i = 0; i < N; i++)
        printf("%f ", wi[i]);

    printf("\n");

    if (info > 0)
    {
        printf("The algorithm failed to compute eigenvalues.\n");
        exit(1);
    }
    exit(0);

    magma_finalize();
}
</code>```

As the documentation says, the arrays wr and wi hold the results of the computation. However, there are two issues with this code,

When I try to access the wr and wi, I get a segmentation fault. I am not aware of the inner workings of the magma library, what am I missing, and how do I fix it ?

When I increase the size of the matrix, for example from 5x5 to 10x10. I get a segmentation fault in the first call of magma_sgeev itself. What am I missing

Body:
I am trying to access the results of the eigenvalue decomposition of a general real matrix, using the magma_sgeev routine. My code is as follows -

#include <cstdlib>
#include <iostream>
#include <map>

#include <typeindex>
#include <typeinfo>

#include <magma_v2.h>
#include <random>

#define N 10
#define LDA N
#define LDVL N
#define LDVR N

/* Main program */
int main()
{
    magma_init();
    /* Locals */
    int n = N, lda = LDA, ldvl = LDVL, ldvr = LDVR, info, lwork;
    float wkopt;
    float *work;
    /* Local arrays */
    float wr[N], wi[N], vl[LDVL * N], vr[LDVR * N];
    float *a = (float *)malloc(LDA * N * sizeof(float));
    for (int i = 0; i < LDA * N; i++)
        a[i] = rand();
    printf("Done populating matrix\n");

    lwork = -1;
    magma_sgeev_m(MagmaNoVec, MagmaNoVec, n, a, lda, wr, wi, vl, ldvl, vr, ldvr,
                  work, lwork, &info);

    lwork = (int)work[0];
    work = (float *)malloc(lwork * sizeof(float));
    printf("%d\n", lwork);

    magma_sgeev_m(MagmaNoVec, MagmaNoVec, n, a, lda, wr, wi, vl, ldvl, vr, ldvr,
                  work, lwork, &info);

    for (int i = 0; i < N; i++)
        printf("%f ", wr[i]);

    std::cout << std::endl;

    for (int i = 0; i < N; i++)
        printf("%f ", wi[i]);

    printf("\n");

    if (info > 0)
    {
        printf("The algorithm failed to compute eigenvalues.\n");
        exit(1);
    }
    exit(0);

    magma_finalize();
}

As the documentation says, the arrays wr and wi hold the results of the computation. However, there are two issues with this code,

When I try to access the wr and wi, I get a segmentation fault. I am not aware of the inner workings of the magma library, what am I missing, and how do I fix it ?

When I increase the size of the matrix, for example from 5x5 to 10x10. I get a segmentation fault in the first call of magma_sgeev itself. What am I missing


问:
dropEnum function not recognized by TypeScript
I'm using TypeScript and trying to drop a single enum using the function specified in the API Reference here:

https://sequelize.org/api/v6/class/src/dialects/postgres/query-interface.js~postgresqueryinterface#instance-method-dropEnum

Yet I get the TypeScript error:

```<code>Property 'dropEnum' does not exist on type 'QueryInterface'.
</code>```

Code snippet:

```<code>export const down: Migration = async ({ context: queryInterface }) => {
  ...
  await queryInterface.dropEnum(); // Error here
};
</code>```

I tried updating sequelize & sequelize-typescript, but I still get the same error.

EDIT

Until I know what I'm doing wrong/This gets fixed you can use this:

export const down: Migration = async ({ context: queryInterface }) => {
  await queryInterface.dropTable('<table_name>', {});
  await queryInterface.sequelize.query(
    'DROP TYPE IF EXISTS enum_<enum_name>'
  );
};
```

References (More info):

https://github.com/sequelize/sequelize/issues/13184

Drop all data types in Postgres

Execute raw query in migration - Sequelize 3.30

Body:
I'm using TypeScript and trying to drop a single enum using the function specified in the API Reference here:

https://sequelize.org/api/v6/class/src/dialects/postgres/query-interface.js~postgresqueryinterface#instance-method-dropEnum

Yet I get the TypeScript error:

Property 'dropEnum' does not exist on type 'QueryInterface'.

Code snippet:

export const down: Migration = async ({ context: queryInterface }) => {
  ...
  await queryInterface.dropEnum(); // Error here
};

I tried updating sequelize & sequelize-typescript, but I still get the same error.

EDIT

Until I know what I'm doing wrong/This gets fixed you can use this:

export const down: Migration = async ({ context: queryInterface }) => {
  await queryInterface.dropTable('<table_name>', {});
  await queryInterface.sequelize.query(
    'DROP TYPE IF EXISTS enum_<enum_name>'
  );
};

References (More info):

https://github.com/sequelize/sequelize/issues/13184

Drop all data types in Postgres

Execute raw query in migration - Sequelize 3.30


问:
How to migrate existing nrwl/nx Angular project into new Spring boot application
I have an existing nrwl nx Angular project with libs and components inside it. I generated an Spring boot project and want to integrate my existing frontend project into this spring boot application.
Here on this site: https://www.evoketechnologies.com/blog/integrate-angular-spring-boot-restful-api/#:~:text=Import%20Angular%20client%20project%20into,project%20structure%20in%20your%20IDE.

it was recommended to use spring boot tools suite but I could not find an option to import the project (tried on eclipse and vs code) How can I cleanly import the nrwl nx Angular project into my spring boot project, so it will be recognized directly.


问:
opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
i imported a reat project on visual studio code. i installed npm and then i runned npm start . but it gives me error.  opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],

can some ome help me?
thanks.


Title: Using Python to add properties in GeoJSON and fill it with calculated result

Body:
I cannot find a way to alter a geojson file with the following demands:

add property for every feature

fill property with calculated result

The file I am trying to alter is the following:

    {
"type": "FeatureCollection",
"name": "contour",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "ID": 0, "elev": 200 }, "geometry": { "type": "LineString", "coordinates": [ [ 15.256250000529057, 52.454722222212162 ], [ 15.25611111150125, 52.454583333184353 ], [ 15.255833333723411, 52.454722222073272 ], [ 15.255833333445633, 52.454722222212162 ], [ 15.25555555594557, 52.454999999712228 ], [ 15.255555555852979, 52.454999999990001 ], [ 15.25555555594557, 52.455000000267781 ], [ 15.255833333723411, 52.455000000267781 ], [ 15.25611111150125, 52.455000000267781 ], [ 15.256111111640138, 52.454999999990001 ], [ 15.256250000529057, 52.454722222212162 ] ] } },
{ "type": "Feature", "properties": { "ID": 1, "elev": 200 }, "geometry": { "type": "LineString", "coordinates": [ [ 15.274166667338594, 52.445833333321303 ], [ 15.274166667060816, 52.445833333182414 ], [ 15.273888889282977, 52.445833333043524 ], [ 15.2738888890052, 52.445833333321303 ], [ 15.273750000255168, 52.446111111099142 ], [ 15.273888889282977, 52.446250000126945 ], [ 15.274166667060816, 52.446111111191733 ], [ 15.274166667199705, 52.446111111099142 ], [ 15.274166667338594, 52.445833333321303 ] ] } }
]
}

It is just some LineString with properties "ID" and "elev".
Id like to add the "length" property with the calculated lenght of the LineString in meters.

I used QQis to to that before, but right now im building a little gui and would put a function behind the button, which does all the process odd adding property, calucating line length and putting the results into the property, all at once.

Does anyone can lead me to good documentations, examples or other sites, because my research didnt succeed so far :/

I generated the contour line file with the following function (ignore the variables, im a noob and just trying out things :D). Maybe its even possible to integrate such property already in the process? (whereas I dont know how the calculation of the lengths should work, since there must be finished features first to calculate)

dem_contour = gdal.Open(entry_sourcefile_dem_contourlines.get())
            in1 = dem_contour.GetRasterBand(1)

            # Generate layer to save Contourlines in
            ogr_ds = ogr.GetDriverByName(formatcalc).CreateDataSource(destination_file_contour)
            sr = osr.SpatialReference()
            sr.ImportFromEPSG(4326)
            contour_spatial = ogr_ds.CreateLayer('contour', sr)
            contour_spatial.CreateField(ogr.FieldDefn("ID", ogr.OFTInteger))
            contour_spatial.CreateField(ogr.FieldDefn("elev", ogr.OFTInteger))

            # Generate Contourlines
            interval_steps = int(entry_settings_interval_contourlines.get())
            contourline_start = int(entry_settings_start_contourlines.get())
            contourline_stop = int(entry_settings_end_contourlines.get())
            intervals = list(range(contourline_start, contourline_stop, interval_steps)) # start, end, step
            gdal.ContourGenerate(in1, 100, 0, intervals, 0, 0, contour_spatial, 0, 1)
            ogr_ds = None
            del ogr_ds

Thanks in advance for any kind of help.

Im on python 3.11


问:
GitlabCI error: 'detached pipeline job' needs 'branch pipeline job', but 'branch pipeline job' is not in any previous stage
I want to run some jobs automatically on merge request and otherwise as manual in GitLab CI. Is there any way of accessing artefacts from previous jobs from inside detached job created on merge request? Here is a sample pipeline for reference,

```<code>branch_job1:
  stage: stage1
  script:
    - touch log.txt
  artifacts:
    paths:
      - log.txt

detached_job2:
  stage: stage2
  dependencies: [branch_job1]
  needs:
    - job: branch_job1
      artifacts: true
  script:
    - echo "hello"
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      when: always
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      when: always
    - if: $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH
      when: manual
      allow_failure: true
</code>```

Here branch_job1 runs on pushing code to branch, detached_job2 runs  if its pushed to default branch or as a detached job on merge request. job2 needs job1 but as jobs2 is detached, its not finding job1. How to solve this issue?

Body:
I want to run some jobs automatically on merge request and otherwise as manual in GitLab CI. Is there any way of accessing artefacts from previous jobs from inside detached job created on merge request? Here is a sample pipeline for reference,

branch_job1:
  stage: stage1
  script:
    - touch log.txt
  artifacts:
    paths:
      - log.txt

detached_job2:
  stage: stage2
  dependencies: [branch_job1]
  needs:
    - job: branch_job1
      artifacts: true
  script:
    - echo "hello"
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      when: always
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      when: always
    - if: $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH
      when: manual
      allow_failure: true

Here branch_job1 runs on pushing code to branch, detached_job2 runs  if its pushed to default branch or as a detached job on merge request. job2 needs job1 but as jobs2 is detached, its not finding job1. How to solve this issue?


问:
Getting System Error Code 1060 (service does not exist) after using function OpenServiceA
I would like to control a Service (e.g. WinRM) using Powershell via the WinAPI. (Just for an exercise).
After running the script, I get a handle to the service control manager database. However, I dont get a handle of the "WinRM"-Service. I only get the Error-Code 1060 (The specified service does not exist as an installed service.) after executing the OpenServiceA-Function.

Service.ps1

```<code>$loadAdvapi32 = @"

  public struct LPSERVICE_STATUS {
      public uint dwServiceType;
      public uint dwCurrentState;
      public uint dwControlsAccepted;
      public uint dwWin32ExitCode;
      public uint dwServiceSpecificExitCode;
      public uint dwCheckPoint;
      public uint dwWaitHint;
  }

 [DllImport("Advapi32.dll", CharSet=CharSet.Auto)]
 public static extern
 IntPtr OpenSCManager(string  lpMachineName,
                      string  lpDatabaseName,
                      uint    dwDesiredAccess);

 [DllImport("Advapi32.dll", CharSet=CharSet.Auto)]
 public static extern
 IntPtr OpenServiceA(IntPtr    hSCManager,
                     string    lpServiceName,
                     uint      dwDesiredAccess);

 [DllImport("Advapi32.dll", CharSet=CharSet.Auto)]
 public static extern
 bool ControlService(IntPtr           hService,
                     uint             dwControl,
                     out LPSERVICE_STATUS lpServiceStatus);
"@

$loadKernel32 = @"
 [DllImport("Kernel32.dll", CharSet=CharSet.Auto)]
 public static extern
 int GetLastError();
"@

Add-Type -MemberDefinition $loadAdvapi32 -Name 'Advapi32' -Namespace 'Win32';
Add-Type -MemberDefinition $loadKernel32 -Name 'Kernel32' -Namespace 'Win32';

$lpMachineName = [NullString]::Value;
$lpDatabaseName = [NullString]::Value;

# https://learn.microsoft.com/en-us/windows/win32/services/service-security-and-access-rights
$SC_MANAGER_ALL_ACCESS = 0xF003F;
$SERVICE_ALL_ACCESS = 0xF01FF;

$hSCManager = [Win32.Advapi32]::OpenSCManager($lpMachineName, $lpDatabaseName, $SC_MANAGER_ALL_ACCESS);
[Win32.Kernel32]::GetLastError()

$schService = [Win32.Advapi32]::OpenServiceA($hSCManager, "WinRM", $SERVICE_ALL_ACCESS);
[Win32.Kernel32]::GetLastError()

</code>```

Output

```<code>PS C:\Windows\system32> C:\Service.ps1
0
1060
</code>```

I already tried/checked:

WinRM-Service exists and is installed

Running the script in an elevated Powershell

Checked if the Name of the Service is correct

Body:
I would like to control a Service (e.g. WinRM) using Powershell via the WinAPI. (Just for an exercise).
After running the script, I get a handle to the service control manager database. However, I dont get a handle of the "WinRM"-Service. I only get the Error-Code 1060 (The specified service does not exist as an installed service.) after executing the OpenServiceA-Function.

Service.ps1

$loadAdvapi32 = @"

  public struct LPSERVICE_STATUS {
      public uint dwServiceType;
      public uint dwCurrentState;
      public uint dwControlsAccepted;
      public uint dwWin32ExitCode;
      public uint dwServiceSpecificExitCode;
      public uint dwCheckPoint;
      public uint dwWaitHint;
  }

 [DllImport("Advapi32.dll", CharSet=CharSet.Auto)]
 public static extern
 IntPtr OpenSCManager(string  lpMachineName,
                      string  lpDatabaseName,
                      uint    dwDesiredAccess);

 [DllImport("Advapi32.dll", CharSet=CharSet.Auto)]
 public static extern
 IntPtr OpenServiceA(IntPtr    hSCManager,
                     string    lpServiceName,
                     uint      dwDesiredAccess);

 [DllImport("Advapi32.dll", CharSet=CharSet.Auto)]
 public static extern
 bool ControlService(IntPtr           hService,
                     uint             dwControl,
                     out LPSERVICE_STATUS lpServiceStatus);
"@

$loadKernel32 = @"
 [DllImport("Kernel32.dll", CharSet=CharSet.Auto)]
 public static extern
 int GetLastError();
"@

Add-Type -MemberDefinition $loadAdvapi32 -Name 'Advapi32' -Namespace 'Win32';
Add-Type -MemberDefinition $loadKernel32 -Name 'Kernel32' -Namespace 'Win32';

$lpMachineName = [NullString]::Value;
$lpDatabaseName = [NullString]::Value;

# https://learn.microsoft.com/en-us/windows/win32/services/service-security-and-access-rights
$SC_MANAGER_ALL_ACCESS = 0xF003F;
$SERVICE_ALL_ACCESS = 0xF01FF;

$hSCManager = [Win32.Advapi32]::OpenSCManager($lpMachineName, $lpDatabaseName, $SC_MANAGER_ALL_ACCESS);
[Win32.Kernel32]::GetLastError()

$schService = [Win32.Advapi32]::OpenServiceA($hSCManager, "WinRM", $SERVICE_ALL_ACCESS);
[Win32.Kernel32]::GetLastError()

Output

PS C:\Windows\system32> C:\Service.ps1
0
1060

I already tried/checked:

WinRM-Service exists and is installed

Running the script in an elevated Powershell

Checked if the Name of the Service is correct


问:
Random string generator gets the same result in Java
Hello we are developing a Quiz game in Java.In our project we use Hashmap that consist of countries and their details.Each time in the loop we want to get three random countries with a random method, and we want  User to answer questions related to that random country.Everytime user answers the questions related to the country  we get another random country from hashmap.But we don't want these three random countries to be the same.How can we avoid that?

```<code>import java.util.HashMap;
import java.util.Random;

public class Countries {
    private HashMap<String, String[]> countrieseasy;
    private HashMap<String, String[]> countriesmedium;
    private HashMap<String, String[]> countrieshard;
    private String previousEasyCountry;
    private String secondPreviousEasyCountry;
    private String previousMediumCountry;
    private String secondPreviousMediumCountry;
    private String previousHardCountry;
    private String secondPreviousHardCountry;
    private Random random;

    public Countries() {
        countrieseasy = new HashMap<>();
        countriesmedium = new HashMap<>();  // create a new HashMap object
        countrieshard = new HashMap<>();
        previousEasyCountry = null;
        secondPreviousEasyCountry = null;
        previousMediumCountry = null;
        secondPreviousMediumCountry = null;
        previousHardCountry = null;
        secondPreviousHardCountry = null;
        random = new Random();
    }

    public void addCountryeasy(String name, String capital, String language, String continent, String currency) {
        String[] details = {name, capital, language, continent, currency};
        countrieseasy.put(name, details);
    }

    public void addCountrymedium(String name, String capital, String language, String continent, String currency) {
        String[] details = {name, capital, language, continent, currency};
        countriesmedium.put(name, details);
    }

    public void addCountryhard(String name, String capital, String language, String continent, String currency) {
        String[] details = {name, capital, language, continent, currency};
        countrieshard.put(name, details);
    }

    public String[] getCountryeasyDetails(String name) {

        return countrieseasy.get(name);

    }

    public String[] getCountrymediumDetails(String name) {

        return countriesmedium.get(name);

    }

    public String[] getCountryhardDetails(String name) {

        return countrieshard.get(name);

    }

    private String getRandomCountryName(HashMap<String, String[]> countries, String previousCountry, String secondPreviousCountry) {
        Object[] countryNames = countries.keySet().toArray();
        int randomIndex = random.nextInt(countryNames.length);
        String countryName = (String) countryNames[randomIndex];
        while (countryName.equals(previousCountry) || ( countryName.equals(secondPreviousCountry)) || (secondPreviousCountry != null && secondPreviousCountry.equals(previousCountry))) {
            randomIndex = random.nextInt(countryNames.length);
            countryName = (String) countryNames[randomIndex];
        }
        return countryName;
    }

    public String getRandomCountryeasyName() {
        String secondPreviousCountry = previousEasyCountry;
        previousEasyCountry = secondPreviousEasyCountry;
        secondPreviousEasyCountry = secondPreviousCountry;
        String countryName = getRandomCountryName(countrieseasy, previousEasyCountry, secondPreviousEasyCountry);
        return countryName;
    }

    public String getRandomCountrymediumName() {
        String secondPreviousCountry = previousMediumCountry;
        previousMediumCountry = secondPreviousMediumCountry;
        secondPreviousMediumCountry = secondPreviousCountry;
        String countryName = getRandomCountryName(countriesmedium, previousEasyCountry, secondPreviousEasyCountry);

        return countryName;
    }

    public String getRandomCountryhardName() {
        String secondPreviousCountry = previousMediumCountry;
        previousHardCountry = secondPreviousHardCountry;
        secondPreviousHardCountry = secondPreviousCountry;
        String countryName = getRandomCountryName(countriesmedium, previousEasyCountry, secondPreviousEasyCountry);
        return countryName;
    }

}
</code>```

So here is our code we tried to give each country a string value previousName , and ckecked if it is equal to the next random country we get from hashmap but it didn't work.

Body:
Hello we are developing a Quiz game in Java.In our project we use Hashmap that consist of countries and their details.Each time in the loop we want to get three random countries with a random method, and we want  User to answer questions related to that random country.Everytime user answers the questions related to the country  we get another random country from hashmap.But we don't want these three random countries to be the same.How can we avoid that?

import java.util.HashMap;
import java.util.Random;

public class Countries {
    private HashMap<String, String[]> countrieseasy;
    private HashMap<String, String[]> countriesmedium;
    private HashMap<String, String[]> countrieshard;
    private String previousEasyCountry;
    private String secondPreviousEasyCountry;
    private String previousMediumCountry;
    private String secondPreviousMediumCountry;
    private String previousHardCountry;
    private String secondPreviousHardCountry;
    private Random random;

    public Countries() {
        countrieseasy = new HashMap<>();
        countriesmedium = new HashMap<>();  // create a new HashMap object
        countrieshard = new HashMap<>();
        previousEasyCountry = null;
        secondPreviousEasyCountry = null;
        previousMediumCountry = null;
        secondPreviousMediumCountry = null;
        previousHardCountry = null;
        secondPreviousHardCountry = null;
        random = new Random();
    }

    public void addCountryeasy(String name, String capital, String language, String continent, String currency) {
        String[] details = {name, capital, language, continent, currency};
        countrieseasy.put(name, details);
    }

    public void addCountrymedium(String name, String capital, String language, String continent, String currency) {
        String[] details = {name, capital, language, continent, currency};
        countriesmedium.put(name, details);
    }

    public void addCountryhard(String name, String capital, String language, String continent, String currency) {
        String[] details = {name, capital, language, continent, currency};
        countrieshard.put(name, details);
    }

    public String[] getCountryeasyDetails(String name) {

        return countrieseasy.get(name);

    }

    public String[] getCountrymediumDetails(String name) {

        return countriesmedium.get(name);

    }

    public String[] getCountryhardDetails(String name) {

        return countrieshard.get(name);

    }

    private String getRandomCountryName(HashMap<String, String[]> countries, String previousCountry, String secondPreviousCountry) {
        Object[] countryNames = countries.keySet().toArray();
        int randomIndex = random.nextInt(countryNames.length);
        String countryName = (String) countryNames[randomIndex];
        while (countryName.equals(previousCountry) || ( countryName.equals(secondPreviousCountry)) || (secondPreviousCountry != null && secondPreviousCountry.equals(previousCountry))) {
            randomIndex = random.nextInt(countryNames.length);
            countryName = (String) countryNames[randomIndex];
        }
        return countryName;
    }

    public String getRandomCountryeasyName() {
        String secondPreviousCountry = previousEasyCountry;
        previousEasyCountry = secondPreviousEasyCountry;
        secondPreviousEasyCountry = secondPreviousCountry;
        String countryName = getRandomCountryName(countrieseasy, previousEasyCountry, secondPreviousEasyCountry);
        return countryName;
    }

    public String getRandomCountrymediumName() {
        String secondPreviousCountry = previousMediumCountry;
        previousMediumCountry = secondPreviousMediumCountry;
        secondPreviousMediumCountry = secondPreviousCountry;
        String countryName = getRandomCountryName(countriesmedium, previousEasyCountry, secondPreviousEasyCountry);

        return countryName;
    }

    public String getRandomCountryhardName() {
        String secondPreviousCountry = previousMediumCountry;
        previousHardCountry = secondPreviousHardCountry;
        secondPreviousHardCountry = secondPreviousCountry;
        String countryName = getRandomCountryName(countriesmedium, previousEasyCountry, secondPreviousEasyCountry);
        return countryName;
    }

}

So here is our code we tried to give each country a string value previousName , and ckecked if it is equal to the next random country we get from hashmap but it didn't work.


问:
Mean for multiple BigWig files
I want to combine multiple BigWig files into one BigWig file in R or Python. This one BigWig file needs to be the mean of the input files.

I've tried multiple packages such as wiggletools, but I can't seem to get it to work.

Title: Mean for multiple BigWig files


问:
How can I add google reviews to angular project?
I'm currently working on an angular project for a client who wants the google reviews that are published inside the main page.
I've tried using external widgets like the ones supplied by TrustMary and ElfSight but when I paste the script on the component html it just won't render it.

I'm a little stuck can anyone show me an example of how can I do this??

Thanks in advice :)


问:
Streamlit on win7 without internet connection
I am struggling with streamlit installation on win7 computer without internet connection. I tried to solve this with winpython, only to find out that versions of winpython (<3.9) that work on windows 7 don't include streamlit and pyarrow (dependecy of streamlit). Pyarrow won't install due to cmake error.</p>


问:
How to execute script.js once before parsing HTML while using"npm run build"?
While working on a recent tailwind project, I came across this issue.
Let me explain it with an analogy.

Let there are 10 divs and 10 img files inside a folder "asset".
So, I linked 5 images with 5 divs respectively (1 img inside 1 div), and I linked other 5 images by adding value to .src with the help of Form.array() and for.Each() methods.
Now, when I am opening the page with liveserver, I am getting all the 10 images, but when I am running "npm run build" for deployment purposes then those 5 images which I had linked with src are there in the /asset but the rest 5 images( which I was calling via Js) are not.

I get it, that "npm run build" is parsing those file which are directly linked inside html, but rest 5 images are not there, since they are added later on after Js

I have tried adding type="module" attribute and "defer" in the script tag, but nothing seems to work


问:
Python JSON: raise JSONDecodeError from parse_constant
I am currently using the json module to load some JSON content and I need to exclude NaN values. The standard way to do this seems to be to implement a parse_constant method and then pass this method to json.loads.

Example:

def parse_constant(c: str) -> float:
    if c == "NaN":
        raise ValueError("NaN is not valid JSON")
    return float(c)

json_content = json.loads(some_json_string, parse_constant=parse_constant)
```

Apparently, the decode implementation does not catch the ValueError and transform it into a JSONDecodeError, which forces me to check for both exception types. I miss the context (line number, JSON document) to build the decode error myself. I know I could just catch ValueError, but is there a way to configure the json module to raise what I would expect to be the logical exception type?

Body:
I am currently using the json module to load some JSON content and I need to exclude NaN values. The standard way to do this seems to be to implement a parse_constant method and then pass this method to json.loads.

Example:

def parse_constant(c: str) -> float:
    if c == "NaN":
        raise ValueError("NaN is not valid JSON")
    return float(c)

json_content = json.loads(some_json_string, parse_constant=parse_constant)

Apparently, the decode implementation does not catch the ValueError and transform it into a JSONDecodeError, which forces me to check for both exception types. I miss the context (line number, JSON document) to build the decode error myself. I know I could just catch ValueError, but is there a way to configure the json module to raise what I would expect to be the logical exception type?


问:
How compare error message from TestRestTemplate?
I am writing an integration test where I want to get and compare the code as well as the error message.

```<code>ResponseEntity<Response> response = testRestTemplate
    .exchange(url, HttpMethod.GET, requestEntity, Response.class);

assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
assertThat(response.getErrorMessage()).isEqualTo("Response not found");
</code>```

How can I compare the error message from TestRestTemplate?

Body:
I am writing an integration test where I want to get and compare the code as well as the error message.

ResponseEntity<Response> response = testRestTemplate
    .exchange(url, HttpMethod.GET, requestEntity, Response.class);

assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
assertThat(response.getErrorMessage()).isEqualTo("Response not found");

How can I compare the error message from TestRestTemplate?


问:
cross correlation C++ and python
While trying to do a cross correlation in C++ with 1D vectors and already having a python example, using 2D arrays i have noticed that the end results differ for both methods.

Since i do not know too much about FFT and cross correlation i am wondering if that is normal?
The input data is the same, but i use it differently, as 1D vectors C++ and 2D arrays for python

On the C++ side i have 2, 1D vectors one with size 144 and one 6.
The process is the following:

apply FFT on the bigger one, and return the transform (padded to 0) of size 256

padd to 0 the second one (to be the size of the bigger one) and apply FFT

the actual cross correlation: result vector = the first one * conjugate(second one)

apply an IFFT on the result

The result is a 256 (16x16 if i have to see it as 2D) sized vector with values that can go up to
40.7079 or down to 2.0316e-320.

On the python side i have 2, 2D array (one 12x12, one 2x3) and i am
doing only one step:

1.correlation_result= signal.correlate2d (bigArray,smallArray)

The result in this case is a 13x14 2D array with values not that
extreme as i have on C++ side.

Is that normal, something is missing or do i have to do something else to them?

Title: cross correlation C++ and python


问:
Angular - Can't import a component from a library
I'm learning Angular and I decided to create separate generic elements in addition to the main project (in a library) and then import and use them according to my needs.
My problem is due to the fact that I can't import the generic components now... (I can import the Module from the library, but when I try to use my component's selector, Angular warns that the element is unknown to it and doesn't compile the server ).

Generic Component:

(.html)

```<code><p>f-base-screen works!</p>
</code>```

(.ts)

```<code>import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'nx-flow-base-screen',
  templateUrl: './f-base-screen.component.html',
  styleUrls: ['./f-base-screen.component.scss'],
})
export class FBaseScreenComponent implements OnInit {
  constructor() {}
  ngOnInit(): void {}
}
</code>```

Library Module:

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FBaseScreenComponent } from './f-base-screen/f-base-screen.component';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [
    FBaseScreenComponent
  ],
  exports: [
    FBaseScreenComponent
  ],
})
export class FLibrariesModule {}
</code>```

f-libraries.ts (exports the module and its components):

```<code>export * from './f-libraries.module';
export * from './f-base-screen/f-base-screen.component';
</code>```

My SharedModule (it's later imported into my app.module):

```<code>import { CommonModule } from "@angular/common";
import { NgModule } from "@angular/core";
import { FLibrariesModule } from "@nx-flow/f-libraries";

@NgModule({
    imports: [CommonModule, FLibrariesModule],
    exports: [CommonModule, FLibrariesModule],
    providers: []
})
export class SharedModule {}
</code>```

App.module.ts:

```<code>import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';
import { FRestService } from './shared/utils/rest.service';
import { SharedModule } from './shared/shared.module';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, AppRoutingModule, HttpClientModule, SharedModule],
  exports: [],
  providers: [FRestService],
  bootstrap: [AppComponent],
})
export class AppModule {}
</code>```

My Home.component.module.ts (which imports the SharedModule to use the nx-flow-base-screen component):

```<code>import { NgModule } from '@angular/core';
import { WelcomeService } from '../../shared/services/flow-services/welcome.service';
import { SharedModule } from '../../shared/shared.module';
import { FRestService } from '../../shared/utils/rest.service';

import { HomeComponent } from './home.component';

@NgModule({
  declarations: [HomeComponent],
  imports: [SharedModule],
  providers: [WelcomeService, FRestService],
  bootstrap: [HomeComponent],
})
export class HomeComponentModule {}
</code>```

My Home.component.html (using the component, the error that appears in the image is the same as angular throws when I compile):

```<code><div>
    <span>Home Page</span>
</div>
<nx-flow-base-screen></nx-flow-base-screen>
</code>```

I already researched and followed tutorials, none of them worked so far. Are there any changes I still need to make to be able to use my component, from the library, within my main project?
If any more files are needed to reach a conclusion, I'll post a print of it.

Error:

apps/flow/src/app/views/home/home.component.html:4:3 - error
NG8001: 'nx-flow-base-screen' is not a known element:

If 'nx-flow-base-screen' is an Angular component, then verify that it is part of this module.

If 'nx-flow-base-screen' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component
to suppress this message.

Body:
I'm learning Angular and I decided to create separate generic elements in addition to the main project (in a library) and then import and use them according to my needs.
My problem is due to the fact that I can't import the generic components now... (I can import the Module from the library, but when I try to use my component's selector, Angular warns that the element is unknown to it and doesn't compile the server ).

Generic Component:

(.html)

f-base-screen works!

(.ts)

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'nx-flow-base-screen',
  templateUrl: './f-base-screen.component.html',
  styleUrls: ['./f-base-screen.component.scss'],
})
export class FBaseScreenComponent implements OnInit {
  constructor() {}
  ngOnInit(): void {}
}

Library Module:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FBaseScreenComponent } from './f-base-screen/f-base-screen.component';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [
    FBaseScreenComponent
  ],
  exports: [
    FBaseScreenComponent
  ],
})
export class FLibrariesModule {}

f-libraries.ts (exports the module and its components):

export * from './f-libraries.module';
export * from './f-base-screen/f-base-screen.component';

My SharedModule (it's later imported into my app.module):

import { CommonModule } from "@angular/common";
import { NgModule } from "@angular/core";
import { FLibrariesModule } from "@nx-flow/f-libraries";

@NgModule({
    imports: [CommonModule, FLibrariesModule],
    exports: [CommonModule, FLibrariesModule],
    providers: []
})
export class SharedModule {}

App.module.ts:

import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';
import { FRestService } from './shared/utils/rest.service';
import { SharedModule } from './shared/shared.module';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, AppRoutingModule, HttpClientModule, SharedModule],
  exports: [],
  providers: [FRestService],
  bootstrap: [AppComponent],
})
export class AppModule {}

My Home.component.module.ts (which imports the SharedModule to use the nx-flow-base-screen component):

import { NgModule } from '@angular/core';
import { WelcomeService } from '../../shared/services/flow-services/welcome.service';
import { SharedModule } from '../../shared/shared.module';
import { FRestService } from '../../shared/utils/rest.service';

import { HomeComponent } from './home.component';

@NgModule({
  declarations: [HomeComponent],
  imports: [SharedModule],
  providers: [WelcomeService, FRestService],
  bootstrap: [HomeComponent],
})
export class HomeComponentModule {}

My Home.component.html (using the component, the error that appears in the image is the same as angular throws when I compile):

    Home Page

<nx-flow-base-screen></nx-flow-base-screen>

I already researched and followed tutorials, none of them worked so far. Are there any changes I still need to make to be able to use my component, from the library, within my main project?
If any more files are needed to reach a conclusion, I'll post a print of it.

Error:

apps/flow/src/app/views/home/home.component.html:4:3 - error
NG8001: 'nx-flow-base-screen' is not a known element:

If 'nx-flow-base-screen' is an Angular component, then verify that it is part of this module.

If 'nx-flow-base-screen' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component
to suppress this message.


问:
You must be logged in to the server (Unauthorized)
I ran following commands to create a user in minikube, but I'm getting following error:

You must be logged in to the server (Unauthorized)

Commands I ran:

```<code>$ mkdir cert && cd cert

$ openssl genrsa -out user1.key 2048

$ openssl req -new -key user1.key -out user1.csr -subj "/CN=user1/O=group1"

$ openssl x509 -req -in user1.csr -CA ~/.minikube/ca.crt -CAkey ~/.minikube/ca.key -CAcreateserial -out user1.crt -days 500

$ kubectl config set-credentials user1 --client-certificate=user1.crt --client-key=user1.key

$ kubectl config set-context user1-context --cluster=minikube --user=user1

$ kubectl config use-context user1-context

$ kubectl get pods
</code>```

So, the last command to get pods is failing. May I know what I am missing?

Body:
I ran following commands to create a user in minikube, but I'm getting following error:

You must be logged in to the server (Unauthorized)

Commands I ran:

$ mkdir cert && cd cert

$ openssl genrsa -out user1.key 2048

$ openssl req -new -key user1.key -out user1.csr -subj "/CN=user1/O=group1"

$ openssl x509 -req -in user1.csr -CA ~/.minikube/ca.crt -CAkey ~/.minikube/ca.key -CAcreateserial -out user1.crt -days 500

$ kubectl config set-credentials user1 --client-certificate=user1.crt --client-key=user1.key

$ kubectl config set-context user1-context --cluster=minikube --user=user1

$ kubectl config use-context user1-context

$ kubectl get pods

So, the last command to get pods is failing. May I know what I am missing?


问:
Event propagation on tinymce web-component
When one adds an event handler to a tinymce-editor web component, the target of the received event appears to not be the tinymce-editor element, but another component
below the shadow-root of the tinymce-editor element.

Is there any simple way around this because its quite difficult to determine which tinymce-editor element the event was from if you have more than one for example?

(Is this a common approach for, or limitation of,  web components or something - seems a bit odd??)

Sample Code:

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script>
    function changeHandler(evt) {
        console.log(evt.target.id); //gives something like mce_<n>
    }
</script>
<tinymce-editor id='e1' api-key="<api-key>" on-Change="changeHandler"></tinymce-editor>
<tinymce-editor id='e2' api-key="<api-key>" on-Change="changeHandler"></tinymce-editor>
<script src="https://cdn.jsdelivr.net/npm/@tinymce/tinymce-webcomponent@2/dist/tinymce-webcomponent.min.js"/>
</body>
</html>
</code>```

Body:
When one adds an event handler to a tinymce-editor web component, the target of the received event appears to not be the tinymce-editor element, but another component
below the shadow-root of the tinymce-editor element.

Is there any simple way around this because its quite difficult to determine which tinymce-editor element the event was from if you have more than one for example?

(Is this a common approach for, or limitation of,  web components or something - seems a bit odd??)

Sample Code:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

<tinymce-editor id='e1' api-key="<api-key>" on-Change="changeHandler"></tinymce-editor>
<tinymce-editor id='e2' api-key="<api-key>" on-Change="changeHandler"></tinymce-editor>


问:
how to solve unexpected end with concatenation
I'm trying to concatenate some cells for customers reports, I know the formula works manually as I have used it many times, but when it comes to putting it into a VBA to automate it as much as possible, I get a compile error: Expected: End of Statement.

The Syntax is:

```<code>Range("E8").Value = "=CONCATENATE(E6," ", TEXT(E7,"#,##0.00"))
</code>```

I get the error message in the part ",text(E7,"

Can anyone advise where I am going wrong?

I've tried adding additional " where I think they could be missing,

Body:
I'm trying to concatenate some cells for customers reports, I know the formula works manually as I have used it many times, but when it comes to putting it into a VBA to automate it as much as possible, I get a compile error: Expected: End of Statement.

The Syntax is:

Range("E8").Value = "=CONCATENATE(E6," ", TEXT(E7,"#,##0.00"))

I get the error message in the part ",text(E7,"

Can anyone advise where I am going wrong?

I've tried adding additional " where I think they could be missing,


问:
How do i reset sentence_transformers or distilbert model weights to train from scratch?
ive been trying to reset the weights in a pretrained sentence transformer model but i cant seem to find any information about this and the code ive used before to reset the weights of a pytorch model also doesnt work.
For example, the following code doesn't work for both the transformers.DistilBertModel as well as when replacing the model with a sentence_transformer.SentenceTransformer('distilbert-base-nli-mean-tokens') model.

```<code>from transformers import DistilBertTokenizer, DistilBertModel
tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
model = DistilBertModel.from_pretrained('distilbert-base-uncased')
outputs = model(**inputs)
for i, layer in enumerate(model.encoder.layer):
    model.encoder.layer[i].apply(model._init_weights)

Output:

AttributeError: 'DistilBertModel' object has no attribute 'encoder'
</code>```

When trying to iterate through the models body like this:

```<code>from sentence_transformers import SentenceTransformer, SentencesDataset, losses
from sentence_transformers.readers import InputExample

model = SentenceTransformer('distilbert-base-nli-mean-tokens')
for name, module in model.named_children():
    print('resetting ', model[int(name)])
    print(module._modules)

Output:

resetting  Transformer({'max_seq_length': 128, 'do_lower_case': False}) with     Transformer model: DistilBertModel
OrderedDict([('auto_model', DistilBertModel(
  (embeddings): Embeddings(
    (word_embeddings): Embedding(30522, 768, padding_idx=0)
    (position_embeddings): Embedding(512, 768)
    (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)
    (dropout): Dropout(p=0.1, inplace=False)
  )
  (transformer): Transformer(...........
.......etc.......
</code>```

How do i access all of these layers and reset all of their weights?

Body:
ive been trying to reset the weights in a pretrained sentence transformer model but i cant seem to find any information about this and the code ive used before to reset the weights of a pytorch model also doesnt work.
For example, the following code doesn't work for both the transformers.DistilBertModel as well as when replacing the model with a sentence_transformer.SentenceTransformer('distilbert-base-nli-mean-tokens') model.

from transformers import DistilBertTokenizer, DistilBertModel
tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
model = DistilBertModel.from_pretrained('distilbert-base-uncased')
outputs = model(**inputs)
for i, layer in enumerate(model.encoder.layer):
    model.encoder.layer[i].apply(model._init_weights)

Output:

AttributeError: 'DistilBertModel' object has no attribute 'encoder'

When trying to iterate through the models body like this:

from sentence_transformers import SentenceTransformer, SentencesDataset, losses
from sentence_transformers.readers import InputExample

model = SentenceTransformer('distilbert-base-nli-mean-tokens')
for name, module in model.named_children():
    print('resetting ', model[int(name)])
    print(module._modules)

Output:

resetting  Transformer({'max_seq_length': 128, 'do_lower_case': False}) with     Transformer model: DistilBertModel
OrderedDict([('auto_model', DistilBertModel(
  (embeddings): Embeddings(
    (word_embeddings): Embedding(30522, 768, padding_idx=0)
    (position_embeddings): Embedding(512, 768)
    (LayerNorm): LayerNorm((768,), eps=1e-12, elementwise_affine=True)
    (dropout): Dropout(p=0.1, inplace=False)
  )
  (transformer): Transformer(...........
.......etc.......

How do i access all of these layers and reset all of their weights?


问:
Social networking analysis
Do you know How to code Link Prediction in DiGraph Network?

```<code>d=nx.preferential_attachment(G1)
d.sort(key=operator.itemgetter(2), reverse = True)
print('preferential_attachment_G1: {}'.format(d))
</code>```

error: not implemented for directed type

Title: Social networking analysis

Body:
Do you know How to code Link Prediction in DiGraph Network?

d=nx.preferential_attachment(G1)
d.sort(key=operator.itemgetter(2), reverse = True)
print('preferential_attachment_G1: {}'.format(d))

error: not implemented for directed type


问:
Keyword highlighting in Notepad++ UDL
I am trying to create a User-Defined Language Syntax Highlighting Style in Notepad++ that would allow me to use wildcard chars or some other mechanism to detect keywords. For example, in the Language I am using, there are many system functions that start with the letter f (lower-case, mandatory). ALL function name declarations must end with $ like this:

```<code>fGetCurrentState$ (listParams) {Code}
</code>```

Also, user-created functions can be added, as long as they follow the same rules:

```<code>fMyFunction$ (listParams) {Code}
</code>```

I know I can exhaustively add all System function names to the Keywords list and highlight the line, but this is unsustainable and leaves all user functions out. So, finally, my question (thanks for reading this far):

Is it possible to define smart highlighting? What I want to tell Notepad++ is this: 'Highlight any word that STARTS with f and ENDS with $ AND f MUST be the first character in the line.

Title: Keyword highlighting in Notepad++ UDL

Body:
I am trying to create a User-Defined Language Syntax Highlighting Style in Notepad++ that would allow me to use wildcard chars or some other mechanism to detect keywords. For example, in the Language I am using, there are many system functions that start with the letter f (lower-case, mandatory). ALL function name declarations must end with $ like this:

fGetCurrentState$ (listParams) {Code}

Also, user-created functions can be added, as long as they follow the same rules:

fMyFunction$ (listParams) {Code}

I know I can exhaustively add all System function names to the Keywords list and highlight the line, but this is unsustainable and leaves all user functions out. So, finally, my question (thanks for reading this far):

Is it possible to define smart highlighting? What I want to tell Notepad++ is this: 'Highlight any word that STARTS with f and ENDS with $ AND f MUST be the first character in the line.


问:
Elastic Search Query on String Array Field
I'm working on Elastic Search and facing an issue regarding Array field. I've index named test-index with following mapping.

```<code>{
  "test-index": {
    "mappings": {
      "properties": {
        "courses": {
          "type": "keyword"
        }
      }
    }
  }
}
</code>```

My elastic search documents looks like this.

```<code>"hits": [
      {
        "_index": "test-index",
        "_id": "1ac:0000000000_1",
        "_score": 1,
        "_source": {
          "courses": [
            "Course-1A",
            "Course-1B",
            "Course-1C",
            "Course-1D",
            "Course-1E",
            "Course-1F"
          ]
        }
      },
      {
        "_index": "test-index",
        "_id": "1ac:0000000000_2",
        "_score": 1,
        "_source": {
          "courses": [
            "Course-2A",
            "Course-2B",
            "Course-2C",
            "Course-1A"
          ]
        }
      }
    ]
</code>```

The document _id is my student ID. I want to get results with the maximum/highest relevance at the top and lowest on the bottom.

e.g

If I'm searching for courses ["Course-2A","Course-2B","Course-1C"] then user 1ac:0000000000_2 should appear at the top and user 1ac:0000000000_1 at the bottom.

I've tried following queries.

```<code>GET test-index/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "terms": {
            "courses": [
              "Course-1A",
              "Course-2A",
              "Course-2B"
            ]
          }
        }
      ]
    }
  }
}
</code>```

User 1ac:0000000000_1 at the top and other at the bottom.

```<code>GET test-index/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "courses": "Course-1A",
          }
        },
        {
          "term": {
            "courses": "Course-2A",
          }
        },
        {
          "term": {
            "courses": "Course-2B",
          }
        }
      ],
      "minimum_should_match": "70%"
    }
  }
}
</code>```

This gives me some desired results but not sure for larger dataset.

Body:
I'm working on Elastic Search and facing an issue regarding Array field. I've index named test-index with following mapping.

{
  "test-index": {
    "mappings": {
      "properties": {
        "courses": {
          "type": "keyword"
        }
      }
    }
  }
}

My elastic search documents looks like this.

"hits": [
      {
        "_index": "test-index",
        "_id": "1ac:0000000000_1",
        "_score": 1,
        "_source": {
          "courses": [
            "Course-1A",
            "Course-1B",
            "Course-1C",
            "Course-1D",
            "Course-1E",
            "Course-1F"
          ]
        }
      },
      {
        "_index": "test-index",
        "_id": "1ac:0000000000_2",
        "_score": 1,
        "_source": {
          "courses": [
            "Course-2A",
            "Course-2B",
            "Course-2C",
            "Course-1A"
          ]
        }
      }
    ]

The document _id is my student ID. I want to get results with the maximum/highest relevance at the top and lowest on the bottom.

e.g

If I'm searching for courses ["Course-2A","Course-2B","Course-1C"] then user 1ac:0000000000_2 should appear at the top and user 1ac:0000000000_1 at the bottom.

I've tried following queries.

GET test-index/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "terms": {
            "courses": [
              "Course-1A",
              "Course-2A",
              "Course-2B"
            ]
          }
        }
      ]
    }
  }
}

User 1ac:0000000000_1 at the top and other at the bottom.

GET test-index/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "courses": "Course-1A",
          }
        },
        {
          "term": {
            "courses": "Course-2A",
          }
        },
        {
          "term": {
            "courses": "Course-2B",
          }
        }
      ],
      "minimum_should_match": "70%"
    }
  }
}

This gives me some desired results but not sure for larger dataset.